diff --git a/dist/kuzzle.js b/dist/kuzzle.js index acccbce28..040a32059 100644 --- a/dist/kuzzle.js +++ b/dist/kuzzle.js @@ -1,5 +1,5 @@ /*! Kuzzle javascript SDK version 5.0.10 */ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Kuzzle=t():e.Kuzzle=t()}(this,function(){return function(e){function t(i){if(r[i])return r[i].exports;var n=r[i]={exports:{},id:i,loaded:!1};return e[i].call(n.exports,n,n.exports,t),n.loaded=!0,n.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){function i(e,t,r){var n=this;if(!(this instanceof i))return new i(e,t,r);if(h.call(this),r||"function"!=typeof t||(r=t,t=null),!e||""===e)throw new Error("host argument missing");return Object.defineProperties(this,{cleanHistoryTimer:{value:null,writable:!0},collections:{value:{},writable:!0},connectCB:{value:r},eventActions:{value:["connected","networkError","disconnected","reconnected","tokenExpired","loginAttempt","offlineQueuePush","offlineQueuePop","queryError","discarded"],writable:!1},queuing:{value:!1,writable:!0},requestHistory:{value:{},writable:!0},state:{value:"initializing",writable:!0},subscriptions:{value:{pending:{}},writable:!0},autoReconnect:{value:!t||"boolean"!=typeof t.autoReconnect||t.autoReconnect,writable:!0,enumerable:!0},defaultIndex:{value:t&&"string"==typeof t.defaultIndex?t.defaultIndex:void 0,writable:!0,enumerable:!0},reconnectionDelay:{value:t&&"number"==typeof t.reconnectionDelay?t.reconnectionDelay:1e3,writable:!0,enumerable:!0},host:{value:e,writable:!0,enumerable:!0},port:{value:t&&"number"==typeof t.port?t.port:7512,enumerable:!0,writable:!0},sslConnection:{value:!(!t||"boolean"!=typeof t.sslConnection)&&t.sslConnection,writable:!0,enumerable:!0},autoQueue:{value:!1,enumerable:!0,writable:!0},autoReplay:{value:!1,enumerable:!0,writable:!0},autoResubscribe:{value:!0,enumerable:!0,writable:!0},headers:{value:{},enumerable:!0,writable:!0},volatile:{value:{},enumerable:!0,writable:!0},offlineQueue:{value:[],enumerable:!0,writable:!0},queueFilter:{value:null,enumerable:!0,writable:!0},queueMaxSize:{value:500,enumerable:!0,writable:!0},queueTTL:{value:12e4,enumerable:!0,writable:!0},replayInterval:{value:10,enumerable:!0,writable:!0},jwtToken:{value:void 0,enumerable:!0,writable:!0},offlineQueueLoader:{value:void 0,enumerable:!0,writable:!0},sdkVersion:{value:"5.0.10",writable:!1}}),t&&(Object.keys(t).forEach(function(e){n.hasOwnProperty(e)&&Object.getOwnPropertyDescriptor(n,e).writable&&(n[e]=t[e])}),"auto"===t.offlineMode&&this.autoReconnect&&(this.autoQueue=this.autoReplay=this.autoResubscribe=!0)),Object.defineProperty(this,"isValid",{value:function(){if("disconnected"===n.state)throw new Error("This Kuzzle object has been invalidated. Did you try to access it after a disconnect call?")}}),Object.defineProperty(this,"addHeaders",{value:function(e,t){return Object.keys(t).forEach(function(r){e[r]||(e[r]=t[r])}),e}}),Object.defineProperty(this,"callbackRequired",{value:function(e,t){if(!t||"function"!=typeof t)throw new Error(e+": a callback argument is required for read queries")}}),Object.defineProperty(this,"security",{value:new y(this),enumerable:!0}),Object.defineProperty(this,"memoryStorage",{value:new v(this),enumerable:!0}),Object.defineProperties(this,{eventTimeout:{value:t&&"number"==typeof t.eventTimeout?t.eventTimeout:200,writeable:!1}}),Object.defineProperty(this,"protectedEvents",{value:{connected:{timeout:this.eventTimeout},error:{timeout:this.eventTimeout},disconnected:{timeout:this.eventTimeout},reconnected:{timeout:this.eventTimeout},tokenExpired:{timeout:this.eventTimeout},loginAttempt:{timeout:this.eventTimeout}},writeable:!1}),t&&t.connect&&"auto"!==t.connect?this.state="ready":this.connect(),this.cleanHistoryTimer=setInterval(function(){o(n.requestHistory)},1e3),this.bluebird?this.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,i){var n=["getAllStatistics","getServerInfo","getStatistics","listCollections","createIndex","listIndexes","login","logout","now","query","checkToken","whoAmI","updateSelf","getMyRights","refreshIndex","getAutoRefresh","setAutoRefresh"];return i&&n.indexOf(e)!==-1}}):void 0}function n(){var e=this,t=Date.now(),r=-1;e.queueTTL>0&&(e.offlineQueue.forEach(function(i,n){i.ts0&&e.offlineQueue.length>e.queueMaxSize&&e.offlineQueue.splice(0,e.offlineQueue.length-e.queueMaxSize).forEach(function(t){e.emitEvent("offlineQueuePop",t.query)})}function o(e){var t=Date.now();Object.keys(e).forEach(function(r){e[r]0?(s.call(t,t.offlineQueue[0].query,t.offlineQueue[0].cb),t.emitEvent("offlineQueuePop",t.offlineQueue.shift()),setTimeout(function(){i()},Math.max(0,t.replayInterval))):t.queuing=!1};if(t.offlineQueueLoader){if("function"!=typeof t.offlineQueueLoader)throw new Error("Invalid value for offlineQueueLoader property. Expected: function. Got: "+typeof t.offlineQueueLoader);if(e=t.offlineQueueLoader(),!Array.isArray(e))throw new Error("Invalid value returned by the offlineQueueLoader function. Expected: array. Got: "+typeof e);t.offlineQueue=e.concat(t.offlineQueue).filter(function(e){if(!e.query||void 0===e.query.requestId||!e.query.action||!e.query.controller)throw new Error("Invalid offline queue request. One or more missing properties: requestId, action, controller.");return!r.hasOwnProperty(e.query.requestId)&&(r[e.query.requestId]=!0)})}i()}function l(){var e=this;Object.keys(e.subscriptions).forEach(function(t){Object.keys(e.subscriptions[t]).forEach(function(r){var i=e.subscriptions[t][r];i.renew(i.callback)})})}function c(){var e=this;Object.keys(e.subscriptions).forEach(function(t){Object.keys(e.subscriptions[t]).forEach(function(r){var i=e.subscriptions[t][r];i.unsubscribe()})})}function a(e,t){t&&t(new Error("Unable to execute request: not connected to a Kuzzle server.\nDiscarded request: "+JSON.stringify(e)))}function d(){var e=this;Object.keys(e.subscriptions).forEach(function(t){Object.keys(e.subscriptions[t]).forEach(function(r){var i=e.subscriptions[t][r];i.subscribing=!1})})}var f=r(6),h=r(3),p=r(7),y=r(17),v=r(9),b=r(5),m=r(13);i.prototype=Object.create(h.prototype),i.prototype.constructor=i,i.prototype.emit=function(e){var t=Date.now(),r=this.protectedEvents[e];if(r){if(r.lastEmitted&&r.lastEmitted>t-r.timeout)return!1;r.lastEmitted=t}h.prototype.emit.apply(this,arguments)},i.prototype.emitEvent=i.prototype.emit,i.prototype.connect=function(){var e=this;return e.network&&e.disconnect(),e.network=m(e.host,e.port,e.sslConnection),["initializing","ready","disconnected","error","offline"].indexOf(this.state)===-1?(e.connectCB&&e.connectCB(null,e),e):(e.state="connecting",e.network.connect(e.autoReconnect,e.reconnectionDelay),e.network.onConnect(function(){e.state="connected",l.call(e),u.call(e),e.emitEvent("connected"),e.connectCB&&e.connectCB(null,e)}),e.network.on("discarded",function(t){e.emitEvent("discarded",t)}),e.network.onConnectError(function(t){var r=new Error('Unable to connect to kuzzle proxy server at "'+e.host+":"+e.port+'"');r.internal=t,e.state="error",e.emitEvent("networkError",r),d.call(e),e.connectCB&&e.connectCB(r)}),e.network.onDisconnect(function(){e.state="offline",e.autoReconnect||e.disconnect(),e.autoQueue&&(e.queuing=!0),e.emitEvent("disconnected")}),e.network.onReconnect(function(){var t=function(){e.autoResubscribe&&l.call(e),e.autoReplay&&(n.call(e),u.call(e)),e.emitEvent("reconnected")};e.state="connected",e.jwtToken?e.checkToken(e.jwtToken,function(r,i){!r&&i.valid||(e.jwtToken=void 0,e.emitEvent("tokenExpired")),t()}):t()}),this)},i.prototype.setJwtToken=function(e){if("string"==typeof e)this.jwtToken=e;else{if("object"!=typeof e)return this.emitEvent("loginAttempt",{success:!1,error:"Invalid token argument: "+e}),this;if(!e.result||!e.result.jwt||"string"!=typeof e.result.jwt)return this.emitEvent("loginAttempt",{success:!1,error:"Cannot find a valid JWT token in the following object: "+JSON.stringify(e)}),this;this.jwtToken=e.result.jwt}return l.call(this),this.emitEvent("loginAttempt",{success:!0}),this},i.prototype.unsetJwtToken=function(){return this.jwtToken=void 0,c.call(this),this},i.prototype.getJwtToken=function(){return this.jwtToken},i.prototype.login=function(e){var t=this,r={body:{},strategy:e},i=null;if(!e||"string"!=typeof e)throw new Error("Kuzzle.login: strategy required");arguments[1]&&("object"==typeof arguments[1]?r.body=arguments[1]:"number"==typeof arguments[1]||"string"==typeof arguments[1]?r.expiresIn=arguments[1]:"function"==typeof arguments[1]&&(i=arguments[1])),arguments[2]&&("number"==typeof arguments[2]||"string"==typeof arguments[2]?r.expiresIn=arguments[2]:"function"==typeof arguments[2]&&(i=arguments[2])),arguments[3]&&"function"==typeof arguments[3]&&(i=arguments[3]),this.query({controller:"auth",action:"login"},r,{queuable:!1},function(e,r){e?(i&&i(e),t.emitEvent("loginAttempt",{success:!1,error:e.message})):(r.result.jwt&&t.setJwtToken(r.result.jwt),i&&i(null,r.result))})},i.prototype.createMyCredentials=function(e,t,r,i){return i||"function"!=typeof r||(i=r,r=null),this.query({controller:"auth",action:"createMyCredentials"},{strategy:e,body:t},r,function(e,t){e?i&&i(e):i&&i(null,t.result._source)}),this},i.prototype.deleteMyCredentials=function(e,t,r){return r||"function"!=typeof t||(r=t,t=null),this.query({controller:"auth",action:"deleteMyCredentials"},{strategy:e},t,"function"!=typeof r?null:function(e,t){e?r&&r(e):r&&r(null,t.result)}),this},i.prototype.getMyCredentials=function(e,t,r){r||"function"!=typeof t||(r=t,t=null),this.query({controller:"auth",action:"getMyCredentials"},{strategy:e},t,"function"!=typeof r?null:function(e,t){e?r&&r(e):r&&r(null,t.result)})},i.prototype.updateMyCredentials=function(e,t,r,i){return i||"function"!=typeof r||(i=r,r=null),this.query({controller:"auth",action:"updateMyCredentials"},{strategy:e,body:t},r,"function"!=typeof i?null:function(e,t){e?i&&i(e):i&&i(null,t.result)}),this},i.prototype.validateMyCredentials=function(e,t,r,i){i||"function"!=typeof r||(i=r,r=null),this.query({controller:"auth",action:"validateMyCredentials"},{strategy:e,body:t},r,"function"!=typeof i?null:function(e,t){e?i&&i(e):i&&i(null,t.result)})},i.prototype.createIndex=function(e,t,r){if(!e){if(!this.defaultIndex)throw new Error("Kuzzle.createIndex: index required");e=this.defaultIndex}return r||"function"!=typeof t||(r=t,t=null),this.query({controller:"index",action:"create",index:e},{},t,"function"!=typeof r?null:function(e,t){r(e,e?void 0:t.result)}),this},i.prototype.logout=function(e){var t=this,r={action:"logout",controller:"auth",requestId:f(),body:{}};return this.query({controller:"auth",action:"logout"},r,{queuable:!1},"function"!=typeof e?null:function(r){e(r,t)}),t.unsetJwtToken(),t},i.prototype.checkToken=function(e,t){var r={body:{token:e}};this.callbackRequired("Kuzzle.checkToken",t),this.query({controller:"auth",action:"checkToken"},r,{queuable:!1},function(e,r){t(e,e?void 0:r.result)})},i.prototype.whoAmI=function(e){var t=this;t.callbackRequired("Kuzzle.whoAmI",e),t.query({controller:"auth",action:"getCurrentUser"},{},{},function(r,i){e(r,r?void 0:new b(t.security,i.result._id,i.result._source,i.result._meta))})},i.prototype.getMyRights=function(e,t){var r=this;t||"function"!=typeof e||(t=e,e=null),r.callbackRequired("Kuzzle.getMyRights",t),r.query({controller:"auth",action:"getMyRights"},{},e,function(e,r){t(e,e?void 0:r.result.hits)})},i.prototype.updateSelf=function(e,t,r){var i=this,n={},o={controller:"auth",action:"updateSelf"};return r||"function"!=typeof t||(r=t,t=null),n.body=e,i.query(o,n,t,r&&function(e,t){r(e,e?void 0:t.result)}),this},i.prototype.addListener=function(e,t){if(this.isValid(),this.eventActions.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+this.eventActions.toString());return h.prototype.addListener.call(this,e,t)},i.prototype.getAllStatistics=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.getAllStatistics",t),this.query({controller:"server",action:"getAllStats"},{},e,function(e,r){t(e,e?void 0:r.result.hits)})},i.prototype.getStatistics=function(e,t,r){var i,n;r||(1===arguments.length?(r=arguments[0],t=null,e=null):(r=arguments[1],"object"==typeof arguments[0]?(t=arguments[0],e=null):(e=arguments[0],t=null))),i=function(t,i){return t?r(t):void r(null,e?i.result.hits:[i.result])},this.callbackRequired("Kuzzle.getStatistics",r),n=e?{body:{startTime:e}}:{},this.query({controller:"server",action:e?"getStats":"getLastStats"},n,t,i)},i.prototype.collection=function(e,t){if(this.isValid(),!t){if(!this.defaultIndex)throw new Error("Unable to create a new data collection object: no index specified");t=this.defaultIndex}if("string"!=typeof t||"string"!=typeof e)throw new Error("Invalid index or collection argument: string expected");return this.collections[t]||(this.collections[t]={}),this.collections[t][e]||(this.collections[t][e]=new p(this,e,t)),this.collections[t][e]},i.prototype.flushQueue=function(){return this.offlineQueue=[],this},i.prototype.listCollections=function(){var e,t,r,i,n=Array.prototype.slice.call(arguments);if(n.forEach(function(i){switch(typeof i){case"string":e=i;break;case"object":t=i;break;case"function":r=i}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.listCollections: index required");e=this.defaultIndex}this.callbackRequired("Kuzzle.listCollections",r),i={type:t&&t.type||"all"},this.query({index:e,controller:"collection",action:"list"},i,t,function(e,t){r(e,e?void 0:t.result.collections)})},i.prototype.listIndexes=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.listIndexes",t),this.query({controller:"index",action:"list"},{},e,function(e,r){t(e,e?void 0:r.result.indexes)})},i.prototype.disconnect=function(){var e;clearInterval(this.cleanHistoryTimer),this.state="disconnected",this.network.close(),this.network=null;for(e in this.collections)this.collections.hasOwnProperty(e)&&delete this.collections[e]},i.prototype.getServerInfo=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.getServerInfo",t),this.query({controller:"server",action:"info"},{},e,function(e,r){t(e,e?void 0:r.result.serverInfo)})},i.prototype.refreshIndex=function(){var e,t,r;if(Array.prototype.slice.call(arguments).forEach(function(i){switch(typeof i){case"string":e=i;break;case"object":t=i;break;case"function":r=i}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.refreshIndex: index required");e=this.defaultIndex}return this.query({index:e,controller:"index",action:"refresh"},{},t,r),this},i.prototype.getAutoRefresh=function(){var e,t,r;if(Array.prototype.slice.call(arguments).forEach(function(i){switch(typeof i){case"string":e=i;break;case"object":t=i;break;case"function":r=i}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.getAutoRefresh: index required");e=this.defaultIndex}this.callbackRequired("Kuzzle.getAutoRefresh",r),this.query({index:e,controller:"index",action:"getAutoRefresh"},{},t,r)},i.prototype.setAutoRefresh=function(){var e,t,r,i;if(Array.prototype.slice.call(arguments).forEach(function(n){switch(typeof n){case"string":e=n;break;case"boolean":t=n;break;case"object":r=n;break;case"function":i=n}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.setAutoRefresh: index required");e=this.defaultIndex}if(void 0===t)throw new Error("Kuzzle.setAutoRefresh: autoRefresh value is required");return this.query({index:e,controller:"index",action:"setAutoRefresh"},{body:{autoRefresh:t}},r,i),this},i.prototype.now=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.now",t),this.query({controller:"server",action:"now"},{},e,function(e,r){t(e,e?void 0:r.result.now)})},i.prototype.query=function(e,t,r,i){var o,u={action:e.action,controller:e.controller,volatile:this.volatile},l=this;if(this.isValid(),i||"function"!=typeof r||(i=r,r=null),r){if(r.queuable===!1&&"offline"===l.state)return l;r.refresh&&(u.refresh=r.refresh),"undefined"!=typeof r.from&&null!==r.from&&(u.from=r.from),r.size&&(u.size=r.size),r.scroll&&(u.scroll=r.scroll),r.scrollId&&(u.scrollId=r.scrollId),r.volatile&&Object.keys(r.volatile).forEach(function(e){u.volatile[e]=r.volatile[e]})}if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("Invalid query parameter: "+t);t.volatile&&Object.keys(t.volatile).forEach(function(e){u.volatile[e]=t.volatile[e]});for(o in t)"volatile"!==o&&t.hasOwnProperty(o)&&(u[o]=t[o]);return u=l.addHeaders(u,this.headers),void 0===l.jwtToken||"auth"===u.controller&&"checkToken"===u.action||(u.jwt=l.jwtToken),e.collection&&(u.collection=e.collection),e.index&&(u.index=e.index),u.requestId||(u.requestId=f()),u.volatile.sdkVersion=this.sdkVersion,"connected"===l.state||r&&r.queuable===!1?"connected"===l.state?s.call(this,u,i):a(u,i):l.queuing||r&&r.queuable===!0||["initializing","connecting"].indexOf(l.state)!==-1?(n.call(this,u,i),!l.queueFilter||l.queueFilter(u)?(l.offlineQueue.push({ts:Date.now(),query:u,cb:i}),l.emitEvent("offlineQueuePush",{query:u,cb:i})):a(u,i)):a(u,i),l},i.prototype.replayQueue=function(){return"offline"===this.state||this.autoReplay||(n.call(this),u.call(this)),this},i.prototype.setDefaultIndex=function(e){if("string"!=typeof e)throw new Error("Invalid default index: ["+e+"] (an index name is expected)");if(0===e.length)throw new Error("Cannot set an empty index as the default index");return this.defaultIndex=e,this},i.prototype.setHeaders=function(e,t){var r=this;if("object"!=typeof e||Array.isArray(e))throw new Error("Expected a content object, received a "+typeof e);return t?r.headers=e:Object.keys(e).forEach(function(t){r.headers[t]=e[t]}),r},i.prototype.startQueuing=function(){return"offline"!==this.state||this.autoQueue||(this.queuing=!0),this},i.prototype.stopQueuing=function(){return"offline"!==this.state||this.autoQueue||(this.queuing=!1),this},e.exports=i},function(e,t){function r(e,t,r,i){if(!t)throw new Error("A security document must have an id");if(Object.defineProperties(this,{kuzzle:{value:e.kuzzle},Security:{value:e},id:{value:t,enumerable:!0},content:{value:{},writable:!0,enumerable:!0},meta:{value:i||{},writable:!0,enumerable:!0}}),r&&this.setContent(r,!0),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,i){var n=["delete","update"];return i&&n.indexOf(e)!==-1}})}r.prototype.setContent=function(e){return this.content=e,this},r.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e.meta=this.meta,e},r.prototype.delete=function(e,t){var r=this;e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r.kuzzle.query(this.Security.buildQueryArgs(this.deleteActionName),{_id:this.id},e,function(e,r){return e?!!t&&t(e):void(t&&t(null,r.result._id))})},r.prototype.update=function(e,t,r){var i={},n=this;if("object"!=typeof e)throw new Error('Parameter "content" must be a object');return t&&void 0===r&&"function"==typeof t&&(r=t,t=null),i._id=n.id,i.body=e,n.kuzzle.query(this.Security.buildQueryArgs(this.updateActionName),i,t,function(e,t){return e?!!r&&r(e):(n.setContent(t.result._source),void(r&&r(null,n)))}),this},e.exports=r},function(e,t){function r(e,t,r,i){return Object.defineProperties(this,{collection:{value:e.collection,enumerable:!0},dataCollection:{value:e,enumerable:!1},kuzzle:{value:e.kuzzle,enumerable:!1},id:{value:void 0,enumerable:!0,writable:!0},content:{value:{},writable:!0,enumerable:!0},headers:{value:JSON.parse(JSON.stringify(e.headers)),enumerable:!0,writable:!0},version:{value:void 0,enumerable:!0,writable:!0},meta:{value:i||{},enumerable:!0,writable:!1}}),!r&&t&&"object"==typeof t&&(r=t,t=null),r&&(r._version&&(this.version=r._version,delete r._version),this.setContent(r,!0)),t&&Object.defineProperty(this,"id",{value:t,enumerable:!0}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,i){var n=["delete","refresh","save"];return i&&n.indexOf(e)!==-1}}):this}r.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),this.version&&(e._version=this.version),e.body=this.content,e.meta=this.meta,e=this.kuzzle.addHeaders(e,this.headers)},r.prototype.toString=function(){return JSON.stringify(this.serialize())},r.prototype.delete=function(e,t){var r=this;if(t||"function"!=typeof e||(t=e,e=null),!r.id)throw new Error("Document.delete: cannot delete a document without a document ID");this.kuzzle.query(this.dataCollection.buildQueryArgs("document","delete"),this.serialize(),e,t&&function(e){t(e,e?void 0:r.id)})},r.prototype.exists=function(e,t){var r=this;if(t||"function"!=typeof e||(t=e,e=null),!r.id)throw new Error("Document.exists: cannot check if the document exists if no id has been provided");this.kuzzle.query(this.dataCollection.buildQueryArgs("document","exists"),this.serialize(),e,t&&function(e,r){t(e,e?void 0:r.result)})},r.prototype.refresh=function(e,t){var i=this;if(t||"function"!=typeof e||(t=e,e=null),!i.id)throw new Error("Document.refresh: cannot retrieve a document if no ID has been provided");this.kuzzle.callbackRequired("Document.refresh",t),i.kuzzle.query(i.dataCollection.buildQueryArgs("document","get"),{_id:i.id},e,function(e,n){var o;return e?t(e):(o=new r(i.dataCollection,i.id,n.result._source,n.result._meta),o.version=n.result._version,void t(null,o))})},r.prototype.save=function(e,t){var r=this.serialize(),i=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),i.kuzzle.query(this.dataCollection.buildQueryArgs("document","createOrReplace"),r,e,function(e,r){return e?t&&t(e):(i.id=r.result._id,i.version=r.result._version,void(t&&t(null,i)))}),i},r.prototype.publish=function(e){var t=this.serialize();return this.kuzzle.query(this.dataCollection.buildQueryArgs("realtime","publish"),t,e),this},r.prototype.setContent=function(e,t){var r=this;return t?this.content=e:Object.keys(e).forEach(function(t){r.content[t]=e[t]}),this},r.prototype.subscribe=function(e,t){var r;if(e&&!t&&"function"==typeof e&&(t=e,e=null),this.kuzzle.callbackRequired("Document.subscribe",t),!this.id)throw new Error("Document.subscribe: cannot subscribe to a document if no ID has been provided");return r={ids:{values:[this.id]}},this.dataCollection.subscribe(r,e,t)},r.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=r},function(e,t,r){function i(){"undefined"!=typeof window&&(this._events={},this._onceEvents={})}"undefined"==typeof window?(i.prototype=r(18).prototype,i.prototype.constructor=i):(i.prototype.on=function(e,t){var r,i=typeof t;if(e&&t){if("function"!==i)throw new Error("Invalid listener type: expected a function, got a "+i);return r=this.listeners(e),r.indexOf(t)===-1&&r.push(t),this.emit("newListener",e,t),this}},i.prototype.addListener=i.prototype.on,i.prototype.prependListener=function(e,t){var r;if(e&&t)return r=this.listeners(e),r.indexOf(t)===-1&&(this._events[e]=new Array(t).concat(r)),this.emit("newListener",e,t),this},i.prototype.once=function(e,t){var r;if(e&&t)return this.on(e,t),r=this._onceEvents[e]=this._onceEvents[e]||{},r[t]=!0,this},i.prototype.prependOnceListener=function(e,t){var r;if(e&&t)return this.prependListener(e,t),r=this._onceEvents[e]=this._onceEvents[e]||{},r[t]=!0,this},i.prototype.removeListener=function(e,t){var r,i=this._events[e];if(i&&i.length)return r=i.indexOf(t),r!==-1&&i.splice(r,1),0===i.length&&delete this._events[e],this.emit("removeListener",e,t),this},i.prototype.removeAllListeners=function(e){return e?(delete this._events[e],delete this._onceEvents[e]):(this._events=[],this._onceEvents=[]),this},i.prototype.emit=function(e){var t,r,i,n,o=0;if(t=this._events&&this._events[e],t&&t.length){for(r=Array.prototype.slice.call(arguments,1),i=this._onceEvents&&this._onceEvents[e]||{},n=new Array,listener=t[o];listener;)n.push(listener),i[listener]?(this.removeListener(e,listener),delete i[listener]):o++,listener=t[o];for(item in n)void 0!==n[item]&&n[item].apply(this,r);return this}},i.prototype.eventNames=function(){return Object.keys(this._events)},i.prototype.listenerCount=function(e){return this._events[e]&&this._events[e].length||0},i.prototype.listeners=function(e){return void 0===this._events[e]&&(this._events[e]=[]),this._events[e]}),i.prototype.emitEvent=i.prototype.emit,i.prototype.off=i.prototype.removeListener,e.exports=i},function(e,t,r){function i(e,t,i){var s=this;o.call(this),this.WebSocket="undefined"!=typeof WebSocket?WebSocket:r(!function(){var e=new Error('Cannot find module "ws"');throw e.code="MODULE_NOT_FOUND",e}()),this.host=e,this.port=t,this.ssl=i,this.client=null,this.wasConnected=!1,this.retrying=!1,this.lasturl=null,this.stopRetryingToConnect=!1,this.connect=function(e,t){var r=(this.ssl?"wss://":"ws://")+this.host+":"+this.port,i="undefined"!=typeof window?void 0:{perMessageDeflate:!1};r!==this.lasturl&&(s.wasConnected=!1,this.lasturl=r),this.client=new this.WebSocket(r,i),this.client.onopen=function(){s.wasConnected?s.emitEvent("reconnect"):s.emitEvent("connect"),s.wasConnected=!0,s.stopRetryingToConnect=!1},this.client.onclose=function(r,i){var o,u,l=i;"number"==typeof r?u=r:(u=r.code,r.reason&&(l=r.reason)),1e3===u?s.emitEvent("disconnect"):(o=new Error(l),o.status=u,n(s,e,t,o))},this.client.onerror=function(r){r instanceof Error||(r=new Error(r)),n(s,e,t,r)},this.client.onmessage=function(e){var t=JSON.parse(e.data||e);t.room?s.emitEvent(t.room,t):s.emitEvent("discarded",t)}},this.onConnect=function(e){this.addListener("connect",e)},this.onConnectError=function(e){this.addListener("networkError",e)},this.onDisconnect=function(e){this.addListener("disconnect",e)},this.onReconnect=function(e){this.addListener("reconnect",e)},this.send=function(e){this.client&&this.client.readyState===this.client.OPEN&&this.client.send(JSON.stringify(e))},this.close=function(){this.removeAllListeners(),this.wasConnected=!1,this.client.close(),this.client=null,s.stopRetryingToConnect=!0}}function n(e,t,r,i){!t||e.retrying||e.stopRetryingToConnect||(e.retrying=!0,setTimeout(function(){e.retrying=!1,e.connect(t,r)},r)),e.emitEvent("networkError",i)}var o=r(3);i.prototype=Object.create(o.prototype),i.prototype.constructor=i,e.exports=i},function(e,t,r){function i(e,t,r,i){if(n.call(this,e,t,r,i),Object.defineProperties(this,{deleteActionName:{value:"deleteUser"},updateActionName:{value:"updateUser"},credentials:{value:{},writable:!0,enumerable:!0}}),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,i){var n=["create","replace","saveRestricted","update","getProfiles"];return i&&n.indexOf(e)!==-1}})}var n=r(1);i.prototype=Object.create(n.prototype,{constructor:{value:i}}),i.prototype.setProfiles=function(e){if(!Array.isArray(e)||"string"!=typeof e[0])throw new Error('Parameter "profileIds" must be an array of strings');return this.content.profileIds=e,this},i.prototype.setCredentials=function(e){if("object"!=typeof e)throw new Error('Parameter "credentials" must be a object');return this.credentials=e,this},i.prototype.addProfile=function(e){if("string"!=typeof e)throw new Error('Parameter "profileId" must be a string');return this.content.profileIds||(this.content.profileIds=[]),this.content.profileIds.indexOf(e)===-1&&this.content.profileIds.push(e),this},i.prototype.create=function(e,t){var r=this.creationSerialize(),i=this;if(!this.content.profileIds)throw new Error('Argument "profileIds" is mandatory in a user. This argument contains an array of profile identifiers.');return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),this.kuzzle.query(this.Security.buildQueryArgs("createUser"),r,null,t&&function(e){t(e,e?void 0:i)}),this},i.prototype.replace=function(e,t){var r=this.serialize(),i=this;if(!this.content.profileIds)throw new Error('Argument "profileIds" is mandatory in a user. This argument contains an array of profile identifiers.');return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),this.kuzzle.query(this.Security.buildQueryArgs("replaceUser"),r,null,t&&function(e){t(e,e?void 0:i)}),this},i.prototype.saveRestricted=function(e,t){var r=this.serialize(),i=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),i.kuzzle.query(this.Security.buildQueryArgs("createRestrictedUser"),r,e,t&&function(e){t(e,e?void 0:i)}),i},i.prototype.serialize=function(){return{_id:this.id,body:this.content,meta:this.meta}},i.prototype.creationSerialize=function(){return{_id:this.id,body:{content:this.content,credentials:this.credentials,meta:this.meta}}},i.prototype.getProfileIds=function(){return this.content.profileIds||[]},i.prototype.getProfiles=function(e,t){var r=this,i=[],n=!1;return e&&!t&&"function"==typeof e&&(t=e,e=null),r.Security.kuzzle.callbackRequired("User.getProfiles",t),r.content.profileIds?void r.content.profileIds.forEach(function(o){r.Security.fetchProfile(o,e,function(e,o){if(e){if(n)return;return n=!0,t(e)}i.push(o),i.length===r.content.profileIds.length&&t(null,i)})}):t(null,i)},e.exports=i},function(e,t,r){function i(e,t,r){var i=t&&r||0;"string"==typeof e&&(t="binary"==e?new Array(16):null,e=null),e=e||{};var s=e.random||(e.rng||n)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var u=0;u<16;++u)t[i+u]=s[u];return t||o(s)}var n=r(20),o=r(19);e.exports=i},function(e,t,r){function i(e,t,r){if(!r||!t)throw new Error("The Collection object constructor needs an index and a collection arguments");return Object.defineProperties(this,{collection:{value:t,enumerable:!0},index:{value:r,enumerable:!0},kuzzle:{value:e,enumerable:!0},headers:{value:JSON.parse(JSON.stringify(e.headers)),enumerable:!0,writable:!0}}),Object.defineProperty(this,"buildQueryArgs",{value:function(e,t){return{controller:e,action:t,collection:this.collection,index:this.index}}}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,i){var n=["publishMessage","setHeaders","subscribe"];return i&&n.indexOf(e)===-1}}):this}var n=r(11),o=r(2),s=r(8),u=r(10),l=r(12);i.prototype.count=function(e,t,r){var i;r||"function"!=typeof t||(r=t,t=null),this.kuzzle.callbackRequired("Collection.count",r),i=this.kuzzle.addHeaders({body:e},this.headers),this.kuzzle.query(this.buildQueryArgs("document","count"),i,t,function(e,t){r(e,e?void 0:t.result.count)})},i.prototype.create=function(e,t){var r={},i=this;return t||"function"!=typeof e||(t=e,e=null),r=this.kuzzle.addHeaders(r,this.headers),this.kuzzle.query(this.buildQueryArgs("collection","create"),r,e,function(e){t(e,e?void 0:i)}),this},i.prototype.createDocument=function(e,t,r,i){var n=this,s={},u="create";if(e&&"string"!=typeof e&&(i=r,r=t,t=e,e=null),i||"function"!=typeof r||(i=r,r=null),t instanceof o?s=t.serialize():s.body=t,r&&r.ifExist)if("replace"===r.ifExist)u="createOrReplace";else if("error"!==r.ifExist)throw new Error('Invalid value for the "ifExist" option: '+r.ifExist);return e&&(s._id=e),s=n.kuzzle.addHeaders(s,n.headers),n.kuzzle.query(this.buildQueryArgs("document",u),s,r,i&&function(e,t){var r;return e?i(e):(r=new o(n,t.result._id,t.result._source,t.result._meta),r.version=t.result._version,void i(null,r))}),this},i.prototype.deleteDocument=function(e,t,r){var i,n={};return"string"==typeof e?(n._id=e,i="delete"):(n.body={query:e},i="deleteByQuery"),r||"function"!=typeof t||(r=t,t=null),n=this.kuzzle.addHeaders(n,this.headers),this.kuzzle.query(this.buildQueryArgs("document",i),n,t,r&&function(e,t){e?r(e):r(null,"delete"===i?[t.result._id]:t.result.ids)}),this},i.prototype.deleteSpecifications=function(e,t){var r={index:this.index,collection:this.collection -},i=this;return t||"function"!=typeof e||(t=e,e=null),r=i.kuzzle.addHeaders(r,this.headers),i.kuzzle.query(this.buildQueryArgs("collection","deleteSpecifications"),r,e,function(e,r){t(e,e?void 0:r.result)}),i},i.prototype.documentExists=function(e,t,r){var i={_id:e},n=this;r||"function"!=typeof t||(r=t,t=null),n.kuzzle.callbackRequired("Collection.documentExists",r),n.kuzzle.query(this.buildQueryArgs("document","exists"),i,t,function(e,t){r(e,e?void 0:t.result)})},i.prototype.fetchDocument=function(e,t,r){var i={_id:e},n=this;r||"function"!=typeof t||(r=t,t=null),n.kuzzle.callbackRequired("Collection.fetch",r),i=n.kuzzle.addHeaders(i,this.headers),n.kuzzle.query(this.buildQueryArgs("document","get"),i,t,function(e,t){var i;return e?r(e):(i=new o(n,t.result._id,t.result._source,t.result._meta),i.version=t.result._version,void r(null,i))})},i.prototype.getMapping=function(e,t){var r;t||"function"!=typeof e||(t=e,e=null),this.kuzzle.callbackRequired("Collection.getMapping",t),r=new s(this),r.refresh(e,t)},i.prototype.mCreateDocument=function(e,t,r){var i={body:{}},n=this;return r||"function"!=typeof t||(r=t,t=null),Array.isArray(e)?(n.kuzzle.callbackRequired("Collection.mCreate",r),i.body.documents=e.map(function(e){return e instanceof o?e.serialize():e}),i=n.kuzzle.addHeaders(i,this.headers),n.kuzzle.query(this.buildQueryArgs("document","mCreate"),i,t,r&&function(e,t){r(e,e?void 0:t.result)}),n):r(new Error("Collection.mCreateDocument: documents parameter format is invalid (should be an array of documents)"))},i.prototype.mCreateOrReplaceDocument=function(e,t,r){var i={body:{}},n=this;return r||"function"!=typeof t||(r=t,t=null),Array.isArray(e)?(n.kuzzle.callbackRequired("Collection.mCreateOrReplace",r),i.body.documents=e.map(function(e){return e instanceof o?e.serialize():e}),i=n.kuzzle.addHeaders(i,this.headers),n.kuzzle.query(this.buildQueryArgs("document","mCreateOrReplace"),i,t,r&&function(e,t){r(e,e?void 0:t.result)}),n):r(new Error("Collection.mCreateOrReplaceDocument: documents parameter format is invalid (should be an array of documents)"))},i.prototype.mDeleteDocument=function(e,t,r){var i={body:{ids:e}},n=this;return r||"function"!=typeof t||(r=t,t=null),Array.isArray(e)?(n.kuzzle.callbackRequired("Collection.mDelete",r),i=n.kuzzle.addHeaders(i,this.headers),n.kuzzle.query(this.buildQueryArgs("document","mDelete"),i,t,r&&function(e,t){r(e,e?void 0:t.result)}),n):r(new Error("Collection.mDeleteDocument: documentIds parameter format is invalid (should be an array of IDs)"))},i.prototype.mGetDocument=function(e,t,r){var i={body:{ids:e}},n=this;return r||"function"!=typeof t||(r=t,t=null),Array.isArray(e)?(n.kuzzle.callbackRequired("Collection.mGet",r),i=n.kuzzle.addHeaders(i,this.headers),void n.kuzzle.query(this.buildQueryArgs("document","mGet"),i,t,r&&function(e,t){r(e,e?void 0:t.result)})):r(new Error("Collection.mGetDocument: documentIds parameter format is invalid (should be an array of IDs)"))},i.prototype.mReplaceDocument=function(e,t,r){var i={body:{}},n=this;return r||"function"!=typeof t||(r=t,t=null),Array.isArray(e)?(n.kuzzle.callbackRequired("Collection.mReplace",r),i.body.documents=e.map(function(e){return e instanceof o?e.serialize():e}),i=n.kuzzle.addHeaders(i,this.headers),n.kuzzle.query(this.buildQueryArgs("document","mReplace"),i,t,r&&function(e,t){r(e,e?void 0:t.result)}),n):r(new Error("Collection.mReplaceDocument: documents parameter format is invalid (should be an array of documents)"))},i.prototype.mUpdateDocument=function(e,t,r){var i={body:{}},n=this;return r||"function"!=typeof t||(r=t,t=null),Array.isArray(e)?(n.kuzzle.callbackRequired("Collection.mUpdate",r),i.body.documents=e.map(function(e){return e instanceof o?e.serialize():e}),i=n.kuzzle.addHeaders(i,this.headers),n.kuzzle.query(this.buildQueryArgs("document","mUpdate"),i,t,r&&function(e,t){r(e,e?void 0:t.result)}),n):r(new Error("Collection.mUpdateDocument: documents parameter format is invalid (should be an array of documents)"))},i.prototype.getSpecifications=function(e,t){var r={index:this.index,collection:this.collection},i=this;t||"function"!=typeof e||(t=e,e=null),i.kuzzle.callbackRequired("Collection.getSpecifications",t),r=i.kuzzle.addHeaders(r,this.headers),i.kuzzle.query(this.buildQueryArgs("collection","getSpecifications"),r,e,function(e,r){t(e,e?void 0:r.result)})},i.prototype.publishMessage=function(e,t,r){var i={};return e instanceof o?i=e.serialize():i.body=e,i=this.kuzzle.addHeaders(i,this.headers),this.kuzzle.query(this.buildQueryArgs("realtime","publish"),i,t,r),this},i.prototype.replaceDocument=function(e,t,r,i){var n=this,s={_id:e,body:t};return i||"function"!=typeof r||(i=r,r=null),s=n.kuzzle.addHeaders(s,this.headers),n.kuzzle.query(this.buildQueryArgs("document","createOrReplace"),s,r,i&&function(e,t){var r;return e?i(e):(r=new o(n,t.result._id,t.result._source,t.result._meta),r.version=t.result._version,void i(null,r))}),this},i.prototype.search=function(e,t,r){var i,s=this;r||"function"!=typeof t||(r=t,t={}),s.kuzzle.callbackRequired("Collection.search",r),i=s.kuzzle.addHeaders({body:e},this.headers),s.kuzzle.query(this.buildQueryArgs("document","search"),i,t,function(i,u){var l=[];return i?r(i):(u.result.hits.forEach(function(e){var t=new o(s,e._id,e._source,e._meta);t.version=e._version,l.push(t)}),u.result._scroll_id&&(t.scrollId=u.result._scroll_id),void r(null,new n(s,u.result.total,l,u.result.aggregations?u.result.aggregations:{},t,e,t.previous||null)))})},i.prototype.scroll=function(e,t,r,i){var s={},u=this;if(!e)throw new Error("Collection.scroll: scrollId is required");return i||(i=r,r=null),i||"function"!=typeof t||(i=t,t={}),this.kuzzle.callbackRequired("Collection.scroll",i),s.scrollId=e,t&&t.scroll&&(s.scroll=t.scroll),this.kuzzle.query({controller:"document",action:"scroll"},s,t,function(e,s){var l=[];return e?i(e):(s.result.hits.forEach(function(e){var t=new o(u,e._id,e._source,e._meta);t.version=e._version,l.push(t)}),s.result._scroll_id&&(t.scrollId=s.result._scroll_id),void i(null,new n(u,s.result.total,l,{},t,r,t.previous||null)))}),this},i.prototype.scrollSpecifications=function(e,t,r){var i={scrollId:e};if(!e)throw new Error("Collection.scrollSpecifications: scrollId is required");r||"function"!=typeof t||(r=t,t={}),this.kuzzle.callbackRequired("Collection.scrollSpecifications",r),t&&t.scroll&&(i.scroll=t.scroll),this.kuzzle.query({controller:"collection",action:"scrollSpecifications"},this.kuzzle.addHeaders(i,this.headers),t,function(e,t){r(e,e?void 0:t.result)})},i.prototype.searchSpecifications=function(e,t,r){var i={body:{query:e}},n=this;r||"function"!=typeof t||(r=t,t={}),n.kuzzle.callbackRequired("Collection.searchSpecifications",r),i=n.kuzzle.addHeaders(i,this.headers),n.kuzzle.query({controller:"collection",action:"searchSpecifications"},i,t,function(e,t){r(e,e?void 0:t.result)})},i.prototype.subscribe=function(e,t,r){var i,n;return r||"function"!=typeof t||(r=t,t=null),this.kuzzle.callbackRequired("Collection.subscribe",r),n=new l,i=new u(this,t),i.renew(e,r,n.done.bind(n)),n},i.prototype.truncate=function(e,t){var r={};return t||"function"!=typeof e||(t=e,e=null),r=this.kuzzle.addHeaders(r,this.headers),this.kuzzle.query(this.buildQueryArgs("collection","truncate"),r,e,t),this},i.prototype.updateDocument=function(e,t,r,i){var n={_id:e,body:t},s=this;return i||"function"!=typeof r||(i=r,r=null),r&&r.retryOnConflict&&(n.retryOnConflict=r.retryOnConflict),n=s.kuzzle.addHeaders(n,this.headers),s.kuzzle.query(this.buildQueryArgs("document","update"),n,r,i&&function(e,t){return e?i(e):void new o(s,t.result._id).refresh(i)}),s},i.prototype.updateSpecifications=function(e,t,r){var i={},n={body:{}},o=this;return i[this.collection]=e,n.body[this.index]=i,r||"function"!=typeof t||(r=t,t=null),n=o.kuzzle.addHeaders(n,this.headers),o.kuzzle.query(this.buildQueryArgs("collection","updateSpecifications"),n,t,r&&function(e,t){r(e,e?void 0:t.result)}),o},i.prototype.validateSpecifications=function(e,t,r){var i={},n={body:{}},o=this;i[this.collection]=e,n.body[this.index]=i,r||"function"!=typeof t||(r=t,t=null),o.kuzzle.callbackRequired("Collection.validateSpecifications",r),n=o.kuzzle.addHeaders(n,this.headers),o.kuzzle.query(this.buildQueryArgs("collection","validateSpecifications"),n,t,function(e,t){r(e,e?void 0:t.result.valid)})},i.prototype.document=function(e,t){return new o(this,e,t)},i.prototype.room=function(e){return new u(this,e)},i.prototype.collectionMapping=function(e){return new s(this,e)},i.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=i},function(e,t){function r(e,t){return Object.defineProperties(this,{collection:{value:e,enumerable:!0},kuzzle:{value:e.kuzzle,enumerable:!0},headers:{value:JSON.parse(JSON.stringify(e.headers)),enumerable:!0,writable:!0},mapping:{value:t||{},enumerable:!0,writable:!0}}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,i){var n=["set","setHeaders"];return i&&n.indexOf(e)===-1}}):this}r.prototype.apply=function(e,t){var r=this,i=this.kuzzle.addHeaders({body:{properties:this.mapping}},this.headers);return t||"function"!=typeof e||(t=e,e=null),r.kuzzle.query(this.collection.buildQueryArgs("collection","updateMapping"),i,e,function(i){return i?t&&t(i):void r.refresh(e,t)}),this},r.prototype.refresh=function(e,t){var r=this,i=this.kuzzle.addHeaders({},this.headers);return t||"function"!=typeof e||(t=e,e=null),this.kuzzle.query(this.collection.buildQueryArgs("collection","getMapping"),i,e,function(e,i){return e?!!t&&t(e):i.result[r.collection.index]?i.result[r.collection.index].mappings[r.collection.collection]?(r.mapping=i.result[r.collection.index].mappings[r.collection.collection].properties,void 0===r.mapping&&(r.mapping={}),void(t&&t(null,r))):t&&t(new Error("No mapping found for collection "+r.collection.collection)):t&&t(new Error("No mapping found for index "+r.collection.index))}),this},r.prototype.set=function(e,t){return this.mapping[e]=t,this},r.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=r},function(e,t){function r(e){return Object.defineProperties(this,{kuzzle:{value:e,enumerable:!0},headers:{value:JSON.parse(JSON.stringify(e.headers)),enumerable:!0,writable:!0}}),this.setHeaders=e.setHeaders.bind(this),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,i){var n=["setHeaders"];return i&&n.indexOf(e)===-1}}):this}function i(e,t,r,i){t||"_id"===r?e[r]=i:e.body[r]=i}function n(e,t){var r=[];Object.keys(t).filter(function(e){return t[e]&&["withcoord","withdist","count","sort"].indexOf(e)!==-1}).forEach(function(e){"withcoord"===e||"withdist"===e?(r.push(e),delete t[e]):"count"!==e&&"sort"!==e||("count"===e&&r.push("count"),r.push(t[e])),delete t[e]}),r.length>0&&(e.options=r)}function o(e,t){e.options=["withscores"],t.limit&&(e.limit=t.limit,delete t.limit)}function s(e){return e.map(function(e){return e.map(function(e){return parseFloat(e)})})}function u(e){return Array.isArray(e[0])?e.map(function(e){var t,r={name:e[0]};for(t=1;t1)throw new Error("MemoryStorage."+e+": Too many parameters provided");if(1===r.length&&"object"!=typeof r[0]||Array.isArray(r[0]))throw new Error("MemoryStorage."+e+": Invalid optional parameter (expected an object)");if(r.length&&(n=Object.assign({},r[0]),Array.isArray(q[e].opts)&&q[e].opts.forEach(function(t){null!==n[t]&&void 0!==n[t]&&(i(s,q[e].getter,t,n[t]),delete n[t])})),"function"==typeof q[e].opts&&q[e].opts(s,n||{}),this.kuzzle.query(o,s,n,t&&function(r,i){return r?t(r):q[e].mapResults?t(null,q[e].mapResults(i.result)):void t(null,i.result)}),!q[e].getter)return this}})}(),e.exports=r},function(e,t,r){function i(e,t){return Object.defineProperties(this,{callback:{value:null,writable:!0},channel:{value:null,writable:!0},id:{value:u()},lastRenewal:{value:null,writable:!0},notifier:{value:null,writable:!0},onDoneCB:{value:null,writable:!0},queue:{value:[],writable:!0},renewalDelay:{value:500},scope:{value:t&&t.scope?t.scope:"all"},state:{value:t&&t.state?t.state:"done"},subscribing:{value:!1,writable:!0},users:{value:t&&t.users?t.users:"none"},collection:{value:e,enumerable:!0},kuzzle:{value:e.kuzzle,enumerable:!0},filters:{value:null,enumerable:!0,writable:!0},headers:{value:JSON.parse(JSON.stringify(e.headers)),enumerable:!0,writable:!0},volatile:{value:t&&t.volatile?t.volatile:{},enumerable:!0,writable:!0},roomId:{value:null,enumerable:!0,writable:!0},subscribeToSelf:{value:!t||"boolean"!=typeof t.subscribeToSelf||t.subscribeToSelf,enumerable:!0,writable:!0}}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,i){var n=["count"];return i&&n.indexOf(e)!==-1}}):this}function n(e){return"TokenExpired"===e.type?(this.kuzzle.jwtToken=void 0,this.kuzzle.emitEvent("tokenExpired")):("document"===e.type&&(e.document=new l(this.collection,e.result._id,e.result._source,e.result._meta),delete e.result),void(this.kuzzle.requestHistory[e.requestId]?(this.subscribeToSelf&&this.callback(null,e),delete this.kuzzle.requestHistory[e.requestId]):this.callback(null,e)))}function o(){for(var e;this.queue.length>0;)e=this.queue.shift(),this[e.action].apply(this,e.args)}function s(){return"connected"===this.kuzzle.state&&!this.subscribing}var u=r(6),l=r(2);i.prototype.count=function(e){var t;if(this.kuzzle.callbackRequired("Room.count",e),t=this.kuzzle.addHeaders({body:{roomId:this.roomId}},this.headers),!s.call(this))return void this.queue.push({action:"count",args:[e]});if(!this.roomId)throw new Error("Room.count: cannot count subscriptions on an inactive room");this.kuzzle.query(this.collection.buildQueryArgs("realtime","count"),t,function(t,r){e(t,r&&r.result.count)})},i.prototype.renew=function(e,t,r){var i=this,s=Date.now(),u={scope:i.scope,state:i.state,users:i.users};return"function"==typeof e&&(r=t,t=e,e=null),r||(r=i.onDoneCB),i.kuzzle.callbackRequired("Room.renew",t),i.lastRenewal&&s-i.lastRenewal<=i.renewalDelay?r&&r(new Error("Subscription already renewed less than "+i.renewalDelay+"ms ago")):(e&&(i.filters=e),"connected"!==i.kuzzle.state?(i.callback=t,i.onDoneCB=r,void(i.kuzzle.subscriptions.pending[i.id]=i)):i.subscribing?void i.queue.push({action:"renew",args:[e,t,r]}):(i.unsubscribe(),i.roomId=null,i.subscribing=!0,i.callback=t,i.onDoneCB=r,i.kuzzle.subscriptions.pending[i.id]=i,u.body=i.filters,u=i.kuzzle.addHeaders(u,i.headers),void i.kuzzle.query(i.collection.buildQueryArgs("realtime","subscribe"),u,{volatile:i.volatile},function(e,t){return delete i.kuzzle.subscriptions.pending[i.id],i.subscribing=!1,e?(i.queue=[],r&&r(new Error("Error during Kuzzle subscription: "+e.message))):(i.lastRenewal=s,i.roomId=t.result.roomId,i.channel=t.result.channel,i.kuzzle.subscriptions[i.roomId]||(i.kuzzle.subscriptions[i.roomId]={}),i.kuzzle.subscriptions[i.roomId][i.id]=i,i.notifier=n.bind(i),i.kuzzle.network.on(i.channel,i.notifier),o.call(i),void(r&&r(null,i)))})))},i.prototype.unsubscribe=function(){var e,t=this,r=t.roomId;return s.call(this)?(r&&(t.kuzzle.network.off(t.channel,this.notifier),1===Object.keys(t.kuzzle.subscriptions[r]).length?(delete t.kuzzle.subscriptions[r],0===Object.keys(t.kuzzle.subscriptions.pending).length?t.kuzzle.query(t.collection.buildQueryArgs("realtime","unsubscribe"),{body:{roomId:r}}):e=setInterval(function(){0===Object.keys(t.kuzzle.subscriptions.pending).length&&(t.kuzzle.subscriptions[r]||t.kuzzle.query(t.collection.buildQueryArgs("realtime","unsubscribe"),{body:{roomId:r}}),clearInterval(e))},100)):delete t.kuzzle.subscriptions[r][t.id],t.roomId=null),t):(t.queue.push({action:"unsubscribe",args:[]}),t)},i.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=i},function(e,t){function r(e,t,i,n,o,s,u){return Object.defineProperties(this,{collection:{value:e,enumerable:!0},total:{value:t,enumerable:!0},documents:{value:i,enumerable:!0},aggregations:{value:n||{},enumerable:!0},options:{value:o||{},enumerable:!0},filters:{value:s||{},enumerable:!0},fetchedDocument:{value:u instanceof r?i.length+u.fetchedDocument:i.length,enumerable:!0,writable:!0}}),this.collection.kuzzle.bluebird?this.collection.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,i){var n=["fetchNext"];return i&&n.indexOf(e)!==-1}}):this}r.prototype.fetchNext=function(e){var t,r=Object.assign({},this.options),i=this;return r.previous=this,r.scrollId?this.fetchedDocument>=this.getTotal()?void e(null,null):("undefined"!=typeof r.from&&delete r.from,r.size&&delete r.size,void this.collection.scroll(r.scrollId,r,this.filters||{},e)):r.size&&this.filters.sort?this.fetchedDocument>=this.getTotal()?void e(null,null):(r.from&&delete r.from,t=Object.assign(this.filters,{search_after:[]}),t.sort.forEach(function(e){t.search_after.push(i.documents[i.documents.length-1].content[Object.keys(e)[0]])}),void this.collection.search(t,r,e)):void 0!==r.from&&void 0!==r.size?(t=Object.assign({},this.filters),r.from+=r.size,r.from>=this.getTotal()?void e(null,null):void this.collection.search(t,r,e)):void e(new Error("Unable to retrieve next results from search: missing scrollId or from/size params"))},r.prototype.getDocuments=function(){return this.documents},r.prototype.getTotal=function(){return this.total},r.prototype.getAggregations=function(){return this.aggregations},r.prototype.getOptions=function(){return this.options},r.prototype.getFilters=function(){return this.filters},r.prototype.getCollection=function(){return this.collection},r.prototype.getFetchedDocument=function(){return this.fetchedDocument},e.exports=r},function(e,t){function r(){this.cbs=[],this.error=null,this.room=null}r.prototype.onDone=function(e){return this.error||this.room?e(this.error,this.room):this.cbs.push(e),this},r.prototype.done=function(e,t){this.error=e,this.room=t,this.cbs.forEach(function(r){r(e,t)})},e.exports=r},function(e,t,r){function i(e,t,i){if("undefined"!=typeof window){if("undefined"!=typeof WebSocket)return new(r(4))(e,t,i);if(window.io)return new(r(14))(e,t,i);throw new Error("Aborting: no websocket support detected and no socket.io library loaded either.")}return new(r(4))(e,t,i)}e.exports=i},function(e,t){function r(e,t,r){this.host=e,this.port=t,this.ssl=r,this.socket=null,this.wasConnected=!1,this.forceDisconnect=!1,this.handlers={connect:[],reconnect:[],connectError:[],disconnect:[]},this.retrying=!1,this.connect=function(e,t){var r=this;this.socket=window.io((this.ssl?"https://":"http://")+this.host+":"+this.port,{reconnection:e,reconnectionDelay:t,forceNew:!0}),this.socket.on("connect",function(){r.wasConnected?r.handlers.reconnect.forEach(function(e){e()}):r.handlers.connect.forEach(function(e){e()}),r.wasConnected=!0}),this.socket.on("connect_error",function(n){i(r,e,t,n)}),this.socket.on("disconnect",function(){var n;r.forceDisconnect?r.handlers.disconnect.forEach(function(e){e()}):(n=new Error("An error occurred, this may due that kuzzle was not ready yet"),n.status=500,i(r,e,t,n)),r.forceDisconnect=!1})},this.onConnect=function(e){this.handlers.connect.indexOf(e)===-1&&this.handlers.connect.push(e)},this.onConnectError=function(e){this.handlers.connectError.indexOf(e)===-1&&this.handlers.connectError.push(e)},this.onDisconnect=function(e){this.handlers.disconnect.indexOf(e)===-1&&this.handlers.disconnect.push(e)},this.onReconnect=function(e){this.handlers.reconnect.indexOf(e)===-1&&this.handlers.reconnect.push(e)},this.once=function(e,t){this.socket.once(e,t)},this.on=function(e,t){this.socket.on(e,t)},this.off=function(e,t){this.socket.off(e,t)},this.send=function(e){this.socket.emit("kuzzle",e)},this.close=function(){this.forceDisconnect=!0,this.socket.close(),this.socket=null}}function i(e,t,r,i){!t||e.retrying||e.stopRetryingToConnect||(e.retrying=!0,setTimeout(function(){e.retrying=!1,e.connect(t,r)},r)),e.handlers.connectError.forEach(function(e){e(i)})}e.exports=r},function(e,t,r){function i(e,t,r,i){if(n.call(this,e,t,r,i),Object.defineProperties(this,{deleteActionName:{value:"deleteProfile"},updateActionName:{value:"updateProfile"}}),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,i){var n=["hydrate","save"];return i&&n.indexOf(e)!==-1}})}var n=r(1);i.prototype=Object.create(n.prototype,{constructor:{value:i}}),i.prototype.save=function(e,t){var r,i=this;if(!this.content.policies)throw new Error('Argument "policies" is mandatory in a profile. This argument contains an array of objects.');return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r=this.serialize(),i.kuzzle.query(i.Security.buildQueryArgs("createOrReplaceProfile"),r,e,t&&function(e){t(e,e?void 0:i)}),i},i.prototype.addPolicy=function(e){if("object"!=typeof e||"string"!=typeof e.roleId)throw new Error('Parameter "policies" must be an object containing at least a "roleId" member which must be a string.');return this.content.policies||(this.content.policies=[]),this.content.policies.push(e),this},i.prototype.setPolicies=function(e){if(!Array.isArray(e))throw new Error('Parameter "policies" must be an array of objects containing at least a "roleId" member which must be a string');return e.map(function(e){if("object"!=typeof e||"string"!=typeof e.roleId)throw new Error('Parameter "policies" must be an array of objects containing at least a "roleId" member which must be a string')}),this.content.policies=e,this},i.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e.meta=this.meta,e},i.prototype.getPolicies=function(){return this.content.policies},e.exports=i},function(e,t,r){function i(e,t,r,i){if(n.call(this,e,t,r,i),Object.defineProperties(this,{deleteActionName:{value:"deleteRole"},updateActionName:{value:"updateRole"}}),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,i){var n=["save"];return i&&n.indexOf(e)!==-1}})}var n=r(1);i.prototype=Object.create(n.prototype,{constructor:{value:i}}),i.prototype.save=function(e,t){var r=this.serialize(),i=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),i.kuzzle.query(this.Security.buildQueryArgs("createOrReplaceRole"),r,e,t&&function(e){t(e,e?void 0:i)}),this},e.exports=i},function(e,t,r){function i(e){return Object.defineProperty(this,"kuzzle",{value:e}),Object.defineProperty(this,"buildQueryArgs",{value:function(e){return{controller:"security",action:e}}}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,i){var n=["role","profile","user","isActionAllowed"];return i&&n.indexOf(e)===-1}}):this}var n=r(16),o=r(15),s=r(5);i.prototype.fetchRole=function(e,t,r){var i,o=this;if(!e)throw new Error("Id parameter is mandatory for fetchRole function");r||"function"!=typeof t||(r=t,t=null),i={_id:e},o.kuzzle.callbackRequired("Security.fetchRole",r),o.kuzzle.query(this.buildQueryArgs("getRole"),i,t,function(e,t){r(e,e?void 0:new n(o,t.result._id,t.result._source,t.result._meta))})},i.prototype.searchRoles=function(e,t,r){var i=this;r||"function"!=typeof t||(r=t,t=null),i.kuzzle.callbackRequired("Security.searchRoles",r),i.kuzzle.query(this.buildQueryArgs("searchRoles"),{body:e},t,function(e,t){var o;return e?r(e):(o=t.result.hits.map(function(e){return new n(i,e._id,e._source,e._meta)}),void r(null,{total:t.result.total,roles:o}))})},i.prototype.createRole=function(e,t,r,i){var o=this,s={},u="createRole";if(!e||"string"!=typeof e)throw new Error("Security.createRole: cannot create a role without a role ID");i||"function"!=typeof r||(i=r,r=null),s._id=e,s.body=t,r&&(u=r.replaceIfExist?"createOrReplaceRole":"createRole"),o.kuzzle.query(this.buildQueryArgs(u),s,r,i&&function(e,t){i(e,e?void 0:new n(o,t.result._id,t.result._source,t.result._meta))})},i.prototype.updateRole=function(e,t,r,i){var o=this,s={_id:e,body:t},u="updateRole";if(!e||"string"!=typeof e)throw new Error("Security.updateRole: cannot update a role without a role ID");return i||"function"!=typeof r||(i=r,r=null),o.kuzzle.query(this.buildQueryArgs(u),s,r,i&&function(r,s){i(r,r?void 0:new n(o,e,t,s.result._meta))}),this},i.prototype.deleteRole=function(e,t,r){var i={_id:e};return r||"function"!=typeof t||(r=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteRole"),i,t,r&&function(e,t){r(e,e?void 0:t.result._id)}),this},i.prototype.role=function(e,t,r){return new n(this,e,t,r)},i.prototype.fetchProfile=function(e,t,r){var i,n=this;if(r||"function"!=typeof t||(r=t,t=null),!e||"string"!=typeof e)throw new Error("Id parameter is mandatory for fetchProfile function");i={_id:e},n.kuzzle.callbackRequired("Security.fetchProfile",r),n.kuzzle.query(this.buildQueryArgs("getProfile"),i,t,function(e,t){r(e,e?void 0:new o(n,t.result._id,t.result._source,t.result._meta))})},i.prototype.searchProfiles=function(e,t,r){var i=this;r||"function"!=typeof t||(r=t,t=null),i.kuzzle.callbackRequired("Security.searchProfiles",r),i.kuzzle.query(this.buildQueryArgs("searchProfiles"),{body:e},t,function(e,t){var n,s;return e?r(e):(n=t.result.hits.map(function(e){return new o(i,e._id,e._source,e._meta)}),t.result.scrollId&&(s=t.result.scrollId),void r(null,{total:t.result.total,profiles:n,scrollId:s}))})},i.prototype.createProfile=function(e,t,r,i){var n=this,s={},u="createProfile";if(!e||"string"!=typeof e)throw new Error("Security.createProfile: cannot create a profile without a profile ID");i||"function"!=typeof r||(i=r,r=null),s._id=e,t&&(s.body={policies:t}),r&&(u=r.replaceIfExist?"createOrReplaceProfile":"createProfile"),n.kuzzle.query(this.buildQueryArgs(u),s,r,i&&function(e,t){i(e,e?void 0:new o(n,t.result._id,t.result._source,t.result._meta))})},i.prototype.updateProfile=function(e,t,r,i){var n=this,s={},u="updateProfile";if(!e||"string"!=typeof e)throw new Error("Security.updateProfile: cannot update a profile without a profile ID");return i||"function"!=typeof r||(i=r,r=null),s._id=e,t&&(s.body={policies:t}),n.kuzzle.query(this.buildQueryArgs(u),s,r,i&&function(e,t){var r={};return e?i(e):(Object.keys(t.result._source).forEach(function(e){r[e]=t.result._source[e]}),void i(null,new o(n,t.result._id,r,t.result._meta)))}),this},i.prototype.deleteProfile=function(e,t,r){var i={_id:e};return r||"function"!=typeof t||(r=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteProfile"),i,t,r&&function(e,t){r(e,e?void 0:t.result._id)}),this},i.prototype.scrollProfiles=function(e,t,r){var i={},n=this;if(!e)throw new Error("Security.scrollProfiles: scrollId is required");r||"function"!=typeof t||(r=t,t={}),this.kuzzle.callbackRequired("Security.scrollProfiles",r),i.scrollId=e,t&&t.scroll&&(i.scroll=t.scroll),this.kuzzle.query({controller:"security",action:"scrollProfiles"},i,t,function(t,i){var s=[];return t?r(t):(i.result.hits.forEach(function(e){var t=new o(n,e._id,e._source,e._meta);t.version=e._version, -s.push(t)}),void r(null,{total:i.result.total,profiles:s,scrollId:e}))})},i.prototype.profile=function(e,t,r){return new o(this,e,t,r)},i.prototype.fetchUser=function(e,t,r){var i={_id:e},n=this;if(!e||"string"!=typeof e)throw new Error("Id parameter is mandatory for fetchUser function");r||"function"!=typeof t||(r=t,t=null),n.kuzzle.callbackRequired("Security.fetchUser",r),n.kuzzle.query(this.buildQueryArgs("getUser"),i,t,function(e,t){r(e,e?void 0:new s(n,t.result._id,t.result._source,t.result._meta))})},i.prototype.searchUsers=function(e,t,r){var i=this;r||"function"!=typeof t||(r=t,t=null),i.kuzzle.callbackRequired("Security.searchUsers",r),i.kuzzle.query(this.buildQueryArgs("searchUsers"),{body:e},t,function(e,t){var n,o=null;return e?r(e):(n=t.result.hits.map(function(e){return new s(i,e._id,e._source,e._meta)}),t.result.scrollId&&(o=t.result.scrollId),void r(null,{total:t.result.total,users:n,scrollId:o}))})},i.prototype.createUser=function(e,t,r,i){var n=this,o={_id:e,body:t};i||"function"!=typeof r||(i=r,r=null),n.kuzzle.query(n.buildQueryArgs("createUser"),o,null,i&&function(e,t){i(e,e?void 0:new s(n,t.result._id,t.result._source,t.result._meta))})},i.prototype.replaceUser=function(e,t,r,i){var n=this,o={_id:e,body:t};if(!e||"string"!=typeof e)throw new Error("Security.replaceUser: cannot replace a user without a user ID");i||"function"!=typeof r||(i=r,r=null),n.kuzzle.query(this.buildQueryArgs("replaceUser"),o,r,i&&function(e,t){i(e,e?void 0:new s(n,t.result._id,t.result._source,t.result._meta))})},i.prototype.createRestrictedUser=function(e,t,r,i){var n=this,o={_id:e,body:t};if(t.profileIds)throw new Error("Security.createRestrictedUser: cannot provide profileIds");i||"function"!=typeof r||(i=r,r=null),n.kuzzle.query(this.buildQueryArgs("createRestrictedUser"),o,null,i&&function(e,t){i(e,e?void 0:new s(n,t.result._id,t.result._source))})},i.prototype.updateUser=function(e,t,r,i){var n=this,o={},u="updateUser";if(!e||"string"!=typeof e)throw new Error("Security.updateUser: cannot update an user without an user ID");return i||"function"!=typeof r||(i=r,r=null),o._id=e,o.body=t,n.kuzzle.query(this.buildQueryArgs(u),o,r,i&&function(e,t){i(e,e?void 0:new s(n,t.result._id,t.result._source,t.result._meta))}),this},i.prototype.deleteUser=function(e,t,r){var i={_id:e};return r||"function"!=typeof t||(r=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteUser"),i,t,r&&function(e,t){r(e,e?void 0:t.result._id)}),this},i.prototype.scrollUsers=function(e,t,r){var i={},n=this;if(!e)throw new Error("Security.scrollUsers: scrollId is required");return r||"function"!=typeof t||(r=t,t={}),this.kuzzle.callbackRequired("Security.scrollUsers",r),i.scrollId=e,t&&t.scroll&&(i.scroll=t.scroll),this.kuzzle.query({controller:"security",action:"scrollUsers"},i,t,function(t,i){var o=[];return t?r(t):(i.result.hits.forEach(function(e){var t=new s(n,e._id,e._source,e._meta);t.version=e._version,o.push(t)}),void r(null,{total:i.result.total,users:o,scrollId:e}))}),this},i.prototype.user=function(e,t,r){return new s(this,e,t,r)},i.prototype.isActionAllowed=function(e,t,r,i,n){var o;if(!e||"object"!=typeof e)throw new Error("rights parameter is mandatory for isActionAllowed function");if(!t||"string"!=typeof t)throw new Error("controller parameter is mandatory for isActionAllowed function");if(!r||"string"!=typeof r)throw new Error("action parameter is mandatory for isActionAllowed function");return o=e.filter(function(e){return e.controller===t||"*"===e.controller}).filter(function(e){return e.action===r||"*"===e.action}).filter(function(e){return e.index===i||"*"===e.index}).filter(function(e){return e.collection===n||"*"===e.collection}),o.some(function(e){return"allowed"===e.value})?"allowed":o.some(function(e){return"conditional"===e.value})?"conditional":"denied"},i.prototype.getUserRights=function(e,t,r){var i={_id:e},n=this;if(!e||"string"!=typeof e)throw new Error("userId parameter is mandatory for getUserRights function");r||"function"!=typeof t||(r=t,t=null),n.kuzzle.callbackRequired("Kuzzle.getUserRights",r),this.kuzzle.query(this.buildQueryArgs("getUserRights"),i,t,r&&function(e,t){r(e,e?void 0:t.result.hits)})},i.prototype.createCredentials=function(e,t,r,i,n){return n||"function"!=typeof i||(n=i,i=null),this.kuzzle.query({controller:"security",action:"createCredentials"},{_id:t,strategy:e,body:r},i,function(e,t){e?n&&n(e):n&&n(null,t.result._source)}),this},i.prototype.deleteCredentials=function(e,t,r,i){return i||"function"!=typeof r||(i=r,r=null),this.kuzzle.query({controller:"security",action:"deleteCredentials"},{strategy:e,_id:t},r,"function"!=typeof i?null:function(e,t){e?i&&i(e):i&&i(null,t.result)}),this},i.prototype.getAllCredentialFields=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.kuzzle.query({controller:"security",action:"getAllCredentialFields"},{},e,"function"!=typeof t?null:function(e,r){e?t&&t(e):t&&t(null,r.result)})},i.prototype.getCredentialFields=function(e,t,r){r||"function"!=typeof t||(r=t,t=null),this.kuzzle.query({controller:"security",action:"getCredentialFields"},{strategy:e},t,"function"!=typeof r?null:function(e,t){e?r&&r(e):r&&r(null,t.result)})},i.prototype.getCredentials=function(e,t,r,i){i||"function"!=typeof r||(i=r,r=null),this.kuzzle.query({controller:"security",action:"getCredentials"},{strategy:e,_id:t},r,"function"!=typeof i?null:function(e,t){e?i&&i(e):i&&i(null,t.result)})},i.prototype.hasCredentials=function(e,t,r,i){i||"function"!=typeof r||(i=r,r=null),this.kuzzle.query({controller:"security",action:"hasCredentials"},{strategy:e,_id:t},r,"function"!=typeof i?null:function(e,t){e?i&&i(e):i&&i(null,t.result)})},i.prototype.updateCredentials=function(e,t,r,i,n){return n||"function"!=typeof i||(n=i,i=null),this.kuzzle.query({controller:"security",action:"updateCredentials"},{strategy:e,_id:t,body:r},i,"function"!=typeof n?null:function(e,t){e?n&&n(e):n&&n(null,t.result)}),this},i.prototype.validateCredentials=function(e,t,r,i,n){n||"function"!=typeof i||(n=i,i=null),this.kuzzle.query({controller:"security",action:"validateCredentials"},{strategy:e,_id:t,body:r},i,"function"!=typeof n?null:function(e,t){e?n&&n(e):n&&n(null,t.result)})},e.exports=i},function(e,t){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e}function n(e){return"number"==typeof e}function o(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}e.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!n(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,r,n,u,l,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;var a=new Error('Uncaught, unspecified "error" event. ('+t+")");throw a.context=t,a}if(r=this._events[e],s(r))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:u=Array.prototype.slice.call(arguments,1),r.apply(this,u)}else if(o(r))for(u=Array.prototype.slice.call(arguments,1),c=r.slice(),n=c.length,l=0;l0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}if(!i(t))throw TypeError("listener must be a function");var n=!1;return r.listener=t,this.on(e,r),this},r.prototype.removeListener=function(e,t){var r,n,s,u;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=this._events[e],s=r.length,n=-1,r===t||i(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(o(r)){for(u=s;u-- >0;)if(r[u]===t||r[u].listener&&r[u].listener===t){n=u;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[e],i(r))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t){function r(e,t){var r=t||0,n=i;return n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]}for(var i=[],n=0;n<256;++n)i[n]=(n+256).toString(16).substr(1);e.exports=r},function(e,t,r){var i,n=window.crypto||window.msCrypto;if(n&&n.getRandomValues){var o=new Uint8Array(16);i=function(){return n.getRandomValues(o),o}}if(!i){var s=new Array(16);i=function(){for(var e,t=0;t<16;t++)0===(3&t)&&(e=4294967296*Math.random()),s[t]=e>>>((3&t)<<3)&255;return s}}e.exports=i}])}); +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Kuzzle=t():e.Kuzzle=t()}(this,function(){return function(e){function t(n){if(r[n])return r[n].exports;var i=r[n]={exports:{},id:n,loaded:!1};return e[n].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e,t,r){var n="array"===t?!Array.isArray(r):("undefined"==typeof r?"undefined":l(r))!==t;if(n)throw new Error("Can only assign a "+t+' value to property "'+e+'"')}var l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s=function(){function e(e,t){for(var r=0;rn-i.timeout)return!1;i.lastEmitted=n}for(var o=arguments.length,u=Array(o>1?o-1:0),l=1;l1&&void 0!==arguments[1]&&arguments[1];r(this,e),this.fn=t,this.once=n},u=function(){function e(){r(this,e),this._events={}}return i(e,[{key:"_exists",value:function(e,t){return Boolean(e.find(function(e){return e.fn===t}))}},{key:"listeners",value:function(e){return void 0===this._events[e]?[]:this._events[e].map(function(e){return e.fn})}},{key:"addListener",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!e||!t)return this;var i="undefined"==typeof t?"undefined":n(t);if("function"!==i)throw new Error("Invalid listener type: expected a function, got a "+i);return void 0===this._events[e]&&(this._events[e]=[]),this._exists(this._events[e],t)||this._events[e].push(new o(t,r)),this}},{key:"on",value:function(e,t){return this.addListener(e,t)}},{key:"prependListener",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return e&&t?(void 0===this._events[e]&&(this._events[e]=[]),this._exists(this._events[e],t)||(this._events[e]=[new o(t,r)].concat(this._events[e])),this):this}},{key:"addOnceListener",value:function(e,t){return this.addListener(e,t,!0)}},{key:"once",value:function(e,t){return this.addOnceListener(e,t)}},{key:"prependOnceListener",value:function(e,t){return this.prependListener(e,t,!0)}},{key:"removeListener",value:function(e,t){var r=this._events[e];if(!r||!r.length)return this;var n=r.findIndex(function(e){return e.fn===t});return n!==-1&&r.splice(n,1),0===r.length&&delete this._events[e],this}},{key:"removeAllListeners",value:function(e){return e?delete this._events[e]:this._events={},this}},{key:"emit",value:function(e){var t=this._events[e];if(void 0===t)return!1;for(var r=[],n=arguments.length,i=Array(n>1?n-1:0),o=1;o0&&(e.offlineQueue.forEach(function(n,i){n.ts0&&e.offlineQueue.length>e.queueMaxSize&&e.offlineQueue.splice(0,e.offlineQueue.length-e.queueMaxSize).forEach(function(t){e.emit("offlineQueuePop",t.query)})}function c(e){var t={},r=function t(){e.offlineQueue.length>0&&(u(e,e.offlineQueue[0].query,e.offlineQueue[0].cb),e.emit("offlineQueuePop",e.offlineQueue.shift()),setTimeout(function(){t()},Math.max(0,e.replayInterval)))};if(e.offlineQueueLoader){if("function"!=typeof e.offlineQueueLoader)throw new Error("Invalid value for offlineQueueLoader property. Expected: function. Got: "+f(e.offlineQueueLoader));var n=e.offlineQueueLoader();if(!Array.isArray(n))throw new Error("Invalid value returned by the offlineQueueLoader function. Expected: array. Got: "+("undefined"==typeof n?"undefined":f(n)));e.offlineQueue=n.concat(e.offlineQueue).filter(function(e){if(!e.query||void 0===e.query.requestId||!e.query.action||!e.query.controller)throw new Error("Invalid offline queue request. One or more missing properties: requestId, action, controller.");return!t.hasOwnProperty(e.query.requestId)&&(t[e.query.requestId]=!0)})}r()}function a(e){var t=Date.now();Object.keys(e).forEach(function(r){e[r]}");return e.fromSelf&&!this.subscribeToSelf||this.emit(e.type,e),this}},{key:"onDone",value:function(e){if(!e||"function"!=typeof e)throw new Error("Room.onDone: a callback argument is required.");return this.error?e(this.error):"active"===this.roomstate?e(null,this):this.once("done",e),this}}]),t}(l);e.exports=s},function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var u=function(){function e(e,t){for(var r=0;r2&&void 0!==arguments[2]&&arguments[2];return this._addEventWrapper(e,r,n),l(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"addListener",this).call(this,e,r,n),this}},{key:"on",value:function(e,t){return this.addListener(e,t)}},{key:"prependListener",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return this._addEventWrapper(e,t,r),this.prependListener(e,t,r)}},{key:"removeListener",value:function(e,r){return this.eventsWrapper[e]&&(this.eventsWrapper[e].listeners.delete(r),0===this.eventsWrapper[e].listeners.size&&(this.socket.off(e,this.eventsWrapper[e].wrapper),delete this.eventsWrapper[e]),l(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"removeListener",this).call(this,e,r)),this}},{key:"removeAllListeners",value:function(e){if(void 0!==e&&void 0!==this.eventsWrapper[e]){var t=!0,r=!1,n=void 0;try{for(var i,o=this.eventsWrapper[e].listeners[Symbol.iterator]();!(t=(i=o.next()).done);t=!0){var u=i.value;this.removeListener(e,u)}}catch(e){r=!0,n=e}finally{try{!t&&o.return&&o.return()}finally{if(r)throw n}}}else{var l=!0,s=!1,c=void 0;try{for(var a,f=Object.keys(this.eventsWrapper)[Symbol.iterator]();!(l=(a=f.next()).done);l=!0){var d=a.value;this.removeAllListeners(d)}}catch(e){s=!0,c=e}finally{try{!l&&f.return&&f.return()}finally{if(s)throw c}}}return this}},{key:"send",value:function(e){this.socket.emit("kuzzle",e)}},{key:"close",value:function(){this.forceDisconnect=!0,this.state="offline",this.socket.close(),this.socket=null}},{key:"_addEventWrapper",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.eventsWrapper[e]){var i=function(){for(var t=arguments.length,n=Array(t),i=0;i0&&(e.options=r)}function o(e,t){e.options=["withscores"],t.limit&&(e.limit=t.limit,delete t.limit)}function u(e){return e.map(function(e){return e.map(function(e){return parseFloat(e)})})}function l(e){return Array.isArray(e[0])?e.map(function(e){var t,r={name:e[0]};for(t=1;t1)throw new Error("MemoryStorage."+e+": Too many parameters provided");if(1===r.length&&"object"!=typeof r[0]||Array.isArray(r[0]))throw new Error("MemoryStorage."+e+": Invalid optional parameter (expected an object)");if(r.length&&(i=Object.assign({},r[0]),Array.isArray(z[e].opts)&&z[e].opts.forEach(function(t){null!==i[t]&&void 0!==i[t]&&(n(u,z[e].getter,t,i[t]),delete i[t])})),"function"==typeof z[e].opts&&z[e].opts(u,i||{}),this.kuzzle.query(o,u,i,t&&function(r,n){return r?t(r):z[e].mapResults?t(null,z[e].mapResults(n.result)):void t(null,n.result)}),!z[e].getter)return this}})}(),e.exports=r},function(e,t){function r(e,t,n,i,o,u,l){return Object.defineProperties(this,{collection:{value:e,enumerable:!0},total:{value:t,enumerable:!0},documents:{value:n,enumerable:!0},aggregations:{value:i||{},enumerable:!0},options:{value:o||{},enumerable:!0},filters:{value:u||{},enumerable:!0},fetchedDocument:{value:l instanceof r?n.length+l.fetchedDocument:n.length,enumerable:!0,writable:!0}}),this.collection.kuzzle.bluebird?this.collection.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,n){var i=["fetchNext"];return n&&i.indexOf(e)!==-1}}):this}r.prototype.fetchNext=function(e){var t,r=Object.assign({},this.options),n=this;return r.previous=this,r.scrollId?this.fetchedDocument>=this.getTotal()?void e(null,null):("undefined"!=typeof r.from&&delete r.from,r.size&&delete r.size,void this.collection.scroll(r.scrollId,r,this.filters||{},e)):r.size&&this.filters.sort?this.fetchedDocument>=this.getTotal()?void e(null,null):(r.from&&delete r.from,t=Object.assign(this.filters,{search_after:[]}),t.sort.forEach(function(e){t.search_after.push(n.documents[n.documents.length-1].content[Object.keys(e)[0]])}),void this.collection.search(t,r,e)):void 0!==r.from&&void 0!==r.size?(t=Object.assign({},this.filters),r.from+=r.size,r.from>=this.getTotal()?void e(null,null):void this.collection.search(t,r,e)):void e(new Error("Unable to retrieve next results from search: missing scrollId or from/size params"))},r.prototype.getDocuments=function(){return this.documents},r.prototype.getTotal=function(){return this.total},r.prototype.getAggregations=function(){return this.aggregations},r.prototype.getOptions=function(){return this.options},r.prototype.getFilters=function(){return this.filters},r.prototype.getCollection=function(){return this.collection},r.prototype.getFetchedDocument=function(){return this.fetchedDocument},e.exports=r},function(e,t,r){function n(e,t,n){switch(e){case"websocket":if("undefined"!=typeof window&&"undefined"==typeof WebSocket)throw new Error("Aborting: no websocket support detected.");return new(r(8))(t,n);case"socketio":if(!window.io)throw new Error("Aborting: no socket.io library loaded.");return new(r(7))(t,n);default:throw new Error('Aborting: unknown protocol "'+e+'" (only "websocket" and "socketio" are available).')}}e.exports=n},function(e,t,r){function n(e,t,r,n){if(i.call(this,e,t,r,n),Object.defineProperties(this,{deleteActionName:{value:"deleteProfile"},updateActionName:{value:"updateProfile"}}),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,n){var i=["hydrate","save"];return n&&i.indexOf(e)!==-1}})}var i=r(2);n.prototype=Object.create(i.prototype,{constructor:{value:n}}),n.prototype.save=function(e,t){var r,n=this;if(!this.content.policies)throw new Error('Argument "policies" is mandatory in a profile. This argument contains an array of objects.');return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r=this.serialize(),n.kuzzle.query(n.Security.buildQueryArgs("createOrReplaceProfile"),r,e,t&&function(e){t(e,e?void 0:n)}),n},n.prototype.addPolicy=function(e){if("object"!=typeof e||"string"!=typeof e.roleId)throw new Error('Parameter "policies" must be an object containing at least a "roleId" member which must be a string.');return this.content.policies||(this.content.policies=[]),this.content.policies.push(e),this},n.prototype.setPolicies=function(e){if(!Array.isArray(e))throw new Error('Parameter "policies" must be an array of objects containing at least a "roleId" member which must be a string');return e.map(function(e){if("object"!=typeof e||"string"!=typeof e.roleId)throw new Error('Parameter "policies" must be an array of objects containing at least a "roleId" member which must be a string')}),this.content.policies=e,this},n.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e.meta=this.meta,e},n.prototype.getPolicies=function(){return this.content.policies},e.exports=n},function(e,t,r){function n(e,t,r,n){if(i.call(this,e,t,r,n),Object.defineProperties(this,{deleteActionName:{value:"deleteRole"},updateActionName:{value:"updateRole"}}),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,n){var i=["save"];return n&&i.indexOf(e)!==-1}})}var i=r(2);n.prototype=Object.create(i.prototype,{constructor:{value:n}}),n.prototype.save=function(e,t){var r=this.serialize(),n=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),n.kuzzle.query(this.Security.buildQueryArgs("createOrReplaceRole"),r,e,t&&function(e){t(e,e?void 0:n)}),this},e.exports=n},function(e,t,r){function n(e){return Object.defineProperty(this,"kuzzle",{value:e}),Object.defineProperty(this,"buildQueryArgs",{value:function(e){return{controller:"security",action:e}}}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,n){var i=["role","profile","user","isActionAllowed"];return n&&i.indexOf(e)===-1}}):this}var i=r(15),o=r(14),u=r(5);n.prototype.fetchRole=function(e,t,r){var n,o=this;if(!e)throw new Error("Id parameter is mandatory for fetchRole function");r||"function"!=typeof t||(r=t,t=null),n={_id:e},o.kuzzle.callbackRequired("Security.fetchRole",r),o.kuzzle.query(this.buildQueryArgs("getRole"),n,t,function(e,t){r(e,e?void 0:new i(o,t.result._id,t.result._source,t.result._meta))})},n.prototype.searchRoles=function(e,t,r){var n=this;r||"function"!=typeof t||(r=t,t=null),n.kuzzle.callbackRequired("Security.searchRoles",r),n.kuzzle.query(this.buildQueryArgs("searchRoles"),{body:e},t,function(e,t){var o;return e?r(e):(o=t.result.hits.map(function(e){return new i(n,e._id,e._source,e._meta)}),void r(null,{total:t.result.total,roles:o}))})},n.prototype.createRole=function(e,t,r,n){var o=this,u={},l="createRole";if(!e||"string"!=typeof e)throw new Error("Security.createRole: cannot create a role without a role ID");n||"function"!=typeof r||(n=r,r=null),u._id=e,u.body=t,r&&(l=r.replaceIfExist?"createOrReplaceRole":"createRole"),o.kuzzle.query(this.buildQueryArgs(l),u,r,n&&function(e,t){n(e,e?void 0:new i(o,t.result._id,t.result._source,t.result._meta))})},n.prototype.updateRole=function(e,t,r,n){var o=this,u={_id:e,body:t},l="updateRole";if(!e||"string"!=typeof e)throw new Error("Security.updateRole: cannot update a role without a role ID");return n||"function"!=typeof r||(n=r,r=null),o.kuzzle.query(this.buildQueryArgs(l),u,r,n&&function(r,u){n(r,r?void 0:new i(o,e,t,u.result._meta))}),this},n.prototype.deleteRole=function(e,t,r){var n={_id:e};return r||"function"!=typeof t||(r=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteRole"),n,t,r&&function(e,t){r(e,e?void 0:t.result._id)}),this},n.prototype.role=function(e,t,r){return new i(this,e,t,r)},n.prototype.fetchProfile=function(e,t,r){var n,i=this;if(r||"function"!=typeof t||(r=t,t=null),!e||"string"!=typeof e)throw new Error("Id parameter is mandatory for fetchProfile function");n={_id:e},i.kuzzle.callbackRequired("Security.fetchProfile",r),i.kuzzle.query(this.buildQueryArgs("getProfile"),n,t,function(e,t){r(e,e?void 0:new o(i,t.result._id,t.result._source,t.result._meta))})},n.prototype.searchProfiles=function(e,t,r){var n=this;r||"function"!=typeof t||(r=t,t=null),n.kuzzle.callbackRequired("Security.searchProfiles",r),n.kuzzle.query(this.buildQueryArgs("searchProfiles"),{body:e},t,function(e,t){var i,u;return e?r(e):(i=t.result.hits.map(function(e){return new o(n,e._id,e._source,e._meta)}),t.result.scrollId&&(u=t.result.scrollId),void r(null,{total:t.result.total,profiles:i,scrollId:u}))})},n.prototype.createProfile=function(e,t,r,n){var i=this,u={},l="createProfile";if(!e||"string"!=typeof e)throw new Error("Security.createProfile: cannot create a profile without a profile ID");n||"function"!=typeof r||(n=r,r=null),u._id=e,t&&(u.body={policies:t}),r&&(l=r.replaceIfExist?"createOrReplaceProfile":"createProfile"),i.kuzzle.query(this.buildQueryArgs(l),u,r,n&&function(e,t){n(e,e?void 0:new o(i,t.result._id,t.result._source,t.result._meta))})},n.prototype.updateProfile=function(e,t,r,n){var i=this,u={},l="updateProfile";if(!e||"string"!=typeof e)throw new Error("Security.updateProfile: cannot update a profile without a profile ID");return n||"function"!=typeof r||(n=r,r=null),u._id=e,t&&(u.body={policies:t}),i.kuzzle.query(this.buildQueryArgs(l),u,r,n&&function(e,t){var r={};return e?n(e):(Object.keys(t.result._source).forEach(function(e){r[e]=t.result._source[e]}),void n(null,new o(i,t.result._id,r,t.result._meta)))}),this},n.prototype.deleteProfile=function(e,t,r){var n={_id:e};return r||"function"!=typeof t||(r=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteProfile"),n,t,r&&function(e,t){r(e,e?void 0:t.result._id)}),this},n.prototype.scrollProfiles=function(e,t,r){var n={},i=this;if(!e)throw new Error("Security.scrollProfiles: scrollId is required");r||"function"!=typeof t||(r=t,t={}),this.kuzzle.callbackRequired("Security.scrollProfiles",r),n.scrollId=e,t&&t.scroll&&(n.scroll=t.scroll),this.kuzzle.query({controller:"security",action:"scrollProfiles"},n,t,function(t,n){var u=[];return t?r(t):(n.result.hits.forEach(function(e){var t=new o(i,e._id,e._source,e._meta);t.version=e._version,u.push(t)}),void r(null,{total:n.result.total,profiles:u,scrollId:e}))})},n.prototype.profile=function(e,t,r){return new o(this,e,t,r)},n.prototype.fetchUser=function(e,t,r){var n={_id:e},i=this;if(!e||"string"!=typeof e)throw new Error("Id parameter is mandatory for fetchUser function");r||"function"!=typeof t||(r=t,t=null),i.kuzzle.callbackRequired("Security.fetchUser",r),i.kuzzle.query(this.buildQueryArgs("getUser"),n,t,function(e,t){r(e,e?void 0:new u(i,t.result._id,t.result._source,t.result._meta))})},n.prototype.searchUsers=function(e,t,r){var n=this;r||"function"!=typeof t||(r=t,t=null),n.kuzzle.callbackRequired("Security.searchUsers",r),n.kuzzle.query(this.buildQueryArgs("searchUsers"),{body:e},t,function(e,t){var i,o=null;return e?r(e):(i=t.result.hits.map(function(e){return new u(n,e._id,e._source,e._meta)}),t.result.scrollId&&(o=t.result.scrollId),void r(null,{total:t.result.total,users:i,scrollId:o}))})},n.prototype.createUser=function(e,t,r,n){var i=this,o={_id:e,body:t};n||"function"!=typeof r||(n=r,r=null),i.kuzzle.query(i.buildQueryArgs("createUser"),o,null,n&&function(e,t){n(e,e?void 0:new u(i,t.result._id,t.result._source,t.result._meta))})},n.prototype.replaceUser=function(e,t,r,n){var i=this,o={_id:e,body:t};if(!e||"string"!=typeof e)throw new Error("Security.replaceUser: cannot replace a user without a user ID");n||"function"!=typeof r||(n=r,r=null),i.kuzzle.query(this.buildQueryArgs("replaceUser"),o,r,n&&function(e,t){n(e,e?void 0:new u(i,t.result._id,t.result._source,t.result._meta))})},n.prototype.createRestrictedUser=function(e,t,r,n){var i=this,o={_id:e,body:t};if(t.profileIds)throw new Error("Security.createRestrictedUser: cannot provide profileIds");n||"function"!=typeof r||(n=r,r=null),i.kuzzle.query(this.buildQueryArgs("createRestrictedUser"),o,null,n&&function(e,t){n(e,e?void 0:new u(i,t.result._id,t.result._source))})},n.prototype.updateUser=function(e,t,r,n){var i=this,o={},l="updateUser";if(!e||"string"!=typeof e)throw new Error("Security.updateUser: cannot update an user without an user ID");return n||"function"!=typeof r||(n=r,r=null),o._id=e,o.body=t,i.kuzzle.query(this.buildQueryArgs(l),o,r,n&&function(e,t){n(e,e?void 0:new u(i,t.result._id,t.result._source,t.result._meta))}),this},n.prototype.deleteUser=function(e,t,r){var n={_id:e};return r||"function"!=typeof t||(r=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteUser"),n,t,r&&function(e,t){r(e,e?void 0:t.result._id)}),this},n.prototype.scrollUsers=function(e,t,r){var n={},i=this;if(!e)throw new Error("Security.scrollUsers: scrollId is required");return r||"function"!=typeof t||(r=t,t={}),this.kuzzle.callbackRequired("Security.scrollUsers",r),n.scrollId=e,t&&t.scroll&&(n.scroll=t.scroll),this.kuzzle.query({controller:"security",action:"scrollUsers"},n,t,function(t,n){var o=[];return t?r(t):(n.result.hits.forEach(function(e){var t=new u(i,e._id,e._source,e._meta);t.version=e._version,o.push(t)}),void r(null,{total:n.result.total,users:o,scrollId:e}))}),this},n.prototype.user=function(e,t,r){return new u(this,e,t,r)},n.prototype.isActionAllowed=function(e,t,r,n,i){var o;if(!e||"object"!=typeof e)throw new Error("rights parameter is mandatory for isActionAllowed function");if(!t||"string"!=typeof t)throw new Error("controller parameter is mandatory for isActionAllowed function");if(!r||"string"!=typeof r)throw new Error("action parameter is mandatory for isActionAllowed function");return o=e.filter(function(e){return e.controller===t||"*"===e.controller}).filter(function(e){return e.action===r||"*"===e.action}).filter(function(e){return e.index===n||"*"===e.index}).filter(function(e){return e.collection===i||"*"===e.collection}),o.some(function(e){return"allowed"===e.value})?"allowed":o.some(function(e){return"conditional"===e.value})?"conditional":"denied"},n.prototype.getUserRights=function(e,t,r){var n={_id:e},i=this;if(!e||"string"!=typeof e)throw new Error("userId parameter is mandatory for getUserRights function");r||"function"!=typeof t||(r=t,t=null),i.kuzzle.callbackRequired("Kuzzle.getUserRights",r),this.kuzzle.query(this.buildQueryArgs("getUserRights"),n,t,r&&function(e,t){r(e,e?void 0:t.result.hits)})},n.prototype.createCredentials=function(e,t,r,n,i){return i||"function"!=typeof n||(i=n,n=null),this.kuzzle.query({controller:"security",action:"createCredentials"},{_id:t,strategy:e,body:r},n,function(e,t){e?i&&i(e):i&&i(null,t.result._source)}),this},n.prototype.deleteCredentials=function(e,t,r,n){return n||"function"!=typeof r||(n=r,r=null),this.kuzzle.query({controller:"security",action:"deleteCredentials"},{strategy:e,_id:t},r,"function"!=typeof n?null:function(e,t){e?n&&n(e):n&&n(null,t.result)}),this},n.prototype.getAllCredentialFields=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.kuzzle.query({controller:"security",action:"getAllCredentialFields"},{},e,"function"!=typeof t?null:function(e,r){e?t&&t(e):t&&t(null,r.result)})},n.prototype.getCredentialFields=function(e,t,r){r||"function"!=typeof t||(r=t,t=null),this.kuzzle.query({controller:"security",action:"getCredentialFields"},{strategy:e},t,"function"!=typeof r?null:function(e,t){e?r&&r(e):r&&r(null,t.result)})},n.prototype.getCredentials=function(e,t,r,n){n||"function"!=typeof r||(n=r,r=null),this.kuzzle.query({controller:"security",action:"getCredentials"},{strategy:e,_id:t},r,"function"!=typeof n?null:function(e,t){e?n&&n(e):n&&n(null,t.result)})},n.prototype.hasCredentials=function(e,t,r,n){n||"function"!=typeof r||(n=r,r=null),this.kuzzle.query({controller:"security",action:"hasCredentials"},{strategy:e,_id:t},r,"function"!=typeof n?null:function(e,t){e?n&&n(e):n&&n(null,t.result)})},n.prototype.updateCredentials=function(e,t,r,n,i){return i||"function"!=typeof n||(i=n,n=null),this.kuzzle.query({controller:"security",action:"updateCredentials"},{strategy:e,_id:t,body:r},n,"function"!=typeof i?null:function(e,t){e?i&&i(e):i&&i(null,t.result)}),this},n.prototype.validateCredentials=function(e,t,r,n,i){i||"function"!=typeof n||(i=n,n=null),this.kuzzle.query({controller:"security",action:"validateCredentials"},{strategy:e,_id:t,body:r},n,"function"!=typeof i?null:function(e,t){e?i&&i(e):i&&i(null,t.result)})},e.exports=n},function(e,t){function r(e,t){var r=t||0,i=n;return i[e[r++]]+i[e[r++]]+i[e[r++]]+i[e[r++]]+"-"+i[e[r++]]+i[e[r++]]+"-"+i[e[r++]]+i[e[r++]]+"-"+i[e[r++]]+i[e[r++]]+"-"+i[e[r++]]+i[e[r++]]+i[e[r++]]+i[e[r++]]+i[e[r++]]+i[e[r++]]}for(var n=[],i=0;i<256;++i)n[i]=(i+256).toString(16).substr(1);e.exports=r},function(e,t,r){var n,i=window.crypto||window.msCrypto;if(i&&i.getRandomValues){var o=new Uint8Array(16);n=function(){return i.getRandomValues(o),o}}if(!n){var u=new Array(16);n=function(){for(var e,t=0;t<16;t++)0===(3&t)&&(e=4294967296*Math.random()),u[t]=e>>>((3&t)<<3)&255;return u}}e.exports=n},function(e,t,r){function n(e,t,r){var n=t&&r||0;"string"==typeof e&&(t="binary"==e?new Array(16):null,e=null),e=e||{};var u=e.random||(e.rng||i)();if(u[6]=15&u[6]|64,u[8]=63&u[8]|128,t)for(var l=0;l<16;++l)t[n+l]=u[l];return t||o(u)}var i=r(18),o=r(17);e.exports=n}])}); //# sourceMappingURL=kuzzle.js.map \ No newline at end of file diff --git a/dist/kuzzle.js.map b/dist/kuzzle.js.map index 2ca741b85..02f7e0f1e 100644 --- a/dist/kuzzle.js.map +++ b/dist/kuzzle.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///kuzzle.js","webpack:///webpack/bootstrap acd8f2ec6a57e2c5517f","webpack:///./src/Kuzzle.js","webpack:///./src/security/SecurityDocument.js","webpack:///./src/Document.js","webpack:///./src/eventEmitter/index.js","webpack:///./src/networkWrapper/wrappers/websocket.js","webpack:///./src/security/User.js","webpack:///../~/uuid/v4.js","webpack:///./src/Collection.js","webpack:///./src/CollectionMapping.js","webpack:///./src/MemoryStorage.js","webpack:///./src/Room.js","webpack:///./src/SearchResult.js","webpack:///./src/SubscribeResult.js","webpack:///./src/networkWrapper/index.js","webpack:///./src/networkWrapper/wrappers/socketio.js","webpack:///./src/security/Profile.js","webpack:///./src/security/Role.js","webpack:///./src/security/Security.js","webpack:///../~/events/events.js","webpack:///../~/uuid/lib/bytesToUuid.js","webpack:///../~/uuid/lib/rng-browser.js"],"names":["root","factory","exports","module","define","amd","this","modules","__webpack_require__","moduleId","installedModules","id","loaded","call","m","c","p","Kuzzle","host","options","cb","self","KuzzleEventEmitter","Error","Object","defineProperties","cleanHistoryTimer","value","writable","collections","connectCB","eventActions","queuing","requestHistory","state","subscriptions","pending","autoReconnect","enumerable","defaultIndex","undefined","reconnectionDelay","port","sslConnection","autoQueue","autoReplay","autoResubscribe","headers","volatile","offlineQueue","queueFilter","queueMaxSize","queueTTL","replayInterval","jwtToken","offlineQueueLoader","sdkVersion","keys","forEach","opt","hasOwnProperty","getOwnPropertyDescriptor","offlineMode","defineProperty","query","header","errorMessagePrefix","callback","Security","MemoryStorage","eventTimeout","writeable","connected","timeout","error","disconnected","reconnected","tokenExpired","loginAttempt","connect","setInterval","cleanHistory","bluebird","promisifyAll","suffix","filter","name","func","target","passes","whitelist","indexOf","cleanQueue","now","Date","lastDocumentIndex","index","ts","splice","droppedRequest","emitEvent","length","key","emitRequest","request","network","once","requestId","response","action","message","assign","status","send","dequeue","additionalQueue","uniqueQueue","dequeuingProcess","shift","setTimeout","Math","max","Array","isArray","concat","controller","renewAllSubscriptions","roomId","subscriptionId","subscription","renew","removeAllSubscriptions","unsubscribe","discardRequest","object","JSON","stringify","disableAllSubscriptions","subscribing","uuidv4","Collection","User","networkWrapper","prototype","create","constructor","emit","eventName","protectedEvent","protectedEvents","lastEmitted","apply","arguments","disconnect","onConnect","on","data","onConnectError","connectionError","internal","onDisconnect","onReconnect","reconnect","checkToken","err","res","valid","setJwtToken","token","success","result","jwt","unsetJwtToken","getJwtToken","login","strategy","body","expiresIn","queuable","createMyCredentials","credentials","_source","deleteMyCredentials","getMyCredentials","updateMyCredentials","validateMyCredentials","createIndex","logout","callbackRequired","whoAmI","security","_id","_meta","getMyRights","hits","updateSelf","content","queryArgs","addListener","event","listener","isValid","toString","getAllStatistics","getStatistics","timestamp","queryCB","startTime","collection","flushQueue","listCollections","args","slice","arg","type","listIndexes","indexes","clearInterval","close","getServerInfo","serverInfo","refreshIndex","getAutoRefresh","setAutoRefresh","autoRefresh","attr","refresh","from","size","scroll","scrollId","meta","addHeaders","push","replayQueue","setDefaultIndex","setHeaders","replace","startQueuing","stopQueuing","SecurityDocument","kuzzle","setContent","serialize","delete","buildQueryArgs","deleteActionName","update","updateActionName","Document","documentId","dataCollection","parse","version","_version","exists","newDocument","save","publish","subscribe","filters","ids","values","window","_events","_onceEvents","listeners","listenerType","prependListener","onceListeners","prependOnceListener","removeListener","removeAllListeners","notifyList","i","item","eventNames","listenerCount","off","WSNode","ssl","WebSocket","e","code","client","wasConnected","retrying","lasturl","stopRetryingToConnect","url","perMessageDeflate","onopen","onclose","closeEvent","reason","onClientNetworkError","onerror","onmessage","payload","room","readyState","OPEN","ws","KuzzleSecurityDocument","setProfiles","profileIds","setCredentials","addProfile","profileId","creationSerialize","saveRestricted","getProfileIds","getProfiles","fetchedProfiles","errored","fetchProfile","profile","v4","buf","offset","rnds","random","rng","ii","bytesToUuid","blacklist","KuzzleSearchResult","CollectionMapping","Room","SubscribeResult","count","createDocument","document","ifExist","doc","deleteDocument","deleteSpecifications","documentExists","fetchDocument","getMapping","kuzzleMapping","mCreateDocument","documents","map","mCreateOrReplaceDocument","mDeleteDocument","documentIds","mGetDocument","mReplaceDocument","mUpdateDocument","getSpecifications","publishMessage","replaceDocument","search","_scroll_id","total","aggregations","previous","scrollSpecifications","searchSpecifications","subscribeResult","done","bind","truncate","updateDocument","retryOnConflict","updateSpecifications","specifications","validateSpecifications","collectionMapping","mapping","properties","mappings","set","field","assignParameter","getter","assignGeoRadiusOptions","parsed","assignZrangeOptions","limit","mapGeoposResults","results","coords","latlon","parseFloat","mapGeoRadiusResults","point","coordinates","coord","distance","mapStringToArray","mapArrayStringToArrayInt","parseInt","mapZrangeResults","buffer","mapped","member","score","mapScanResults","cursor","getId","required","getIdField","getKeys","getMember","getxScan","opts","mapResults","getZrange","getZrangeBy","setId","setIdValue","setIdFieldValue","setEntries","commands","append","bitcount","bitop","bitpos","dbsize","decr","decrby","del","expire","expireat","flushdb","geoadd","geodist","geohash","geopos","georadius","georadiusbymember","get","getbit","getrange","getset","hdel","hexists","hget","hgetall","hincrby","hincrbyfloat","hkeys","hlen","hmget","hmset","hscan","hset","hsetnx","hstrlen","hvals","incr","incrby","incrbyfloat","lindex","linsert","llen","lpop","lpush","lpushx","lrange","lrem","lset","ltrim","mget","mset","msetnx","persist","pexpire","pexpireat","pfadd","pfcount","pfmerge","ping","psetex","pttl","randomkey","rename","renamenx","rpop","rpoplpush","rpush","rpushx","sadd","scan","scard","sdiff","sdiffstore","setex","setnx","sinter","sinterstore","sismember","smembers","smove","sort","spop","srandmember","srem","sscan","strlen","sunion","sunionstore","time","touch","ttl","zadd","zcard","zcount","zincrby","zinterstore","zlexcount","zrange","zrangebylex","zrevrangebylex","zrangebyscore","zrank","zrem","zremrangebylex","zremrangebyrank","zremrangebyscore","zrevrange","zrevrangebyscore","zrevrank","zscan","zscore","zunionstore","command","pop","param","channel","lastRenewal","notifier","onDoneCB","queue","renewalDelay","scope","users","subscribeToSelf","notificationCallback","element","isReady","notificationCB","subscribeQuery","interval","SearchResult","fetchedDocument","fetchNext","getTotal","search_after","sortRule","getDocuments","getAggregations","getOptions","getFilters","getCollection","getFetchedDocument","cbs","onDone","io","SocketIO","socket","forceDisconnect","handlers","connectError","reconnection","forceNew","handler","socketio","Profile","policies","addPolicy","policy","roleId","setPolicies","getPolicies","Role","fetchRole","searchRoles","roles","createRole","replaceIfExist","updateRole","deleteRole","role","searchProfiles","profiles","createProfile","updateProfile","updatedContent","property","deleteProfile","scrollProfiles","newProfile","fetchUser","searchUsers","createUser","replaceUser","createRestrictedUser","updateUser","deleteUser","scrollUsers","user","newUser","isActionAllowed","rights","filteredRights","right","some","getUserRights","userId","createCredentials","kuid","deleteCredentials","getAllCredentialFields","getCredentialFields","getCredentials","hasCredentials","updateCredentials","validateCredentials","EventEmitter","_maxListeners","isFunction","isNumber","isObject","isUndefined","defaultMaxListeners","setMaxListeners","n","isNaN","TypeError","er","len","context","newListener","warned","console","trace","g","fired","list","position","ret","evlistener","emitter","bth","byteToHex","substr","crypto","msCrypto","getRandomValues","rnds8","Uint8Array","r"],"mappings":";CAAA,SAAAA,EAAAC,GACA,gBAAAC,UAAA,gBAAAC,QACAA,OAAAD,QAAAD,IACA,kBAAAG,gBAAAC,IACAD,UAAAH,GACA,gBAAAC,SACAA,QAAA,OAAAD,IAEAD,EAAA,OAAAC,KACCK,KAAA,WACD,MCCgB,UAAUC,GCP1B,QAAAC,GAAAC,GAGA,GAAAC,EAAAD,GACA,MAAAC,GAAAD,GAAAP,OAGA,IAAAC,GAAAO,EAAAD,IACA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,EAAA,EAAsBA,EAAA,GAAQA,IAC9B,OAAAA,KAAA4X,EAAA,WAAAthB,KAAAyM,UACAD,EAAA9C,GAAA4X,MAAA,EAAA5X,IAAA,MAGA,OAAA8C,IAIA7T,EAAAD,QAAAgU","file":"kuzzle.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Kuzzle\"] = factory();\n\telse\n\t\troot[\"Kuzzle\"] = factory();\n})(this, function() {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition","/*! Kuzzle javascript SDK version 5.0.10 */\n(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Kuzzle\"] = factory();\n\telse\n\t\troot[\"Kuzzle\"] = factory();\n})(this, function() {\nreturn /******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId])\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\texports: {},\n/******/ \t\t\tid: moduleId,\n/******/ \t\t\tloaded: false\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.loaded = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(0);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tvar\n\t uuidv4 = __webpack_require__(6),\n\t KuzzleEventEmitter = __webpack_require__(3),\n\t Collection = __webpack_require__(7),\n\t Security = __webpack_require__(17),\n\t MemoryStorage = __webpack_require__(9),\n\t User = __webpack_require__(5),\n\t networkWrapper = __webpack_require__(13);\n\t\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t/**\n\t * Kuzzle object constructor.\n\t *\n\t * @constructor\n\t * @param host - Server name or IP Address to the Kuzzle instance\n\t * @param [options] - Connection options\n\t * @param {responseCallback} [cb] - Handles connection response\n\t */\n\tfunction Kuzzle (host, options, cb) {\n\t var self = this;\n\t\n\t if (!(this instanceof Kuzzle)) {\n\t return new Kuzzle(host, options, cb);\n\t }\n\t KuzzleEventEmitter.call(this);\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!host || host === '') {\n\t throw new Error('host argument missing');\n\t }\n\t\n\t Object.defineProperties(this, {\n\t // 'private' properties\n\t cleanHistoryTimer: {\n\t value: null,\n\t writable: true\n\t },\n\t collections: {\n\t value: {},\n\t writable: true\n\t },\n\t connectCB: {\n\t value: cb\n\t },\n\t eventActions: {\n\t value: [\n\t 'connected',\n\t 'networkError',\n\t 'disconnected',\n\t 'reconnected',\n\t 'tokenExpired',\n\t 'loginAttempt',\n\t 'offlineQueuePush',\n\t 'offlineQueuePop',\n\t 'queryError',\n\t 'discarded'\n\t ],\n\t writable: false\n\t },\n\t queuing: {\n\t value: false,\n\t writable: true\n\t },\n\t requestHistory: {\n\t value: {},\n\t writable: true\n\t },\n\t state: {\n\t value: 'initializing',\n\t writable: true\n\t },\n\t subscriptions: {\n\t /*\n\t Contains the centralized subscription list in the following format:\n\t pending: {\n\t subscriptionUid_1: kuzzleRoomInstance_1,\n\t subscriptionUid_2: kuzzleRoomInstance_2,\n\t subscriptionUid_...: kuzzleRoomInstance_...\n\t },\n\t 'roomId': {\n\t subscriptionUid_1: kuzzleRoomInstance_1,\n\t subscriptionUid_2: kuzzleRoomInstance_2,\n\t subscriptionUid_...: kuzzleRoomInstance_...\n\t }\n\t\n\t This was made to allow multiple subscriptions on the same set of filters, something that Kuzzle does not permit.\n\t This structure also allows renewing subscriptions after a connection loss\n\t */\n\t value: {\n\t pending: {}\n\t },\n\t writable: true\n\t },\n\t // configuration properties\n\t autoReconnect: {\n\t value: (options && typeof options.autoReconnect === 'boolean') ? options.autoReconnect : true,\n\t writable: true,\n\t enumerable: true\n\t },\n\t defaultIndex: {\n\t value: (options && typeof options.defaultIndex === 'string') ? options.defaultIndex : undefined,\n\t writable: true,\n\t enumerable: true\n\t },\n\t reconnectionDelay: {\n\t value: (options && typeof options.reconnectionDelay === 'number') ? options.reconnectionDelay : 1000,\n\t writable: true,\n\t enumerable: true\n\t },\n\t host: {\n\t value: host,\n\t writable: true,\n\t enumerable: true\n\t },\n\t port: {\n\t value: (options && typeof options.port === 'number') ? options.port : 7512,\n\t enumerable: true,\n\t writable: true\n\t },\n\t sslConnection: {\n\t value: (options && typeof options.sslConnection === 'boolean') ? options.sslConnection : false,\n\t writable: true,\n\t enumerable: true\n\t },\n\t autoQueue: {\n\t value: false,\n\t enumerable: true,\n\t writable: true\n\t },\n\t autoReplay: {\n\t value: false,\n\t enumerable: true,\n\t writable: true\n\t },\n\t autoResubscribe: {\n\t value: true,\n\t enumerable: true,\n\t writable: true\n\t },\n\t headers: {\n\t value: {},\n\t enumerable: true,\n\t writable: true\n\t },\n\t volatile: {\n\t value: {},\n\t enumerable: true,\n\t writable: true\n\t },\n\t /*\n\t Offline queue use the following format:\n\t [\n\t {\n\t ts: ,\n\t query: 'query',\n\t cb: callbackFunction\n\t }\n\t ]\n\t */\n\t offlineQueue: {\n\t value: [],\n\t enumerable: true,\n\t writable: true\n\t },\n\t queueFilter: {\n\t value: null,\n\t enumerable: true,\n\t writable: true\n\t },\n\t queueMaxSize: {\n\t value: 500,\n\t enumerable: true,\n\t writable: true\n\t },\n\t queueTTL: {\n\t value: 120000,\n\t enumerable: true,\n\t writable: true\n\t },\n\t replayInterval: {\n\t value: 10,\n\t enumerable: true,\n\t writable: true\n\t },\n\t jwtToken: {\n\t value: undefined,\n\t enumerable: true,\n\t writable: true\n\t },\n\t offlineQueueLoader: {\n\t value: undefined,\n\t enumerable: true,\n\t writable: true\n\t },\n\t sdkVersion: {\n\t value: ( false) ? require('../package.json').version : (\"5.0.10\"),\n\t writable: false\n\t }\n\t });\n\t\n\t if (options) {\n\t Object.keys(options).forEach(function (opt) {\n\t if (self.hasOwnProperty(opt) && Object.getOwnPropertyDescriptor(self, opt).writable) {\n\t self[opt] = options[opt];\n\t }\n\t });\n\t\n\t if (options.offlineMode === 'auto' && this.autoReconnect) {\n\t this.autoQueue = this.autoReplay = this.autoResubscribe = true;\n\t }\n\t }\n\t\n\t // Helper function ensuring that this Kuzzle object is still valid before performing a query\n\t Object.defineProperty(this, 'isValid', {\n\t value: function () {\n\t if (self.state === 'disconnected') {\n\t throw new Error('This Kuzzle object has been invalidated. Did you try to access it after a disconnect call?');\n\t }\n\t }\n\t });\n\t\n\t // Helper function copying headers to the query data\n\t Object.defineProperty(this, 'addHeaders', {\n\t value: function (query, headers) {\n\t Object.keys(headers).forEach(function (header) {\n\t if (!query[header]) {\n\t query[header] = headers[header];\n\t }\n\t });\n\t\n\t return query;\n\t }\n\t });\n\t\n\t /**\n\t * Some methods (mainly read queries) require a callback function. This function exists to avoid repetition of code,\n\t * and is called by these methods\n\t */\n\t Object.defineProperty(this, 'callbackRequired', {\n\t value: function (errorMessagePrefix, callback) {\n\t if (!callback || typeof callback !== 'function') {\n\t throw new Error(errorMessagePrefix + ': a callback argument is required for read queries');\n\t }\n\t }\n\t });\n\t\n\t /**\n\t * Create an attribute security that embed all methods to manage Role, Profile and User\n\t */\n\t Object.defineProperty(this, 'security', {\n\t value: new Security(this),\n\t enumerable: true\n\t });\n\t\n\t Object.defineProperty(this, 'memoryStorage', {\n\t value: new MemoryStorage(this),\n\t enumerable: true\n\t });\n\t\n\t Object.defineProperties(this, {\n\t eventTimeout: {\n\t value: options && typeof options.eventTimeout === 'number' ? options.eventTimeout : 200,\n\t writeable: false\n\t }\n\t });\n\t\n\t Object.defineProperty(this, 'protectedEvents', {\n\t value: {\n\t connected: {timeout: this.eventTimeout},\n\t error: {timeout: this.eventTimeout},\n\t disconnected: {timeout: this.eventTimeout},\n\t reconnected: {timeout: this.eventTimeout},\n\t tokenExpired: {timeout: this.eventTimeout},\n\t loginAttempt: {timeout: this.eventTimeout}\n\t },\n\t writeable: false\n\t });\n\t\n\t if (!options || !options.connect || options.connect === 'auto') {\n\t this.connect();\n\t } else {\n\t this.state = 'ready';\n\t }\n\t\n\t this.cleanHistoryTimer = setInterval(function () { cleanHistory(self.requestHistory); }, 1000);\n\t\n\t if (this.bluebird) {\n\t return this.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['getAllStatistics', 'getServerInfo', 'getStatistics',\n\t 'listCollections', 'createIndex', 'listIndexes', 'login', 'logout',\n\t 'now', 'query', 'checkToken', 'whoAmI', 'updateSelf', 'getMyRights',\n\t 'refreshIndex', 'getAutoRefresh', 'setAutoRefresh'\n\t ];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t}\n\tKuzzle.prototype = Object.create(KuzzleEventEmitter.prototype);\n\tKuzzle.prototype.constructor = Kuzzle;\n\t\n\t/**\n\t* Emit an event to all registered listeners\n\t* An event cannot be emitted multiple times before a timeout has been reached.\n\t*/\n\tKuzzle.prototype.emit = function(eventName) {\n\t var\n\t now = Date.now(),\n\t protectedEvent = this.protectedEvents[eventName];\n\t\n\t if (protectedEvent) {\n\t if (protectedEvent.lastEmitted && protectedEvent.lastEmitted > now - protectedEvent.timeout) {\n\t return false;\n\t }\n\t protectedEvent.lastEmitted = now;\n\t }\n\t KuzzleEventEmitter.prototype.emit.apply(this, arguments);\n\t};\n\tKuzzle.prototype.emitEvent = Kuzzle.prototype.emit;\n\t\n\t/**\n\t * Connects to a Kuzzle instance using the provided host name.\n\t * @returns {Object} this\n\t */\n\tKuzzle.prototype.connect = function () {\n\t var self = this;\n\t\n\t if (self.network) {\n\t self.disconnect();\n\t }\n\t\n\t self.network = networkWrapper(self.host, self.port, self.sslConnection);\n\t\n\t if (['initializing', 'ready', 'disconnected', 'error', 'offline'].indexOf(this.state) === -1) {\n\t if (self.connectCB) {\n\t self.connectCB(null, self);\n\t }\n\t return self;\n\t }\n\t\n\t self.state = 'connecting';\n\t self.network.connect(self.autoReconnect, self.reconnectionDelay);\n\t\n\t self.network.onConnect(function () {\n\t self.state = 'connected';\n\t renewAllSubscriptions.call(self);\n\t dequeue.call(self);\n\t self.emitEvent('connected');\n\t\n\t if (self.connectCB) {\n\t self.connectCB(null, self);\n\t }\n\t });\n\t\n\t self.network.on('discarded', function (data) {\n\t self.emitEvent('discarded', data);\n\t });\n\t\n\t self.network.onConnectError(function (error) {\n\t var connectionError = new Error('Unable to connect to kuzzle proxy server at \"' + self.host + ':' + self.port + '\"');\n\t\n\t connectionError.internal = error;\n\t self.state = 'error';\n\t self.emitEvent('networkError', connectionError);\n\t\n\t disableAllSubscriptions.call(self);\n\t\n\t if (self.connectCB) {\n\t self.connectCB(connectionError);\n\t }\n\t });\n\t\n\t self.network.onDisconnect(function () {\n\t self.state = 'offline';\n\t\n\t if (!self.autoReconnect) {\n\t self.disconnect();\n\t }\n\t\n\t if (self.autoQueue) {\n\t self.queuing = true;\n\t }\n\t\n\t self.emitEvent('disconnected');\n\t });\n\t\n\t self.network.onReconnect(function () {\n\t var reconnect = function () {\n\t // renew subscriptions\n\t if (self.autoResubscribe) {\n\t renewAllSubscriptions.call(self);\n\t }\n\t\n\t // replay queued requests\n\t if (self.autoReplay) {\n\t cleanQueue.call(self);\n\t dequeue.call(self);\n\t }\n\t\n\t // alert listeners\n\t self.emitEvent('reconnected');\n\t };\n\t\n\t self.state = 'connected';\n\t\n\t if (self.jwtToken) {\n\t self.checkToken(self.jwtToken, function (err, res) {\n\t // shouldn't obtain an error but let's invalidate the token anyway\n\t if (err || !res.valid) {\n\t self.jwtToken = undefined;\n\t self.emitEvent('tokenExpired');\n\t }\n\t\n\t reconnect();\n\t });\n\t } else {\n\t reconnect();\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Set the jwtToken used to query kuzzle\n\t * @param token\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.setJwtToken = function(token) {\n\t if (typeof token === 'string') {\n\t this.jwtToken = token;\n\t } else if (typeof token === 'object') {\n\t if (token.result && token.result.jwt && typeof token.result.jwt === 'string') {\n\t this.jwtToken = token.result.jwt;\n\t } else {\n\t this.emitEvent('loginAttempt', {\n\t success: false,\n\t error: 'Cannot find a valid JWT token in the following object: ' + JSON.stringify(token)\n\t });\n\t\n\t return this;\n\t }\n\t } else {\n\t this.emitEvent('loginAttempt', {success: false, error: 'Invalid token argument: ' + token});\n\t return this;\n\t }\n\t\n\t renewAllSubscriptions.call(this);\n\t this.emitEvent('loginAttempt', {success: true});\n\t return this;\n\t};\n\t\n\t/**\n\t * Unset the jwtToken used to query kuzzle\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.unsetJwtToken = function() {\n\t this.jwtToken = undefined;\n\t\n\t removeAllSubscriptions.call(this);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Get the jwtToken used by kuzzle\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.getJwtToken = function() {\n\t return this.jwtToken;\n\t};\n\t\n\t/**\n\t * Send login request to kuzzle with credentials\n\t * If login success, store the jwtToken into kuzzle object\n\t *\n\t * @param strategy\n\t * @param credentials\n\t * @param expiresIn\n\t * @param cb\n\t */\n\tKuzzle.prototype.login = function (strategy) {\n\t var\n\t self = this,\n\t request = {\n\t body: {},\n\t strategy: strategy\n\t },\n\t cb = null;\n\t\n\t if (!strategy || typeof strategy !== 'string') {\n\t throw new Error('Kuzzle.login: strategy required');\n\t }\n\t\n\t // Handle arguments (credentials, expiresIn, cb)\n\t if (arguments[1]) {\n\t if (typeof arguments[1] === 'object') {\n\t request.body = arguments[1];\n\t } else if (typeof arguments[1] === 'number' || typeof arguments[1] === 'string') {\n\t request.expiresIn = arguments[1];\n\t } else if (typeof arguments[1] === 'function') {\n\t cb = arguments[1];\n\t }\n\t }\n\t if (arguments[2]) {\n\t if (typeof arguments[2] === 'number' || typeof arguments[2] === 'string') {\n\t request.expiresIn = arguments[2];\n\t } else if (typeof arguments[2] === 'function') {\n\t cb = arguments[2];\n\t }\n\t }\n\t if (arguments[3] && typeof arguments[3] === 'function') {\n\t cb = arguments[3];\n\t }\n\t\n\t this.query({controller: 'auth', action: 'login'}, request, {queuable: false}, function(error, response) {\n\t if (!error) {\n\t if (response.result.jwt) {\n\t self.setJwtToken(response.result.jwt);\n\t }\n\t\n\t cb && cb(null, response.result);\n\t }\n\t else {\n\t cb && cb(error);\n\t self.emitEvent('loginAttempt', {success: false, error: error.message});\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Create credentials of the specified for the current user.\n\t *\n\t * @param credentials\n\t * @param strategy\n\t * @param options\n\t * @param cb\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.createMyCredentials = function (strategy, credentials, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.query({controller: 'auth', action: 'createMyCredentials'}, {strategy: strategy, body: credentials}, options, function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result._source);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete credentials of the specified for the current user.\n\t *\n\t * @param strategy\n\t * @param options\n\t * @param cb\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.deleteMyCredentials = function (strategy, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.query({controller: 'auth', action: 'deleteMyCredentials'}, {strategy: strategy}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Get credential information of the specified for the current user.\n\t *\n\t * @param strategy\n\t * @param options\n\t * @param cb\n\t */\n\tKuzzle.prototype.getMyCredentials = function (strategy, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.query({controller: 'auth', action: 'getMyCredentials'}, {strategy: strategy}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Update credentials of the specified for the current user.\n\t *\n\t * @param strategy\n\t * @param credentals\n\t * @param options\n\t * @param cb\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.updateMyCredentials = function (strategy, credentials, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.query({controller: 'auth', action: 'updateMyCredentials'}, {strategy: strategy, body: credentials}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Validate credentials of the specified for the current user.\n\t *\n\t * @param strategy\n\t * @param credentials\n\t * @param options\n\t * @param cb\n\t */\n\tKuzzle.prototype.validateMyCredentials = function (strategy, credentials, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.query({controller: 'auth', action: 'validateMyCredentials'}, {strategy: strategy, body: credentials}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Create a kuzzle index\n\t *\n\t * @param {string} index\n\t * @param {object} [options]\n\t * @param {responseCallback} cb\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.createIndex = function (index, options, cb) {\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.createIndex: index required');\n\t }\n\t index = this.defaultIndex;\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.query({controller: 'index', action: 'create', index: index}, {}, options, typeof cb !== 'function' ? null : function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Send logout request to kuzzle with jwtToken.\n\t *\n\t * @param cb\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.logout = function (cb) {\n\t var\n\t self = this,\n\t request = {\n\t action: 'logout',\n\t controller: 'auth',\n\t requestId: uuidv4(),\n\t body: {}\n\t };\n\t\n\t this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, typeof cb !== 'function' ? null : function(error) {\n\t cb(error, self);\n\t });\n\t\n\t self.unsetJwtToken();\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Checks whether a given jwt token still represents a valid session in Kuzzle.\n\t *\n\t * @param {string} token The jwt token to check\n\t * @param {function} cb The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t */\n\tKuzzle.prototype.checkToken = function (token, cb) {\n\t var\n\t request = {\n\t body: {\n\t token: token\n\t }\n\t };\n\t\n\t this.callbackRequired('Kuzzle.checkToken', cb);\n\t\n\t this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t};\n\t\n\t/**\n\t * Fetches the current user.\n\t *\n\t * @param {function} cb The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t */\n\tKuzzle.prototype.whoAmI = function (cb) {\n\t var self = this;\n\t\n\t self.callbackRequired('Kuzzle.whoAmI', cb);\n\t\n\t self.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, function (err, res) {\n\t cb(err, err ? undefined : new User(self.security, res.result._id, res.result._source, res.result._meta));\n\t });\n\t};\n\t\n\t/**\n\t * Gets the rights array of the currently logged user.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {function} cb The callback containing the normalized array of rights.\n\t */\n\tKuzzle.prototype.getMyRights = function (options, cb) {\n\t var self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.callbackRequired('Kuzzle.getMyRights', cb);\n\t\n\t self.query({controller: 'auth', action:'getMyRights'}, {}, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.hits);\n\t });\n\t};\n\t\n\t/**\n\t * Update current user in Kuzzle.\n\t *\n\t * @param {object} content - a plain javascript object representing the user's modification\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {Kuzzle} this object\n\t */\n\tKuzzle.prototype.updateSelf = function (content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t queryArgs = {controller: 'auth', action: 'updateSelf'};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data.body = content;\n\t\n\t self.query(queryArgs, data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Clean up the queue, ensuring the queryTTL and queryMaxSize properties are respected\n\t */\n\tfunction cleanQueue () {\n\t var\n\t self = this,\n\t now = Date.now(),\n\t lastDocumentIndex = -1;\n\t\n\t if (self.queueTTL > 0) {\n\t self.offlineQueue.forEach(function (query, index) {\n\t if (query.ts < now - self.queueTTL) {\n\t lastDocumentIndex = index;\n\t }\n\t });\n\t\n\t if (lastDocumentIndex !== -1) {\n\t self.offlineQueue\n\t .splice(0, lastDocumentIndex + 1)\n\t .forEach(function (droppedRequest) {\n\t self.emitEvent('offlineQueuePop', droppedRequest.query);\n\t });\n\t }\n\t }\n\t\n\t if (self.queueMaxSize > 0 && self.offlineQueue.length > self.queueMaxSize) {\n\t self.offlineQueue\n\t .splice(0, self.offlineQueue.length - self.queueMaxSize)\n\t .forEach(function (droppedRequest) {\n\t self.emitEvent('offlineQueuePop', droppedRequest.query);\n\t });\n\t }\n\t}\n\t\n\t\n\t/**\n\t * Clean history from requests made more than 10s ago\n\t */\n\tfunction cleanHistory (requestHistory) {\n\t var\n\t now = Date.now();\n\t\n\t Object.keys(requestHistory).forEach(function (key) {\n\t if (requestHistory[key] < now - 10000) {\n\t delete requestHistory[key];\n\t }\n\t });\n\t}\n\t\n\t/**\n\t * Emit a request to Kuzzle\n\t *\n\t * @param {object} request\n\t * @param {responseCallback} [cb]\n\t */\n\tfunction emitRequest (request, cb) {\n\t var\n\t self = this;\n\t\n\t if (self.jwtToken !== undefined || cb) {\n\t self.network.once(request.requestId, function (response) {\n\t var error = null;\n\t\n\t if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n\t self.jwtToken = undefined;\n\t self.emitEvent('tokenExpired', request, cb);\n\t }\n\t\n\t if (response.error) {\n\t error = new Error(response.error.message);\n\t Object.assign(error, response.error);\n\t error.status = response.status;\n\t self.emitEvent('queryError', error, request, cb);\n\t }\n\t\n\t if (cb) {\n\t cb(error, response);\n\t }\n\t });\n\t }\n\t\n\t this.network.send(request);\n\t\n\t // Track requests made to allow Room.subscribeToSelf to work\n\t self.requestHistory[request.requestId] = Date.now();\n\t}\n\t\n\t/**\n\t * Play all queued requests, in order.\n\t */\n\tfunction dequeue () {\n\t var\n\t self = this,\n\t additionalQueue,\n\t uniqueQueue = {},\n\t dequeuingProcess = function () {\n\t if (self.offlineQueue.length > 0) {\n\t emitRequest.call(self, self.offlineQueue[0].query, self.offlineQueue[0].cb);\n\t self.emitEvent('offlineQueuePop', self.offlineQueue.shift());\n\t\n\t setTimeout(function () {\n\t dequeuingProcess();\n\t }, Math.max(0, self.replayInterval));\n\t } else {\n\t self.queuing = false;\n\t }\n\t };\n\t\n\t if (self.offlineQueueLoader) {\n\t if (typeof self.offlineQueueLoader !== 'function') {\n\t throw new Error('Invalid value for offlineQueueLoader property. Expected: function. Got: ' + typeof self.offlineQueueLoader);\n\t }\n\t\n\t additionalQueue = self.offlineQueueLoader();\n\t if (Array.isArray(additionalQueue)) {\n\t self.offlineQueue = additionalQueue\n\t .concat(self.offlineQueue)\n\t .filter(function (request) {\n\t // throws if the query object does not contain required attributes\n\t if (!request.query || request.query.requestId === undefined || !request.query.action || !request.query.controller) {\n\t throw new Error('Invalid offline queue request. One or more missing properties: requestId, action, controller.');\n\t }\n\t\n\t return uniqueQueue.hasOwnProperty(request.query.requestId) ? false : (uniqueQueue[request.query.requestId] = true);\n\t });\n\t } else {\n\t throw new Error('Invalid value returned by the offlineQueueLoader function. Expected: array. Got: ' + typeof additionalQueue);\n\t }\n\t }\n\t\n\t dequeuingProcess();\n\t}\n\t\n\t/**\n\t * Renew all registered subscriptions. Triggered either by a successful connection/reconnection or by a\n\t * successful login attempt\n\t */\n\tfunction renewAllSubscriptions() {\n\t var self = this;\n\t\n\t Object.keys(self.subscriptions).forEach(function (roomId) {\n\t Object.keys(self.subscriptions[roomId]).forEach(function (subscriptionId) {\n\t var subscription = self.subscriptions[roomId][subscriptionId];\n\t subscription.renew(subscription.callback);\n\t });\n\t });\n\t}\n\t\n\t/**\n\t * Remove all registered subscriptions. Triggered either by a logout query or by un-setting the token\n\t */\n\tfunction removeAllSubscriptions() {\n\t var self = this;\n\t\n\t Object.keys(self.subscriptions).forEach(function (roomId) {\n\t Object.keys(self.subscriptions[roomId]).forEach(function (subscriptionId) {\n\t var subscription = self.subscriptions[roomId][subscriptionId];\n\t subscription.unsubscribe();\n\t });\n\t });\n\t}\n\t\n\t/**\n\t * Adds a listener to a Kuzzle global event. When an event is fired, listeners are called in the order of their\n\t * insertion.\n\t *\n\t * @param {string} event - name of the global event to subscribe to\n\t * @param {function} listener - callback to invoke each time an event is fired\n\t */\n\tKuzzle.prototype.addListener = function(event, listener) {\n\t this.isValid();\n\t\n\t if (this.eventActions.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + this.eventActions.toString());\n\t }\n\t\n\t return KuzzleEventEmitter.prototype.addListener.call(this, event, listener);\n\t};\n\t\n\t/**\n\t * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n\t * This method returns all available statistics from Kuzzle.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.getAllStatistics = function (options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.getAllStatistics', cb);\n\t\n\t this.query({controller:'server', action: 'getAllStats'}, {}, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.hits);\n\t });\n\t};\n\t\n\t/**\n\t * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n\t * This method allows getting either the last statistics frame, or a set of frames starting from a provided timestamp.\n\t *\n\t * @param {number} timestamp - Epoch time. Starting time from which the frames are to be retrieved\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.getStatistics = function (timestamp, options, cb) {\n\t var\n\t queryCB,\n\t body;\n\t\n\t if (!cb) {\n\t if (arguments.length === 1) {\n\t cb = arguments[0];\n\t options = null;\n\t timestamp = null;\n\t } else {\n\t cb = arguments[1];\n\t if (typeof arguments[0] === 'object') {\n\t options = arguments[0];\n\t timestamp = null;\n\t } else {\n\t timestamp = arguments[0];\n\t options = null;\n\t }\n\t }\n\t }\n\t\n\t queryCB = function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, timestamp ? res.result.hits : [res.result]);\n\t };\n\t\n\t this.callbackRequired('Kuzzle.getStatistics', cb);\n\t\n\t body = timestamp ? {body: {startTime: timestamp}} : {};\n\t this.query({controller: 'server', action: timestamp ? 'getStats' : 'getLastStats'}, body, options, queryCB);\n\t};\n\t\n\t/**\n\t * Create a new instance of a Collection object.\n\t * If no index is specified, takes the default index.\n\t *\n\t * @param {string} collection - The name of the data collection you want to manipulate\n\t * @param {string} [index] - The name of the data index containing the data collection\n\t * @returns {Collection} A Collection instance\n\t */\n\tKuzzle.prototype.collection = function(collection, index) {\n\t this.isValid();\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Unable to create a new data collection object: no index specified');\n\t }\n\t\n\t index = this.defaultIndex;\n\t }\n\t\n\t if (typeof index !== 'string' || typeof collection !== 'string') {\n\t throw new Error('Invalid index or collection argument: string expected');\n\t }\n\t\n\t if (!this.collections[index]) {\n\t this.collections[index] = {};\n\t }\n\t\n\t if (!this.collections[index][collection]) {\n\t this.collections[index][collection] = new Collection(this, collection, index);\n\t }\n\t\n\t return this.collections[index][collection];\n\t};\n\t\n\t/**\n\t * Empties the offline queue without replaying it.\n\t *\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.flushQueue = function () {\n\t this.offlineQueue = [];\n\t return this;\n\t};\n\t\n\t/**\n\t * Returns the list of known persisted data collections.\n\t *\n\t * @param {string} [index] - Index containing collections to be listed\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.listCollections = function () {\n\t var\n\t index,\n\t options,\n\t cb,\n\t args = Array.prototype.slice.call(arguments),\n\t query;\n\t\n\t args.forEach(function(arg) {\n\t switch (typeof arg) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t });\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.listCollections: index required');\n\t }\n\t\n\t index = this.defaultIndex;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.listCollections', cb);\n\t\n\t query = {type: options && options.type || 'all'};\n\t\n\t this.query({index: index, controller: 'collection', action: 'list'}, query, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.collections);\n\t });\n\t};\n\t\n\t/**\n\t * Returns the list of existing indexes in Kuzzle\n\t *\n\t * @param {object} [options] - Optional arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.listIndexes = function (options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.listIndexes', cb);\n\t\n\t this.query({controller: 'index', action: 'list'}, {}, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.indexes);\n\t });\n\t};\n\t\n\t/**\n\t * Disconnects from Kuzzle and invalidate this instance.\n\t */\n\tKuzzle.prototype.disconnect = function () {\n\t var collection;\n\t\n\t clearInterval(this.cleanHistoryTimer);\n\t this.state = 'disconnected';\n\t this.network.close();\n\t this.network = null;\n\t\n\t for (collection in this.collections) {\n\t if (this.collections.hasOwnProperty(collection)) {\n\t delete this.collections[collection];\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Returns the server informations\n\t *\n\t * @param {object} [options] - Optional arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.getServerInfo = function (options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.getServerInfo', cb);\n\t\n\t this.query({controller: 'server', action: 'info'}, {}, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.serverInfo);\n\t });\n\t};\n\t\n\t/**\n\t * Forces an index refresh\n\t *\n\t * @param {string} index - The index to refresh. Defaults to Kuzzle.defaultIndex\n\t * @param {object} options - Optional arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.refreshIndex = function () {\n\t var\n\t index,\n\t options,\n\t cb;\n\t\n\t Array.prototype.slice.call(arguments).forEach(function(arg) {\n\t switch (typeof arg) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t });\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.refreshIndex: index required');\n\t }\n\t index = this.defaultIndex;\n\t }\n\t\n\t this.query({ index: index, controller: 'index', action: 'refresh'}, {}, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Returns de current autoRefresh status for the given index\n\t *\n\t * @param {string} index - The index to get the status from. Defaults to Kuzzle.defaultIndex\n\t * @param {object} options - Optinal arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.getAutoRefresh = function () {\n\t var\n\t index,\n\t options,\n\t cb;\n\t\n\t Array.prototype.slice.call(arguments).forEach(function (arg) {\n\t switch (typeof arg) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t });\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.getAutoRefresh: index required');\n\t }\n\t index = this.defaultIndex;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.getAutoRefresh', cb);\n\t this.query({ index: index, controller: 'index', action: 'getAutoRefresh'}, {}, options, cb);\n\t};\n\t\n\t/**\n\t * (Un)Sets the autoRefresh flag on the given index\n\t *\n\t * @param {string} index - the index to modify. Defaults to Kuzzle.defaultIndex\n\t * @param {boolean} autoRefresh - The autoRefresh value to set\n\t * @param {object} options - Optional arguments\n\t * @param {responseCallback} cb - Handles the query result\n\t * @returns {object} this\n\t */\n\tKuzzle.prototype.setAutoRefresh = function () {\n\t var\n\t index,\n\t autoRefresh,\n\t options,\n\t cb;\n\t\n\t Array.prototype.slice.call(arguments).forEach(function (arg) {\n\t switch (typeof arg) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'boolean':\n\t autoRefresh = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t });\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.setAutoRefresh: index required');\n\t }\n\t index = this.defaultIndex;\n\t }\n\t\n\t if (autoRefresh === undefined) {\n\t throw new Error('Kuzzle.setAutoRefresh: autoRefresh value is required');\n\t }\n\t\n\t this.query({ index: index, controller: 'index', action: 'setAutoRefresh'}, { body: { autoRefresh: autoRefresh }}, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Return the current Kuzzle's UTC Epoch time, in milliseconds\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tKuzzle.prototype.now = function (options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.now', cb);\n\t\n\t this.query({controller: 'server', action: 'now'}, {}, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.now);\n\t });\n\t};\n\t\n\t/**\n\t * This is a low-level method, exposed to allow advanced SDK users to bypass high-level methods.\n\t * Base method used to send read queries to Kuzzle\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} queryArgs - Query configuration\n\t * @param {object} query - The query data\n\t * @param {object} [options] - Optional arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzle.prototype.query = function (queryArgs, query, options, cb) {\n\t var\n\t attr,\n\t object = {\n\t action: queryArgs.action,\n\t controller: queryArgs.controller,\n\t volatile: this.volatile\n\t },\n\t self = this;\n\t\n\t this.isValid();\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (options) {\n\t if (options.queuable === false && self.state === 'offline') {\n\t return self;\n\t }\n\t\n\t if (options.refresh) {\n\t object.refresh = options.refresh;\n\t }\n\t\n\t if (typeof options.from !== 'undefined' && options.from !== null) {\n\t object.from = options.from;\n\t }\n\t\n\t if (options.size) {\n\t object.size = options.size;\n\t }\n\t\n\t if (options.scroll) {\n\t object.scroll = options.scroll;\n\t }\n\t\n\t if (options.scrollId) {\n\t object.scrollId = options.scrollId;\n\t }\n\t\n\t if (options.volatile) {\n\t Object.keys(options.volatile).forEach(function (meta) {\n\t object.volatile[meta] = options.volatile[meta];\n\t });\n\t }\n\t }\n\t\n\t if (!query || typeof query !== 'object' || Array.isArray(query)) {\n\t throw new Error('Invalid query parameter: ' + query);\n\t }\n\t\n\t if (query.volatile) {\n\t Object.keys(query.volatile).forEach(function (meta) {\n\t object.volatile[meta] = query.volatile[meta];\n\t });\n\t }\n\t\n\t for (attr in query) {\n\t if (attr !== 'volatile' && query.hasOwnProperty(attr)) {\n\t object[attr] = query[attr];\n\t }\n\t }\n\t\n\t object = self.addHeaders(object, this.headers);\n\t\n\t /*\n\t * Do not add the token for the checkToken route, to avoid getting a token error when\n\t * a developer simply wish to verify his token\n\t */\n\t if (self.jwtToken !== undefined && !(object.controller === 'auth' && object.action === 'checkToken')) {\n\t object.jwt = self.jwtToken;\n\t }\n\t\n\t if (queryArgs.collection) {\n\t object.collection = queryArgs.collection;\n\t }\n\t\n\t if (queryArgs.index) {\n\t object.index = queryArgs.index;\n\t }\n\t\n\t if (!object.requestId) {\n\t object.requestId = uuidv4();\n\t }\n\t\n\t object.volatile.sdkVersion = this.sdkVersion;\n\t\n\t if (self.state === 'connected' || (options && options.queuable === false)) {\n\t if (self.state === 'connected') {\n\t emitRequest.call(this, object, cb);\n\t } else {\n\t discardRequest(object, cb);\n\t }\n\t } else if (self.queuing || (options && options.queuable === true) || ['initializing', 'connecting'].indexOf(self.state) !== -1) {\n\t cleanQueue.call(this, object, cb);\n\t if (!self.queueFilter || self.queueFilter(object)) {\n\t self.offlineQueue.push({ts: Date.now(), query: object, cb: cb});\n\t self.emitEvent('offlineQueuePush', {query: object, cb: cb});\n\t } else {\n\t discardRequest(object, cb);\n\t }\n\t }\n\t else {\n\t discardRequest(object, cb);\n\t }\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Replays the requests queued during offline mode.\n\t * Works only if the SDK is not in a disconnected state, and if the autoReplay option is set to false.\n\t */\n\tKuzzle.prototype.replayQueue = function () {\n\t if (this.state !== 'offline' && !this.autoReplay) {\n\t cleanQueue.call(this);\n\t dequeue.call(this);\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Sets the default Kuzzle index\n\t *\n\t * @param index\n\t * @returns this\n\t */\n\tKuzzle.prototype.setDefaultIndex = function (index) {\n\t if (typeof index !== 'string') {\n\t throw new Error('Invalid default index: [' + index + '] (an index name is expected)');\n\t }\n\t\n\t if (index.length === 0) {\n\t throw new Error('Cannot set an empty index as the default index');\n\t }\n\t\n\t this.defaultIndex = index;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Helper function allowing to set headers while chaining calls.\n\t *\n\t * If the replace argument is set to true, replace the current headers with the provided content.\n\t * Otherwise, it appends the content to the current headers, only replacing already existing values\n\t *\n\t * @param content - new headers content\n\t * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n\t */\n\tKuzzle.prototype.setHeaders = function (content, replace) {\n\t var self = this;\n\t\n\t if (typeof content !== 'object' || Array.isArray(content)) {\n\t throw new Error('Expected a content object, received a ' + typeof content);\n\t }\n\t\n\t if (replace) {\n\t self.headers = content;\n\t } else {\n\t Object.keys(content).forEach(function (key) {\n\t self.headers[key] = content[key];\n\t });\n\t }\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Starts the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n\t */\n\tKuzzle.prototype.startQueuing = function () {\n\t if (this.state === 'offline' && !this.autoQueue) {\n\t this.queuing = true;\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Stops the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n\t */\n\tKuzzle.prototype.stopQueuing = function () {\n\t if (this.state === 'offline' && !this.autoQueue) {\n\t this.queuing = false;\n\t }\n\t\n\t return this;\n\t};\n\t\n\tfunction discardRequest(object, cb) {\n\t if (cb) {\n\t cb(new Error('Unable to execute request: not connected to a Kuzzle server.\\nDiscarded request: ' + JSON.stringify(object)));\n\t }\n\t}\n\t\n\tfunction disableAllSubscriptions() {\n\t var self = this;\n\t\n\t Object.keys(self.subscriptions).forEach(function (roomId) {\n\t Object.keys(self.subscriptions[roomId]).forEach(function (subscriptionId) {\n\t var subscription = self.subscriptions[roomId][subscriptionId];\n\t subscription.subscribing = false;\n\t });\n\t });\n\t}\n\t\n\tmodule.exports = Kuzzle;\n\n\n/***/ }),\n/* 1 */\n/***/ (function(module, exports) {\n\n\tfunction SecurityDocument(Security, id, content, meta) {\n\t\n\t if (!id) {\n\t throw new Error('A security document must have an id');\n\t }\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t kuzzle: {\n\t value: Security.kuzzle\n\t },\n\t Security: {\n\t value: Security\n\t },\n\t // read-only properties\n\t // writable properties\n\t id: {\n\t value: id,\n\t enumerable: true\n\t },\n\t content: {\n\t value: {},\n\t writable: true,\n\t enumerable: true\n\t },\n\t meta: {\n\t value: meta || {},\n\t writable: true,\n\t enumerable: true\n\t }\n\t });\n\t\n\t if (content) {\n\t this.setContent(content, true);\n\t }\n\t\n\t // promisifying\n\t if (Security.kuzzle.bluebird) {\n\t return Security.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['delete', 'update'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t}\n\t\n\t/**\n\t * Replaces the current content with new data.\n\t * Changes made by this function won’t be applied until the save method is called.\n\t *\n\t * @param {Object} data - New securityDocument content\n\t * @return {SecurityDocument} this\n\t */\n\tSecurityDocument.prototype.setContent = function (data) {\n\t this.content = data;\n\t return this;\n\t};\n\t\n\t/**\n\t * Serialize this object into a pojo\n\t *\n\t * @return {object} pojo representing this securityDocument\n\t */\n\tSecurityDocument.prototype.serialize = function () {\n\t var\n\t data = {};\n\t\n\t if (this.id) {\n\t data._id = this.id;\n\t }\n\t\n\t data.body = this.content;\n\t data.meta = this.meta;\n\t\n\t return data;\n\t};\n\t\n\t/**\n\t * Delete the current KuzzleSecurityDocument into Kuzzle.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tSecurityDocument.prototype.delete = function (options, cb) {\n\t var\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.Security.buildQueryArgs(this.deleteActionName), {_id: this.id}, options, function (error, res) {\n\t if (error) {\n\t return cb ? cb(error) : false;\n\t }\n\t\n\t if (cb) {\n\t cb(null, res.result._id);\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Update the current KuzzleSecurityDocument into Kuzzle.\n\t *\n\t * @param {object} content - Content to add to KuzzleSecurityDocument\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {SecurityDocument} this\n\t */\n\tSecurityDocument.prototype.update = function (content, options, cb) {\n\t var\n\t data = {},\n\t self = this;\n\t\n\t if (typeof content !== 'object') {\n\t throw new Error('Parameter \"content\" must be a object');\n\t }\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = self.id;\n\t data.body = content;\n\t\n\t self.kuzzle.query(this.Security.buildQueryArgs(this.updateActionName), data, options, function (error, response) {\n\t if (error) {\n\t return cb ? cb(error) : false;\n\t }\n\t\n\t self.setContent(response.result._source);\n\t\n\t if (cb) {\n\t cb(null, self);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\tmodule.exports = SecurityDocument;\n\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports) {\n\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t/**\n\t * Kuzzle handles documents either as realtime messages or as stored documents.\n\t * Document is the object representation of one of these documents.\n\t *\n\t * Notes:\n\t * - this constructor may be called either with a documentId, a content, neither or both.\n\t * - providing a documentID to the constructor will automatically call refresh, unless a content is also provided\n\t *\n\t *\n\t * @param {Collection} collection - an instanciated Collection object\n\t * @param {string} [documentId] - ID of an existing document\n\t * @param {object} [content] - Initializes this document with the provided content\n\t * @param {object} [meta] - Initializes this document with the provided meta\n\t * @constructor\n\t */\n\tfunction Document(collection, documentId, content, meta) {\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t collection: {\n\t value: collection.collection,\n\t enumerable: true\n\t },\n\t dataCollection: {\n\t value: collection,\n\t enumerable: false\n\t },\n\t kuzzle: {\n\t value: collection.kuzzle,\n\t enumerable: false\n\t },\n\t // writable properties\n\t id: {\n\t value: undefined,\n\t enumerable: true,\n\t writable: true\n\t },\n\t content: {\n\t value: {},\n\t writable: true,\n\t enumerable: true\n\t },\n\t headers: {\n\t value: JSON.parse(JSON.stringify(collection.headers)),\n\t enumerable: true,\n\t writable: true\n\t },\n\t version: {\n\t value: undefined,\n\t enumerable: true,\n\t writable: true\n\t },\n\t meta: {\n\t value: meta || {},\n\t enumerable: true,\n\t writable: false\n\t }\n\t });\n\t\n\t // handling provided arguments\n\t if (!content && documentId && typeof documentId === 'object') {\n\t content = documentId;\n\t documentId = null;\n\t }\n\t\n\t if (content) {\n\t if (content._version) {\n\t this.version = content._version;\n\t delete content._version;\n\t }\n\t this.setContent(content, true);\n\t }\n\t\n\t if (documentId) {\n\t Object.defineProperty(this, 'id', {\n\t value: documentId,\n\t enumerable: true\n\t });\n\t }\n\t\n\t // promisifying\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['delete', 'refresh', 'save'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * Serialize this object into a JSON object\n\t *\n\t * @return {object} JSON object representing this document\n\t */\n\tDocument.prototype.serialize = function () {\n\t var\n\t data = {};\n\t\n\t if (this.id) {\n\t data._id = this.id;\n\t }\n\t\n\t if (this.version) {\n\t data._version = this.version;\n\t }\n\t\n\t data.body = this.content;\n\t data.meta = this.meta;\n\t data = this.kuzzle.addHeaders(data, this.headers);\n\t\n\t return data;\n\t};\n\t\n\t/**\n\t * Overrides the toString() method in order to return a serialized version of the document\n\t *\n\t * @return {string} serialized version of this object\n\t */\n\tDocument.prototype.toString = function () {\n\t return JSON.stringify(this.serialize());\n\t};\n\t\n\t/**\n\t * Deletes this document in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tDocument.prototype.delete = function (options, cb) {\n\t var self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!self.id) {\n\t throw new Error('Document.delete: cannot delete a document without a document ID');\n\t }\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('document', 'delete'), this.serialize(), options, cb && function (err) {\n\t cb(err, err ? undefined : self.id);\n\t });\n\t};\n\t\n\t/**\n\t * Checks if this document exists in Kuzzle.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tDocument.prototype.exists = function (options, cb) {\n\t var self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!self.id) {\n\t throw new Error('Document.exists: cannot check if the document exists if no id has been provided');\n\t }\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('document', 'exists'), this.serialize(), options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t};\n\t\n\t/**\n\t * Replaces the current content with the last version of this document stored in Kuzzle.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tDocument.prototype.refresh = function (options, cb) {\n\t var self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!self.id) {\n\t throw new Error('Document.refresh: cannot retrieve a document if no ID has been provided');\n\t }\n\t\n\t this.kuzzle.callbackRequired('Document.refresh', cb);\n\t\n\t self.kuzzle.query(self.dataCollection.buildQueryArgs('document', 'get'), {_id: self.id}, options, function (error, res) {\n\t var newDocument;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t newDocument = new Document(self.dataCollection, self.id, res.result._source, res.result._meta);\n\t newDocument.version = res.result._version;\n\t\n\t cb(null, newDocument);\n\t });\n\t};\n\t\n\t/**\n\t * Saves this document into Kuzzle.\n\t *\n\t * If this is a new document, this function will create it in Kuzzle and the id property will be made available.\n\t * Otherwise, this method will replace the latest version of this document in Kuzzle by the current content\n\t * of this object.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tDocument.prototype.save = function (options, cb) {\n\t var\n\t data = this.serialize(),\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.dataCollection.buildQueryArgs('document', 'createOrReplace'), data, options, function (error, res) {\n\t if (error) {\n\t return cb && cb(error);\n\t }\n\t\n\t self.id = res.result._id;\n\t self.version = res.result._version;\n\t\n\t if (cb) {\n\t cb(null, self);\n\t }\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Sends the content of this document as a realtime message.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @returns {*} this\n\t */\n\tDocument.prototype.publish = function (options) {\n\t var data = this.serialize();\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('realtime', 'publish'), data, options);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Replaces the current content with new data.\n\t * Changes made by this function won’t be applied until the save method is called.\n\t *\n\t * @param {object} data - New content\n\t * @param {boolean} replace - if true: replace this document content with the provided data\n\t */\n\tDocument.prototype.setContent = function (data, replace) {\n\t var self = this;\n\t\n\t if (replace) {\n\t this.content = data;\n\t }\n\t else {\n\t Object.keys(data).forEach(function (key) {\n\t self.content[key] = data[key];\n\t });\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Listens to events concerning this document. Has no effect if the document does not have an ID\n\t * (i.e. if the document has not yet been created as a persisted document).\n\t *\n\t * @param {object} [options] - subscription options\n\t * @param {responseCallback} cb - callback that will be called each time a change has been detected on this document\n\t */\n\tDocument.prototype.subscribe = function (options, cb) {\n\t var filters;\n\t\n\t if (options && !cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('Document.subscribe', cb);\n\t\n\t if (!this.id) {\n\t throw new Error('Document.subscribe: cannot subscribe to a document if no ID has been provided');\n\t }\n\t\n\t filters = { ids: { values: [this.id] } };\n\t\n\t return this.dataCollection.subscribe(filters, options, cb);\n\t};\n\t\n\t/**\n\t * Helper function allowing to set headers while chaining calls.\n\t *\n\t * If the replace argument is set to true, replace the current headers with the provided content.\n\t * Otherwise, it appends the content to the current headers, only replacing already existing values\n\t *\n\t * @param content - new headers content\n\t * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n\t */\n\tDocument.prototype.setHeaders = function (content, replace) {\n\t this.kuzzle.setHeaders.call(this, content, replace);\n\t return this;\n\t};\n\t\n\t\n\tmodule.exports = Document;\n\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tfunction KuzzleEventEmitter() {\n\t if (typeof window !== 'undefined') {\n\t this._events = {};\n\t this._onceEvents = {};\n\t }\n\t}\n\t\n\tif (typeof window === 'undefined') {\n\t KuzzleEventEmitter.prototype = __webpack_require__(18).prototype;\n\t KuzzleEventEmitter.prototype.constructor = KuzzleEventEmitter;\n\t} else {\n\t\n\t KuzzleEventEmitter.prototype.on = function(eventName, listener) {\n\t var\n\t listenerType = typeof listener,\n\t listeners;\n\t\n\t if (!eventName || !listener) {\n\t return;\n\t }\n\t\n\t if (listenerType !== 'function') {\n\t throw new Error('Invalid listener type: expected a function, got a ' + listenerType);\n\t }\n\t\n\t listeners = this.listeners(eventName);\n\t // only add once\n\t if (listeners.indexOf(listener) === -1) {\n\t listeners.push(listener);\n\t }\n\t\n\t // Handles `newListener` event (see https://nodejs.org/api/events.html#events_event_newlistener)\n\t this.emit('newListener', eventName, listener);\n\t\n\t return this;\n\t };\n\t KuzzleEventEmitter.prototype.addListener = KuzzleEventEmitter.prototype.on;\n\t\n\t KuzzleEventEmitter.prototype.prependListener = function(eventName, listener) {\n\t var listeners;\n\t\n\t if (!eventName || !listener) {\n\t return;\n\t }\n\t\n\t listeners = this.listeners(eventName);\n\t // only add once\n\t if (listeners.indexOf(listener) === -1) {\n\t this._events[eventName] = new Array(listener).concat(listeners);\n\t }\n\t\n\t // Handles `newListener` event (see https://nodejs.org/api/events.html#events_event_newlistener)\n\t this.emit('newListener', eventName, listener);\n\t\n\t return this;\n\t };\n\t\n\t KuzzleEventEmitter.prototype.once = function(eventName, listener) {\n\t var onceListeners;\n\t\n\t if (!eventName || !listener) {\n\t return;\n\t }\n\t\n\t\n\t this.on(eventName, listener);\n\t onceListeners = this._onceEvents[eventName] = this._onceEvents[eventName] || {};\n\t onceListeners[listener] = true;\n\t\n\t return this;\n\t };\n\t\n\t KuzzleEventEmitter.prototype.prependOnceListener = function(eventName, listener) {\n\t var onceListeners;\n\t\n\t if (!eventName || !listener) {\n\t return;\n\t }\n\t this.prependListener(eventName, listener);\n\t onceListeners = this._onceEvents[eventName] = this._onceEvents[eventName] || {};\n\t onceListeners[listener] = true;\n\t\n\t return this;\n\t };\n\t\n\t KuzzleEventEmitter.prototype.removeListener = function(eventName, listener) {\n\t var\n\t index,\n\t listeners = this._events[eventName];\n\t\n\t if (!listeners || !listeners.length) {\n\t return;\n\t }\n\t\n\t index = listeners.indexOf(listener);\n\t if (index !== -1) {\n\t listeners.splice(index, 1);\n\t }\n\t if (listeners.length === 0) {\n\t delete this._events[eventName];\n\t }\n\t\n\t // Handles `removeListener` event (see https://nodejs.org/api/events.html#events_event_removeListener)\n\t this.emit('removeListener', eventName, listener);\n\t\n\t return this;\n\t };\n\t\n\t KuzzleEventEmitter.prototype.removeAllListeners = function(eventName) {\n\t if (eventName) {\n\t delete this._events[eventName];\n\t delete this._onceEvents[eventName];\n\t } else {\n\t this._events = [];\n\t this._onceEvents = [];\n\t }\n\t\n\t return this;\n\t };\n\t\n\t KuzzleEventEmitter.prototype.emit = function(eventName) {\n\t var\n\t i = 0,\n\t listeners,\n\t args,\n\t onceListeners,\n\t notifyList;\n\t\n\t listeners = this._events && this._events[eventName];\n\t\n\t if (!listeners || !listeners.length) {\n\t return;\n\t }\n\t\n\t args = Array.prototype.slice.call(arguments, 1);\n\t // once stuff\n\t onceListeners = this._onceEvents && this._onceEvents[eventName] || {};\n\t\n\t notifyList = new Array();\n\t\n\t listener = listeners[i];\n\t while (listener) {\n\t // trigger listener\n\t notifyList.push(listener);\n\t // get next listener\n\t if (onceListeners[listener]) {\n\t // remove listener\n\t this.removeListener(eventName,listener);\n\t // unset once flag\n\t delete onceListeners[listener];\n\t } else {\n\t i++;\n\t }\n\t listener = listeners[i];\n\t }\n\t for (item in notifyList) {\n\t // trigger listener\n\t if (notifyList[item] !== undefined) {\n\t notifyList[item].apply(this, args);\n\t }\n\t }\n\t\n\t return this;\n\t };\n\t\n\t KuzzleEventEmitter.prototype.eventNames = function () {\n\t return Object.keys(this._events);\n\t };\n\t\n\t KuzzleEventEmitter.prototype.listenerCount = function (eventName) {\n\t return this._events[eventName] && this._events[eventName].length || 0;\n\t };\n\t\n\t KuzzleEventEmitter.prototype.listeners = function (eventName) {\n\t if (this._events[eventName] === undefined) {\n\t this._events[eventName] = [];\n\t }\n\t return this._events[eventName];\n\t };\n\t\n\t}\n\t// Aliases:\n\tKuzzleEventEmitter.prototype.emitEvent = KuzzleEventEmitter.prototype.emit;\n\tKuzzleEventEmitter.prototype.off = KuzzleEventEmitter.prototype.removeListener;\n\t\n\tmodule.exports = KuzzleEventEmitter;\n\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleEventEmitter = __webpack_require__(3);\n\t\n\tfunction WSNode(host, port, ssl) {\n\t var self = this;\n\t KuzzleEventEmitter.call(this);\n\t\n\t this.WebSocket = typeof WebSocket !== 'undefined' ? WebSocket : __webpack_require__(!(function webpackMissingModule() { var e = new Error(\"Cannot find module \\\"ws\\\"\"); e.code = 'MODULE_NOT_FOUND'; throw e; }()));\n\t this.host = host;\n\t this.port = port;\n\t this.ssl = ssl;\n\t this.client = null;\n\t this.wasConnected = false;\n\t this.retrying = false;\n\t this.lasturl = null;\n\t this.stopRetryingToConnect = false;\n\t\n\t /**\n\t * Creates a new socket from the provided arguments\n\t *\n\t * @constructor\n\t * @param {boolean} autoReconnect\n\t * @param {int} reconnectionDelay\n\t * @returns {Object} Socket\n\t */\n\t this.connect = function (autoReconnect, reconnectionDelay) {\n\t var\n\t url = (this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port,\n\t options = typeof window !== 'undefined' ? undefined : {perMessageDeflate: false};\n\t\n\t if (url !== this.lasturl) {\n\t self.wasConnected = false;\n\t this.lasturl = url;\n\t }\n\t\n\t this.client = new this.WebSocket(url, options);\n\t\n\t this.client.onopen = function () {\n\t if (self.wasConnected) {\n\t self.emitEvent('reconnect');\n\t }\n\t else {\n\t self.emitEvent('connect');\n\t }\n\t self.wasConnected = true;\n\t self.stopRetryingToConnect = false;\n\t };\n\t\n\t this.client.onclose = function (closeEvent, message) {\n\t var error;\n\t var status;\n\t var reason = message;\n\t\n\t if (typeof closeEvent === 'number') {\n\t status = closeEvent;\n\t }\n\t else {\n\t status = closeEvent.code;\n\t\n\t if (closeEvent.reason) {\n\t reason = closeEvent.reason;\n\t }\n\t }\n\t\n\t if (status === 1000) {\n\t self.emitEvent('disconnect');\n\t }\n\t else {\n\t error = new Error(reason);\n\t error.status = status;\n\t\n\t onClientNetworkError(self, autoReconnect, reconnectionDelay, error);\n\t }\n\t };\n\t\n\t this.client.onerror = function (error) {\n\t if (!(error instanceof Error)) {\n\t error = new Error(error);\n\t }\n\t\n\t onClientNetworkError(self, autoReconnect, reconnectionDelay, error);\n\t };\n\t\n\t this.client.onmessage = function (payload) {\n\t var data = JSON.parse(payload.data || payload);\n\t\n\t if (data.room) {\n\t self.emitEvent(data.room, data);\n\t }\n\t else {\n\t self.emitEvent('discarded', data);\n\t }\n\t };\n\t };\n\t\n\t /**\n\t * Fires the provided callback whence a connection is established\n\t *\n\t * @param {function} callback\n\t */\n\t this.onConnect = function (callback) {\n\t this.addListener('connect', callback);\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a connection error is received\n\t * @param {function} callback\n\t */\n\t this.onConnectError = function (callback) {\n\t this.addListener('networkError', callback);\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a disconnection occurred\n\t * @param {function} callback\n\t */\n\t this.onDisconnect = function (callback) {\n\t this.addListener('disconnect', callback);\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a connection has been reestablished\n\t * @param {function} callback\n\t */\n\t this.onReconnect = function (callback) {\n\t this.addListener('reconnect', callback);\n\t };\n\t\n\t /**\n\t * Sends a payload to the connected server\n\t *\n\t * @param {Object} payload\n\t */\n\t this.send = function (payload) {\n\t if (this.client && this.client.readyState === this.client.OPEN) {\n\t this.client.send(JSON.stringify(payload));\n\t }\n\t };\n\t\n\t /**\n\t * Closes the connection\n\t */\n\t this.close = function () {\n\t this.removeAllListeners();\n\t this.wasConnected = false;\n\t this.client.close();\n\t this.client = null;\n\t self.stopRetryingToConnect = true;\n\t };\n\t}\n\tWSNode.prototype = Object.create(KuzzleEventEmitter.prototype);\n\tWSNode.prototype.constructor = WSNode;\n\t\n\t\n\t/**\n\t * Called when the connection closes with an error state\n\t *\n\t * @param {WSNode} \n\t * @param {boolean} autoReconnect\n\t * @param {number} reconnectionDelay\n\t * @param {Error} error\n\t */\n\tfunction onClientNetworkError(ws, autoReconnect, reconnectionDelay, error) {\n\t if (autoReconnect && !ws.retrying && !ws.stopRetryingToConnect) {\n\t ws.retrying = true;\n\t setTimeout(function () {\n\t ws.retrying = false;\n\t ws.connect(autoReconnect, reconnectionDelay);\n\t }, reconnectionDelay);\n\t }\n\t\n\t ws.emitEvent('networkError', error);\n\t}\n\t\n\tmodule.exports = WSNode;\n\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\t/**\n\t * @param {Security} Security\n\t * @param {string} id\n\t * @param {Object} content\n\t * @constructor\n\t */\n\tfunction User(Security, id, content, meta) {\n\t KuzzleSecurityDocument.call(this, Security, id, content, meta);\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t deleteActionName: {\n\t value: 'deleteUser'\n\t },\n\t updateActionName: {\n\t value: 'updateUser'\n\t },\n\t credentials: {\n\t value: {},\n\t writable: true,\n\t enumerable: true\n\t }\n\t });\n\t\n\t // promisifying\n\t if (Security.kuzzle.bluebird) {\n\t return Security.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['create', 'replace', 'saveRestricted', 'update', 'getProfiles'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t}\n\t\n\tUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: User\n\t }\n\t});\n\t\n\t/**\n\t * Set profiles in content\n\t * @param {array} profileIds - an array of profiles ids string\n\t *\n\t * @returns {User} this\n\t */\n\tUser.prototype.setProfiles = function (profileIds) {\n\t if (!Array.isArray(profileIds) || typeof profileIds[0] !== 'string') {\n\t throw new Error('Parameter \"profileIds\" must be an array of strings');\n\t }\n\t\n\t this.content.profileIds = profileIds;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * @param {object} credentials\n\t */\n\tUser.prototype.setCredentials = function (credentials) {\n\t if (typeof credentials !== 'object') {\n\t throw new Error('Parameter \"credentials\" must be a object');\n\t }\n\t\n\t this.credentials = credentials;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Add a profile\n\t * @param {string} profileId - a profile ids string\n\t *\n\t * @returns {User} this\n\t */\n\tUser.prototype.addProfile = function (profileId) {\n\t if (typeof profileId !== 'string') {\n\t throw new Error('Parameter \"profileId\" must be a string');\n\t }\n\t\n\t if (!this.content.profileIds) {\n\t this.content.profileIds = [];\n\t }\n\t\n\t if (this.content.profileIds.indexOf(profileId) === -1) {\n\t this.content.profileIds.push(profileId);\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Creates this user into Kuzzle\n\t *\n\t * @param {object|responseCallback} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {User} this\n\t */\n\tUser.prototype.create = function (options, cb) {\n\t var\n\t data = this.creationSerialize(),\n\t self = this;\n\t\n\t if (!this.content.profileIds) {\n\t throw new Error('Argument \"profileIds\" is mandatory in a user. This argument contains an array of profile identifiers.');\n\t }\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.Security.buildQueryArgs('createUser'), data, null, cb && function (err) {\n\t cb(err, err ? undefined : self);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t\n\t/**\n\t * Replaces the latest version of this user in Kuzzle by the current content of this object.\n\t *\n\t * @param {object|responseCallback} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {User} this\n\t */\n\tUser.prototype.replace = function (options, cb) {\n\t var\n\t data = this.serialize(),\n\t self = this;\n\t\n\t if (!this.content.profileIds) {\n\t throw new Error('Argument \"profileIds\" is mandatory in a user. This argument contains an array of profile identifiers.');\n\t }\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t\n\t this.kuzzle.query(this.Security.buildQueryArgs('replaceUser'), data, null, cb && function (err) {\n\t cb(err, err ? undefined : self);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Saves this user as restricted into Kuzzle.\n\t *\n\t * This function will create a new user. It is not usable to update an existing user.\n\t * The \"profileIds\" property must not be provided, or the request will be rejected by Kuzzle.\n\t * This function allows anonymous users to create a \"restricted\" user with predefined rights.\n\t *\n\t * @param {object|responseCallback} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {User} this\n\t */\n\tUser.prototype.saveRestricted = function (options, cb) {\n\t var\n\t data = this.serialize(),\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.Security.buildQueryArgs('createRestrictedUser'), data, options, cb && function (error) {\n\t cb(error, error ? undefined : self);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Serialize this object into a JSON object\n\t *\n\t * @return {object} JSON object representing this User\n\t */\n\tUser.prototype.serialize = function () {\n\t return {_id: this.id, body: this.content, meta: this.meta};\n\t};\n\t\n\t/**\n\t * Serialize this object into a JSON object\n\t *\n\t * @return {object} JSON object representing this User\n\t */\n\tUser.prototype.creationSerialize = function () {\n\t return {_id: this.id, body: {content: this.content, credentials: this.credentials, meta: this.meta}};\n\t};\n\t\n\t/**\n\t * Return the associated profiles IDs\n\t *\n\t * @return {array.} the associated profiles IDs\n\t */\n\tUser.prototype.getProfileIds = function () {\n\t return this.content.profileIds || [];\n\t};\n\t\n\t/**\n\t * Return the associated Profile objects\n\t *\n\t * @param {object|responseCallback} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tUser.prototype.getProfiles = function (options, cb) {\n\t var \n\t self = this,\n\t fetchedProfiles = [],\n\t errored = false;\n\t\n\t if (options && !cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.Security.kuzzle.callbackRequired('User.getProfiles', cb);\n\t\n\t if (!self.content.profileIds) {\n\t return cb(null, fetchedProfiles);\n\t }\n\t\n\t self.content.profileIds.forEach(function (profileId) {\n\t self.Security.fetchProfile(profileId, options, function (error, profile) {\n\t if (error) {\n\t if (errored) {\n\t return;\n\t }\n\t\n\t errored = true; // prevents multiple callback resolutions\n\t return cb(error);\n\t }\n\t\n\t fetchedProfiles.push(profile);\n\t\n\t if (fetchedProfiles.length === self.content.profileIds.length) {\n\t cb(null, fetchedProfiles);\n\t }\n\t });\n\t });\n\t};\n\t\n\tmodule.exports = User;\n\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tvar rng = __webpack_require__(20);\n\tvar bytesToUuid = __webpack_require__(19);\n\t\n\tfunction v4(options, buf, offset) {\n\t var i = buf && offset || 0;\n\t\n\t if (typeof(options) == 'string') {\n\t buf = options == 'binary' ? new Array(16) : null;\n\t options = null;\n\t }\n\t options = options || {};\n\t\n\t var rnds = options.random || (options.rng || rng)();\n\t\n\t // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\t rnds[6] = (rnds[6] & 0x0f) | 0x40;\n\t rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\t\n\t // Copy bytes to buffer, if provided\n\t if (buf) {\n\t for (var ii = 0; ii < 16; ++ii) {\n\t buf[i + ii] = rnds[ii];\n\t }\n\t }\n\t\n\t return buf || bytesToUuid(rnds);\n\t}\n\t\n\tmodule.exports = v4;\n\n\n/***/ }),\n/* 7 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSearchResult = __webpack_require__(11),\n\t Document = __webpack_require__(2),\n\t CollectionMapping = __webpack_require__(8),\n\t Room = __webpack_require__(10),\n\t SubscribeResult = __webpack_require__(12);\n\t\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t/**\n\t * A data collection is a set of data managed by Kuzzle. It acts like a data table for persistent documents,\n\t * or like a room for pub/sub messages.\n\t *\n\t * @property {string} collection\n\t * @property {string} index\n\t * @property {Kuzzle} kuzzle\n\t * @property {Array.} collection\n\t * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @param {string} collection - name of the data collection to handle\n\t * @param {string} index - Index containing the data collection\n\t * @constructor\n\t */\n\tfunction Collection(kuzzle, collection, index) {\n\t if (!index || !collection) {\n\t throw new Error('The Collection object constructor needs an index and a collection arguments');\n\t }\n\t\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t collection: {\n\t value: collection,\n\t enumerable: true\n\t },\n\t index: {\n\t value: index,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzle.headers)),\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t Object.defineProperty(this, 'buildQueryArgs', {\n\t value: function (controller, action) {\n\t return {\n\t controller: controller,\n\t action: action,\n\t collection: this.collection,\n\t index: this.index\n\t };\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = ['publishMessage', 'setHeaders', 'subscribe'];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * Returns the number of documents matching the provided set of filters.\n\t *\n\t * There is a small delay between documents creation and their existence in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a document that was just been created won’t be returned by this function\n\t *\n\t * @param {object} filters - Filters in Elasticsearch Query DSL format\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tCollection.prototype.count = function (filters, options, cb) {\n\t var\n\t query;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('Collection.count', cb);\n\t\n\t query = this.kuzzle.addHeaders({body: filters}, this.headers);\n\t\n\t this.kuzzle.query(this.buildQueryArgs('document', 'count'), query, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.count);\n\t });\n\t};\n\t\n\t/**\n\t * Create a new empty data collection, with no associated mapping.\n\t * Kuzzle automatically creates data collections when storing documents, but there are cases where we\n\t * want to create and prepare data collections before storing documents in it.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t * @returns {*} this\n\t */\n\tCollection.prototype.create = function (options, cb) {\n\t var data = {},\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = this.kuzzle.addHeaders(data, this.headers);\n\t this.kuzzle.query(this.buildQueryArgs('collection', 'create'), data, options, function(err) {\n\t cb(err, err ? undefined : self);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Create a new document in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t * - ifExist (string, allowed values: \"error\" (default), \"replace\"):\n\t * If the same document already exists:\n\t * - resolves with an error if set to \"error\".\n\t * - replaces the existing document if set to \"replace\"\n\t *\n\t * @param {string} [id] - (optional) document identifier\n\t * @param {object} document - either an instance of a Document object, or a document\n\t * @param {object} [options] - optional arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Object} this\n\t */\n\tCollection.prototype.createDocument = function (id, document, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'create';\n\t\n\t if (id && typeof id !== 'string') {\n\t cb = options;\n\t options = document;\n\t document = id;\n\t id = null;\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (document instanceof Document) {\n\t data = document.serialize();\n\t } else {\n\t data.body = document;\n\t }\n\t\n\t if (options && options.ifExist) {\n\t if (options.ifExist === 'replace') {\n\t action = 'createOrReplace';\n\t }\n\t else if (options.ifExist !== 'error') {\n\t throw new Error('Invalid value for the \"ifExist\" option: ' + options.ifExist);\n\t }\n\t }\n\t\n\t if (id) {\n\t data._id = id;\n\t }\n\t\n\t data = self.kuzzle.addHeaders(data, self.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', action), data, options, cb && function (err, res) {\n\t var doc;\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t doc = new Document(self, res.result._id, res.result._source, res.result._meta);\n\t doc.version = res.result._version;\n\t cb(null, doc);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete persistent documents.\n\t *\n\t * There is a small delay between documents creation and their existence in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a document that was just been created won’t be returned by this function\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {string|object} arg - Either a document ID (will delete only this particular document), or a set of filters\n\t * @param {object} [options] - optional arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Collection} this\n\t */\n\tCollection.prototype.deleteDocument = function (arg, options, cb) {\n\t var\n\t action,\n\t data = {};\n\t\n\t if (typeof arg === 'string') {\n\t data._id = arg;\n\t action = 'delete';\n\t } else {\n\t data.body = {query: arg};\n\t action = 'deleteByQuery';\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = this.kuzzle.addHeaders(data, this.headers);\n\t\n\t this.kuzzle.query(this.buildQueryArgs('document', action), data, options, cb && function (err, res) {\n\t if (err) {\n\t cb(err);\n\t }\n\t else {\n\t cb(null, (action === 'delete' ? [res.result._id] : res.result.ids));\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Deletes the current specifications of this collection\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @return {object} this\n\t */\n\tCollection.prototype.deleteSpecifications = function (options, cb) {\n\t var\n\t data = { index: this.index, collection: this.collection },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('collection', 'deleteSpecifications'), data, options, function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Returns a boolean indicating whether or not a document with provided ID exists.\n\t *\n\t * @param {string} documentId - Unique document identifier\n\t * @param {object} options [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tCollection.prototype.documentExists = function (documentId, options, cb) {\n\t var\n\t data = {_id: documentId},\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.documentExists', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'exists'), data, options, function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t};\n\t\n\t/**\n\t * Retrieve a single stored document using its unique document ID.\n\t *\n\t * @param {string} documentId - Unique document identifier\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tCollection.prototype.fetchDocument = function (documentId, options, cb) {\n\t var\n\t data = {_id: documentId},\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.fetch', cb);\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'get'), data, options, function (err, res) {\n\t var document;\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t document = new Document(self, res.result._id, res.result._source, res.result._meta);\n\t document.version = res.result._version;\n\t cb(null, document);\n\t });\n\t};\n\t\n\t/**\n\t * Instantiates a CollectionMapping object containing the current mapping of this collection.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n\t */\n\tCollection.prototype.getMapping = function (options, cb) {\n\t var kuzzleMapping;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('Collection.getMapping', cb);\n\t\n\t kuzzleMapping = new CollectionMapping(this);\n\t kuzzleMapping.refresh(options, cb);\n\t};\n\t\n\t/**\n\t * Create the provided documents\n\t *\n\t * @param {Array.} documents - Array of documents to create\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n\t * @returns {object} this\n\t */\n\tCollection.prototype.mCreateDocument = function (documents, options, cb) {\n\t var data = {\n\t body: {},\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!Array.isArray(documents)) {\n\t return cb(new Error('Collection.mCreateDocument: documents parameter format is invalid (should be an array of documents)'));\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.mCreate', cb);\n\t\n\t data.body.documents = documents.map(function (doc) {\n\t return (doc instanceof Document) ? doc.serialize() : doc;\n\t });\n\t\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'mCreate'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Create or replace the provided documents\n\t *\n\t * @param {Array.} documents - Array of documents to create or replace\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n\t * @returns {object} this\n\t */\n\tCollection.prototype.mCreateOrReplaceDocument = function (documents, options, cb) {\n\t var data = {\n\t body: {},\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!Array.isArray(documents)) {\n\t return cb(new Error('Collection.mCreateOrReplaceDocument: documents parameter format is invalid (should be an array of documents)'));\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.mCreateOrReplace', cb);\n\t\n\t data.body.documents = documents.map(function (doc) {\n\t return (doc instanceof Document) ? doc.serialize() : doc;\n\t });\n\t\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'mCreateOrReplace'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Delete specific documents according to given IDs\n\t *\n\t * @param {Array.} documentIds - IDs of the documents to delete\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n\t * @returns {object} this\n\t */\n\tCollection.prototype.mDeleteDocument = function (documentIds, options, cb) {\n\t var data = {\n\t body: {\n\t ids: documentIds\n\t }\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!Array.isArray(documentIds)) {\n\t return cb(new Error('Collection.mDeleteDocument: documentIds parameter format is invalid (should be an array of IDs)'));\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.mDelete', cb);\n\t\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'mDelete'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Get specific documents according to given IDs\n\t *\n\t * @param {Array.} documentIds - IDs of the documents to retrieve\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n\t */\n\tCollection.prototype.mGetDocument = function (documentIds, options, cb) {\n\t var data = {\n\t body: {\n\t ids: documentIds\n\t }\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!Array.isArray(documentIds)) {\n\t return cb(new Error('Collection.mGetDocument: documentIds parameter format is invalid (should be an array of IDs)'));\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.mGet', cb);\n\t\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'mGet'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t};\n\t\n\t/**\n\t * Replace the provided documents\n\t *\n\t * @param {Array.} documents - Array of documents to replace\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n\t * @returns {object} this\n\t */\n\tCollection.prototype.mReplaceDocument = function (documents, options, cb) {\n\t var data = {\n\t body: {}\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!Array.isArray(documents)) {\n\t return cb(new Error('Collection.mReplaceDocument: documents parameter format is invalid (should be an array of documents)'));\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.mReplace', cb);\n\t\n\t data.body.documents = documents.map(function (doc) {\n\t return (doc instanceof Document) ? doc.serialize() : doc;\n\t });\n\t\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'mReplace'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Update the provided documents\n\t *\n\t * @param {Array.} documents - Array of documents to update\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n\t * @returns {object} this\n\t */\n\tCollection.prototype.mUpdateDocument = function (documents, options, cb) {\n\t var data = {\n\t body: {}\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!Array.isArray(documents)) {\n\t return cb(new Error('Collection.mUpdateDocument: documents parameter format is invalid (should be an array of documents)'));\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.mUpdate', cb);\n\t\n\t data.body.documents = documents.map(function (doc) {\n\t return (doc instanceof Document) ? doc.serialize() : doc;\n\t });\n\t\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'mUpdate'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Retrieves the current specifications of this collection\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tCollection.prototype.getSpecifications = function (options, cb) {\n\t var\n\t data = { index: this.index, collection: this.collection },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.getSpecifications', cb);\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('collection', 'getSpecifications'), data, options, function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t};\n\t\n\t/**\n\t * Publish a realtime message\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} document - either a Document instance or a JSON object\n\t * @param {object} [options] - optional arguments\n\t * @param {responseCallback} [cb] - Returns a raw Kuzzle response\n\t * @returns {*} this\n\t */\n\tCollection.prototype.publishMessage = function (document, options, cb) {\n\t var data = {};\n\t\n\t if (document instanceof Document) {\n\t data = document.serialize();\n\t } else {\n\t data.body = document;\n\t }\n\t\n\t data = this.kuzzle.addHeaders(data, this.headers);\n\t this.kuzzle.query(this.buildQueryArgs('realtime', 'publish'), data, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Replace an existing document with a new one.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {string} documentId - Unique document identifier of the document to replace\n\t * @param {object} content - JSON object representing the new document version\n\t * @param {object} [options] - additional arguments\n\t * @param {responseCallback} [cb] - Returns an instantiated Document object\n\t * @return {object} this\n\t */\n\tCollection.prototype.replaceDocument = function (documentId, content, options, cb) {\n\t var\n\t self = this,\n\t data = {\n\t _id: documentId,\n\t body: content\n\t };\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'createOrReplace'), data, options, cb && function (err, res) {\n\t var document;\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t document = new Document(self, res.result._id, res.result._source, res.result._meta);\n\t document.version = res.result._version;\n\t cb(null, document);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Executes an advanced search on the data collection.\n\t *\n\t * /!\\ There is a small delay between documents creation and their existence in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a document that was just been created won’t be returned by this function.\n\t *\n\t * @param {object} filters - Filters in Elasticsearch Query DSL format\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\t\n\tCollection.prototype.search = function (filters, options, cb) {\n\t var\n\t query,\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = {};\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.search', cb);\n\t\n\t query = self.kuzzle.addHeaders({body: filters}, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'search'), query, options, function (error, result) {\n\t var documents = [];\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t result.result.hits.forEach(function (doc) {\n\t var newDocument = new Document(self, doc._id, doc._source, doc._meta);\n\t\n\t newDocument.version = doc._version;\n\t\n\t documents.push(newDocument);\n\t });\n\t\n\t if (result.result._scroll_id) {\n\t options.scrollId = result.result._scroll_id;\n\t }\n\t\n\t cb(null, new KuzzleSearchResult(\n\t self,\n\t result.result.total,\n\t documents,\n\t result.result.aggregations ? result.result.aggregations : {},\n\t options,\n\t filters,\n\t options.previous || null\n\t ));\n\t });\n\t};\n\t\n\t/**\n\t * A \"scroll\" option can be passed to search queries, creating persistent\n\t * paginated results.\n\t * This method can be used to manually get the next page of a search result,\n\t * instead of using KuzzleSearchResult.next()\n\t *\n\t * @param {string} scrollId\n\t * @param {object} [options]\n\t * @param {object} [filters]\n\t * @param {responseCallback} cb\n\t */\n\tCollection.prototype.scroll = function (scrollId, options, filters, cb) {\n\t var\n\t request = {},\n\t self = this;\n\t\n\t if (!scrollId) {\n\t throw new Error('Collection.scroll: scrollId is required');\n\t }\n\t\n\t if (!cb) {\n\t cb = filters;\n\t filters = null;\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = {};\n\t }\n\t\n\t this.kuzzle.callbackRequired('Collection.scroll', cb);\n\t\n\t request.scrollId = scrollId;\n\t\n\t if (options && options.scroll) {\n\t request.scroll = options.scroll;\n\t }\n\t\n\t this.kuzzle.query({controller: 'document', action: 'scroll'}, request, options, function (error, result) {\n\t var documents = [];\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t result.result.hits.forEach(function (doc) {\n\t var newDocument = new Document(self, doc._id, doc._source, doc._meta);\n\t\n\t newDocument.version = doc._version;\n\t\n\t documents.push(newDocument);\n\t });\n\t\n\t if (result.result._scroll_id) {\n\t options.scrollId = result.result._scroll_id;\n\t }\n\t\n\t cb(null, new KuzzleSearchResult(\n\t self,\n\t result.result.total,\n\t documents,\n\t {},\n\t options,\n\t filters,\n\t options.previous || null\n\t ));\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Retrieves next result of a search with scroll query.\n\t *\n\t * @param {string} scrollId\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tCollection.prototype.scrollSpecifications = function (scrollId, options, cb) {\n\t var\n\t data = { scrollId: scrollId };\n\t\n\t if (!scrollId) {\n\t throw new Error('Collection.scrollSpecifications: scrollId is required');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = {};\n\t }\n\t\n\t this.kuzzle.callbackRequired('Collection.scrollSpecifications', cb);\n\t\n\t if (options && options.scroll) {\n\t data.scroll = options.scroll;\n\t }\n\t\n\t this.kuzzle.query(\n\t { controller: 'collection', action: 'scrollSpecifications'},\n\t this.kuzzle.addHeaders(data, this.headers),\n\t options,\n\t function (err, res) {\n\t cb (err, err ? undefined : res.result);\n\t }\n\t );\n\t};\n\t\n\t/**\n\t * Searches specifications across indexes/collections according to the provided filters\n\t *\n\t * @param {object} [filters] - Optional filters in ElasticSearch Query DSL format\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tCollection.prototype.searchSpecifications = function (filters, options, cb) {\n\t var\n\t data = { body: { query: filters } },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = {};\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.searchSpecifications', cb);\n\t\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query({ controller: 'collection', action: 'searchSpecifications' }, data, options, function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t};\n\t\n\t/**\n\t * Subscribes to this data collection with a set of filters.\n\t * To subscribe to the entire data collection, simply provide an empty filter.\n\t *\n\t * @param {object} filters - Filters in Kuzzle DSL format\n\t * @param {object} [options] - subscriptions options\n\t * @param {responseCallback} cb - called for each new notification\n\t * @returns {*} KuzzleSubscribeResult object\n\t */\n\tCollection.prototype.subscribe = function (filters, options, cb) {\n\t var\n\t room,\n\t subscribeResult;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('Collection.subscribe', cb);\n\t\n\t subscribeResult = new SubscribeResult();\n\t room = new Room(this, options);\n\t\n\t room.renew(filters, cb, subscribeResult.done.bind(subscribeResult));\n\t\n\t return subscribeResult;\n\t};\n\t\n\t/**\n\t * Truncate the data collection, removing all stored documents but keeping all associated mappings.\n\t * This method is a lot faster than removing all documents using a query.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t * @returns {*} this\n\t */\n\tCollection.prototype.truncate = function (options, cb) {\n\t var data = {};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = this.kuzzle.addHeaders(data, this.headers);\n\t this.kuzzle.query(this.buildQueryArgs('collection', 'truncate'), data, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t\n\t/**\n\t * Update parts of a document\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {string} documentId - Unique document identifier of the document to update\n\t * @param {object} content - JSON object containing changes to perform on the document\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Returns an instantiated Document object\n\t * @return {object} this\n\t */\n\tCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n\t var data = {\n\t _id: documentId,\n\t body: content\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (options && options.retryOnConflict) {\n\t data.retryOnConflict = options.retryOnConflict;\n\t }\n\t\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'update'), data, options, cb && function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t (new Document(self, res.result._id)).refresh(cb);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Updates the current specifications of this collection\n\t *\n\t * @param {object} specifications - Specifications content\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @return {object} this\n\t */\n\tCollection.prototype.updateSpecifications = function (specifications, options, cb) {\n\t var\n\t collection = {},\n\t data = { body: {} },\n\t self = this;\n\t\n\t collection[this.collection] = specifications;\n\t data.body[this.index] = collection;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('collection', 'updateSpecifications'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Validates the provided specifications\n\t *\n\t * @param {object} specifications - Specifications content\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tCollection.prototype.validateSpecifications = function (specifications, options, cb) {\n\t var\n\t collection = {},\n\t data = { body: {} },\n\t self = this;\n\t\n\t collection[this.collection] = specifications;\n\t data.body[this.index] = collection;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.validateSpecifications', cb);\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('collection', 'validateSpecifications'), data, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.valid);\n\t });\n\t};\n\t\n\t/**\n\t * Instantiate a new Document object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - document id\n\t * @param {object} content - document content\n\t * @constructor\n\t */\n\tCollection.prototype.document = function (id, content) {\n\t return new Document(this, id, content);\n\t};\n\t\n\t/**\n\t * Instantiate a new Room object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {object} [options] - subscription configuration\n\t * @constructor\n\t */\n\tCollection.prototype.room = function (options) {\n\t return new Room(this, options);\n\t};\n\t\n\t/**\n\t * Instantiate a new CollectionMapping object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {object} [mapping] - mapping to instantiate the CollectionMapping object with\n\t * @constructor\n\t */\n\tCollection.prototype.collectionMapping = function (mapping) {\n\t return new CollectionMapping(this, mapping);\n\t};\n\t\n\t/**\n\t * Helper function allowing to set headers while chaining calls.\n\t *\n\t * If the replace argument is set to true, replace the current headers with the provided content.\n\t * Otherwise, it appends the content to the current headers, only replacing already existing values\n\t *\n\t * @param content - new headers content\n\t * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n\t */\n\tCollection.prototype.setHeaders = function (content, replace) {\n\t this.kuzzle.setHeaders.call(this, content, replace);\n\t return this;\n\t};\n\t\n\tmodule.exports = Collection;\n\n\n/***/ }),\n/* 8 */\n/***/ (function(module, exports) {\n\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t\n\t/**\n\t * When creating a new data collection in the persistent data storage layer, Kuzzle uses a default mapping.\n\t * It means that, by default, you won’t be able to exploit the full capabilities of our persistent data storage layer\n\t * (currently handled by ElasticSearch), and your searches may suffer from below-average performances, depending on\n\t * the amount of data you stored in a collection and the complexity of your database.\n\t *\n\t * The CollectionMapping object allow to get the current mapping of a data collection and to modify it if needed.\n\t *\n\t * @param {object} collection - Instance of the inherited Collection object\n\t * @param {object} [mapping] - mappings\n\t * @constructor\n\t */\n\tfunction CollectionMapping(collection, mapping) {\n\t Object.defineProperties(this, {\n\t //read-only properties\n\t collection: {\n\t value: collection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: collection.kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t headers: {\n\t value: JSON.parse(JSON.stringify(collection.headers)),\n\t enumerable: true,\n\t writable: true\n\t },\n\t mapping: {\n\t value: mapping || {},\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = ['set', 'setHeaders'];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * Applies the new mapping to the data collection.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tCollectionMapping.prototype.apply = function (options, cb) {\n\t var\n\t self = this,\n\t data = this.kuzzle.addHeaders({body: {properties: this.mapping}}, this.headers);\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.collection.buildQueryArgs('collection', 'updateMapping'), data, options, function (err) {\n\t if (err) {\n\t return cb && cb(err);\n\t }\n\t\n\t self.refresh(options, cb);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Replaces the current content with the mapping stored in Kuzzle\n\t *\n\t * Calling this function will discard any uncommited changes. You can commit changes by calling the “apply” function\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tCollectionMapping.prototype.refresh = function (options, cb) {\n\t var\n\t self = this,\n\t data = this.kuzzle.addHeaders({}, this.headers);\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.collection.buildQueryArgs('collection', 'getMapping'), data, options, function (err, res) {\n\t if (err) {\n\t return cb ? cb(err) : false;\n\t }\n\t\n\t if (res.result[self.collection.index]) {\n\t if (res.result[self.collection.index].mappings[self.collection.collection]) {\n\t self.mapping = res.result[self.collection.index].mappings[self.collection.collection].properties;\n\t\n\t // Mappings can be empty. The mapping property should never be \"undefined\"\n\t if (self.mapping === undefined) {\n\t self.mapping = {};\n\t }\n\t } else {\n\t return cb && cb(new Error('No mapping found for collection ' + self.collection.collection));\n\t }\n\t } else {\n\t return cb && cb(new Error('No mapping found for index ' + self.collection.index));\n\t }\n\t\n\t if (cb) {\n\t cb(null, self);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t\n\t/**\n\t * Adds or updates a field mapping.\n\t *\n\t * Changes made by this function won’t be applied until you call the apply method\n\t *\n\t * @param {string} field - Name of the field from which the mapping is to be added or updated\n\t * @param {object} mapping - corresponding field mapping\n\t * @returns {CollectionMapping}\n\t */\n\tCollectionMapping.prototype.set = function (field, mapping) {\n\t this.mapping[field] = mapping;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Helper function allowing to set headers while chaining calls.\n\t *\n\t * If the replace argument is set to true, replace the current headers with the provided content.\n\t * Otherwise, it appends the content to the current headers, only replacing already existing values\n\t *\n\t * @param content - new headers content\n\t * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n\t */\n\tCollectionMapping.prototype.setHeaders = function (content, replace) {\n\t this.kuzzle.setHeaders.call(this, content, replace);\n\t return this;\n\t};\n\t\n\tmodule.exports = CollectionMapping;\n\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports) {\n\n\t// Parameter mutualization\n\tvar\n\t getId = {getter: true, required: ['_id']},\n\t getIdField = {getter: true, required: ['_id', 'field']},\n\t getKeys = {getter: true, required: ['keys']},\n\t getMember = {getter: true, required: ['_id', 'member']},\n\t getxScan = {\n\t getter: true, \n\t required: ['_id', 'cursor'], \n\t opts: ['match', 'count'],\n\t mapResults: mapScanResults\n\t },\n\t getZrange = {\n\t getter: true,\n\t required: ['_id', 'start', 'stop'],\n\t opts: assignZrangeOptions,\n\t mapResults: mapZrangeResults\n\t },\n\t getZrangeBy = {\n\t getter: true,\n\t required: ['_id', 'min', 'max'],\n\t opts: assignZrangeOptions,\n\t mapResults: mapZrangeResults\n\t },\n\t setId = {required: ['_id']},\n\t setIdValue = {required: ['_id', 'value']},\n\t setIdFieldValue = {required: ['_id', 'field', 'value']},\n\t setEntries = {required: ['entries']};\n\t\n\t// Redis commands\n\tvar\n\t commands = {\n\t append: setIdValue,\n\t bitcount: {getter: true, required: ['_id'], opts: ['start', 'end']},\n\t bitop: {required: ['_id', 'operation', 'keys']},\n\t bitpos: {getter: true, required: ['_id', 'bit'], opts: ['start', 'end']},\n\t dbsize: {getter: true},\n\t decr: setId,\n\t decrby: setIdValue,\n\t del: {required: ['keys']},\n\t exists: getKeys,\n\t expire: {required: ['_id', 'seconds']},\n\t expireat: {required: ['_id', 'timestamp']},\n\t flushdb: {},\n\t geoadd: {required: ['_id', 'points']},\n\t geodist: {\n\t getter: true,\n\t required: ['_id', 'member1', 'member2'],\n\t opts: ['unit'],\n\t mapResults: parseFloat\n\t },\n\t geohash: {getter: true, required: ['_id', 'members']},\n\t geopos: {getter: true, required: ['_id', 'members'], mapResults: mapGeoposResults},\n\t georadius: {\n\t getter: true,\n\t required: ['_id', 'lon', 'lat', 'distance', 'unit'],\n\t opts: assignGeoRadiusOptions,\n\t mapResults: mapGeoRadiusResults\n\t },\n\t georadiusbymember: {\n\t getter: true,\n\t required: ['_id', 'member', 'distance', 'unit'],\n\t opts: assignGeoRadiusOptions,\n\t mapResults: mapGeoRadiusResults\n\t },\n\t get: getId,\n\t getbit: {getter: true, required: ['_id', 'offset']},\n\t getrange: {getter: true, required: ['_id', 'start', 'end']},\n\t getset: setIdValue,\n\t hdel: {required: ['_id', 'fields']},\n\t hexists: getIdField,\n\t hget: getIdField,\n\t hgetall: {getter: true, required: ['_id']},\n\t hincrby: setIdFieldValue,\n\t hincrbyfloat: {required: ['_id', 'field', 'value'], mapResults: parseFloat},\n\t hkeys: getId,\n\t hlen: getId,\n\t hmget: {getter: true, required: ['_id', 'fields']},\n\t hmset: {required: ['_id', 'entries']},\n\t hscan: getxScan,\n\t hset: setIdFieldValue,\n\t hsetnx: setIdFieldValue,\n\t hstrlen: getIdField,\n\t hvals: getId,\n\t incr: setId,\n\t incrby: setIdValue,\n\t incrbyfloat: {required: ['_id', 'value'], mapResults: parseFloat},\n\t keys: {getter: true, required: ['pattern']},\n\t lindex: {getter: true, required: ['_id', 'idx']},\n\t linsert: {required: ['_id', 'position', 'pivot', 'value']},\n\t llen: getId,\n\t lpop: setId,\n\t lpush: {required: ['_id', 'values']},\n\t lpushx: setIdValue,\n\t lrange: {getter: true, required: ['_id', 'start', 'stop']},\n\t lrem: {required: ['_id', 'count', 'value']},\n\t lset: {required: ['_id', 'index', 'value']},\n\t ltrim: {required: ['_id', 'start', 'stop']},\n\t mget: getKeys,\n\t mset: setEntries,\n\t msetnx: setEntries,\n\t object: {getter: true, required: ['_id', 'subcommand']},\n\t persist: setId,\n\t pexpire: {required: ['_id', 'milliseconds']},\n\t pexpireat: {required: ['_id', 'timestamp']},\n\t pfadd: {required: ['_id', 'elements']},\n\t pfcount: getKeys,\n\t pfmerge: {required: ['_id', 'sources']},\n\t ping: {getter: true},\n\t psetex: {required: ['_id', 'value', 'milliseconds']},\n\t pttl: getId,\n\t randomkey: {getter: true},\n\t rename: {required: ['_id', 'newkey']},\n\t renamenx: {required: ['_id', 'newkey']},\n\t rpop: setId,\n\t rpoplpush: {required: ['source', 'destination']},\n\t rpush: {required: ['_id', 'values']},\n\t rpushx: setIdValue,\n\t sadd: {required: ['_id', 'members']},\n\t scan: {getter: true, required: ['cursor'], opts: ['match', 'count'], mapResults: mapScanResults},\n\t scard: getId,\n\t sdiff: {getter: true, required: ['_id', 'keys']},\n\t sdiffstore: {required: ['_id', 'keys', 'destination']},\n\t set: {required: ['_id', 'value'], opts: ['ex', 'px', 'nx', 'xx']},\n\t setex: {required: ['_id', 'value', 'seconds']},\n\t setnx: setIdValue,\n\t sinter: getKeys,\n\t sinterstore: {required: ['destination', 'keys']},\n\t sismember: getMember,\n\t smembers: getId,\n\t smove: {required: ['_id', 'destination', 'member']},\n\t sort: {getter: true, required: ['_id'], opts: ['alpha', 'by', 'direction', 'get', 'limit']},\n\t spop: {required: ['_id'], opts: ['count'], mapResults: mapStringToArray },\n\t srandmember: {getter: true, required: ['_id'], opts: ['count'], mapResults: mapStringToArray},\n\t srem: {required: ['_id', 'members']},\n\t sscan: getxScan,\n\t strlen: getId,\n\t sunion: getKeys,\n\t sunionstore: {required: ['destination', 'keys']},\n\t time: {getter: true, mapResults: mapArrayStringToArrayInt},\n\t touch: {required: ['keys']},\n\t ttl: getId,\n\t type: getId,\n\t zadd: {required: ['_id', 'elements'], opts: ['nx', 'xx', 'ch', 'incr']},\n\t zcard: getId,\n\t zcount: {getter: true, required: ['_id', 'min', 'max']},\n\t zincrby: {required: ['_id', 'member', 'value']},\n\t zinterstore: {required: ['_id', 'keys'], opts: ['weights', 'aggregate']},\n\t zlexcount: {getter: true, required: ['_id', 'min', 'max']},\n\t zrange: getZrange,\n\t zrangebylex: {getter: true, required: ['_id', 'min', 'max'], opts: ['limit']},\n\t zrevrangebylex: {getter: true, required: ['_id', 'min', 'max'], opts: ['limit']},\n\t zrangebyscore: getZrangeBy,\n\t zrank: getMember,\n\t zrem: {required: ['_id', 'members']},\n\t zremrangebylex: {required: ['_id', 'min', 'max']},\n\t zremrangebyrank: {required: ['_id', 'start', 'stop']},\n\t zremrangebyscore: {required: ['_id', 'min', 'max']},\n\t zrevrange: getZrange,\n\t zrevrangebyscore: getZrangeBy,\n\t zrevrank: getMember,\n\t zscan: getxScan,\n\t zscore: {getter: true, required: ['_id', 'member'], mapResults: parseFloat},\n\t zunionstore: {required: ['_id', 'keys'], opts: ['weights', 'aggregate']}\n\t };\n\t\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t\n\t/**\n\t * Kuzzle's memory storage is a separate data store from the database layer.\n\t * It is internaly based on Redis. You can access most of Redis functions (all\n\t * lowercased), except functions falling in the following categories:\n\t *\n\t * - blocking functions\n\t * - cluster commands\n\t * - configuration commands\n\t * - cursor functions\n\t * - database administration commands\n\t * - debugging functions\n\t * - script based functions\n\t * - transaction functions\n\t *\n\t * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @constructor\n\t */\n\tfunction MemoryStorage(kuzzle) {\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t kuzzle: {\n\t value: kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzle.headers)),\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t this.setHeaders = kuzzle.setHeaders.bind(this);\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = ['setHeaders'];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t// Dynamically builds this class' prototypes using the \"commands\" global variable\n\t(function () {\n\t Object.keys(commands).forEach(function (command) {\n\t MemoryStorage.prototype[command] = function () {\n\t var\n\t args = Array.prototype.slice.call(arguments),\n\t options = null,\n\t cb,\n\t query = {\n\t controller: 'ms',\n\t action: command\n\t },\n\t data = {};\n\t\n\t if (args.length && typeof args[args.length - 1] === 'function') {\n\t cb = args.pop();\n\t }\n\t\n\t commands[command].getter && this.kuzzle.callbackRequired('MemoryStorage.' + command, cb);\n\t\n\t if (!commands[command].getter) {\n\t data.body = {};\n\t }\n\t\n\t if (commands[command].required) {\n\t commands[command].required.forEach(function (param) {\n\t var value = args.shift();\n\t\n\t if (value === undefined) {\n\t throw new Error('MemoryStorage.' + command + ': Missing parameter \"' + param + '\"');\n\t }\n\t\n\t assignParameter(data, commands[command].getter, param, value);\n\t });\n\t }\n\t\n\t if (args.length > 1) {\n\t throw new Error('MemoryStorage.' + command + ': Too many parameters provided');\n\t }\n\t\n\t if (args.length === 1 && typeof args[0] !== 'object' || Array.isArray(args[0])) {\n\t throw new Error('MemoryStorage.' + command + ': Invalid optional parameter (expected an object)');\n\t }\n\t\n\t if (args.length) {\n\t options = Object.assign({}, args[0]);\n\t\n\t if (Array.isArray(commands[command].opts)) {\n\t commands[command].opts.forEach(function (opt) {\n\t if (options[opt] !== null && options[opt] !== undefined) {\n\t assignParameter(data, commands[command].getter, opt, options[opt]);\n\t delete options[opt];\n\t }\n\t });\n\t }\n\t }\n\t\n\t /*\n\t Options function mapper does not necessarily need\n\t options to be passed by clients.\n\t */\n\t if (typeof commands[command].opts === 'function') {\n\t commands[command].opts(data, options || {});\n\t }\n\t\n\t this.kuzzle.query(query, data, options, cb && function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t if (commands[command].mapResults) {\n\t return cb(null, commands[command].mapResults(res.result));\n\t }\n\t\n\t cb(null, res.result);\n\t });\n\t\n\t if (!commands[command].getter) {\n\t return this;\n\t }\n\t };\n\t });\n\t})();\n\t\n\t/**\n\t *\n\t * @param {object} data - target data object\n\t * @param {boolean} getter - tells if the command is a getter one\n\t * @param {string} name - parameter name\n\t * @param {*} value - parameter value\n\t */\n\tfunction assignParameter(data, getter, name, value) {\n\t if (getter || name === '_id') {\n\t data[name] = value;\n\t }\n\t else {\n\t data.body[name] = value;\n\t }\n\t}\n\t\n\t/**\n\t * Assign the provided options for the georadius* redis functions\n\t * to the request object, as expected by Kuzzle API\n\t *\n\t * Mutates the provided data and options objects\n\t *\n\t * @param {object} data\n\t * @param {object} options\n\t */\n\tfunction assignGeoRadiusOptions(data, options) {\n\t var parsed = [];\n\t\n\t Object.keys(options)\n\t .filter(function (opt) {\n\t return options[opt] && ['withcoord', 'withdist', 'count', 'sort'].indexOf(opt) !== -1;\n\t })\n\t .forEach(function (opt) {\n\t if (opt === 'withcoord' || opt === 'withdist') {\n\t parsed.push(opt);\n\t delete options[opt];\n\t }\n\t else if (opt === 'count' || opt === 'sort') {\n\t if (opt === 'count') {\n\t parsed.push('count');\n\t }\n\t\n\t parsed.push(options[opt]);\n\t }\n\t\n\t delete options[opt];\n\t });\n\t\n\t if (parsed.length > 0) {\n\t data.options = parsed;\n\t }\n\t}\n\t\n\t/**\n\t * Force the WITHSCORES option on z*range* routes\n\t *\n\t * Mutates the provided data and options objects\n\t *\n\t * @param {object} data\n\t * @param {object} options\n\t */\n\tfunction assignZrangeOptions(data, options) {\n\t data.options = ['withscores'];\n\t\n\t if (options.limit) {\n\t data.limit = options.limit;\n\t delete options.limit;\n\t }\n\t}\n\t\n\t/**\n\t * Maps geopos results, from array> to array>\n\t *\n\t * @param {Array.>} results\n\t * @return {Array.>}\n\t */\n\tfunction mapGeoposResults(results) {\n\t return results.map(function (coords) {\n\t return coords.map(function (latlon) {\n\t return parseFloat(latlon);\n\t });\n\t });\n\t}\n\t\n\t\n\t/**\n\t * Maps georadius results to the format specified in the SDK documentation,\n\t * preventing different formats depending on the passed options\n\t *\n\t * Results can be either an array of point names, or an array\n\t * of arrays, each one of them containing the point name,\n\t * and additional informations depending on the passed options\n\t * (coordinates, distances)\n\t *\n\t * @param {Array} results\n\t * @return {Array.}\n\t */\n\tfunction mapGeoRadiusResults(results) {\n\t // Simple array of point names (no options provided)\n\t if (!Array.isArray(results[0])) {\n\t return results.map(function (point) {\n\t return {name: point};\n\t });\n\t }\n\t\n\t return results.map(function (point) {\n\t // The point id is always the first item\n\t var p = {\n\t name: point[0]\n\t },\n\t i;\n\t\n\t for (i = 1; i < point.length; i++) {\n\t // withcoord result are in an array...\n\t if (Array.isArray(point[i])) {\n\t p.coordinates = point[i].map(function (coord) {\n\t return parseFloat(coord);\n\t });\n\t }\n\t else {\n\t // ... and withdist are not\n\t p.distance = parseFloat(point[i]);\n\t }\n\t }\n\t\n\t return p;\n\t });\n\t}\n\t\n\t/**\n\t * Map a string result to an array of strings.\n\t * Used to uniformize polymorphic results from redis\n\t *\n\t * @param {Array|string} results\n\t * @return {Array.}\n\t */\n\tfunction mapStringToArray (results) {\n\t return Array.isArray(results) ? results : [results];\n\t}\n\t\n\t/**\n\t * Map an array of strings to an array of integers\n\t *\n\t * @param {Array.} results\n\t * @return {Array.}\n\t */\n\tfunction mapArrayStringToArrayInt(results) {\n\t return results.map(function (value) {\n\t return parseInt(value);\n\t });\n\t}\n\t\n\t/**\n\t * Map zrange results with WITHSCORES:\n\t * [\n\t * \"member1\",\n\t * \"score of member1\",\n\t * \"member2\",\n\t * \"score of member2\"\n\t * ]\n\t *\n\t * into the following format:\n\t * [\n\t * {\"member\": \"member1\", \"score\": },\n\t * {\"member\": \"member2\", \"score\": },\n\t * ]\n\t *\n\t *\n\t * @param {Array.} results\n\t * @return {Array.}\n\t */\n\tfunction mapZrangeResults(results) {\n\t var\n\t buffer = null,\n\t mapped = [];\n\t\n\t results.forEach(function (value) {\n\t if (buffer === null) {\n\t buffer = value;\n\t }\n\t else {\n\t mapped.push({member: buffer, score: parseFloat(value)});\n\t buffer = null;\n\t }\n\t });\n\t\n\t return mapped;\n\t}\n\t\n\t/**\n\t * Map *scan calls results, from:\n\t * [\n\t * \"\",\n\t * [\n\t * \"value1\",\n\t * \"value2\", \n\t * \"...\"\n\t * ]\n\t * ]\n\t *\n\t * To:\n\t * {\n\t * cursor: ,\n\t * values: [\n\t * \"value1\",\n\t * \"value2\",\n\t * \"...\"\n\t * ]\n\t * }\n\t * \n\t * @param {array.} results \n\t * @return {object}\n\t */\n\tfunction mapScanResults(results) {\n\t return {\n\t cursor: results[0],\n\t values: results[1]\n\t };\n\t}\n\t\n\tmodule.exports = MemoryStorage;\n\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tvar\n\t uuidv4 = __webpack_require__(6),\n\t Document = __webpack_require__(2);\n\t\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t/**\n\t * This object is the result of a subscription request, allowing to manipulate the subscription itself.\n\t *\n\t * In Kuzzle, you don’t exactly subscribe to a room or a topic but, instead, you subscribe to documents.\n\t *\n\t * What it means is that, to subscribe, you provide to Kuzzle a set of matching filters.\n\t * Once you have subscribed, if a pub/sub message is published matching your filters, or if a matching stored\n\t * document change (because it is created, updated or deleted), then you’ll receive a notification about it.\n\t *\n\t * @param {object} collection - an instantiated and valid kuzzle object\n\t * @param {object} [options] - subscription optional configuration\n\t * @constructor\n\t */\n\tfunction Room(collection, options) {\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t callback: {\n\t value: null,\n\t writable: true\n\t },\n\t channel: {\n\t value: null,\n\t writable: true\n\t },\n\t id: {\n\t value: uuidv4()\n\t },\n\t lastRenewal: {\n\t value: null,\n\t writable: true\n\t },\n\t notifier: {\n\t value: null,\n\t writable: true\n\t },\n\t onDoneCB: {\n\t value: null,\n\t writable: true\n\t },\n\t queue: {\n\t value: [],\n\t writable: true\n\t },\n\t // Delay before allowing a subscription renewal\n\t renewalDelay: {\n\t value: 500\n\t },\n\t scope: {\n\t value: options && options.scope ? options.scope : 'all'\n\t },\n\t state: {\n\t value: options && options.state ? options.state : 'done'\n\t },\n\t subscribing: {\n\t value: false,\n\t writable: true\n\t },\n\t users: {\n\t value: options && options.users ? options.users : 'none'\n\t },\n\t // read-only properties\n\t collection: {\n\t value: collection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: collection.kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t filters: {\n\t value: null,\n\t enumerable: true,\n\t writable: true\n\t },\n\t headers: {\n\t value: JSON.parse(JSON.stringify(collection.headers)),\n\t enumerable: true,\n\t writable: true\n\t },\n\t volatile: {\n\t value: (options && options.volatile) ? options.volatile : {},\n\t enumerable: true,\n\t writable: true\n\t },\n\t roomId: {\n\t value: null,\n\t enumerable: true,\n\t writable: true\n\t },\n\t subscribeToSelf: {\n\t value: options && typeof options.subscribeToSelf === 'boolean' ? options.subscribeToSelf : true,\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['count'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * Returns the number of other subscriptions on that room.\n\t *\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tRoom.prototype.count = function (cb) {\n\t var data;\n\t\n\t this.kuzzle.callbackRequired('Room.count', cb);\n\t\n\t data = this.kuzzle.addHeaders({body: {roomId: this.roomId}}, this.headers);\n\t\n\t if (!isReady.call(this)) {\n\t this.queue.push({action: 'count', args: [cb]});\n\t return;\n\t }\n\t\n\t if (!this.roomId) {\n\t throw new Error('Room.count: cannot count subscriptions on an inactive room');\n\t }\n\t\n\t this.kuzzle.query(this.collection.buildQueryArgs('realtime', 'count'), data, function (err, res) {\n\t cb(err, res && res.result.count);\n\t });\n\t};\n\t\n\t/**\n\t * Renew the subscription using new filters\n\t *\n\t * @param {object} [filters] - Filters in Kuzzle DSL format\n\t * @param {responseCallback} notificationCB - called for each new notification\n\t * @param {responseCallback} [cb] - handles the query response\n\t */\n\tRoom.prototype.renew = function (filters, notificationCB, cb) {\n\t var\n\t self = this,\n\t now = Date.now(),\n\t subscribeQuery = {\n\t scope: self.scope,\n\t state: self.state,\n\t users: self.users\n\t };\n\t\n\t if (typeof filters === 'function') {\n\t cb = notificationCB;\n\t notificationCB = filters;\n\t filters = null;\n\t }\n\t\n\t if (!cb) {\n\t cb = self.onDoneCB;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Room.renew', notificationCB);\n\t\n\t /*\n\t Skip subscription renewal if another one was performed a moment before\n\t */\n\t if (self.lastRenewal && (now - self.lastRenewal) <= self.renewalDelay) {\n\t return cb && cb(new Error('Subscription already renewed less than ' + self.renewalDelay + 'ms ago'));\n\t }\n\t\n\t if (filters) {\n\t self.filters = filters;\n\t }\n\t\n\t /*\n\t if not yet connected, register itself to the subscriptions list and wait for the\n\t main Kuzzle object to renew once online\n\t */\n\t if (self.kuzzle.state !== 'connected') {\n\t self.callback = notificationCB;\n\t self.onDoneCB = cb;\n\t self.kuzzle.subscriptions.pending[self.id] = self;\n\t return;\n\t }\n\t\n\t if (self.subscribing) {\n\t self.queue.push({action: 'renew', args: [filters, notificationCB, cb]});\n\t return;\n\t }\n\t\n\t self.unsubscribe();\n\t self.roomId = null;\n\t self.subscribing = true;\n\t self.callback = notificationCB;\n\t self.onDoneCB = cb;\n\t self.kuzzle.subscriptions.pending[self.id] = self;\n\t\n\t subscribeQuery.body = self.filters;\n\t subscribeQuery = self.kuzzle.addHeaders(subscribeQuery, self.headers);\n\t\n\t self.kuzzle.query(self.collection.buildQueryArgs('realtime', 'subscribe'), subscribeQuery, {volatile: self.volatile}, function (error, response) {\n\t delete self.kuzzle.subscriptions.pending[self.id];\n\t self.subscribing = false;\n\t\n\t if (error) {\n\t self.queue = [];\n\t return cb && cb(new Error('Error during Kuzzle subscription: ' + error.message));\n\t }\n\t\n\t self.lastRenewal = now;\n\t self.roomId = response.result.roomId;\n\t self.channel = response.result.channel;\n\t\n\t if (!self.kuzzle.subscriptions[self.roomId]) {\n\t self.kuzzle.subscriptions[self.roomId] = {};\n\t }\n\t\n\t self.kuzzle.subscriptions[self.roomId][self.id] = self;\n\t\n\t self.notifier = notificationCallback.bind(self);\n\t self.kuzzle.network.on(self.channel, self.notifier);\n\t\n\t dequeue.call(self);\n\t cb && cb(null, self);\n\t });\n\t};\n\t\n\t/**\n\t * Unsubscribes from Kuzzle.\n\t *\n\t * Stop listening immediately. If there is no listener left on that room, sends an unsubscribe request to Kuzzle, once\n\t * pending subscriptions reaches 0, and only if there is still no listener on that room.\n\t * We wait for pending subscriptions to finish to avoid unsubscribing while another subscription on that room is\n\t *\n\t * @return {*} this\n\t */\n\tRoom.prototype.unsubscribe = function () {\n\t var\n\t self = this,\n\t room = self.roomId,\n\t interval;\n\t\n\t if (!isReady.call(this)) {\n\t self.queue.push({action: 'unsubscribe', args: []});\n\t return self;\n\t }\n\t\n\t if (room) {\n\t self.kuzzle.network.off(self.channel, this.notifier);\n\t\n\t if (Object.keys(self.kuzzle.subscriptions[room]).length === 1) {\n\t delete self.kuzzle.subscriptions[room];\n\t\n\t if (Object.keys(self.kuzzle.subscriptions.pending).length === 0) {\n\t self.kuzzle.query(self.collection.buildQueryArgs('realtime', 'unsubscribe'), {body: {roomId: room}});\n\t } else {\n\t interval = setInterval(function () {\n\t if (Object.keys(self.kuzzle.subscriptions.pending).length === 0) {\n\t if (!self.kuzzle.subscriptions[room]) {\n\t self.kuzzle.query(self.collection.buildQueryArgs('realtime', 'unsubscribe'), {body: {roomId: room}});\n\t }\n\t clearInterval(interval);\n\t }\n\t }, 100);\n\t }\n\t } else {\n\t delete self.kuzzle.subscriptions[room][self.id];\n\t }\n\t\n\t self.roomId = null;\n\t }\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Helper function allowing to set headers while chaining calls.\n\t *\n\t * If the replace argument is set to true, replace the current headers with the provided content.\n\t * Otherwise, it appends the content to the current headers, only replacing already existing values\n\t *\n\t * @param content - new headers content\n\t * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n\t */\n\tRoom.prototype.setHeaders = function (content, replace) {\n\t this.kuzzle.setHeaders.call(this, content, replace);\n\t return this;\n\t};\n\t\n\t/**\n\t * Callback called by the network handler when a message is sent to the subscribed room ID\n\t * Calls the registered callback if the notification passes the subscription filters\n\t *\n\t * @param {object} data - data\n\t * @returns {*}\n\t */\n\tfunction notificationCallback (data) {\n\t if (data.type === 'TokenExpired') {\n\t this.kuzzle.jwtToken = undefined;\n\t return this.kuzzle.emitEvent('tokenExpired');\n\t }\n\t\n\t if (data.type === 'document') {\n\t data.document = new Document(this.collection, data.result._id, data.result._source, data.result._meta);\n\t delete data.result;\n\t }\n\t\n\t if (this.kuzzle.requestHistory[data.requestId]) {\n\t if (this.subscribeToSelf) {\n\t this.callback(null, data);\n\t }\n\t delete this.kuzzle.requestHistory[data.requestId];\n\t } else {\n\t this.callback(null, data);\n\t }\n\t}\n\t\n\t\n\t/**\n\t * Dequeue actions performed while subscription was being renewed\n\t */\n\tfunction dequeue () {\n\t var element;\n\t\n\t while (this.queue.length > 0) {\n\t element = this.queue.shift();\n\t\n\t this[element.action].apply(this, element.args);\n\t }\n\t}\n\t\n\tfunction isReady() {\n\t return this.kuzzle.state === 'connected' && !this.subscribing;\n\t}\n\t\n\tmodule.exports = Room;\n\n\n/***/ }),\n/* 11 */\n/***/ (function(module, exports) {\n\n\t/**\n\t * @param {Collection} collection\n\t * @param {int} total\n\t * @param {Document[]} documents\n\t * @param {object} aggregations\n\t * @param {object} options\n\t * @param {object} filters\n\t * @param {SearchResult} previous\n\t * @property {Collection} collection\n\t * @property {number} total\n\t * @property {Document[]} documents\n\t * @property {object} aggregations\n\t * @property {object} options\n\t * @property {object} filters\n\t * @property {number} fetchedDocument\n\t * @constructor\n\t */\n\tfunction SearchResult (collection, total, documents, aggregations, options, filters, previous) {\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t collection: {\n\t value: collection,\n\t enumerable: true\n\t },\n\t total: {\n\t value: total,\n\t enumerable: true\n\t },\n\t documents: {\n\t value: documents,\n\t enumerable: true\n\t },\n\t aggregations: {\n\t value: aggregations || {},\n\t enumerable: true\n\t },\n\t options: {\n\t value: options || {},\n\t enumerable: true\n\t },\n\t filters: {\n\t value: filters || {},\n\t enumerable: true\n\t },\n\t // writable properties\n\t fetchedDocument: {\n\t value: previous instanceof SearchResult ? documents.length + previous.fetchedDocument : documents.length,\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t // promisifying\n\t if (this.collection.kuzzle.bluebird) {\n\t return this.collection.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['fetchNext'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * @param {function} cb\n\t */\n\tSearchResult.prototype.fetchNext = function (cb) {\n\t var\n\t filters,\n\t options = Object.assign({}, this.options),\n\t self = this;\n\t \n\t options.previous = this;\n\t\n\t // retrieve next results with scroll if original search use it\n\t if (options.scrollId) {\n\t if (this.fetchedDocument >= this.getTotal()) {\n\t cb(null, null);\n\t return;\n\t }\n\t\n\t // from and size parameters are not valid for a scroll action\n\t if (typeof options.from !== 'undefined') {\n\t delete options.from;\n\t }\n\t\n\t if (options.size) {\n\t delete options.size;\n\t }\n\t\n\t this.collection.scroll(options.scrollId, options, this.filters || {}, cb);\n\t\n\t return;\n\t }\n\t\n\t // retrieve next results using ES's search_after\n\t if (options.size && this.filters.sort) {\n\t if (this.fetchedDocument >= this.getTotal()) {\n\t cb(null, null);\n\t return;\n\t }\n\t\n\t if (options.from) {\n\t delete options.from;\n\t }\n\t\n\t filters = Object.assign(this.filters, {search_after: []});\n\t\n\t filters.sort.forEach(function (sortRule) {\n\t filters.search_after.push(self.documents[self.documents.length - 1].content[Object.keys(sortRule)[0]]);\n\t });\n\t\n\t this.collection.search(filters, options, cb);\n\t\n\t return;\n\t }\n\t\n\t // retrieve next results with from/size if original search use it\n\t if (options.from !== undefined && options.size !== undefined) {\n\t filters = Object.assign({}, this.filters);\n\t\n\t // check if we need to do next request to fetch all matching documents\n\t options.from += options.size;\n\t\n\t if (options.from >= this.getTotal()) {\n\t cb(null, null);\n\t\n\t return;\n\t }\n\t\n\t this.collection.search(filters, options, cb);\n\t\n\t return;\n\t }\n\t\n\t cb(new Error('Unable to retrieve next results from search: missing scrollId or from/size params'));\n\t};\n\t\n\t/**\n\t * @returns {Document[]}\n\t */\n\tSearchResult.prototype.getDocuments = function () {\n\t return this.documents;\n\t};\n\t\n\t/**\n\t * @returns {number}\n\t */\n\tSearchResult.prototype.getTotal = function () {\n\t return this.total;\n\t};\n\t\n\t/**\n\t * @returns {object}\n\t */\n\tSearchResult.prototype.getAggregations = function () {\n\t return this.aggregations;\n\t};\n\t\n\t/**\n\t * @returns {Object}\n\t */\n\tSearchResult.prototype.getOptions = function() {\n\t return this.options;\n\t};\n\t\n\t/**\n\t * @returns {object}\n\t */\n\tSearchResult.prototype.getFilters = function() {\n\t return this.filters;\n\t};\n\t\n\t/**\n\t * @returns {object}\n\t */\n\tSearchResult.prototype.getCollection = function () {\n\t return this.collection;\n\t};\n\t\n\t/**\n\t * @returns {number}\n\t */\n\tSearchResult.prototype.getFetchedDocument = function () {\n\t return this.fetchedDocument;\n\t};\n\t\n\tmodule.exports = SearchResult;\n\n\n/***/ }),\n/* 12 */\n/***/ (function(module, exports) {\n\n\t/**\n\t * Sugar-code handling the result of a Room.renew call\n\t * @constructor\n\t */\n\tfunction SubscribeResult() {\n\t this.cbs = [];\n\t this.error = null;\n\t this.room = null;\n\t}\n\t\n\t/**\n\t * Registers a callback to be called with a subscription result\n\t * @param {Function} cb\n\t */\n\tSubscribeResult.prototype.onDone = function (cb) {\n\t if (this.error || this.room) {\n\t cb(this.error, this.room);\n\t }\n\t else {\n\t this.cbs.push(cb);\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Calls all registered callbacks\n\t *\n\t * @param {Object} error object\n\t * @param {Room} room\n\t */\n\tSubscribeResult.prototype.done = function (error, room) {\n\t this.error = error;\n\t this.room = room;\n\t\n\t this.cbs.forEach(function (cb) {\n\t cb(error, room);\n\t });\n\t};\n\t\n\tmodule.exports = SubscribeResult;\n\n\n/***/ }),\n/* 13 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/**\n\t *\n\t * @param host\n\t * @param port\n\t * @param sslConnection\n\t * @returns {Object} tnstantiated WebSocket/Socket.IO object\n\t */\n\t\n\tfunction network(host, port, sslConnection) {\n\t // Web browser / NodeJS websocket handling\n\t if (typeof window !== 'undefined') {\n\t // use native websockets if the browser supports it\n\t if (typeof WebSocket !== 'undefined') {\n\t return new (__webpack_require__(4))(host, port, sslConnection);\n\t }\n\t // otherwise fallback to socket.io, if available\n\t else if (window.io) {\n\t return new (__webpack_require__(14))(host, port, sslConnection);\n\t }\n\t\n\t throw new Error('Aborting: no websocket support detected and no socket.io library loaded either.');\n\t }\n\t\n\t return new (__webpack_require__(4))(host, port, sslConnection);\n\t}\n\t\n\tmodule.exports = network;\n\n\n/***/ }),\n/* 14 */\n/***/ (function(module, exports) {\n\n\tfunction SocketIO(host, port, ssl) {\n\t this.host = host;\n\t this.port = port;\n\t this.ssl = ssl;\n\t this.socket = null;\n\t this.wasConnected = false;\n\t this.forceDisconnect = false;\n\t this.handlers = {\n\t connect: [],\n\t reconnect: [],\n\t connectError: [],\n\t disconnect: []\n\t };\n\t this.retrying = false;\n\t\n\t /**\n\t * Creates a new socket from the provided arguments\n\t *\n\t * @constructor\n\t * @param {boolean} autoReconnect\n\t * @param {int} reconnectionDelay\n\t */\n\t this.connect = function (autoReconnect, reconnectionDelay) {\n\t var self = this;\n\t\n\t this.socket = window.io((this.ssl ? 'https://' : 'http://') + this.host + ':' + this.port, {\n\t reconnection: autoReconnect,\n\t reconnectionDelay: reconnectionDelay,\n\t forceNew: true\n\t });\n\t\n\t this.socket.on('connect', function() {\n\t if (self.wasConnected) {\n\t self.handlers.reconnect.forEach(function(handler) {\n\t handler();\n\t });\n\t }\n\t else {\n\t self.handlers.connect.forEach(function(handler) {\n\t handler();\n\t });\n\t }\n\t\n\t self.wasConnected = true;\n\t });\n\t\n\t this.socket.on('connect_error', function(error) {\n\t onClientNetworkError(self, autoReconnect, reconnectionDelay, error);\n\t });\n\t\n\t this.socket.on('disconnect', function() {\n\t var error;\n\t\n\t if (self.forceDisconnect) {\n\t self.handlers.disconnect.forEach(function(handler) {\n\t handler();\n\t });\n\t }\n\t else {\n\t error = new Error('An error occurred, this may due that kuzzle was not ready yet');\n\t error.status = 500;\n\t\n\t onClientNetworkError(self, autoReconnect, reconnectionDelay, error);\n\t }\n\t\n\t self.forceDisconnect = false;\n\t });\n\t };\n\t\n\t /**\n\t * Fires the provided callback whence a connection is established\n\t *\n\t * @param {function} callback\n\t */\n\t this.onConnect = function (callback) {\n\t if (this.handlers.connect.indexOf(callback) === -1) {\n\t this.handlers.connect.push(callback);\n\t }\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a connection error is received\n\t * @param {function} callback\n\t */\n\t this.onConnectError = function (callback) {\n\t if (this.handlers.connectError.indexOf(callback) === -1) {\n\t this.handlers.connectError.push(callback);\n\t }\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a disconnection occurred\n\t * @param {function} callback\n\t */\n\t this.onDisconnect = function (callback) {\n\t if (this.handlers.disconnect.indexOf(callback) === -1) {\n\t this.handlers.disconnect.push(callback);\n\t }\n\t };\n\t\n\t /**\n\t * Fires the provided callback whenever a connection has been reestablished\n\t * @param {function} callback\n\t */\n\t this.onReconnect = function (callback) {\n\t if (this.handlers.reconnect.indexOf(callback) === -1) {\n\t this.handlers.reconnect.push(callback);\n\t }\n\t };\n\t\n\t /**\n\t * Registers a callback on a room. Once 1 message is received, fires the\n\t * callback and unregister it afterward.\n\t *\n\t * @param {string} roomId\n\t * @param {function} callback\n\t */\n\t this.once = function (roomId, callback) {\n\t this.socket.once(roomId, callback);\n\t };\n\t\n\t /**\n\t * Registers a callback on a room.\n\t *\n\t * @param {string} roomId\n\t * @param {function} callback\n\t */\n\t this.on = function (roomId, callback) {\n\t this.socket.on(roomId, callback);\n\t };\n\t\n\t /**\n\t * Unregisters a callback from a room.\n\t *\n\t * @param {string} roomId\n\t * @param {function} callback\n\t */\n\t this.off = function (roomId, callback) {\n\t this.socket.off(roomId, callback);\n\t };\n\t\n\t\n\t /**\n\t * Sends a payload to the connected server\n\t *\n\t * @param {Object} payload\n\t */\n\t this.send = function (payload) {\n\t this.socket.emit('kuzzle', payload);\n\t };\n\t\n\t /**\n\t * Closes the connection\n\t */\n\t this.close = function () {\n\t this.forceDisconnect = true;\n\t\n\t this.socket.close();\n\t this.socket = null;\n\t };\n\t}\n\t\n\t/**\n\t * Called when the connection closes with an error state\n\t *\n\t * @param {SocketIO}\n\t * @param {boolean} autoReconnect\n\t * @param {number} reconnectionDelay\n\t * @param {Error} error\n\t */\n\tfunction onClientNetworkError(socketio, autoReconnect, reconnectionDelay, error) {\n\t if (autoReconnect && !socketio.retrying && !socketio.stopRetryingToConnect) {\n\t socketio.retrying = true;\n\t setTimeout(function () {\n\t socketio.retrying = false;\n\t socketio.connect(autoReconnect, reconnectionDelay);\n\t }, reconnectionDelay);\n\t }\n\t\n\t socketio.handlers.connectError.forEach(function(handler) {\n\t handler(error);\n\t });\n\t}\n\t\n\t\n\tmodule.exports = SocketIO;\n\n\n/***/ }),\n/* 15 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tvar SecurityDocument = __webpack_require__(1);\n\t\n\tfunction Profile(Security, id, content, meta) {\n\t\n\t SecurityDocument.call(this, Security, id, content, meta);\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t deleteActionName: {\n\t value: 'deleteProfile'\n\t },\n\t updateActionName: {\n\t value: 'updateProfile'\n\t }\n\t });\n\t\n\t // promisifying\n\t if (Security.kuzzle.bluebird) {\n\t return Security.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['hydrate', 'save'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t}\n\t\n\tProfile.prototype = Object.create(SecurityDocument.prototype, {\n\t constructor: {\n\t value: Profile\n\t }\n\t});\n\t\n\t/**\n\t * Persist to the persistent layer the current profile\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Profile} this\n\t */\n\tProfile.prototype.save = function (options, cb) {\n\t var\n\t data,\n\t self = this;\n\t\n\t if (!this.content.policies) {\n\t throw new Error('Argument \"policies\" is mandatory in a profile. This argument contains an array of objects.');\n\t }\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = this.serialize();\n\t\n\t self.kuzzle.query(self.Security.buildQueryArgs('createOrReplaceProfile'), data, options, cb && function (error) {\n\t cb(error, error ? undefined : self);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t\n\t/**\n\t * Add a policy in the policies list\n\t * @param {Object} policy - must be an object containing at least a \"roleId\" member which must be a string.\n\t *\n\t * @returns {Profile} this\n\t */\n\tProfile.prototype.addPolicy = function (policy) {\n\t\n\t if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n\t throw new Error('Parameter \"policies\" must be an object containing at least a \"roleId\" member which must be a string.');\n\t }\n\t\n\t if (!this.content.policies) {\n\t this.content.policies = [];\n\t }\n\t\n\t this.content.policies.push(policy);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Set policies list\n\t * @param {Array} policies - must be an array of objects containing at least a \"roleId\" member which must be a string\n\t *\n\t * @returns {Profile} this\n\t */\n\tProfile.prototype.setPolicies = function (policies) {\n\t\n\t if (!Array.isArray(policies)) {\n\t throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n\t }\n\t\n\t policies.map(function (policy) {\n\t if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n\t throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n\t }\n\t });\n\t\n\t this.content.policies = policies;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Serialize this object into a JSON object\n\t *\n\t * @return {object} JSON object representing this securityDocument\n\t */\n\tProfile.prototype.serialize = function () {\n\t var\n\t data = {};\n\t\n\t if (this.id) {\n\t data._id = this.id;\n\t }\n\t\n\t data.body = this.content;\n\t data.meta = this.meta;\n\t\n\t return data;\n\t};\n\t\n\t/**\n\t * Returns the list of policies associated to this profile.\n\t * Each policy element is an array of objects containing at least a \"roleId\" member which must be a string\n\t *\n\t * @return {object} an array of policies\n\t */\n\tProfile.prototype.getPolicies = function () {\n\t return this.content.policies;\n\t};\n\t\n\tmodule.exports = Profile;\n\n\n/***/ }),\n/* 16 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tvar SecurityDocument = __webpack_require__(1);\n\t\n\tfunction Role(Security, id, content, meta) {\n\t\n\t SecurityDocument.call(this, Security, id, content, meta);\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t deleteActionName: {\n\t value: 'deleteRole'\n\t },\n\t updateActionName: {\n\t value: 'updateRole'\n\t }\n\t });\n\t\n\t // promisifying\n\t if (Security.kuzzle.bluebird) {\n\t return Security.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['save'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t}\n\t\n\tRole.prototype = Object.create(SecurityDocument.prototype, {\n\t constructor: {\n\t value: Role\n\t }\n\t});\n\t\n\t/**\n\t * Saves this role into Kuzzle.\n\t *\n\t * If this is a new role, this function will create it in Kuzzle.\n\t * Otherwise, this method will replace the latest version of this role in Kuzzle by the current content\n\t * of this object.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Role} this object\n\t */\n\tRole.prototype.save = function (options, cb) {\n\t var\n\t data = this.serialize(),\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.Security.buildQueryArgs('createOrReplaceRole'), data, options, cb && function (error) {\n\t cb(error, error ? undefined : self);\n\t });\n\t\n\t return this;\n\t};\n\t\n\tmodule.exports = Role;\n\n\n/***/ }),\n/* 17 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tvar\n\t Role = __webpack_require__(16),\n\t Profile = __webpack_require__(15),\n\t User = __webpack_require__(5);\n\t\n\t/**\n\t * Kuzzle security constructor\n\t *\n\t * @param kuzzle\n\t * @returns {Security}\n\t * @constructor\n\t */\n\tfunction Security(kuzzle) {\n\t\n\t Object.defineProperty(this, 'kuzzle', {\n\t value: kuzzle\n\t });\n\t\n\t Object.defineProperty(this, 'buildQueryArgs', {\n\t value: function (action) {\n\t return {\n\t controller: 'security',\n\t action: action\n\t };\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = ['role', 'profile', 'user', 'isActionAllowed'];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t\n\t/**\n\t * Retrieve a single Role using its unique role ID.\n\t *\n\t * @param {string} id\n\t * @param {object|responseCallback} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tSecurity.prototype.fetchRole = function (id, options, cb) {\n\t var\n\t data,\n\t self = this;\n\t\n\t if (!id) {\n\t throw new Error('Id parameter is mandatory for fetchRole function');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = {_id: id};\n\t\n\t self.kuzzle.callbackRequired('Security.fetchRole', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n\t cb(err, err ? undefined : new Role(self, response.result._id, response.result._source, response.result._meta));\n\t });\n\t};\n\t\n\t/**\n\t * Executes a search on roles according to a filter\n\t *\n\t * /!\\ There is a small delay between role creation and their existence in our persistent search layer,\n\t * usually a couple of seconds.\n\t * That means that a role that was just been created won’t be returned by this function.\n\t *\n\t * @param {Object} filters - this object can contains an array `indexes` with a list of index id, a integer `from` and a integer `size`\n\t * @param {object|responseCallback} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t *\n\t */\n\tSecurity.prototype.searchRoles = function (filters, options, cb) {\n\t var\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Security.searchRoles', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchRoles'), {body: filters}, options, function (error, result) {\n\t var documents;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t documents = result.result.hits.map(function (doc) {\n\t return new Role(self, doc._id, doc._source, doc._meta);\n\t });\n\t\n\t cb(null, { total: result.result.total, roles: documents });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new role in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following property:\n\t * - replaceIfExist (boolean, default: false):\n\t * If the same role already exists: throw an error if sets to false.\n\t * Replace the existing role otherwise\n\t *\n\t * @param {string} id - role identifier\n\t * @param {object} content - a plain javascript object representing the role\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tSecurity.prototype.createRole = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'createRole';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Security.createRole: cannot create a role without a role ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t data.body = content;\n\t\n\t if (options) {\n\t action = options.replaceIfExist ? 'createOrReplaceRole' : 'createRole';\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new Role(self, res.result._id, res.result._source, res.result._meta));\n\t });\n\t};\n\t\n\t\n\t/**\n\t * Update a role in Kuzzle.\n\t *\n\t * @param {string} id - role identifier\n\t * @param {object} content - a plain javascript object representing the role's modification\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {Security} this object\n\t */\n\tSecurity.prototype.updateRole = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {_id: id, body: content},\n\t action = 'updateRole';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Security.updateRole: cannot update a role without a role ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new Role(self, id, content, res.result._meta));\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete role.\n\t *\n\t * There is a small delay between role deletion and their deletion in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a role that was just been delete will be returned by this function\n\t *\n\t *\n\t * @param {string} id - Role id to delete\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Security} this object\n\t */\n\tSecurity.prototype.deleteRole = function (id, options, cb) {\n\t var data = {_id: id};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('deleteRole'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result._id);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Instantiate a new Role object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - role id\n\t * @param {object} content - role content\n\t * @param {object} meta - role metadata\n\t * @constructor\n\t */\n\tSecurity.prototype.role = function(id, content, meta) {\n\t return new Role(this, id, content, meta);\n\t};\n\t\n\t\n\t/**\n\t * Get a specific profile from kuzzle\n\t *\n\t *\n\t * @param {string} id\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tSecurity.prototype.fetchProfile = function (id, options, cb) {\n\t var\n\t data,\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Id parameter is mandatory for fetchProfile function');\n\t }\n\t\n\t\n\t data = {_id: id};\n\t\n\t self.kuzzle.callbackRequired('Security.fetchProfile', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n\t cb(error, error ? undefined : new Profile(self, response.result._id, response.result._source, response.result._meta));\n\t });\n\t};\n\t\n\t/**\n\t * Executes a search on profiles according to a filter\n\t *\n\t *\n\t * /!\\ There is a small delay between profile creation and their existence in our persistent search layer,\n\t * usually a couple of seconds.\n\t * That means that a profile that was just been created won’t be returned by this function.\n\t *\n\t * @param {Object} filters - this object can contains an array `roles` with a list of roles id, a integer `from` and a integer `size`\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tSecurity.prototype.searchProfiles = function (filters, options, cb) {\n\t var\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Security.searchProfiles', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n\t var\n\t documents,\n\t scrollId;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t documents = response.result.hits.map(function (doc) {\n\t return new Profile(self, doc._id, doc._source, doc._meta);\n\t });\n\t\n\t if (response.result.scrollId) {\n\t scrollId = response.result.scrollId;\n\t }\n\t\n\t cb(null, { total: response.result.total, profiles: documents, scrollId: scrollId });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new profile in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following property:\n\t * - replaceIfExist (boolean, default: false):\n\t * If the same profile already exists: throw an error if sets to false.\n\t * Replace the existing profile otherwise\n\t *\n\t * @param {string} id - profile identifier\n\t * @param {array} policies - list of policies to attach to the new profile\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tSecurity.prototype.createProfile = function (id, policies, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'createProfile';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Security.createProfile: cannot create a profile without a profile ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t\n\t if (policies) {\n\t data.body = { policies: policies };\n\t }\n\t\n\t if (options) {\n\t action = options.replaceIfExist ? 'createOrReplaceProfile' : 'createProfile';\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new Profile(self, res.result._id, res.result._source, res.result._meta));\n\t });\n\t};\n\t\n\t\n\t/**\n\t * Update a profile in Kuzzle.\n\t *\n\t * @param {string} id - profile identifier\n\t * @param {array} policies - the list of policies to apply to this profile\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {Security} this object\n\t */\n\tSecurity.prototype.updateProfile = function (id, policies, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'updateProfile';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Security.updateProfile: cannot update a profile without a profile ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t\n\t if (policies) {\n\t data.body = {policies: policies};\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t var updatedContent = {};\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t Object.keys(res.result._source).forEach(function (property) {\n\t updatedContent[property] = res.result._source[property];\n\t });\n\t\n\t cb(null, new Profile(self, res.result._id, updatedContent, res.result._meta));\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete profile.\n\t *\n\t * There is a small delay between profile deletion and their deletion in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a profile that was just been delete will be returned by this function\n\t *\n\t *\n\t * @param {string} id - Profile id to delete\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Security} this object\n\t */\n\tSecurity.prototype.deleteProfile = function (id, options, cb) {\n\t var data = {_id: id};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('deleteProfile'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result._id);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * @param {string} scrollId\n\t * @param {object} [options]\n\t * @param {responseCallback} cb\n\t */\n\tSecurity.prototype.scrollProfiles = function (scrollId, options, cb) {\n\t var\n\t request = {},\n\t self = this;\n\t\n\t if (!scrollId) {\n\t throw new Error('Security.scrollProfiles: scrollId is required');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = {};\n\t }\n\t\n\t this.kuzzle.callbackRequired('Security.scrollProfiles', cb);\n\t\n\t request.scrollId = scrollId;\n\t\n\t if (options && options.scroll) {\n\t request.scroll = options.scroll;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'scrollProfiles'}, request, options, function (error, result) {\n\t var profiles = [];\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t result.result.hits.forEach(function (profile) {\n\t var newProfile = new Profile(self, profile._id, profile._source, profile._meta);\n\t\n\t newProfile.version = profile._version;\n\t\n\t profiles.push(newProfile);\n\t });\n\t\n\t cb(null, {\n\t total: result.result.total,\n\t profiles: profiles,\n\t scrollId: scrollId\n\t });\n\t });\n\t};\n\t\n\t/**\n\t * Instantiate a new Profile object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - profile id\n\t * @param {object} content - profile content\n\t * @param {object} meta - profile metadata\n\t * @constructor\n\t */\n\tSecurity.prototype.profile = function(id, content, meta) {\n\t return new Profile(this, id, content, meta);\n\t};\n\t\n\t/**\n\t * Get a specific user from kuzzle using its unique ID\n\t *\n\t * @param {string} id\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tSecurity.prototype.fetchUser = function (id, options, cb) {\n\t var\n\t data = {_id: id},\n\t self = this;\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Id parameter is mandatory for fetchUser function');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Security.fetchUser', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n\t cb(err, err ? undefined : new User(self, response.result._id, response.result._source, response.result._meta));\n\t });\n\t};\n\t\n\t/**\n\t * Executes a search on user according to a filter\n\t *\n\t * /!\\ There is a small delay between user creation and their existence in our persistent search layer,\n\t * usually a couple of seconds.\n\t * That means that a user that was just been created won’t be returned by this function.\n\t *\n\t * @param {Object} filters - same filters as documents filters\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tSecurity.prototype.searchUsers = function (filters, options, cb) {\n\t var\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Security.searchUsers', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n\t var\n\t documents,\n\t scrollId = null;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t documents = response.result.hits.map(function (doc) {\n\t return new User(self, doc._id, doc._source, doc._meta);\n\t });\n\t\n\t if (response.result.scrollId) {\n\t scrollId = response.result.scrollId;\n\t }\n\t\n\t cb(null, { total: response.result.total, users: documents, scrollId: scrollId });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new user in Kuzzle.\n\t *\n\t * @param {string} id - user identifier\n\t * @param {object} content - attribute `profileIds` in `content` must only contain an array of profile ids\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tSecurity.prototype.createUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {_id: id, body: content};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(self.buildQueryArgs('createUser'), data, null, cb && function (err, res) {\n\t cb(err, err ? undefined : new User(self, res.result._id, res.result._source, res.result._meta));\n\t });\n\t};\n\t\n\t/**\n\t * Replace an user in Kuzzle.\n\t *\n\t * @param {string} id - user identifier\n\t * @param {object} content - attribute `profileIds` in `content` must only contain an array of profile ids\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tSecurity.prototype.replaceUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {_id: id, body: content};\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Security.replaceUser: cannot replace a user without a user ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs('replaceUser'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new User(self, res.result._id, res.result._source, res.result._meta));\n\t });\n\t};\n\t\n\t/**\n\t * Create a new restricted user in Kuzzle.\n\t *\n\t * This function will create a new user. It is not usable to update an existing user.\n\t * This function allows anonymous users to create a \"restricted\" user with predefined rights.\n\t *\n\t * @param {string} id - user identifier\n\t * @param {object} content - attribute `profile` in `content` must only contains the profile id\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tSecurity.prototype.createRestrictedUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {_id: id, body: content};\n\t\n\t if (content.profileIds) {\n\t throw new Error('Security.createRestrictedUser: cannot provide profileIds');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs('createRestrictedUser'), data, null, cb && function (err, res) {\n\t cb(err, err ? undefined : new User(self, res.result._id, res.result._source));\n\t });\n\t};\n\t\n\t\n\t/**\n\t * Update an user in Kuzzle.\n\t *\n\t * @param {string} id - user identifier\n\t * @param {object} content - a plain javascript object representing the user's modification\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {Security} this object\n\t */\n\tSecurity.prototype.updateUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'updateUser';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Security.updateUser: cannot update an user without an user ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t data.body = content;\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new User(self, res.result._id, res.result._source, res.result._meta));\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete user.\n\t *\n\t * There is a small delay between user deletion and their deletion in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a user that was just been delete will be returned by this function\n\t *\n\t *\n\t * @param {string} id - Profile id to delete\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Security} this object\n\t */\n\tSecurity.prototype.deleteUser = function (id, options, cb) {\n\t var data = {_id: id};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('deleteUser'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result._id);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * @param {string} scrollId\n\t * @param {object} [options]\n\t * @param {responseCallback} cb\n\t */\n\tSecurity.prototype.scrollUsers = function (scrollId, options, cb) {\n\t var\n\t request = {},\n\t self = this;\n\t\n\t if (!scrollId) {\n\t throw new Error('Security.scrollUsers: scrollId is required');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = {};\n\t }\n\t\n\t this.kuzzle.callbackRequired('Security.scrollUsers', cb);\n\t\n\t request.scrollId = scrollId;\n\t\n\t if (options && options.scroll) {\n\t request.scroll = options.scroll;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'scrollUsers'}, request, options, function (error, result) {\n\t var users = [];\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t result.result.hits.forEach(function (user) {\n\t var newUser = new User(self, user._id, user._source, user._meta);\n\t\n\t newUser.version = user._version;\n\t\n\t users.push(newUser);\n\t });\n\t\n\t cb(null, {\n\t total: result.result.total,\n\t users: users,\n\t scrollId: scrollId\n\t });\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Instantiate a new User object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - user id\n\t * @param {object} content - user content\n\t * @param {object} meta - user metadata\n\t * @constructor\n\t */\n\tSecurity.prototype.user = function(id, content, meta) {\n\t return new User(this, id, content, meta);\n\t};\n\t\n\t/**\n\t * Tells whether an action is allowed, denied or conditional based on the rights\n\t * rights provided as the first argument. An action is defined as a couple of\n\t * action and controller (mandatory), plus an index and a collection(optional).\n\t *\n\t * @param {object} rights - The rights rights associated to a user\n\t * (see getMyrights and getUserrights).\n\t * @param {string} controller - The controller to check the action onto.\n\t * @param {string} action - The action to perform.\n\t * @param {string} index - (optional) The name of index to perform the action onto.\n\t * @param {string} collection - (optional) The name of the collection to perform the action onto.\n\t *\n\t * @returns {string} ['allowed', 'denied', 'conditional'] where conditional cases\n\t * correspond to rights containing closures.\n\t * See also http://kuzzle.io/guide/#roles-definition\n\t */\n\tSecurity.prototype.isActionAllowed = function(rights, controller, action, index, collection) {\n\t var filteredRights;\n\t\n\t if (!rights || typeof rights !== 'object') {\n\t throw new Error('rights parameter is mandatory for isActionAllowed function');\n\t }\n\t if (!controller || typeof controller !== 'string') {\n\t throw new Error('controller parameter is mandatory for isActionAllowed function');\n\t }\n\t if (!action || typeof action !== 'string') {\n\t throw new Error('action parameter is mandatory for isActionAllowed function');\n\t }\n\t\n\t // We filter in all the rights that match the request (including wildcards).\n\t filteredRights = rights\n\t .filter(function (right) {\n\t return right.controller === controller || right.controller === '*';\n\t })\n\t .filter(function (right) {\n\t return right.action === action || right.action === '*';\n\t })\n\t .filter(function (right) {\n\t return right.index === index || right.index === '*';\n\t })\n\t .filter(function (right) {\n\t return right.collection === collection || right.collection === '*';\n\t });\n\t\n\t // Then, if at least one right allows the action, we return 'allowed'\n\t if (filteredRights.some(function (item) { return item.value === 'allowed'; })) {\n\t return 'allowed';\n\t }\n\t // If no right allows the action, we check for conditionals.\n\t if (filteredRights.some(function (item) { return item.value === 'conditional'; })) {\n\t return 'conditional';\n\t }\n\t // Otherwise we return 'denied'.\n\t return 'denied';\n\t};\n\t\n\t\n\t/**\n\t * Gets the rights array of a given user.\n\t *\n\t * @param {string} userId The id of the user.\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {function} cb The callback containing the normalized array of rights.\n\t */\n\tSecurity.prototype.getUserRights = function (userId, options, cb) {\n\t var\n\t data = {_id: userId},\n\t self = this;\n\t\n\t if (!userId || typeof userId !== 'string') {\n\t throw new Error('userId parameter is mandatory for getUserRights function');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Kuzzle.getUserRights', cb);\n\t\n\t this.kuzzle.query(this.buildQueryArgs('getUserRights'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result.hits);\n\t });\n\t};\n\t\n\t/**\n\t * Create credentials of the specified for the user .\n\t *\n\t * @param strategy\n\t * @param kuid\n\t * @param credentials\n\t * @param options\n\t * @param cb\n\t * @returns {Security}\n\t */\n\tSecurity.prototype.createCredentials = function (strategy, kuid, credentials, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'createCredentials'}, {_id: kuid, strategy: strategy, body: credentials}, options, function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result._source);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete credentials of the specified for the user .\n\t *\n\t * @param strategy\n\t * @param kuid\n\t * @param options\n\t * @param cb\n\t * @returns {Security}\n\t */\n\tSecurity.prototype.deleteCredentials = function (strategy, kuid, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'deleteCredentials'}, {strategy: strategy, _id: kuid}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Retrieve a list of accepted fields per authentication strategy.\n\t *\n\t * @param options\n\t * @param cb\n\t */\n\tSecurity.prototype.getAllCredentialFields = function (options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'getAllCredentialFields'}, {}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Retrieve the list of accepted field names by the specified .\n\t *\n\t * @param strategy\n\t * @param options\n\t * @param cb\n\t */\n\tSecurity.prototype.getCredentialFields = function (strategy, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'getCredentialFields'}, {strategy: strategy}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Get credential information of the specified for the user .\n\t *\n\t * @param strategy\n\t * @param kuid\n\t * @param options\n\t * @param cb\n\t */\n\tSecurity.prototype.getCredentials = function (strategy, kuid, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'getCredentials'}, {strategy: strategy, _id: kuid}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Check the existence of the specified ’s credentials for the user .\n\t *\n\t * @param strategy\n\t * @param kuid\n\t * @param options\n\t * @param cb\n\t */\n\tSecurity.prototype.hasCredentials = function (strategy, kuid, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'hasCredentials'}, {strategy: strategy, _id: kuid}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Updates credentials of the specified for the user .\n\t *\n\t * @param strategy\n\t * @param kuid\n\t * @param credentials\n\t * @param options\n\t * @param cb\n\t * @returns {Security}\n\t */\n\tSecurity.prototype.updateCredentials = function (strategy, kuid, credentials, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'updateCredentials'}, {strategy: strategy, _id: kuid, body: credentials}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Validate credentials of the specified for the user .\n\t *\n\t * @param strategy\n\t * @param kuid\n\t * @param credentials\n\t * @param options\n\t * @param cb\n\t */\n\tSecurity.prototype.validateCredentials = function (strategy, kuid, credentials, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'validateCredentials'}, {strategy: strategy, _id: kuid, body: credentials}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t};\n\t\n\tmodule.exports = Security;\n\n\n/***/ }),\n/* 18 */\n/***/ (function(module, exports) {\n\n\t// Copyright Joyent, Inc. and other Node contributors.\n\t//\n\t// Permission is hereby granted, free of charge, to any person obtaining a\n\t// copy of this software and associated documentation files (the\n\t// \"Software\"), to deal in the Software without restriction, including\n\t// without limitation the rights to use, copy, modify, merge, publish,\n\t// distribute, sublicense, and/or sell copies of the Software, and to permit\n\t// persons to whom the Software is furnished to do so, subject to the\n\t// following conditions:\n\t//\n\t// The above copyright notice and this permission notice shall be included\n\t// in all copies or substantial portions of the Software.\n\t//\n\t// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\t// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\t// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n\t// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\t// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n\t// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n\t// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\t\n\tfunction EventEmitter() {\n\t this._events = this._events || {};\n\t this._maxListeners = this._maxListeners || undefined;\n\t}\n\tmodule.exports = EventEmitter;\n\t\n\t// Backwards-compat with node 0.10.x\n\tEventEmitter.EventEmitter = EventEmitter;\n\t\n\tEventEmitter.prototype._events = undefined;\n\tEventEmitter.prototype._maxListeners = undefined;\n\t\n\t// By default EventEmitters will print a warning if more than 10 listeners are\n\t// added to it. This is a useful default which helps finding memory leaks.\n\tEventEmitter.defaultMaxListeners = 10;\n\t\n\t// Obviously not all Emitters should be limited to 10. This function allows\n\t// that to be increased. Set to zero for unlimited.\n\tEventEmitter.prototype.setMaxListeners = function(n) {\n\t if (!isNumber(n) || n < 0 || isNaN(n))\n\t throw TypeError('n must be a positive number');\n\t this._maxListeners = n;\n\t return this;\n\t};\n\t\n\tEventEmitter.prototype.emit = function(type) {\n\t var er, handler, len, args, i, listeners;\n\t\n\t if (!this._events)\n\t this._events = {};\n\t\n\t // If there is no 'error' event listener then throw.\n\t if (type === 'error') {\n\t if (!this._events.error ||\n\t (isObject(this._events.error) && !this._events.error.length)) {\n\t er = arguments[1];\n\t if (er instanceof Error) {\n\t throw er; // Unhandled 'error' event\n\t } else {\n\t // At least give some kind of context to the user\n\t var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n\t err.context = er;\n\t throw err;\n\t }\n\t }\n\t }\n\t\n\t handler = this._events[type];\n\t\n\t if (isUndefined(handler))\n\t return false;\n\t\n\t if (isFunction(handler)) {\n\t switch (arguments.length) {\n\t // fast cases\n\t case 1:\n\t handler.call(this);\n\t break;\n\t case 2:\n\t handler.call(this, arguments[1]);\n\t break;\n\t case 3:\n\t handler.call(this, arguments[1], arguments[2]);\n\t break;\n\t // slower\n\t default:\n\t args = Array.prototype.slice.call(arguments, 1);\n\t handler.apply(this, args);\n\t }\n\t } else if (isObject(handler)) {\n\t args = Array.prototype.slice.call(arguments, 1);\n\t listeners = handler.slice();\n\t len = listeners.length;\n\t for (i = 0; i < len; i++)\n\t listeners[i].apply(this, args);\n\t }\n\t\n\t return true;\n\t};\n\t\n\tEventEmitter.prototype.addListener = function(type, listener) {\n\t var m;\n\t\n\t if (!isFunction(listener))\n\t throw TypeError('listener must be a function');\n\t\n\t if (!this._events)\n\t this._events = {};\n\t\n\t // To avoid recursion in the case that type === \"newListener\"! Before\n\t // adding it to the listeners, first emit \"newListener\".\n\t if (this._events.newListener)\n\t this.emit('newListener', type,\n\t isFunction(listener.listener) ?\n\t listener.listener : listener);\n\t\n\t if (!this._events[type])\n\t // Optimize the case of one listener. Don't need the extra array object.\n\t this._events[type] = listener;\n\t else if (isObject(this._events[type]))\n\t // If we've already got an array, just append.\n\t this._events[type].push(listener);\n\t else\n\t // Adding the second element, need to change to array.\n\t this._events[type] = [this._events[type], listener];\n\t\n\t // Check for listener leak\n\t if (isObject(this._events[type]) && !this._events[type].warned) {\n\t if (!isUndefined(this._maxListeners)) {\n\t m = this._maxListeners;\n\t } else {\n\t m = EventEmitter.defaultMaxListeners;\n\t }\n\t\n\t if (m && m > 0 && this._events[type].length > m) {\n\t this._events[type].warned = true;\n\t console.error('(node) warning: possible EventEmitter memory ' +\n\t 'leak detected. %d listeners added. ' +\n\t 'Use emitter.setMaxListeners() to increase limit.',\n\t this._events[type].length);\n\t if (typeof console.trace === 'function') {\n\t // not supported in IE 10\n\t console.trace();\n\t }\n\t }\n\t }\n\t\n\t return this;\n\t};\n\t\n\tEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\t\n\tEventEmitter.prototype.once = function(type, listener) {\n\t if (!isFunction(listener))\n\t throw TypeError('listener must be a function');\n\t\n\t var fired = false;\n\t\n\t function g() {\n\t this.removeListener(type, g);\n\t\n\t if (!fired) {\n\t fired = true;\n\t listener.apply(this, arguments);\n\t }\n\t }\n\t\n\t g.listener = listener;\n\t this.on(type, g);\n\t\n\t return this;\n\t};\n\t\n\t// emits a 'removeListener' event iff the listener was removed\n\tEventEmitter.prototype.removeListener = function(type, listener) {\n\t var list, position, length, i;\n\t\n\t if (!isFunction(listener))\n\t throw TypeError('listener must be a function');\n\t\n\t if (!this._events || !this._events[type])\n\t return this;\n\t\n\t list = this._events[type];\n\t length = list.length;\n\t position = -1;\n\t\n\t if (list === listener ||\n\t (isFunction(list.listener) && list.listener === listener)) {\n\t delete this._events[type];\n\t if (this._events.removeListener)\n\t this.emit('removeListener', type, listener);\n\t\n\t } else if (isObject(list)) {\n\t for (i = length; i-- > 0;) {\n\t if (list[i] === listener ||\n\t (list[i].listener && list[i].listener === listener)) {\n\t position = i;\n\t break;\n\t }\n\t }\n\t\n\t if (position < 0)\n\t return this;\n\t\n\t if (list.length === 1) {\n\t list.length = 0;\n\t delete this._events[type];\n\t } else {\n\t list.splice(position, 1);\n\t }\n\t\n\t if (this._events.removeListener)\n\t this.emit('removeListener', type, listener);\n\t }\n\t\n\t return this;\n\t};\n\t\n\tEventEmitter.prototype.removeAllListeners = function(type) {\n\t var key, listeners;\n\t\n\t if (!this._events)\n\t return this;\n\t\n\t // not listening for removeListener, no need to emit\n\t if (!this._events.removeListener) {\n\t if (arguments.length === 0)\n\t this._events = {};\n\t else if (this._events[type])\n\t delete this._events[type];\n\t return this;\n\t }\n\t\n\t // emit removeListener for all listeners on all events\n\t if (arguments.length === 0) {\n\t for (key in this._events) {\n\t if (key === 'removeListener') continue;\n\t this.removeAllListeners(key);\n\t }\n\t this.removeAllListeners('removeListener');\n\t this._events = {};\n\t return this;\n\t }\n\t\n\t listeners = this._events[type];\n\t\n\t if (isFunction(listeners)) {\n\t this.removeListener(type, listeners);\n\t } else if (listeners) {\n\t // LIFO order\n\t while (listeners.length)\n\t this.removeListener(type, listeners[listeners.length - 1]);\n\t }\n\t delete this._events[type];\n\t\n\t return this;\n\t};\n\t\n\tEventEmitter.prototype.listeners = function(type) {\n\t var ret;\n\t if (!this._events || !this._events[type])\n\t ret = [];\n\t else if (isFunction(this._events[type]))\n\t ret = [this._events[type]];\n\t else\n\t ret = this._events[type].slice();\n\t return ret;\n\t};\n\t\n\tEventEmitter.prototype.listenerCount = function(type) {\n\t if (this._events) {\n\t var evlistener = this._events[type];\n\t\n\t if (isFunction(evlistener))\n\t return 1;\n\t else if (evlistener)\n\t return evlistener.length;\n\t }\n\t return 0;\n\t};\n\t\n\tEventEmitter.listenerCount = function(emitter, type) {\n\t return emitter.listenerCount(type);\n\t};\n\t\n\tfunction isFunction(arg) {\n\t return typeof arg === 'function';\n\t}\n\t\n\tfunction isNumber(arg) {\n\t return typeof arg === 'number';\n\t}\n\t\n\tfunction isObject(arg) {\n\t return typeof arg === 'object' && arg !== null;\n\t}\n\t\n\tfunction isUndefined(arg) {\n\t return arg === void 0;\n\t}\n\n\n/***/ }),\n/* 19 */\n/***/ (function(module, exports) {\n\n\t/**\n\t * Convert array of 16 byte values to UUID string format of the form:\n\t * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n\t */\n\tvar byteToHex = [];\n\tfor (var i = 0; i < 256; ++i) {\n\t byteToHex[i] = (i + 0x100).toString(16).substr(1);\n\t}\n\t\n\tfunction bytesToUuid(buf, offset) {\n\t var i = offset || 0;\n\t var bth = byteToHex;\n\t return bth[buf[i++]] + bth[buf[i++]] +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] +\n\t bth[buf[i++]] + bth[buf[i++]] +\n\t bth[buf[i++]] + bth[buf[i++]];\n\t}\n\t\n\tmodule.exports = bytesToUuid;\n\n\n/***/ }),\n/* 20 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t// Unique ID creation requires a high quality random # generator. In the\n\t// browser this is a little complicated due to unknown quality of Math.random()\n\t// and inconsistent support for the `crypto` API. We do the best we can via\n\t// feature-detection\n\tvar rng;\n\t\n\tvar crypto = (window).crypto || (window).msCrypto; // for IE 11\n\tif (crypto && crypto.getRandomValues) {\n\t // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto\n\t var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef\n\t rng = function whatwgRNG() {\n\t crypto.getRandomValues(rnds8);\n\t return rnds8;\n\t };\n\t}\n\t\n\tif (!rng) {\n\t // Math.random()-based (RNG)\n\t //\n\t // If all else fails, use Math.random(). It's fast, but is of unspecified\n\t // quality.\n\t var rnds = new Array(16);\n\t rng = function() {\n\t for (var i = 0, r; i < 16; i++) {\n\t if ((i & 0x03) === 0) r = Math.random() * 0x100000000;\n\t rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n\t }\n\t\n\t return rnds;\n\t };\n\t}\n\t\n\tmodule.exports = rng;\n\n\n/***/ })\n/******/ ])\n});\n;\n\n\n// WEBPACK FOOTER //\n// kuzzle.js"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap acd8f2ec6a57e2c5517f","var\n uuidv4 = require('uuid/v4'),\n KuzzleEventEmitter = require('./eventEmitter'),\n Collection = require('./Collection.js'),\n Security = require('./security/Security'),\n MemoryStorage = require('./MemoryStorage'),\n User = require('./security/User'),\n networkWrapper = require('./networkWrapper');\n\n/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n/**\n * Kuzzle object constructor.\n *\n * @constructor\n * @param host - Server name or IP Address to the Kuzzle instance\n * @param [options] - Connection options\n * @param {responseCallback} [cb] - Handles connection response\n */\nfunction Kuzzle (host, options, cb) {\n var self = this;\n\n if (!(this instanceof Kuzzle)) {\n return new Kuzzle(host, options, cb);\n }\n KuzzleEventEmitter.call(this);\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!host || host === '') {\n throw new Error('host argument missing');\n }\n\n Object.defineProperties(this, {\n // 'private' properties\n cleanHistoryTimer: {\n value: null,\n writable: true\n },\n collections: {\n value: {},\n writable: true\n },\n connectCB: {\n value: cb\n },\n eventActions: {\n value: [\n 'connected',\n 'networkError',\n 'disconnected',\n 'reconnected',\n 'tokenExpired',\n 'loginAttempt',\n 'offlineQueuePush',\n 'offlineQueuePop',\n 'queryError',\n 'discarded'\n ],\n writable: false\n },\n queuing: {\n value: false,\n writable: true\n },\n requestHistory: {\n value: {},\n writable: true\n },\n state: {\n value: 'initializing',\n writable: true\n },\n subscriptions: {\n /*\n Contains the centralized subscription list in the following format:\n pending: {\n subscriptionUid_1: kuzzleRoomInstance_1,\n subscriptionUid_2: kuzzleRoomInstance_2,\n subscriptionUid_...: kuzzleRoomInstance_...\n },\n 'roomId': {\n subscriptionUid_1: kuzzleRoomInstance_1,\n subscriptionUid_2: kuzzleRoomInstance_2,\n subscriptionUid_...: kuzzleRoomInstance_...\n }\n\n This was made to allow multiple subscriptions on the same set of filters, something that Kuzzle does not permit.\n This structure also allows renewing subscriptions after a connection loss\n */\n value: {\n pending: {}\n },\n writable: true\n },\n // configuration properties\n autoReconnect: {\n value: (options && typeof options.autoReconnect === 'boolean') ? options.autoReconnect : true,\n writable: true,\n enumerable: true\n },\n defaultIndex: {\n value: (options && typeof options.defaultIndex === 'string') ? options.defaultIndex : undefined,\n writable: true,\n enumerable: true\n },\n reconnectionDelay: {\n value: (options && typeof options.reconnectionDelay === 'number') ? options.reconnectionDelay : 1000,\n writable: true,\n enumerable: true\n },\n host: {\n value: host,\n writable: true,\n enumerable: true\n },\n port: {\n value: (options && typeof options.port === 'number') ? options.port : 7512,\n enumerable: true,\n writable: true\n },\n sslConnection: {\n value: (options && typeof options.sslConnection === 'boolean') ? options.sslConnection : false,\n writable: true,\n enumerable: true\n },\n autoQueue: {\n value: false,\n enumerable: true,\n writable: true\n },\n autoReplay: {\n value: false,\n enumerable: true,\n writable: true\n },\n autoResubscribe: {\n value: true,\n enumerable: true,\n writable: true\n },\n headers: {\n value: {},\n enumerable: true,\n writable: true\n },\n volatile: {\n value: {},\n enumerable: true,\n writable: true\n },\n /*\n Offline queue use the following format:\n [\n {\n ts: ,\n query: 'query',\n cb: callbackFunction\n }\n ]\n */\n offlineQueue: {\n value: [],\n enumerable: true,\n writable: true\n },\n queueFilter: {\n value: null,\n enumerable: true,\n writable: true\n },\n queueMaxSize: {\n value: 500,\n enumerable: true,\n writable: true\n },\n queueTTL: {\n value: 120000,\n enumerable: true,\n writable: true\n },\n replayInterval: {\n value: 10,\n enumerable: true,\n writable: true\n },\n jwtToken: {\n value: undefined,\n enumerable: true,\n writable: true\n },\n offlineQueueLoader: {\n value: undefined,\n enumerable: true,\n writable: true\n },\n sdkVersion: {\n value: (typeof SDKVERSION === 'undefined') ? require('../package.json').version : SDKVERSION,\n writable: false\n }\n });\n\n if (options) {\n Object.keys(options).forEach(function (opt) {\n if (self.hasOwnProperty(opt) && Object.getOwnPropertyDescriptor(self, opt).writable) {\n self[opt] = options[opt];\n }\n });\n\n if (options.offlineMode === 'auto' && this.autoReconnect) {\n this.autoQueue = this.autoReplay = this.autoResubscribe = true;\n }\n }\n\n // Helper function ensuring that this Kuzzle object is still valid before performing a query\n Object.defineProperty(this, 'isValid', {\n value: function () {\n if (self.state === 'disconnected') {\n throw new Error('This Kuzzle object has been invalidated. Did you try to access it after a disconnect call?');\n }\n }\n });\n\n // Helper function copying headers to the query data\n Object.defineProperty(this, 'addHeaders', {\n value: function (query, headers) {\n Object.keys(headers).forEach(function (header) {\n if (!query[header]) {\n query[header] = headers[header];\n }\n });\n\n return query;\n }\n });\n\n /**\n * Some methods (mainly read queries) require a callback function. This function exists to avoid repetition of code,\n * and is called by these methods\n */\n Object.defineProperty(this, 'callbackRequired', {\n value: function (errorMessagePrefix, callback) {\n if (!callback || typeof callback !== 'function') {\n throw new Error(errorMessagePrefix + ': a callback argument is required for read queries');\n }\n }\n });\n\n /**\n * Create an attribute security that embed all methods to manage Role, Profile and User\n */\n Object.defineProperty(this, 'security', {\n value: new Security(this),\n enumerable: true\n });\n\n Object.defineProperty(this, 'memoryStorage', {\n value: new MemoryStorage(this),\n enumerable: true\n });\n\n Object.defineProperties(this, {\n eventTimeout: {\n value: options && typeof options.eventTimeout === 'number' ? options.eventTimeout : 200,\n writeable: false\n }\n });\n\n Object.defineProperty(this, 'protectedEvents', {\n value: {\n connected: {timeout: this.eventTimeout},\n error: {timeout: this.eventTimeout},\n disconnected: {timeout: this.eventTimeout},\n reconnected: {timeout: this.eventTimeout},\n tokenExpired: {timeout: this.eventTimeout},\n loginAttempt: {timeout: this.eventTimeout}\n },\n writeable: false\n });\n\n if (!options || !options.connect || options.connect === 'auto') {\n this.connect();\n } else {\n this.state = 'ready';\n }\n\n this.cleanHistoryTimer = setInterval(function () { cleanHistory(self.requestHistory); }, 1000);\n\n if (this.bluebird) {\n return this.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['getAllStatistics', 'getServerInfo', 'getStatistics',\n 'listCollections', 'createIndex', 'listIndexes', 'login', 'logout',\n 'now', 'query', 'checkToken', 'whoAmI', 'updateSelf', 'getMyRights',\n 'refreshIndex', 'getAutoRefresh', 'setAutoRefresh'\n ];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n}\nKuzzle.prototype = Object.create(KuzzleEventEmitter.prototype);\nKuzzle.prototype.constructor = Kuzzle;\n\n/**\n* Emit an event to all registered listeners\n* An event cannot be emitted multiple times before a timeout has been reached.\n*/\nKuzzle.prototype.emit = function(eventName) {\n var\n now = Date.now(),\n protectedEvent = this.protectedEvents[eventName];\n\n if (protectedEvent) {\n if (protectedEvent.lastEmitted && protectedEvent.lastEmitted > now - protectedEvent.timeout) {\n return false;\n }\n protectedEvent.lastEmitted = now;\n }\n KuzzleEventEmitter.prototype.emit.apply(this, arguments);\n};\nKuzzle.prototype.emitEvent = Kuzzle.prototype.emit;\n\n/**\n * Connects to a Kuzzle instance using the provided host name.\n * @returns {Object} this\n */\nKuzzle.prototype.connect = function () {\n var self = this;\n\n if (self.network) {\n self.disconnect();\n }\n\n self.network = networkWrapper(self.host, self.port, self.sslConnection);\n\n if (['initializing', 'ready', 'disconnected', 'error', 'offline'].indexOf(this.state) === -1) {\n if (self.connectCB) {\n self.connectCB(null, self);\n }\n return self;\n }\n\n self.state = 'connecting';\n self.network.connect(self.autoReconnect, self.reconnectionDelay);\n\n self.network.onConnect(function () {\n self.state = 'connected';\n renewAllSubscriptions.call(self);\n dequeue.call(self);\n self.emitEvent('connected');\n\n if (self.connectCB) {\n self.connectCB(null, self);\n }\n });\n\n self.network.on('discarded', function (data) {\n self.emitEvent('discarded', data);\n });\n\n self.network.onConnectError(function (error) {\n var connectionError = new Error('Unable to connect to kuzzle proxy server at \"' + self.host + ':' + self.port + '\"');\n\n connectionError.internal = error;\n self.state = 'error';\n self.emitEvent('networkError', connectionError);\n\n disableAllSubscriptions.call(self);\n\n if (self.connectCB) {\n self.connectCB(connectionError);\n }\n });\n\n self.network.onDisconnect(function () {\n self.state = 'offline';\n\n if (!self.autoReconnect) {\n self.disconnect();\n }\n\n if (self.autoQueue) {\n self.queuing = true;\n }\n\n self.emitEvent('disconnected');\n });\n\n self.network.onReconnect(function () {\n var reconnect = function () {\n // renew subscriptions\n if (self.autoResubscribe) {\n renewAllSubscriptions.call(self);\n }\n\n // replay queued requests\n if (self.autoReplay) {\n cleanQueue.call(self);\n dequeue.call(self);\n }\n\n // alert listeners\n self.emitEvent('reconnected');\n };\n\n self.state = 'connected';\n\n if (self.jwtToken) {\n self.checkToken(self.jwtToken, function (err, res) {\n // shouldn't obtain an error but let's invalidate the token anyway\n if (err || !res.valid) {\n self.jwtToken = undefined;\n self.emitEvent('tokenExpired');\n }\n\n reconnect();\n });\n } else {\n reconnect();\n }\n });\n\n return this;\n};\n\n/**\n * Set the jwtToken used to query kuzzle\n * @param token\n * @returns {Kuzzle}\n */\nKuzzle.prototype.setJwtToken = function(token) {\n if (typeof token === 'string') {\n this.jwtToken = token;\n } else if (typeof token === 'object') {\n if (token.result && token.result.jwt && typeof token.result.jwt === 'string') {\n this.jwtToken = token.result.jwt;\n } else {\n this.emitEvent('loginAttempt', {\n success: false,\n error: 'Cannot find a valid JWT token in the following object: ' + JSON.stringify(token)\n });\n\n return this;\n }\n } else {\n this.emitEvent('loginAttempt', {success: false, error: 'Invalid token argument: ' + token});\n return this;\n }\n\n renewAllSubscriptions.call(this);\n this.emitEvent('loginAttempt', {success: true});\n return this;\n};\n\n/**\n * Unset the jwtToken used to query kuzzle\n * @returns {Kuzzle}\n */\nKuzzle.prototype.unsetJwtToken = function() {\n this.jwtToken = undefined;\n\n removeAllSubscriptions.call(this);\n\n return this;\n};\n\n/**\n * Get the jwtToken used by kuzzle\n * @returns {Kuzzle}\n */\nKuzzle.prototype.getJwtToken = function() {\n return this.jwtToken;\n};\n\n/**\n * Send login request to kuzzle with credentials\n * If login success, store the jwtToken into kuzzle object\n *\n * @param strategy\n * @param credentials\n * @param expiresIn\n * @param cb\n */\nKuzzle.prototype.login = function (strategy) {\n var\n self = this,\n request = {\n body: {},\n strategy: strategy\n },\n cb = null;\n\n if (!strategy || typeof strategy !== 'string') {\n throw new Error('Kuzzle.login: strategy required');\n }\n\n // Handle arguments (credentials, expiresIn, cb)\n if (arguments[1]) {\n if (typeof arguments[1] === 'object') {\n request.body = arguments[1];\n } else if (typeof arguments[1] === 'number' || typeof arguments[1] === 'string') {\n request.expiresIn = arguments[1];\n } else if (typeof arguments[1] === 'function') {\n cb = arguments[1];\n }\n }\n if (arguments[2]) {\n if (typeof arguments[2] === 'number' || typeof arguments[2] === 'string') {\n request.expiresIn = arguments[2];\n } else if (typeof arguments[2] === 'function') {\n cb = arguments[2];\n }\n }\n if (arguments[3] && typeof arguments[3] === 'function') {\n cb = arguments[3];\n }\n\n this.query({controller: 'auth', action: 'login'}, request, {queuable: false}, function(error, response) {\n if (!error) {\n if (response.result.jwt) {\n self.setJwtToken(response.result.jwt);\n }\n\n cb && cb(null, response.result);\n }\n else {\n cb && cb(error);\n self.emitEvent('loginAttempt', {success: false, error: error.message});\n }\n });\n};\n\n/**\n * Create credentials of the specified for the current user.\n *\n * @param credentials\n * @param strategy\n * @param options\n * @param cb\n * @returns {Kuzzle}\n */\nKuzzle.prototype.createMyCredentials = function (strategy, credentials, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.query({controller: 'auth', action: 'createMyCredentials'}, {strategy: strategy, body: credentials}, options, function(err, res) {\n if (!err) {\n cb && cb(null, res.result._source);\n } else {\n cb && cb(err);\n }\n });\n\n return this;\n};\n\n/**\n * Delete credentials of the specified for the current user.\n *\n * @param strategy\n * @param options\n * @param cb\n * @returns {Kuzzle}\n */\nKuzzle.prototype.deleteMyCredentials = function (strategy, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.query({controller: 'auth', action: 'deleteMyCredentials'}, {strategy: strategy}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n\n return this;\n};\n\n/**\n * Get credential information of the specified for the current user.\n *\n * @param strategy\n * @param options\n * @param cb\n */\nKuzzle.prototype.getMyCredentials = function (strategy, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.query({controller: 'auth', action: 'getMyCredentials'}, {strategy: strategy}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n};\n\n/**\n * Update credentials of the specified for the current user.\n *\n * @param strategy\n * @param credentals\n * @param options\n * @param cb\n * @returns {Kuzzle}\n */\nKuzzle.prototype.updateMyCredentials = function (strategy, credentials, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.query({controller: 'auth', action: 'updateMyCredentials'}, {strategy: strategy, body: credentials}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n\n return this;\n};\n\n/**\n * Validate credentials of the specified for the current user.\n *\n * @param strategy\n * @param credentials\n * @param options\n * @param cb\n */\nKuzzle.prototype.validateMyCredentials = function (strategy, credentials, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.query({controller: 'auth', action: 'validateMyCredentials'}, {strategy: strategy, body: credentials}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n};\n\n/**\n * Create a kuzzle index\n *\n * @param {string} index\n * @param {object} [options]\n * @param {responseCallback} cb\n * @returns {Kuzzle}\n */\nKuzzle.prototype.createIndex = function (index, options, cb) {\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.createIndex: index required');\n }\n index = this.defaultIndex;\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.query({controller: 'index', action: 'create', index: index}, {}, options, typeof cb !== 'function' ? null : function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return this;\n};\n\n/**\n * Send logout request to kuzzle with jwtToken.\n *\n * @param cb\n * @returns {Kuzzle}\n */\nKuzzle.prototype.logout = function (cb) {\n var\n self = this,\n request = {\n action: 'logout',\n controller: 'auth',\n requestId: uuidv4(),\n body: {}\n };\n\n this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, typeof cb !== 'function' ? null : function(error) {\n cb(error, self);\n });\n\n self.unsetJwtToken();\n\n return self;\n};\n\n/**\n * Checks whether a given jwt token still represents a valid session in Kuzzle.\n *\n * @param {string} token The jwt token to check\n * @param {function} cb The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n */\nKuzzle.prototype.checkToken = function (token, cb) {\n var\n request = {\n body: {\n token: token\n }\n };\n\n this.callbackRequired('Kuzzle.checkToken', cb);\n\n this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n};\n\n/**\n * Fetches the current user.\n *\n * @param {function} cb The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n */\nKuzzle.prototype.whoAmI = function (cb) {\n var self = this;\n\n self.callbackRequired('Kuzzle.whoAmI', cb);\n\n self.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, function (err, res) {\n cb(err, err ? undefined : new User(self.security, res.result._id, res.result._source, res.result._meta));\n });\n};\n\n/**\n * Gets the rights array of the currently logged user.\n *\n * @param {object} [options] - Optional parameters\n * @param {function} cb The callback containing the normalized array of rights.\n */\nKuzzle.prototype.getMyRights = function (options, cb) {\n var self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.callbackRequired('Kuzzle.getMyRights', cb);\n\n self.query({controller: 'auth', action:'getMyRights'}, {}, options, function (err, res) {\n cb(err, err ? undefined : res.result.hits);\n });\n};\n\n/**\n * Update current user in Kuzzle.\n *\n * @param {object} content - a plain javascript object representing the user's modification\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {Kuzzle} this object\n */\nKuzzle.prototype.updateSelf = function (content, options, cb) {\n var\n self = this,\n data = {},\n queryArgs = {controller: 'auth', action: 'updateSelf'};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data.body = content;\n\n self.query(queryArgs, data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return this;\n};\n\n/**\n * Clean up the queue, ensuring the queryTTL and queryMaxSize properties are respected\n */\nfunction cleanQueue () {\n var\n self = this,\n now = Date.now(),\n lastDocumentIndex = -1;\n\n if (self.queueTTL > 0) {\n self.offlineQueue.forEach(function (query, index) {\n if (query.ts < now - self.queueTTL) {\n lastDocumentIndex = index;\n }\n });\n\n if (lastDocumentIndex !== -1) {\n self.offlineQueue\n .splice(0, lastDocumentIndex + 1)\n .forEach(function (droppedRequest) {\n self.emitEvent('offlineQueuePop', droppedRequest.query);\n });\n }\n }\n\n if (self.queueMaxSize > 0 && self.offlineQueue.length > self.queueMaxSize) {\n self.offlineQueue\n .splice(0, self.offlineQueue.length - self.queueMaxSize)\n .forEach(function (droppedRequest) {\n self.emitEvent('offlineQueuePop', droppedRequest.query);\n });\n }\n}\n\n\n/**\n * Clean history from requests made more than 10s ago\n */\nfunction cleanHistory (requestHistory) {\n var\n now = Date.now();\n\n Object.keys(requestHistory).forEach(function (key) {\n if (requestHistory[key] < now - 10000) {\n delete requestHistory[key];\n }\n });\n}\n\n/**\n * Emit a request to Kuzzle\n *\n * @param {object} request\n * @param {responseCallback} [cb]\n */\nfunction emitRequest (request, cb) {\n var\n self = this;\n\n if (self.jwtToken !== undefined || cb) {\n self.network.once(request.requestId, function (response) {\n var error = null;\n\n if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n self.jwtToken = undefined;\n self.emitEvent('tokenExpired', request, cb);\n }\n\n if (response.error) {\n error = new Error(response.error.message);\n Object.assign(error, response.error);\n error.status = response.status;\n self.emitEvent('queryError', error, request, cb);\n }\n\n if (cb) {\n cb(error, response);\n }\n });\n }\n\n this.network.send(request);\n\n // Track requests made to allow Room.subscribeToSelf to work\n self.requestHistory[request.requestId] = Date.now();\n}\n\n/**\n * Play all queued requests, in order.\n */\nfunction dequeue () {\n var\n self = this,\n additionalQueue,\n uniqueQueue = {},\n dequeuingProcess = function () {\n if (self.offlineQueue.length > 0) {\n emitRequest.call(self, self.offlineQueue[0].query, self.offlineQueue[0].cb);\n self.emitEvent('offlineQueuePop', self.offlineQueue.shift());\n\n setTimeout(function () {\n dequeuingProcess();\n }, Math.max(0, self.replayInterval));\n } else {\n self.queuing = false;\n }\n };\n\n if (self.offlineQueueLoader) {\n if (typeof self.offlineQueueLoader !== 'function') {\n throw new Error('Invalid value for offlineQueueLoader property. Expected: function. Got: ' + typeof self.offlineQueueLoader);\n }\n\n additionalQueue = self.offlineQueueLoader();\n if (Array.isArray(additionalQueue)) {\n self.offlineQueue = additionalQueue\n .concat(self.offlineQueue)\n .filter(function (request) {\n // throws if the query object does not contain required attributes\n if (!request.query || request.query.requestId === undefined || !request.query.action || !request.query.controller) {\n throw new Error('Invalid offline queue request. One or more missing properties: requestId, action, controller.');\n }\n\n return uniqueQueue.hasOwnProperty(request.query.requestId) ? false : (uniqueQueue[request.query.requestId] = true);\n });\n } else {\n throw new Error('Invalid value returned by the offlineQueueLoader function. Expected: array. Got: ' + typeof additionalQueue);\n }\n }\n\n dequeuingProcess();\n}\n\n/**\n * Renew all registered subscriptions. Triggered either by a successful connection/reconnection or by a\n * successful login attempt\n */\nfunction renewAllSubscriptions() {\n var self = this;\n\n Object.keys(self.subscriptions).forEach(function (roomId) {\n Object.keys(self.subscriptions[roomId]).forEach(function (subscriptionId) {\n var subscription = self.subscriptions[roomId][subscriptionId];\n subscription.renew(subscription.callback);\n });\n });\n}\n\n/**\n * Remove all registered subscriptions. Triggered either by a logout query or by un-setting the token\n */\nfunction removeAllSubscriptions() {\n var self = this;\n\n Object.keys(self.subscriptions).forEach(function (roomId) {\n Object.keys(self.subscriptions[roomId]).forEach(function (subscriptionId) {\n var subscription = self.subscriptions[roomId][subscriptionId];\n subscription.unsubscribe();\n });\n });\n}\n\n/**\n * Adds a listener to a Kuzzle global event. When an event is fired, listeners are called in the order of their\n * insertion.\n *\n * @param {string} event - name of the global event to subscribe to\n * @param {function} listener - callback to invoke each time an event is fired\n */\nKuzzle.prototype.addListener = function(event, listener) {\n this.isValid();\n\n if (this.eventActions.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + this.eventActions.toString());\n }\n\n return KuzzleEventEmitter.prototype.addListener.call(this, event, listener);\n};\n\n/**\n * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n * This method returns all available statistics from Kuzzle.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.getAllStatistics = function (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.getAllStatistics', cb);\n\n this.query({controller:'server', action: 'getAllStats'}, {}, options, function (err, res) {\n cb(err, err ? undefined : res.result.hits);\n });\n};\n\n/**\n * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n * This method allows getting either the last statistics frame, or a set of frames starting from a provided timestamp.\n *\n * @param {number} timestamp - Epoch time. Starting time from which the frames are to be retrieved\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.getStatistics = function (timestamp, options, cb) {\n var\n queryCB,\n body;\n\n if (!cb) {\n if (arguments.length === 1) {\n cb = arguments[0];\n options = null;\n timestamp = null;\n } else {\n cb = arguments[1];\n if (typeof arguments[0] === 'object') {\n options = arguments[0];\n timestamp = null;\n } else {\n timestamp = arguments[0];\n options = null;\n }\n }\n }\n\n queryCB = function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, timestamp ? res.result.hits : [res.result]);\n };\n\n this.callbackRequired('Kuzzle.getStatistics', cb);\n\n body = timestamp ? {body: {startTime: timestamp}} : {};\n this.query({controller: 'server', action: timestamp ? 'getStats' : 'getLastStats'}, body, options, queryCB);\n};\n\n/**\n * Create a new instance of a Collection object.\n * If no index is specified, takes the default index.\n *\n * @param {string} collection - The name of the data collection you want to manipulate\n * @param {string} [index] - The name of the data index containing the data collection\n * @returns {Collection} A Collection instance\n */\nKuzzle.prototype.collection = function(collection, index) {\n this.isValid();\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Unable to create a new data collection object: no index specified');\n }\n\n index = this.defaultIndex;\n }\n\n if (typeof index !== 'string' || typeof collection !== 'string') {\n throw new Error('Invalid index or collection argument: string expected');\n }\n\n if (!this.collections[index]) {\n this.collections[index] = {};\n }\n\n if (!this.collections[index][collection]) {\n this.collections[index][collection] = new Collection(this, collection, index);\n }\n\n return this.collections[index][collection];\n};\n\n/**\n * Empties the offline queue without replaying it.\n *\n * @returns {Kuzzle}\n */\nKuzzle.prototype.flushQueue = function () {\n this.offlineQueue = [];\n return this;\n};\n\n/**\n * Returns the list of known persisted data collections.\n *\n * @param {string} [index] - Index containing collections to be listed\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.listCollections = function () {\n var\n index,\n options,\n cb,\n args = Array.prototype.slice.call(arguments),\n query;\n\n args.forEach(function(arg) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n });\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.listCollections: index required');\n }\n\n index = this.defaultIndex;\n }\n\n this.callbackRequired('Kuzzle.listCollections', cb);\n\n query = {type: options && options.type || 'all'};\n\n this.query({index: index, controller: 'collection', action: 'list'}, query, options, function (err, res) {\n cb(err, err ? undefined : res.result.collections);\n });\n};\n\n/**\n * Returns the list of existing indexes in Kuzzle\n *\n * @param {object} [options] - Optional arguments\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.listIndexes = function (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.listIndexes', cb);\n\n this.query({controller: 'index', action: 'list'}, {}, options, function (err, res) {\n cb(err, err ? undefined : res.result.indexes);\n });\n};\n\n/**\n * Disconnects from Kuzzle and invalidate this instance.\n */\nKuzzle.prototype.disconnect = function () {\n var collection;\n\n clearInterval(this.cleanHistoryTimer);\n this.state = 'disconnected';\n this.network.close();\n this.network = null;\n\n for (collection in this.collections) {\n if (this.collections.hasOwnProperty(collection)) {\n delete this.collections[collection];\n }\n }\n};\n\n/**\n * Returns the server informations\n *\n * @param {object} [options] - Optional arguments\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.getServerInfo = function (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.getServerInfo', cb);\n\n this.query({controller: 'server', action: 'info'}, {}, options, function (err, res) {\n cb(err, err ? undefined : res.result.serverInfo);\n });\n};\n\n/**\n * Forces an index refresh\n *\n * @param {string} index - The index to refresh. Defaults to Kuzzle.defaultIndex\n * @param {object} options - Optional arguments\n * @param {responseCallback} cb - Handles the query response\n * @returns {Kuzzle}\n */\nKuzzle.prototype.refreshIndex = function () {\n var\n index,\n options,\n cb;\n\n Array.prototype.slice.call(arguments).forEach(function(arg) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n });\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.refreshIndex: index required');\n }\n index = this.defaultIndex;\n }\n\n this.query({ index: index, controller: 'index', action: 'refresh'}, {}, options, cb);\n\n return this;\n};\n\n/**\n * Returns de current autoRefresh status for the given index\n *\n * @param {string} index - The index to get the status from. Defaults to Kuzzle.defaultIndex\n * @param {object} options - Optinal arguments\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.getAutoRefresh = function () {\n var\n index,\n options,\n cb;\n\n Array.prototype.slice.call(arguments).forEach(function (arg) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n });\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.getAutoRefresh: index required');\n }\n index = this.defaultIndex;\n }\n\n this.callbackRequired('Kuzzle.getAutoRefresh', cb);\n this.query({ index: index, controller: 'index', action: 'getAutoRefresh'}, {}, options, cb);\n};\n\n/**\n * (Un)Sets the autoRefresh flag on the given index\n *\n * @param {string} index - the index to modify. Defaults to Kuzzle.defaultIndex\n * @param {boolean} autoRefresh - The autoRefresh value to set\n * @param {object} options - Optional arguments\n * @param {responseCallback} cb - Handles the query result\n * @returns {object} this\n */\nKuzzle.prototype.setAutoRefresh = function () {\n var\n index,\n autoRefresh,\n options,\n cb;\n\n Array.prototype.slice.call(arguments).forEach(function (arg) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'boolean':\n autoRefresh = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n });\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.setAutoRefresh: index required');\n }\n index = this.defaultIndex;\n }\n\n if (autoRefresh === undefined) {\n throw new Error('Kuzzle.setAutoRefresh: autoRefresh value is required');\n }\n\n this.query({ index: index, controller: 'index', action: 'setAutoRefresh'}, { body: { autoRefresh: autoRefresh }}, options, cb);\n\n return this;\n};\n\n/**\n * Return the current Kuzzle's UTC Epoch time, in milliseconds\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nKuzzle.prototype.now = function (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.now', cb);\n\n this.query({controller: 'server', action: 'now'}, {}, options, function (err, res) {\n cb(err, err ? undefined : res.result.now);\n });\n};\n\n/**\n * This is a low-level method, exposed to allow advanced SDK users to bypass high-level methods.\n * Base method used to send read queries to Kuzzle\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} queryArgs - Query configuration\n * @param {object} query - The query data\n * @param {object} [options] - Optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzle.prototype.query = function (queryArgs, query, options, cb) {\n var\n attr,\n object = {\n action: queryArgs.action,\n controller: queryArgs.controller,\n volatile: this.volatile\n },\n self = this;\n\n this.isValid();\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (options) {\n if (options.queuable === false && self.state === 'offline') {\n return self;\n }\n\n if (options.refresh) {\n object.refresh = options.refresh;\n }\n\n if (typeof options.from !== 'undefined' && options.from !== null) {\n object.from = options.from;\n }\n\n if (options.size) {\n object.size = options.size;\n }\n\n if (options.scroll) {\n object.scroll = options.scroll;\n }\n\n if (options.scrollId) {\n object.scrollId = options.scrollId;\n }\n\n if (options.volatile) {\n Object.keys(options.volatile).forEach(function (meta) {\n object.volatile[meta] = options.volatile[meta];\n });\n }\n }\n\n if (!query || typeof query !== 'object' || Array.isArray(query)) {\n throw new Error('Invalid query parameter: ' + query);\n }\n\n if (query.volatile) {\n Object.keys(query.volatile).forEach(function (meta) {\n object.volatile[meta] = query.volatile[meta];\n });\n }\n\n for (attr in query) {\n if (attr !== 'volatile' && query.hasOwnProperty(attr)) {\n object[attr] = query[attr];\n }\n }\n\n object = self.addHeaders(object, this.headers);\n\n /*\n * Do not add the token for the checkToken route, to avoid getting a token error when\n * a developer simply wish to verify his token\n */\n if (self.jwtToken !== undefined && !(object.controller === 'auth' && object.action === 'checkToken')) {\n object.jwt = self.jwtToken;\n }\n\n if (queryArgs.collection) {\n object.collection = queryArgs.collection;\n }\n\n if (queryArgs.index) {\n object.index = queryArgs.index;\n }\n\n if (!object.requestId) {\n object.requestId = uuidv4();\n }\n\n object.volatile.sdkVersion = this.sdkVersion;\n\n if (self.state === 'connected' || (options && options.queuable === false)) {\n if (self.state === 'connected') {\n emitRequest.call(this, object, cb);\n } else {\n discardRequest(object, cb);\n }\n } else if (self.queuing || (options && options.queuable === true) || ['initializing', 'connecting'].indexOf(self.state) !== -1) {\n cleanQueue.call(this, object, cb);\n if (!self.queueFilter || self.queueFilter(object)) {\n self.offlineQueue.push({ts: Date.now(), query: object, cb: cb});\n self.emitEvent('offlineQueuePush', {query: object, cb: cb});\n } else {\n discardRequest(object, cb);\n }\n }\n else {\n discardRequest(object, cb);\n }\n\n return self;\n};\n\n/**\n * Replays the requests queued during offline mode.\n * Works only if the SDK is not in a disconnected state, and if the autoReplay option is set to false.\n */\nKuzzle.prototype.replayQueue = function () {\n if (this.state !== 'offline' && !this.autoReplay) {\n cleanQueue.call(this);\n dequeue.call(this);\n }\n\n return this;\n};\n\n/**\n * Sets the default Kuzzle index\n *\n * @param index\n * @returns this\n */\nKuzzle.prototype.setDefaultIndex = function (index) {\n if (typeof index !== 'string') {\n throw new Error('Invalid default index: [' + index + '] (an index name is expected)');\n }\n\n if (index.length === 0) {\n throw new Error('Cannot set an empty index as the default index');\n }\n\n this.defaultIndex = index;\n\n return this;\n};\n\n/**\n * Helper function allowing to set headers while chaining calls.\n *\n * If the replace argument is set to true, replace the current headers with the provided content.\n * Otherwise, it appends the content to the current headers, only replacing already existing values\n *\n * @param content - new headers content\n * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n */\nKuzzle.prototype.setHeaders = function (content, replace) {\n var self = this;\n\n if (typeof content !== 'object' || Array.isArray(content)) {\n throw new Error('Expected a content object, received a ' + typeof content);\n }\n\n if (replace) {\n self.headers = content;\n } else {\n Object.keys(content).forEach(function (key) {\n self.headers[key] = content[key];\n });\n }\n\n return self;\n};\n\n/**\n * Starts the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n */\nKuzzle.prototype.startQueuing = function () {\n if (this.state === 'offline' && !this.autoQueue) {\n this.queuing = true;\n }\n return this;\n};\n\n/**\n * Stops the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n */\nKuzzle.prototype.stopQueuing = function () {\n if (this.state === 'offline' && !this.autoQueue) {\n this.queuing = false;\n }\n\n return this;\n};\n\nfunction discardRequest(object, cb) {\n if (cb) {\n cb(new Error('Unable to execute request: not connected to a Kuzzle server.\\nDiscarded request: ' + JSON.stringify(object)));\n }\n}\n\nfunction disableAllSubscriptions() {\n var self = this;\n\n Object.keys(self.subscriptions).forEach(function (roomId) {\n Object.keys(self.subscriptions[roomId]).forEach(function (subscriptionId) {\n var subscription = self.subscriptions[roomId][subscriptionId];\n subscription.subscribing = false;\n });\n });\n}\n\nmodule.exports = Kuzzle;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/Kuzzle.js\n// module id = 0\n// module chunks = 0","function SecurityDocument(Security, id, content, meta) {\n\n if (!id) {\n throw new Error('A security document must have an id');\n }\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n kuzzle: {\n value: Security.kuzzle\n },\n Security: {\n value: Security\n },\n // read-only properties\n // writable properties\n id: {\n value: id,\n enumerable: true\n },\n content: {\n value: {},\n writable: true,\n enumerable: true\n },\n meta: {\n value: meta || {},\n writable: true,\n enumerable: true\n }\n });\n\n if (content) {\n this.setContent(content, true);\n }\n\n // promisifying\n if (Security.kuzzle.bluebird) {\n return Security.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['delete', 'update'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n}\n\n/**\n * Replaces the current content with new data.\n * Changes made by this function won’t be applied until the save method is called.\n *\n * @param {Object} data - New securityDocument content\n * @return {SecurityDocument} this\n */\nSecurityDocument.prototype.setContent = function (data) {\n this.content = data;\n return this;\n};\n\n/**\n * Serialize this object into a pojo\n *\n * @return {object} pojo representing this securityDocument\n */\nSecurityDocument.prototype.serialize = function () {\n var\n data = {};\n\n if (this.id) {\n data._id = this.id;\n }\n\n data.body = this.content;\n data.meta = this.meta;\n\n return data;\n};\n\n/**\n * Delete the current KuzzleSecurityDocument into Kuzzle.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n */\nSecurityDocument.prototype.delete = function (options, cb) {\n var\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.Security.buildQueryArgs(this.deleteActionName), {_id: this.id}, options, function (error, res) {\n if (error) {\n return cb ? cb(error) : false;\n }\n\n if (cb) {\n cb(null, res.result._id);\n }\n });\n};\n\n/**\n * Update the current KuzzleSecurityDocument into Kuzzle.\n *\n * @param {object} content - Content to add to KuzzleSecurityDocument\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {SecurityDocument} this\n */\nSecurityDocument.prototype.update = function (content, options, cb) {\n var\n data = {},\n self = this;\n\n if (typeof content !== 'object') {\n throw new Error('Parameter \"content\" must be a object');\n }\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = self.id;\n data.body = content;\n\n self.kuzzle.query(this.Security.buildQueryArgs(this.updateActionName), data, options, function (error, response) {\n if (error) {\n return cb ? cb(error) : false;\n }\n\n self.setContent(response.result._source);\n\n if (cb) {\n cb(null, self);\n }\n });\n\n return this;\n};\n\nmodule.exports = SecurityDocument;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/security/SecurityDocument.js\n// module id = 1\n// module chunks = 0","/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n/**\n * Kuzzle handles documents either as realtime messages or as stored documents.\n * Document is the object representation of one of these documents.\n *\n * Notes:\n * - this constructor may be called either with a documentId, a content, neither or both.\n * - providing a documentID to the constructor will automatically call refresh, unless a content is also provided\n *\n *\n * @param {Collection} collection - an instanciated Collection object\n * @param {string} [documentId] - ID of an existing document\n * @param {object} [content] - Initializes this document with the provided content\n * @param {object} [meta] - Initializes this document with the provided meta\n * @constructor\n */\nfunction Document(collection, documentId, content, meta) {\n Object.defineProperties(this, {\n // read-only properties\n collection: {\n value: collection.collection,\n enumerable: true\n },\n dataCollection: {\n value: collection,\n enumerable: false\n },\n kuzzle: {\n value: collection.kuzzle,\n enumerable: false\n },\n // writable properties\n id: {\n value: undefined,\n enumerable: true,\n writable: true\n },\n content: {\n value: {},\n writable: true,\n enumerable: true\n },\n headers: {\n value: JSON.parse(JSON.stringify(collection.headers)),\n enumerable: true,\n writable: true\n },\n version: {\n value: undefined,\n enumerable: true,\n writable: true\n },\n meta: {\n value: meta || {},\n enumerable: true,\n writable: false\n }\n });\n\n // handling provided arguments\n if (!content && documentId && typeof documentId === 'object') {\n content = documentId;\n documentId = null;\n }\n\n if (content) {\n if (content._version) {\n this.version = content._version;\n delete content._version;\n }\n this.setContent(content, true);\n }\n\n if (documentId) {\n Object.defineProperty(this, 'id', {\n value: documentId,\n enumerable: true\n });\n }\n\n // promisifying\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['delete', 'refresh', 'save'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * Serialize this object into a JSON object\n *\n * @return {object} JSON object representing this document\n */\nDocument.prototype.serialize = function () {\n var\n data = {};\n\n if (this.id) {\n data._id = this.id;\n }\n\n if (this.version) {\n data._version = this.version;\n }\n\n data.body = this.content;\n data.meta = this.meta;\n data = this.kuzzle.addHeaders(data, this.headers);\n\n return data;\n};\n\n/**\n * Overrides the toString() method in order to return a serialized version of the document\n *\n * @return {string} serialized version of this object\n */\nDocument.prototype.toString = function () {\n return JSON.stringify(this.serialize());\n};\n\n/**\n * Deletes this document in Kuzzle.\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nDocument.prototype.delete = function (options, cb) {\n var self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!self.id) {\n throw new Error('Document.delete: cannot delete a document without a document ID');\n }\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('document', 'delete'), this.serialize(), options, cb && function (err) {\n cb(err, err ? undefined : self.id);\n });\n};\n\n/**\n * Checks if this document exists in Kuzzle.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nDocument.prototype.exists = function (options, cb) {\n var self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!self.id) {\n throw new Error('Document.exists: cannot check if the document exists if no id has been provided');\n }\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('document', 'exists'), this.serialize(), options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n};\n\n/**\n * Replaces the current content with the last version of this document stored in Kuzzle.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nDocument.prototype.refresh = function (options, cb) {\n var self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!self.id) {\n throw new Error('Document.refresh: cannot retrieve a document if no ID has been provided');\n }\n\n this.kuzzle.callbackRequired('Document.refresh', cb);\n\n self.kuzzle.query(self.dataCollection.buildQueryArgs('document', 'get'), {_id: self.id}, options, function (error, res) {\n var newDocument;\n\n if (error) {\n return cb(error);\n }\n\n newDocument = new Document(self.dataCollection, self.id, res.result._source, res.result._meta);\n newDocument.version = res.result._version;\n\n cb(null, newDocument);\n });\n};\n\n/**\n * Saves this document into Kuzzle.\n *\n * If this is a new document, this function will create it in Kuzzle and the id property will be made available.\n * Otherwise, this method will replace the latest version of this document in Kuzzle by the current content\n * of this object.\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nDocument.prototype.save = function (options, cb) {\n var\n data = this.serialize(),\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.dataCollection.buildQueryArgs('document', 'createOrReplace'), data, options, function (error, res) {\n if (error) {\n return cb && cb(error);\n }\n\n self.id = res.result._id;\n self.version = res.result._version;\n\n if (cb) {\n cb(null, self);\n }\n });\n\n return self;\n};\n\n/**\n * Sends the content of this document as a realtime message.\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @returns {*} this\n */\nDocument.prototype.publish = function (options) {\n var data = this.serialize();\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('realtime', 'publish'), data, options);\n\n return this;\n};\n\n/**\n * Replaces the current content with new data.\n * Changes made by this function won’t be applied until the save method is called.\n *\n * @param {object} data - New content\n * @param {boolean} replace - if true: replace this document content with the provided data\n */\nDocument.prototype.setContent = function (data, replace) {\n var self = this;\n\n if (replace) {\n this.content = data;\n }\n else {\n Object.keys(data).forEach(function (key) {\n self.content[key] = data[key];\n });\n }\n\n return this;\n};\n\n/**\n * Listens to events concerning this document. Has no effect if the document does not have an ID\n * (i.e. if the document has not yet been created as a persisted document).\n *\n * @param {object} [options] - subscription options\n * @param {responseCallback} cb - callback that will be called each time a change has been detected on this document\n */\nDocument.prototype.subscribe = function (options, cb) {\n var filters;\n\n if (options && !cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('Document.subscribe', cb);\n\n if (!this.id) {\n throw new Error('Document.subscribe: cannot subscribe to a document if no ID has been provided');\n }\n\n filters = { ids: { values: [this.id] } };\n\n return this.dataCollection.subscribe(filters, options, cb);\n};\n\n/**\n * Helper function allowing to set headers while chaining calls.\n *\n * If the replace argument is set to true, replace the current headers with the provided content.\n * Otherwise, it appends the content to the current headers, only replacing already existing values\n *\n * @param content - new headers content\n * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n */\nDocument.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\n\nmodule.exports = Document;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/Document.js\n// module id = 2\n// module chunks = 0","function KuzzleEventEmitter() {\n if (typeof window !== 'undefined') {\n this._events = {};\n this._onceEvents = {};\n }\n}\n\nif (typeof window === 'undefined') {\n KuzzleEventEmitter.prototype = require('events').prototype;\n KuzzleEventEmitter.prototype.constructor = KuzzleEventEmitter;\n} else {\n\n KuzzleEventEmitter.prototype.on = function(eventName, listener) {\n var\n listenerType = typeof listener,\n listeners;\n\n if (!eventName || !listener) {\n return;\n }\n\n if (listenerType !== 'function') {\n throw new Error('Invalid listener type: expected a function, got a ' + listenerType);\n }\n\n listeners = this.listeners(eventName);\n // only add once\n if (listeners.indexOf(listener) === -1) {\n listeners.push(listener);\n }\n\n // Handles `newListener` event (see https://nodejs.org/api/events.html#events_event_newlistener)\n this.emit('newListener', eventName, listener);\n\n return this;\n };\n KuzzleEventEmitter.prototype.addListener = KuzzleEventEmitter.prototype.on;\n\n KuzzleEventEmitter.prototype.prependListener = function(eventName, listener) {\n var listeners;\n\n if (!eventName || !listener) {\n return;\n }\n\n listeners = this.listeners(eventName);\n // only add once\n if (listeners.indexOf(listener) === -1) {\n this._events[eventName] = new Array(listener).concat(listeners);\n }\n\n // Handles `newListener` event (see https://nodejs.org/api/events.html#events_event_newlistener)\n this.emit('newListener', eventName, listener);\n\n return this;\n };\n\n KuzzleEventEmitter.prototype.once = function(eventName, listener) {\n var onceListeners;\n\n if (!eventName || !listener) {\n return;\n }\n\n\n this.on(eventName, listener);\n onceListeners = this._onceEvents[eventName] = this._onceEvents[eventName] || {};\n onceListeners[listener] = true;\n\n return this;\n };\n\n KuzzleEventEmitter.prototype.prependOnceListener = function(eventName, listener) {\n var onceListeners;\n\n if (!eventName || !listener) {\n return;\n }\n this.prependListener(eventName, listener);\n onceListeners = this._onceEvents[eventName] = this._onceEvents[eventName] || {};\n onceListeners[listener] = true;\n\n return this;\n };\n\n KuzzleEventEmitter.prototype.removeListener = function(eventName, listener) {\n var\n index,\n listeners = this._events[eventName];\n\n if (!listeners || !listeners.length) {\n return;\n }\n\n index = listeners.indexOf(listener);\n if (index !== -1) {\n listeners.splice(index, 1);\n }\n if (listeners.length === 0) {\n delete this._events[eventName];\n }\n\n // Handles `removeListener` event (see https://nodejs.org/api/events.html#events_event_removeListener)\n this.emit('removeListener', eventName, listener);\n\n return this;\n };\n\n KuzzleEventEmitter.prototype.removeAllListeners = function(eventName) {\n if (eventName) {\n delete this._events[eventName];\n delete this._onceEvents[eventName];\n } else {\n this._events = [];\n this._onceEvents = [];\n }\n\n return this;\n };\n\n KuzzleEventEmitter.prototype.emit = function(eventName) {\n var\n i = 0,\n listeners,\n args,\n onceListeners,\n notifyList;\n\n listeners = this._events && this._events[eventName];\n\n if (!listeners || !listeners.length) {\n return;\n }\n\n args = Array.prototype.slice.call(arguments, 1);\n // once stuff\n onceListeners = this._onceEvents && this._onceEvents[eventName] || {};\n\n notifyList = new Array();\n\n listener = listeners[i];\n while (listener) {\n // trigger listener\n notifyList.push(listener);\n // get next listener\n if (onceListeners[listener]) {\n // remove listener\n this.removeListener(eventName,listener);\n // unset once flag\n delete onceListeners[listener];\n } else {\n i++;\n }\n listener = listeners[i];\n }\n for (item in notifyList) {\n // trigger listener\n if (notifyList[item] !== undefined) {\n notifyList[item].apply(this, args);\n }\n }\n\n return this;\n };\n\n KuzzleEventEmitter.prototype.eventNames = function () {\n return Object.keys(this._events);\n };\n\n KuzzleEventEmitter.prototype.listenerCount = function (eventName) {\n return this._events[eventName] && this._events[eventName].length || 0;\n };\n\n KuzzleEventEmitter.prototype.listeners = function (eventName) {\n if (this._events[eventName] === undefined) {\n this._events[eventName] = [];\n }\n return this._events[eventName];\n };\n\n}\n// Aliases:\nKuzzleEventEmitter.prototype.emitEvent = KuzzleEventEmitter.prototype.emit;\nKuzzleEventEmitter.prototype.off = KuzzleEventEmitter.prototype.removeListener;\n\nmodule.exports = KuzzleEventEmitter;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/eventEmitter/index.js\n// module id = 3\n// module chunks = 0","var\n KuzzleEventEmitter = require('../../eventEmitter');\n\nfunction WSNode(host, port, ssl) {\n var self = this;\n KuzzleEventEmitter.call(this);\n\n this.WebSocket = typeof WebSocket !== 'undefined' ? WebSocket : require('ws');\n this.host = host;\n this.port = port;\n this.ssl = ssl;\n this.client = null;\n this.wasConnected = false;\n this.retrying = false;\n this.lasturl = null;\n this.stopRetryingToConnect = false;\n\n /**\n * Creates a new socket from the provided arguments\n *\n * @constructor\n * @param {boolean} autoReconnect\n * @param {int} reconnectionDelay\n * @returns {Object} Socket\n */\n this.connect = function (autoReconnect, reconnectionDelay) {\n var\n url = (this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port,\n options = typeof window !== 'undefined' ? undefined : {perMessageDeflate: false};\n\n if (url !== this.lasturl) {\n self.wasConnected = false;\n this.lasturl = url;\n }\n\n this.client = new this.WebSocket(url, options);\n\n this.client.onopen = function () {\n if (self.wasConnected) {\n self.emitEvent('reconnect');\n }\n else {\n self.emitEvent('connect');\n }\n self.wasConnected = true;\n self.stopRetryingToConnect = false;\n };\n\n this.client.onclose = function (closeEvent, message) {\n var error;\n var status;\n var reason = message;\n\n if (typeof closeEvent === 'number') {\n status = closeEvent;\n }\n else {\n status = closeEvent.code;\n\n if (closeEvent.reason) {\n reason = closeEvent.reason;\n }\n }\n\n if (status === 1000) {\n self.emitEvent('disconnect');\n }\n else {\n error = new Error(reason);\n error.status = status;\n\n onClientNetworkError(self, autoReconnect, reconnectionDelay, error);\n }\n };\n\n this.client.onerror = function (error) {\n if (!(error instanceof Error)) {\n error = new Error(error);\n }\n\n onClientNetworkError(self, autoReconnect, reconnectionDelay, error);\n };\n\n this.client.onmessage = function (payload) {\n var data = JSON.parse(payload.data || payload);\n\n if (data.room) {\n self.emitEvent(data.room, data);\n }\n else {\n self.emitEvent('discarded', data);\n }\n };\n };\n\n /**\n * Fires the provided callback whence a connection is established\n *\n * @param {function} callback\n */\n this.onConnect = function (callback) {\n this.addListener('connect', callback);\n };\n\n /**\n * Fires the provided callback whenever a connection error is received\n * @param {function} callback\n */\n this.onConnectError = function (callback) {\n this.addListener('networkError', callback);\n };\n\n /**\n * Fires the provided callback whenever a disconnection occurred\n * @param {function} callback\n */\n this.onDisconnect = function (callback) {\n this.addListener('disconnect', callback);\n };\n\n /**\n * Fires the provided callback whenever a connection has been reestablished\n * @param {function} callback\n */\n this.onReconnect = function (callback) {\n this.addListener('reconnect', callback);\n };\n\n /**\n * Sends a payload to the connected server\n *\n * @param {Object} payload\n */\n this.send = function (payload) {\n if (this.client && this.client.readyState === this.client.OPEN) {\n this.client.send(JSON.stringify(payload));\n }\n };\n\n /**\n * Closes the connection\n */\n this.close = function () {\n this.removeAllListeners();\n this.wasConnected = false;\n this.client.close();\n this.client = null;\n self.stopRetryingToConnect = true;\n };\n}\nWSNode.prototype = Object.create(KuzzleEventEmitter.prototype);\nWSNode.prototype.constructor = WSNode;\n\n\n/**\n * Called when the connection closes with an error state\n *\n * @param {WSNode} \n * @param {boolean} autoReconnect\n * @param {number} reconnectionDelay\n * @param {Error} error\n */\nfunction onClientNetworkError(ws, autoReconnect, reconnectionDelay, error) {\n if (autoReconnect && !ws.retrying && !ws.stopRetryingToConnect) {\n ws.retrying = true;\n setTimeout(function () {\n ws.retrying = false;\n ws.connect(autoReconnect, reconnectionDelay);\n }, reconnectionDelay);\n }\n\n ws.emitEvent('networkError', error);\n}\n\nmodule.exports = WSNode;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/networkWrapper/wrappers/websocket.js\n// module id = 4\n// module chunks = 0","var\n KuzzleSecurityDocument = require('./SecurityDocument');\n\n/**\n * @param {Security} Security\n * @param {string} id\n * @param {Object} content\n * @constructor\n */\nfunction User(Security, id, content, meta) {\n KuzzleSecurityDocument.call(this, Security, id, content, meta);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteUser'\n },\n updateActionName: {\n value: 'updateUser'\n },\n credentials: {\n value: {},\n writable: true,\n enumerable: true\n }\n });\n\n // promisifying\n if (Security.kuzzle.bluebird) {\n return Security.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['create', 'replace', 'saveRestricted', 'update', 'getProfiles'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n}\n\nUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: User\n }\n});\n\n/**\n * Set profiles in content\n * @param {array} profileIds - an array of profiles ids string\n *\n * @returns {User} this\n */\nUser.prototype.setProfiles = function (profileIds) {\n if (!Array.isArray(profileIds) || typeof profileIds[0] !== 'string') {\n throw new Error('Parameter \"profileIds\" must be an array of strings');\n }\n\n this.content.profileIds = profileIds;\n\n return this;\n};\n\n/**\n * @param {object} credentials\n */\nUser.prototype.setCredentials = function (credentials) {\n if (typeof credentials !== 'object') {\n throw new Error('Parameter \"credentials\" must be a object');\n }\n\n this.credentials = credentials;\n\n return this;\n};\n\n/**\n * Add a profile\n * @param {string} profileId - a profile ids string\n *\n * @returns {User} this\n */\nUser.prototype.addProfile = function (profileId) {\n if (typeof profileId !== 'string') {\n throw new Error('Parameter \"profileId\" must be a string');\n }\n\n if (!this.content.profileIds) {\n this.content.profileIds = [];\n }\n\n if (this.content.profileIds.indexOf(profileId) === -1) {\n this.content.profileIds.push(profileId);\n }\n\n return this;\n};\n\n/**\n * Creates this user into Kuzzle\n *\n * @param {object|responseCallback} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {User} this\n */\nUser.prototype.create = function (options, cb) {\n var\n data = this.creationSerialize(),\n self = this;\n\n if (!this.content.profileIds) {\n throw new Error('Argument \"profileIds\" is mandatory in a user. This argument contains an array of profile identifiers.');\n }\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.Security.buildQueryArgs('createUser'), data, null, cb && function (err) {\n cb(err, err ? undefined : self);\n });\n\n return this;\n};\n\n\n/**\n * Replaces the latest version of this user in Kuzzle by the current content of this object.\n *\n * @param {object|responseCallback} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {User} this\n */\nUser.prototype.replace = function (options, cb) {\n var\n data = this.serialize(),\n self = this;\n\n if (!this.content.profileIds) {\n throw new Error('Argument \"profileIds\" is mandatory in a user. This argument contains an array of profile identifiers.');\n }\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n\n this.kuzzle.query(this.Security.buildQueryArgs('replaceUser'), data, null, cb && function (err) {\n cb(err, err ? undefined : self);\n });\n\n return this;\n};\n\n/**\n * Saves this user as restricted into Kuzzle.\n *\n * This function will create a new user. It is not usable to update an existing user.\n * The \"profileIds\" property must not be provided, or the request will be rejected by Kuzzle.\n * This function allows anonymous users to create a \"restricted\" user with predefined rights.\n *\n * @param {object|responseCallback} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {User} this\n */\nUser.prototype.saveRestricted = function (options, cb) {\n var\n data = this.serialize(),\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.Security.buildQueryArgs('createRestrictedUser'), data, options, cb && function (error) {\n cb(error, error ? undefined : self);\n });\n\n return self;\n};\n\n/**\n * Serialize this object into a JSON object\n *\n * @return {object} JSON object representing this User\n */\nUser.prototype.serialize = function () {\n return {_id: this.id, body: this.content, meta: this.meta};\n};\n\n/**\n * Serialize this object into a JSON object\n *\n * @return {object} JSON object representing this User\n */\nUser.prototype.creationSerialize = function () {\n return {_id: this.id, body: {content: this.content, credentials: this.credentials, meta: this.meta}};\n};\n\n/**\n * Return the associated profiles IDs\n *\n * @return {array.} the associated profiles IDs\n */\nUser.prototype.getProfileIds = function () {\n return this.content.profileIds || [];\n};\n\n/**\n * Return the associated Profile objects\n *\n * @param {object|responseCallback} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nUser.prototype.getProfiles = function (options, cb) {\n var \n self = this,\n fetchedProfiles = [],\n errored = false;\n\n if (options && !cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.Security.kuzzle.callbackRequired('User.getProfiles', cb);\n\n if (!self.content.profileIds) {\n return cb(null, fetchedProfiles);\n }\n\n self.content.profileIds.forEach(function (profileId) {\n self.Security.fetchProfile(profileId, options, function (error, profile) {\n if (error) {\n if (errored) {\n return;\n }\n\n errored = true; // prevents multiple callback resolutions\n return cb(error);\n }\n\n fetchedProfiles.push(profile);\n\n if (fetchedProfiles.length === self.content.profileIds.length) {\n cb(null, fetchedProfiles);\n }\n });\n });\n};\n\nmodule.exports = User;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/security/User.js\n// module id = 5\n// module chunks = 0","var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\nfunction v4(options, buf, offset) {\n var i = buf && offset || 0;\n\n if (typeof(options) == 'string') {\n buf = options == 'binary' ? new Array(16) : null;\n options = null;\n }\n options = options || {};\n\n var rnds = options.random || (options.rng || rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n for (var ii = 0; ii < 16; ++ii) {\n buf[i + ii] = rnds[ii];\n }\n }\n\n return buf || bytesToUuid(rnds);\n}\n\nmodule.exports = v4;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../~/uuid/v4.js\n// module id = 6\n// module chunks = 0","var\n KuzzleSearchResult = require('./SearchResult'),\n Document = require('./Document'),\n CollectionMapping = require('./CollectionMapping'),\n Room = require('./Room'),\n SubscribeResult = require('./SubscribeResult');\n\n/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n/**\n * A data collection is a set of data managed by Kuzzle. It acts like a data table for persistent documents,\n * or like a room for pub/sub messages.\n *\n * @property {string} collection\n * @property {string} index\n * @property {Kuzzle} kuzzle\n * @property {Array.} collection\n * @param {object} kuzzle - Kuzzle instance to inherit from\n * @param {string} collection - name of the data collection to handle\n * @param {string} index - Index containing the data collection\n * @constructor\n */\nfunction Collection(kuzzle, collection, index) {\n if (!index || !collection) {\n throw new Error('The Collection object constructor needs an index and a collection arguments');\n }\n\n Object.defineProperties(this, {\n // read-only properties\n collection: {\n value: collection,\n enumerable: true\n },\n index: {\n value: index,\n enumerable: true\n },\n kuzzle: {\n value: kuzzle,\n enumerable: true\n },\n // writable properties\n headers: {\n value: JSON.parse(JSON.stringify(kuzzle.headers)),\n enumerable: true,\n writable: true\n }\n });\n\n Object.defineProperty(this, 'buildQueryArgs', {\n value: function (controller, action) {\n return {\n controller: controller,\n action: action,\n collection: this.collection,\n index: this.index\n };\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = ['publishMessage', 'setHeaders', 'subscribe'];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * Returns the number of documents matching the provided set of filters.\n *\n * There is a small delay between documents creation and their existence in our advanced search layer,\n * usually a couple of seconds.\n * That means that a document that was just been created won’t be returned by this function\n *\n * @param {object} filters - Filters in Elasticsearch Query DSL format\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nCollection.prototype.count = function (filters, options, cb) {\n var\n query;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('Collection.count', cb);\n\n query = this.kuzzle.addHeaders({body: filters}, this.headers);\n\n this.kuzzle.query(this.buildQueryArgs('document', 'count'), query, options, function (err, res) {\n cb(err, err ? undefined : res.result.count);\n });\n};\n\n/**\n * Create a new empty data collection, with no associated mapping.\n * Kuzzle automatically creates data collections when storing documents, but there are cases where we\n * want to create and prepare data collections before storing documents in it.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n * @returns {*} this\n */\nCollection.prototype.create = function (options, cb) {\n var data = {},\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = this.kuzzle.addHeaders(data, this.headers);\n this.kuzzle.query(this.buildQueryArgs('collection', 'create'), data, options, function(err) {\n cb(err, err ? undefined : self);\n });\n\n return this;\n};\n\n/**\n * Create a new document in Kuzzle.\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n * - ifExist (string, allowed values: \"error\" (default), \"replace\"):\n * If the same document already exists:\n * - resolves with an error if set to \"error\".\n * - replaces the existing document if set to \"replace\"\n *\n * @param {string} [id] - (optional) document identifier\n * @param {object} document - either an instance of a Document object, or a document\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Object} this\n */\nCollection.prototype.createDocument = function (id, document, options, cb) {\n var\n self = this,\n data = {},\n action = 'create';\n\n if (id && typeof id !== 'string') {\n cb = options;\n options = document;\n document = id;\n id = null;\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (document instanceof Document) {\n data = document.serialize();\n } else {\n data.body = document;\n }\n\n if (options && options.ifExist) {\n if (options.ifExist === 'replace') {\n action = 'createOrReplace';\n }\n else if (options.ifExist !== 'error') {\n throw new Error('Invalid value for the \"ifExist\" option: ' + options.ifExist);\n }\n }\n\n if (id) {\n data._id = id;\n }\n\n data = self.kuzzle.addHeaders(data, self.headers);\n\n self.kuzzle.query(this.buildQueryArgs('document', action), data, options, cb && function (err, res) {\n var doc;\n\n if (err) {\n return cb(err);\n }\n\n doc = new Document(self, res.result._id, res.result._source, res.result._meta);\n doc.version = res.result._version;\n cb(null, doc);\n });\n\n return this;\n};\n\n/**\n * Delete persistent documents.\n *\n * There is a small delay between documents creation and their existence in our advanced search layer,\n * usually a couple of seconds.\n * That means that a document that was just been created won’t be returned by this function\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {string|object} arg - Either a document ID (will delete only this particular document), or a set of filters\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Collection} this\n */\nCollection.prototype.deleteDocument = function (arg, options, cb) {\n var\n action,\n data = {};\n\n if (typeof arg === 'string') {\n data._id = arg;\n action = 'delete';\n } else {\n data.body = {query: arg};\n action = 'deleteByQuery';\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = this.kuzzle.addHeaders(data, this.headers);\n\n this.kuzzle.query(this.buildQueryArgs('document', action), data, options, cb && function (err, res) {\n if (err) {\n cb(err);\n }\n else {\n cb(null, (action === 'delete' ? [res.result._id] : res.result.ids));\n }\n });\n\n return this;\n};\n\n/**\n * Deletes the current specifications of this collection\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @return {object} this\n */\nCollection.prototype.deleteSpecifications = function (options, cb) {\n var\n data = { index: this.index, collection: this.collection },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('collection', 'deleteSpecifications'), data, options, function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return self;\n};\n\n/**\n * Returns a boolean indicating whether or not a document with provided ID exists.\n *\n * @param {string} documentId - Unique document identifier\n * @param {object} options [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nCollection.prototype.documentExists = function (documentId, options, cb) {\n var\n data = {_id: documentId},\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Collection.documentExists', cb);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'exists'), data, options, function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n};\n\n/**\n * Retrieve a single stored document using its unique document ID.\n *\n * @param {string} documentId - Unique document identifier\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nCollection.prototype.fetchDocument = function (documentId, options, cb) {\n var\n data = {_id: documentId},\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Collection.fetch', cb);\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'get'), data, options, function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new Document(self, res.result._id, res.result._source, res.result._meta);\n document.version = res.result._version;\n cb(null, document);\n });\n};\n\n/**\n * Instantiates a CollectionMapping object containing the current mapping of this collection.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n */\nCollection.prototype.getMapping = function (options, cb) {\n var kuzzleMapping;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('Collection.getMapping', cb);\n\n kuzzleMapping = new CollectionMapping(this);\n kuzzleMapping.refresh(options, cb);\n};\n\n/**\n * Create the provided documents\n *\n * @param {Array.} documents - Array of documents to create\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n * @returns {object} this\n */\nCollection.prototype.mCreateDocument = function (documents, options, cb) {\n var data = {\n body: {},\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!Array.isArray(documents)) {\n return cb(new Error('Collection.mCreateDocument: documents parameter format is invalid (should be an array of documents)'));\n }\n\n self.kuzzle.callbackRequired('Collection.mCreate', cb);\n\n data.body.documents = documents.map(function (doc) {\n return (doc instanceof Document) ? doc.serialize() : doc;\n });\n\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'mCreate'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return self;\n};\n\n/**\n * Create or replace the provided documents\n *\n * @param {Array.} documents - Array of documents to create or replace\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n * @returns {object} this\n */\nCollection.prototype.mCreateOrReplaceDocument = function (documents, options, cb) {\n var data = {\n body: {},\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!Array.isArray(documents)) {\n return cb(new Error('Collection.mCreateOrReplaceDocument: documents parameter format is invalid (should be an array of documents)'));\n }\n\n self.kuzzle.callbackRequired('Collection.mCreateOrReplace', cb);\n\n data.body.documents = documents.map(function (doc) {\n return (doc instanceof Document) ? doc.serialize() : doc;\n });\n\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'mCreateOrReplace'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return self;\n};\n\n/**\n * Delete specific documents according to given IDs\n *\n * @param {Array.} documentIds - IDs of the documents to delete\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n * @returns {object} this\n */\nCollection.prototype.mDeleteDocument = function (documentIds, options, cb) {\n var data = {\n body: {\n ids: documentIds\n }\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!Array.isArray(documentIds)) {\n return cb(new Error('Collection.mDeleteDocument: documentIds parameter format is invalid (should be an array of IDs)'));\n }\n\n self.kuzzle.callbackRequired('Collection.mDelete', cb);\n\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'mDelete'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return self;\n};\n\n/**\n * Get specific documents according to given IDs\n *\n * @param {Array.} documentIds - IDs of the documents to retrieve\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n */\nCollection.prototype.mGetDocument = function (documentIds, options, cb) {\n var data = {\n body: {\n ids: documentIds\n }\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!Array.isArray(documentIds)) {\n return cb(new Error('Collection.mGetDocument: documentIds parameter format is invalid (should be an array of IDs)'));\n }\n\n self.kuzzle.callbackRequired('Collection.mGet', cb);\n\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'mGet'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n};\n\n/**\n * Replace the provided documents\n *\n * @param {Array.} documents - Array of documents to replace\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n * @returns {object} this\n */\nCollection.prototype.mReplaceDocument = function (documents, options, cb) {\n var data = {\n body: {}\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!Array.isArray(documents)) {\n return cb(new Error('Collection.mReplaceDocument: documents parameter format is invalid (should be an array of documents)'));\n }\n\n self.kuzzle.callbackRequired('Collection.mReplace', cb);\n\n data.body.documents = documents.map(function (doc) {\n return (doc instanceof Document) ? doc.serialize() : doc;\n });\n\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'mReplace'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return self;\n};\n\n/**\n * Update the provided documents\n *\n * @param {Array.} documents - Array of documents to update\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n * @returns {object} this\n */\nCollection.prototype.mUpdateDocument = function (documents, options, cb) {\n var data = {\n body: {}\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!Array.isArray(documents)) {\n return cb(new Error('Collection.mUpdateDocument: documents parameter format is invalid (should be an array of documents)'));\n }\n\n self.kuzzle.callbackRequired('Collection.mUpdate', cb);\n\n data.body.documents = documents.map(function (doc) {\n return (doc instanceof Document) ? doc.serialize() : doc;\n });\n\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'mUpdate'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return self;\n};\n\n/**\n * Retrieves the current specifications of this collection\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nCollection.prototype.getSpecifications = function (options, cb) {\n var\n data = { index: this.index, collection: this.collection },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Collection.getSpecifications', cb);\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('collection', 'getSpecifications'), data, options, function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n};\n\n/**\n * Publish a realtime message\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} document - either a Document instance or a JSON object\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Returns a raw Kuzzle response\n * @returns {*} this\n */\nCollection.prototype.publishMessage = function (document, options, cb) {\n var data = {};\n\n if (document instanceof Document) {\n data = document.serialize();\n } else {\n data.body = document;\n }\n\n data = this.kuzzle.addHeaders(data, this.headers);\n this.kuzzle.query(this.buildQueryArgs('realtime', 'publish'), data, options, cb);\n\n return this;\n};\n\n/**\n * Replace an existing document with a new one.\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {string} documentId - Unique document identifier of the document to replace\n * @param {object} content - JSON object representing the new document version\n * @param {object} [options] - additional arguments\n * @param {responseCallback} [cb] - Returns an instantiated Document object\n * @return {object} this\n */\nCollection.prototype.replaceDocument = function (documentId, content, options, cb) {\n var\n self = this,\n data = {\n _id: documentId,\n body: content\n };\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'createOrReplace'), data, options, cb && function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new Document(self, res.result._id, res.result._source, res.result._meta);\n document.version = res.result._version;\n cb(null, document);\n });\n\n return this;\n};\n\n/**\n * Executes an advanced search on the data collection.\n *\n * /!\\ There is a small delay between documents creation and their existence in our advanced search layer,\n * usually a couple of seconds.\n * That means that a document that was just been created won’t be returned by this function.\n *\n * @param {object} filters - Filters in Elasticsearch Query DSL format\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\n\nCollection.prototype.search = function (filters, options, cb) {\n var\n query,\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n self.kuzzle.callbackRequired('Collection.search', cb);\n\n query = self.kuzzle.addHeaders({body: filters}, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'search'), query, options, function (error, result) {\n var documents = [];\n\n if (error) {\n return cb(error);\n }\n\n result.result.hits.forEach(function (doc) {\n var newDocument = new Document(self, doc._id, doc._source, doc._meta);\n\n newDocument.version = doc._version;\n\n documents.push(newDocument);\n });\n\n if (result.result._scroll_id) {\n options.scrollId = result.result._scroll_id;\n }\n\n cb(null, new KuzzleSearchResult(\n self,\n result.result.total,\n documents,\n result.result.aggregations ? result.result.aggregations : {},\n options,\n filters,\n options.previous || null\n ));\n });\n};\n\n/**\n * A \"scroll\" option can be passed to search queries, creating persistent\n * paginated results.\n * This method can be used to manually get the next page of a search result,\n * instead of using KuzzleSearchResult.next()\n *\n * @param {string} scrollId\n * @param {object} [options]\n * @param {object} [filters]\n * @param {responseCallback} cb\n */\nCollection.prototype.scroll = function (scrollId, options, filters, cb) {\n var\n request = {},\n self = this;\n\n if (!scrollId) {\n throw new Error('Collection.scroll: scrollId is required');\n }\n\n if (!cb) {\n cb = filters;\n filters = null;\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n this.kuzzle.callbackRequired('Collection.scroll', cb);\n\n request.scrollId = scrollId;\n\n if (options && options.scroll) {\n request.scroll = options.scroll;\n }\n\n this.kuzzle.query({controller: 'document', action: 'scroll'}, request, options, function (error, result) {\n var documents = [];\n\n if (error) {\n return cb(error);\n }\n\n result.result.hits.forEach(function (doc) {\n var newDocument = new Document(self, doc._id, doc._source, doc._meta);\n\n newDocument.version = doc._version;\n\n documents.push(newDocument);\n });\n\n if (result.result._scroll_id) {\n options.scrollId = result.result._scroll_id;\n }\n\n cb(null, new KuzzleSearchResult(\n self,\n result.result.total,\n documents,\n {},\n options,\n filters,\n options.previous || null\n ));\n });\n\n return this;\n};\n\n/**\n * Retrieves next result of a search with scroll query.\n *\n * @param {string} scrollId\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nCollection.prototype.scrollSpecifications = function (scrollId, options, cb) {\n var\n data = { scrollId: scrollId };\n\n if (!scrollId) {\n throw new Error('Collection.scrollSpecifications: scrollId is required');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n this.kuzzle.callbackRequired('Collection.scrollSpecifications', cb);\n\n if (options && options.scroll) {\n data.scroll = options.scroll;\n }\n\n this.kuzzle.query(\n { controller: 'collection', action: 'scrollSpecifications'},\n this.kuzzle.addHeaders(data, this.headers),\n options,\n function (err, res) {\n cb (err, err ? undefined : res.result);\n }\n );\n};\n\n/**\n * Searches specifications across indexes/collections according to the provided filters\n *\n * @param {object} [filters] - Optional filters in ElasticSearch Query DSL format\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nCollection.prototype.searchSpecifications = function (filters, options, cb) {\n var\n data = { body: { query: filters } },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n self.kuzzle.callbackRequired('Collection.searchSpecifications', cb);\n\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query({ controller: 'collection', action: 'searchSpecifications' }, data, options, function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n};\n\n/**\n * Subscribes to this data collection with a set of filters.\n * To subscribe to the entire data collection, simply provide an empty filter.\n *\n * @param {object} filters - Filters in Kuzzle DSL format\n * @param {object} [options] - subscriptions options\n * @param {responseCallback} cb - called for each new notification\n * @returns {*} KuzzleSubscribeResult object\n */\nCollection.prototype.subscribe = function (filters, options, cb) {\n var\n room,\n subscribeResult;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('Collection.subscribe', cb);\n\n subscribeResult = new SubscribeResult();\n room = new Room(this, options);\n\n room.renew(filters, cb, subscribeResult.done.bind(subscribeResult));\n\n return subscribeResult;\n};\n\n/**\n * Truncate the data collection, removing all stored documents but keeping all associated mappings.\n * This method is a lot faster than removing all documents using a query.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n * @returns {*} this\n */\nCollection.prototype.truncate = function (options, cb) {\n var data = {};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = this.kuzzle.addHeaders(data, this.headers);\n this.kuzzle.query(this.buildQueryArgs('collection', 'truncate'), data, options, cb);\n\n return this;\n};\n\n\n/**\n * Update parts of a document\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {string} documentId - Unique document identifier of the document to update\n * @param {object} content - JSON object containing changes to perform on the document\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Returns an instantiated Document object\n * @return {object} this\n */\nCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n var data = {\n _id: documentId,\n body: content\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (options && options.retryOnConflict) {\n data.retryOnConflict = options.retryOnConflict;\n }\n\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'update'), data, options, cb && function (err, res) {\n if (err) {\n return cb(err);\n }\n\n (new Document(self, res.result._id)).refresh(cb);\n });\n\n return self;\n};\n\n/**\n * Updates the current specifications of this collection\n *\n * @param {object} specifications - Specifications content\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @return {object} this\n */\nCollection.prototype.updateSpecifications = function (specifications, options, cb) {\n var\n collection = {},\n data = { body: {} },\n self = this;\n\n collection[this.collection] = specifications;\n data.body[this.index] = collection;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('collection', 'updateSpecifications'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return self;\n};\n\n/**\n * Validates the provided specifications\n *\n * @param {object} specifications - Specifications content\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nCollection.prototype.validateSpecifications = function (specifications, options, cb) {\n var\n collection = {},\n data = { body: {} },\n self = this;\n\n collection[this.collection] = specifications;\n data.body[this.index] = collection;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Collection.validateSpecifications', cb);\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('collection', 'validateSpecifications'), data, options, function (err, res) {\n cb(err, err ? undefined : res.result.valid);\n });\n};\n\n/**\n * Instantiate a new Document object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - document id\n * @param {object} content - document content\n * @constructor\n */\nCollection.prototype.document = function (id, content) {\n return new Document(this, id, content);\n};\n\n/**\n * Instantiate a new Room object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {object} [options] - subscription configuration\n * @constructor\n */\nCollection.prototype.room = function (options) {\n return new Room(this, options);\n};\n\n/**\n * Instantiate a new CollectionMapping object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {object} [mapping] - mapping to instantiate the CollectionMapping object with\n * @constructor\n */\nCollection.prototype.collectionMapping = function (mapping) {\n return new CollectionMapping(this, mapping);\n};\n\n/**\n * Helper function allowing to set headers while chaining calls.\n *\n * If the replace argument is set to true, replace the current headers with the provided content.\n * Otherwise, it appends the content to the current headers, only replacing already existing values\n *\n * @param content - new headers content\n * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n */\nCollection.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\nmodule.exports = Collection;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/Collection.js\n// module id = 7\n// module chunks = 0","/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n\n/**\n * When creating a new data collection in the persistent data storage layer, Kuzzle uses a default mapping.\n * It means that, by default, you won’t be able to exploit the full capabilities of our persistent data storage layer\n * (currently handled by ElasticSearch), and your searches may suffer from below-average performances, depending on\n * the amount of data you stored in a collection and the complexity of your database.\n *\n * The CollectionMapping object allow to get the current mapping of a data collection and to modify it if needed.\n *\n * @param {object} collection - Instance of the inherited Collection object\n * @param {object} [mapping] - mappings\n * @constructor\n */\nfunction CollectionMapping(collection, mapping) {\n Object.defineProperties(this, {\n //read-only properties\n collection: {\n value: collection,\n enumerable: true\n },\n kuzzle: {\n value: collection.kuzzle,\n enumerable: true\n },\n // writable properties\n headers: {\n value: JSON.parse(JSON.stringify(collection.headers)),\n enumerable: true,\n writable: true\n },\n mapping: {\n value: mapping || {},\n enumerable: true,\n writable: true\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = ['set', 'setHeaders'];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * Applies the new mapping to the data collection.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n */\nCollectionMapping.prototype.apply = function (options, cb) {\n var\n self = this,\n data = this.kuzzle.addHeaders({body: {properties: this.mapping}}, this.headers);\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.collection.buildQueryArgs('collection', 'updateMapping'), data, options, function (err) {\n if (err) {\n return cb && cb(err);\n }\n\n self.refresh(options, cb);\n });\n\n return this;\n};\n\n/**\n * Replaces the current content with the mapping stored in Kuzzle\n *\n * Calling this function will discard any uncommited changes. You can commit changes by calling the “apply” function\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nCollectionMapping.prototype.refresh = function (options, cb) {\n var\n self = this,\n data = this.kuzzle.addHeaders({}, this.headers);\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.collection.buildQueryArgs('collection', 'getMapping'), data, options, function (err, res) {\n if (err) {\n return cb ? cb(err) : false;\n }\n\n if (res.result[self.collection.index]) {\n if (res.result[self.collection.index].mappings[self.collection.collection]) {\n self.mapping = res.result[self.collection.index].mappings[self.collection.collection].properties;\n\n // Mappings can be empty. The mapping property should never be \"undefined\"\n if (self.mapping === undefined) {\n self.mapping = {};\n }\n } else {\n return cb && cb(new Error('No mapping found for collection ' + self.collection.collection));\n }\n } else {\n return cb && cb(new Error('No mapping found for index ' + self.collection.index));\n }\n\n if (cb) {\n cb(null, self);\n }\n });\n\n return this;\n};\n\n\n/**\n * Adds or updates a field mapping.\n *\n * Changes made by this function won’t be applied until you call the apply method\n *\n * @param {string} field - Name of the field from which the mapping is to be added or updated\n * @param {object} mapping - corresponding field mapping\n * @returns {CollectionMapping}\n */\nCollectionMapping.prototype.set = function (field, mapping) {\n this.mapping[field] = mapping;\n\n return this;\n};\n\n/**\n * Helper function allowing to set headers while chaining calls.\n *\n * If the replace argument is set to true, replace the current headers with the provided content.\n * Otherwise, it appends the content to the current headers, only replacing already existing values\n *\n * @param content - new headers content\n * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n */\nCollectionMapping.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\nmodule.exports = CollectionMapping;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/CollectionMapping.js\n// module id = 8\n// module chunks = 0","// Parameter mutualization\nvar\n getId = {getter: true, required: ['_id']},\n getIdField = {getter: true, required: ['_id', 'field']},\n getKeys = {getter: true, required: ['keys']},\n getMember = {getter: true, required: ['_id', 'member']},\n getxScan = {\n getter: true, \n required: ['_id', 'cursor'], \n opts: ['match', 'count'],\n mapResults: mapScanResults\n },\n getZrange = {\n getter: true,\n required: ['_id', 'start', 'stop'],\n opts: assignZrangeOptions,\n mapResults: mapZrangeResults\n },\n getZrangeBy = {\n getter: true,\n required: ['_id', 'min', 'max'],\n opts: assignZrangeOptions,\n mapResults: mapZrangeResults\n },\n setId = {required: ['_id']},\n setIdValue = {required: ['_id', 'value']},\n setIdFieldValue = {required: ['_id', 'field', 'value']},\n setEntries = {required: ['entries']};\n\n// Redis commands\nvar\n commands = {\n append: setIdValue,\n bitcount: {getter: true, required: ['_id'], opts: ['start', 'end']},\n bitop: {required: ['_id', 'operation', 'keys']},\n bitpos: {getter: true, required: ['_id', 'bit'], opts: ['start', 'end']},\n dbsize: {getter: true},\n decr: setId,\n decrby: setIdValue,\n del: {required: ['keys']},\n exists: getKeys,\n expire: {required: ['_id', 'seconds']},\n expireat: {required: ['_id', 'timestamp']},\n flushdb: {},\n geoadd: {required: ['_id', 'points']},\n geodist: {\n getter: true,\n required: ['_id', 'member1', 'member2'],\n opts: ['unit'],\n mapResults: parseFloat\n },\n geohash: {getter: true, required: ['_id', 'members']},\n geopos: {getter: true, required: ['_id', 'members'], mapResults: mapGeoposResults},\n georadius: {\n getter: true,\n required: ['_id', 'lon', 'lat', 'distance', 'unit'],\n opts: assignGeoRadiusOptions,\n mapResults: mapGeoRadiusResults\n },\n georadiusbymember: {\n getter: true,\n required: ['_id', 'member', 'distance', 'unit'],\n opts: assignGeoRadiusOptions,\n mapResults: mapGeoRadiusResults\n },\n get: getId,\n getbit: {getter: true, required: ['_id', 'offset']},\n getrange: {getter: true, required: ['_id', 'start', 'end']},\n getset: setIdValue,\n hdel: {required: ['_id', 'fields']},\n hexists: getIdField,\n hget: getIdField,\n hgetall: {getter: true, required: ['_id']},\n hincrby: setIdFieldValue,\n hincrbyfloat: {required: ['_id', 'field', 'value'], mapResults: parseFloat},\n hkeys: getId,\n hlen: getId,\n hmget: {getter: true, required: ['_id', 'fields']},\n hmset: {required: ['_id', 'entries']},\n hscan: getxScan,\n hset: setIdFieldValue,\n hsetnx: setIdFieldValue,\n hstrlen: getIdField,\n hvals: getId,\n incr: setId,\n incrby: setIdValue,\n incrbyfloat: {required: ['_id', 'value'], mapResults: parseFloat},\n keys: {getter: true, required: ['pattern']},\n lindex: {getter: true, required: ['_id', 'idx']},\n linsert: {required: ['_id', 'position', 'pivot', 'value']},\n llen: getId,\n lpop: setId,\n lpush: {required: ['_id', 'values']},\n lpushx: setIdValue,\n lrange: {getter: true, required: ['_id', 'start', 'stop']},\n lrem: {required: ['_id', 'count', 'value']},\n lset: {required: ['_id', 'index', 'value']},\n ltrim: {required: ['_id', 'start', 'stop']},\n mget: getKeys,\n mset: setEntries,\n msetnx: setEntries,\n object: {getter: true, required: ['_id', 'subcommand']},\n persist: setId,\n pexpire: {required: ['_id', 'milliseconds']},\n pexpireat: {required: ['_id', 'timestamp']},\n pfadd: {required: ['_id', 'elements']},\n pfcount: getKeys,\n pfmerge: {required: ['_id', 'sources']},\n ping: {getter: true},\n psetex: {required: ['_id', 'value', 'milliseconds']},\n pttl: getId,\n randomkey: {getter: true},\n rename: {required: ['_id', 'newkey']},\n renamenx: {required: ['_id', 'newkey']},\n rpop: setId,\n rpoplpush: {required: ['source', 'destination']},\n rpush: {required: ['_id', 'values']},\n rpushx: setIdValue,\n sadd: {required: ['_id', 'members']},\n scan: {getter: true, required: ['cursor'], opts: ['match', 'count'], mapResults: mapScanResults},\n scard: getId,\n sdiff: {getter: true, required: ['_id', 'keys']},\n sdiffstore: {required: ['_id', 'keys', 'destination']},\n set: {required: ['_id', 'value'], opts: ['ex', 'px', 'nx', 'xx']},\n setex: {required: ['_id', 'value', 'seconds']},\n setnx: setIdValue,\n sinter: getKeys,\n sinterstore: {required: ['destination', 'keys']},\n sismember: getMember,\n smembers: getId,\n smove: {required: ['_id', 'destination', 'member']},\n sort: {getter: true, required: ['_id'], opts: ['alpha', 'by', 'direction', 'get', 'limit']},\n spop: {required: ['_id'], opts: ['count'], mapResults: mapStringToArray },\n srandmember: {getter: true, required: ['_id'], opts: ['count'], mapResults: mapStringToArray},\n srem: {required: ['_id', 'members']},\n sscan: getxScan,\n strlen: getId,\n sunion: getKeys,\n sunionstore: {required: ['destination', 'keys']},\n time: {getter: true, mapResults: mapArrayStringToArrayInt},\n touch: {required: ['keys']},\n ttl: getId,\n type: getId,\n zadd: {required: ['_id', 'elements'], opts: ['nx', 'xx', 'ch', 'incr']},\n zcard: getId,\n zcount: {getter: true, required: ['_id', 'min', 'max']},\n zincrby: {required: ['_id', 'member', 'value']},\n zinterstore: {required: ['_id', 'keys'], opts: ['weights', 'aggregate']},\n zlexcount: {getter: true, required: ['_id', 'min', 'max']},\n zrange: getZrange,\n zrangebylex: {getter: true, required: ['_id', 'min', 'max'], opts: ['limit']},\n zrevrangebylex: {getter: true, required: ['_id', 'min', 'max'], opts: ['limit']},\n zrangebyscore: getZrangeBy,\n zrank: getMember,\n zrem: {required: ['_id', 'members']},\n zremrangebylex: {required: ['_id', 'min', 'max']},\n zremrangebyrank: {required: ['_id', 'start', 'stop']},\n zremrangebyscore: {required: ['_id', 'min', 'max']},\n zrevrange: getZrange,\n zrevrangebyscore: getZrangeBy,\n zrevrank: getMember,\n zscan: getxScan,\n zscore: {getter: true, required: ['_id', 'member'], mapResults: parseFloat},\n zunionstore: {required: ['_id', 'keys'], opts: ['weights', 'aggregate']}\n };\n\n/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n\n/**\n * Kuzzle's memory storage is a separate data store from the database layer.\n * It is internaly based on Redis. You can access most of Redis functions (all\n * lowercased), except functions falling in the following categories:\n *\n * - blocking functions\n * - cluster commands\n * - configuration commands\n * - cursor functions\n * - database administration commands\n * - debugging functions\n * - script based functions\n * - transaction functions\n *\n * @param {object} kuzzle - Kuzzle instance to inherit from\n * @constructor\n */\nfunction MemoryStorage(kuzzle) {\n Object.defineProperties(this, {\n // read-only properties\n kuzzle: {\n value: kuzzle,\n enumerable: true\n },\n // writable properties\n headers: {\n value: JSON.parse(JSON.stringify(kuzzle.headers)),\n enumerable: true,\n writable: true\n }\n });\n\n this.setHeaders = kuzzle.setHeaders.bind(this);\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = ['setHeaders'];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n// Dynamically builds this class' prototypes using the \"commands\" global variable\n(function () {\n Object.keys(commands).forEach(function (command) {\n MemoryStorage.prototype[command] = function () {\n var\n args = Array.prototype.slice.call(arguments),\n options = null,\n cb,\n query = {\n controller: 'ms',\n action: command\n },\n data = {};\n\n if (args.length && typeof args[args.length - 1] === 'function') {\n cb = args.pop();\n }\n\n commands[command].getter && this.kuzzle.callbackRequired('MemoryStorage.' + command, cb);\n\n if (!commands[command].getter) {\n data.body = {};\n }\n\n if (commands[command].required) {\n commands[command].required.forEach(function (param) {\n var value = args.shift();\n\n if (value === undefined) {\n throw new Error('MemoryStorage.' + command + ': Missing parameter \"' + param + '\"');\n }\n\n assignParameter(data, commands[command].getter, param, value);\n });\n }\n\n if (args.length > 1) {\n throw new Error('MemoryStorage.' + command + ': Too many parameters provided');\n }\n\n if (args.length === 1 && typeof args[0] !== 'object' || Array.isArray(args[0])) {\n throw new Error('MemoryStorage.' + command + ': Invalid optional parameter (expected an object)');\n }\n\n if (args.length) {\n options = Object.assign({}, args[0]);\n\n if (Array.isArray(commands[command].opts)) {\n commands[command].opts.forEach(function (opt) {\n if (options[opt] !== null && options[opt] !== undefined) {\n assignParameter(data, commands[command].getter, opt, options[opt]);\n delete options[opt];\n }\n });\n }\n }\n\n /*\n Options function mapper does not necessarily need\n options to be passed by clients.\n */\n if (typeof commands[command].opts === 'function') {\n commands[command].opts(data, options || {});\n }\n\n this.kuzzle.query(query, data, options, cb && function (err, res) {\n if (err) {\n return cb(err);\n }\n\n if (commands[command].mapResults) {\n return cb(null, commands[command].mapResults(res.result));\n }\n\n cb(null, res.result);\n });\n\n if (!commands[command].getter) {\n return this;\n }\n };\n });\n})();\n\n/**\n *\n * @param {object} data - target data object\n * @param {boolean} getter - tells if the command is a getter one\n * @param {string} name - parameter name\n * @param {*} value - parameter value\n */\nfunction assignParameter(data, getter, name, value) {\n if (getter || name === '_id') {\n data[name] = value;\n }\n else {\n data.body[name] = value;\n }\n}\n\n/**\n * Assign the provided options for the georadius* redis functions\n * to the request object, as expected by Kuzzle API\n *\n * Mutates the provided data and options objects\n *\n * @param {object} data\n * @param {object} options\n */\nfunction assignGeoRadiusOptions(data, options) {\n var parsed = [];\n\n Object.keys(options)\n .filter(function (opt) {\n return options[opt] && ['withcoord', 'withdist', 'count', 'sort'].indexOf(opt) !== -1;\n })\n .forEach(function (opt) {\n if (opt === 'withcoord' || opt === 'withdist') {\n parsed.push(opt);\n delete options[opt];\n }\n else if (opt === 'count' || opt === 'sort') {\n if (opt === 'count') {\n parsed.push('count');\n }\n\n parsed.push(options[opt]);\n }\n\n delete options[opt];\n });\n\n if (parsed.length > 0) {\n data.options = parsed;\n }\n}\n\n/**\n * Force the WITHSCORES option on z*range* routes\n *\n * Mutates the provided data and options objects\n *\n * @param {object} data\n * @param {object} options\n */\nfunction assignZrangeOptions(data, options) {\n data.options = ['withscores'];\n\n if (options.limit) {\n data.limit = options.limit;\n delete options.limit;\n }\n}\n\n/**\n * Maps geopos results, from array> to array>\n *\n * @param {Array.>} results\n * @return {Array.>}\n */\nfunction mapGeoposResults(results) {\n return results.map(function (coords) {\n return coords.map(function (latlon) {\n return parseFloat(latlon);\n });\n });\n}\n\n\n/**\n * Maps georadius results to the format specified in the SDK documentation,\n * preventing different formats depending on the passed options\n *\n * Results can be either an array of point names, or an array\n * of arrays, each one of them containing the point name,\n * and additional informations depending on the passed options\n * (coordinates, distances)\n *\n * @param {Array} results\n * @return {Array.}\n */\nfunction mapGeoRadiusResults(results) {\n // Simple array of point names (no options provided)\n if (!Array.isArray(results[0])) {\n return results.map(function (point) {\n return {name: point};\n });\n }\n\n return results.map(function (point) {\n // The point id is always the first item\n var p = {\n name: point[0]\n },\n i;\n\n for (i = 1; i < point.length; i++) {\n // withcoord result are in an array...\n if (Array.isArray(point[i])) {\n p.coordinates = point[i].map(function (coord) {\n return parseFloat(coord);\n });\n }\n else {\n // ... and withdist are not\n p.distance = parseFloat(point[i]);\n }\n }\n\n return p;\n });\n}\n\n/**\n * Map a string result to an array of strings.\n * Used to uniformize polymorphic results from redis\n *\n * @param {Array|string} results\n * @return {Array.}\n */\nfunction mapStringToArray (results) {\n return Array.isArray(results) ? results : [results];\n}\n\n/**\n * Map an array of strings to an array of integers\n *\n * @param {Array.} results\n * @return {Array.}\n */\nfunction mapArrayStringToArrayInt(results) {\n return results.map(function (value) {\n return parseInt(value);\n });\n}\n\n/**\n * Map zrange results with WITHSCORES:\n * [\n * \"member1\",\n * \"score of member1\",\n * \"member2\",\n * \"score of member2\"\n * ]\n *\n * into the following format:\n * [\n * {\"member\": \"member1\", \"score\": },\n * {\"member\": \"member2\", \"score\": },\n * ]\n *\n *\n * @param {Array.} results\n * @return {Array.}\n */\nfunction mapZrangeResults(results) {\n var\n buffer = null,\n mapped = [];\n\n results.forEach(function (value) {\n if (buffer === null) {\n buffer = value;\n }\n else {\n mapped.push({member: buffer, score: parseFloat(value)});\n buffer = null;\n }\n });\n\n return mapped;\n}\n\n/**\n * Map *scan calls results, from:\n * [\n * \"\",\n * [\n * \"value1\",\n * \"value2\", \n * \"...\"\n * ]\n * ]\n *\n * To:\n * {\n * cursor: ,\n * values: [\n * \"value1\",\n * \"value2\",\n * \"...\"\n * ]\n * }\n * \n * @param {array.} results \n * @return {object}\n */\nfunction mapScanResults(results) {\n return {\n cursor: results[0],\n values: results[1]\n };\n}\n\nmodule.exports = MemoryStorage;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/MemoryStorage.js\n// module id = 9\n// module chunks = 0","var\n uuidv4 = require('uuid/v4'),\n Document = require('./Document');\n\n/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n/**\n * This object is the result of a subscription request, allowing to manipulate the subscription itself.\n *\n * In Kuzzle, you don’t exactly subscribe to a room or a topic but, instead, you subscribe to documents.\n *\n * What it means is that, to subscribe, you provide to Kuzzle a set of matching filters.\n * Once you have subscribed, if a pub/sub message is published matching your filters, or if a matching stored\n * document change (because it is created, updated or deleted), then you’ll receive a notification about it.\n *\n * @param {object} collection - an instantiated and valid kuzzle object\n * @param {object} [options] - subscription optional configuration\n * @constructor\n */\nfunction Room(collection, options) {\n // Define properties\n Object.defineProperties(this, {\n // private properties\n callback: {\n value: null,\n writable: true\n },\n channel: {\n value: null,\n writable: true\n },\n id: {\n value: uuidv4()\n },\n lastRenewal: {\n value: null,\n writable: true\n },\n notifier: {\n value: null,\n writable: true\n },\n onDoneCB: {\n value: null,\n writable: true\n },\n queue: {\n value: [],\n writable: true\n },\n // Delay before allowing a subscription renewal\n renewalDelay: {\n value: 500\n },\n scope: {\n value: options && options.scope ? options.scope : 'all'\n },\n state: {\n value: options && options.state ? options.state : 'done'\n },\n subscribing: {\n value: false,\n writable: true\n },\n users: {\n value: options && options.users ? options.users : 'none'\n },\n // read-only properties\n collection: {\n value: collection,\n enumerable: true\n },\n kuzzle: {\n value: collection.kuzzle,\n enumerable: true\n },\n // writable properties\n filters: {\n value: null,\n enumerable: true,\n writable: true\n },\n headers: {\n value: JSON.parse(JSON.stringify(collection.headers)),\n enumerable: true,\n writable: true\n },\n volatile: {\n value: (options && options.volatile) ? options.volatile : {},\n enumerable: true,\n writable: true\n },\n roomId: {\n value: null,\n enumerable: true,\n writable: true\n },\n subscribeToSelf: {\n value: options && typeof options.subscribeToSelf === 'boolean' ? options.subscribeToSelf : true,\n enumerable: true,\n writable: true\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['count'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * Returns the number of other subscriptions on that room.\n *\n * @param {responseCallback} cb - Handles the query response\n */\nRoom.prototype.count = function (cb) {\n var data;\n\n this.kuzzle.callbackRequired('Room.count', cb);\n\n data = this.kuzzle.addHeaders({body: {roomId: this.roomId}}, this.headers);\n\n if (!isReady.call(this)) {\n this.queue.push({action: 'count', args: [cb]});\n return;\n }\n\n if (!this.roomId) {\n throw new Error('Room.count: cannot count subscriptions on an inactive room');\n }\n\n this.kuzzle.query(this.collection.buildQueryArgs('realtime', 'count'), data, function (err, res) {\n cb(err, res && res.result.count);\n });\n};\n\n/**\n * Renew the subscription using new filters\n *\n * @param {object} [filters] - Filters in Kuzzle DSL format\n * @param {responseCallback} notificationCB - called for each new notification\n * @param {responseCallback} [cb] - handles the query response\n */\nRoom.prototype.renew = function (filters, notificationCB, cb) {\n var\n self = this,\n now = Date.now(),\n subscribeQuery = {\n scope: self.scope,\n state: self.state,\n users: self.users\n };\n\n if (typeof filters === 'function') {\n cb = notificationCB;\n notificationCB = filters;\n filters = null;\n }\n\n if (!cb) {\n cb = self.onDoneCB;\n }\n\n self.kuzzle.callbackRequired('Room.renew', notificationCB);\n\n /*\n Skip subscription renewal if another one was performed a moment before\n */\n if (self.lastRenewal && (now - self.lastRenewal) <= self.renewalDelay) {\n return cb && cb(new Error('Subscription already renewed less than ' + self.renewalDelay + 'ms ago'));\n }\n\n if (filters) {\n self.filters = filters;\n }\n\n /*\n if not yet connected, register itself to the subscriptions list and wait for the\n main Kuzzle object to renew once online\n */\n if (self.kuzzle.state !== 'connected') {\n self.callback = notificationCB;\n self.onDoneCB = cb;\n self.kuzzle.subscriptions.pending[self.id] = self;\n return;\n }\n\n if (self.subscribing) {\n self.queue.push({action: 'renew', args: [filters, notificationCB, cb]});\n return;\n }\n\n self.unsubscribe();\n self.roomId = null;\n self.subscribing = true;\n self.callback = notificationCB;\n self.onDoneCB = cb;\n self.kuzzle.subscriptions.pending[self.id] = self;\n\n subscribeQuery.body = self.filters;\n subscribeQuery = self.kuzzle.addHeaders(subscribeQuery, self.headers);\n\n self.kuzzle.query(self.collection.buildQueryArgs('realtime', 'subscribe'), subscribeQuery, {volatile: self.volatile}, function (error, response) {\n delete self.kuzzle.subscriptions.pending[self.id];\n self.subscribing = false;\n\n if (error) {\n self.queue = [];\n return cb && cb(new Error('Error during Kuzzle subscription: ' + error.message));\n }\n\n self.lastRenewal = now;\n self.roomId = response.result.roomId;\n self.channel = response.result.channel;\n\n if (!self.kuzzle.subscriptions[self.roomId]) {\n self.kuzzle.subscriptions[self.roomId] = {};\n }\n\n self.kuzzle.subscriptions[self.roomId][self.id] = self;\n\n self.notifier = notificationCallback.bind(self);\n self.kuzzle.network.on(self.channel, self.notifier);\n\n dequeue.call(self);\n cb && cb(null, self);\n });\n};\n\n/**\n * Unsubscribes from Kuzzle.\n *\n * Stop listening immediately. If there is no listener left on that room, sends an unsubscribe request to Kuzzle, once\n * pending subscriptions reaches 0, and only if there is still no listener on that room.\n * We wait for pending subscriptions to finish to avoid unsubscribing while another subscription on that room is\n *\n * @return {*} this\n */\nRoom.prototype.unsubscribe = function () {\n var\n self = this,\n room = self.roomId,\n interval;\n\n if (!isReady.call(this)) {\n self.queue.push({action: 'unsubscribe', args: []});\n return self;\n }\n\n if (room) {\n self.kuzzle.network.off(self.channel, this.notifier);\n\n if (Object.keys(self.kuzzle.subscriptions[room]).length === 1) {\n delete self.kuzzle.subscriptions[room];\n\n if (Object.keys(self.kuzzle.subscriptions.pending).length === 0) {\n self.kuzzle.query(self.collection.buildQueryArgs('realtime', 'unsubscribe'), {body: {roomId: room}});\n } else {\n interval = setInterval(function () {\n if (Object.keys(self.kuzzle.subscriptions.pending).length === 0) {\n if (!self.kuzzle.subscriptions[room]) {\n self.kuzzle.query(self.collection.buildQueryArgs('realtime', 'unsubscribe'), {body: {roomId: room}});\n }\n clearInterval(interval);\n }\n }, 100);\n }\n } else {\n delete self.kuzzle.subscriptions[room][self.id];\n }\n\n self.roomId = null;\n }\n\n return self;\n};\n\n/**\n * Helper function allowing to set headers while chaining calls.\n *\n * If the replace argument is set to true, replace the current headers with the provided content.\n * Otherwise, it appends the content to the current headers, only replacing already existing values\n *\n * @param content - new headers content\n * @param [replace] - default: false = append the content. If true: replace the current headers with tj\n */\nRoom.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\n/**\n * Callback called by the network handler when a message is sent to the subscribed room ID\n * Calls the registered callback if the notification passes the subscription filters\n *\n * @param {object} data - data\n * @returns {*}\n */\nfunction notificationCallback (data) {\n if (data.type === 'TokenExpired') {\n this.kuzzle.jwtToken = undefined;\n return this.kuzzle.emitEvent('tokenExpired');\n }\n\n if (data.type === 'document') {\n data.document = new Document(this.collection, data.result._id, data.result._source, data.result._meta);\n delete data.result;\n }\n\n if (this.kuzzle.requestHistory[data.requestId]) {\n if (this.subscribeToSelf) {\n this.callback(null, data);\n }\n delete this.kuzzle.requestHistory[data.requestId];\n } else {\n this.callback(null, data);\n }\n}\n\n\n/**\n * Dequeue actions performed while subscription was being renewed\n */\nfunction dequeue () {\n var element;\n\n while (this.queue.length > 0) {\n element = this.queue.shift();\n\n this[element.action].apply(this, element.args);\n }\n}\n\nfunction isReady() {\n return this.kuzzle.state === 'connected' && !this.subscribing;\n}\n\nmodule.exports = Room;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/Room.js\n// module id = 10\n// module chunks = 0","/**\n * @param {Collection} collection\n * @param {int} total\n * @param {Document[]} documents\n * @param {object} aggregations\n * @param {object} options\n * @param {object} filters\n * @param {SearchResult} previous\n * @property {Collection} collection\n * @property {number} total\n * @property {Document[]} documents\n * @property {object} aggregations\n * @property {object} options\n * @property {object} filters\n * @property {number} fetchedDocument\n * @constructor\n */\nfunction SearchResult (collection, total, documents, aggregations, options, filters, previous) {\n Object.defineProperties(this, {\n // read-only properties\n collection: {\n value: collection,\n enumerable: true\n },\n total: {\n value: total,\n enumerable: true\n },\n documents: {\n value: documents,\n enumerable: true\n },\n aggregations: {\n value: aggregations || {},\n enumerable: true\n },\n options: {\n value: options || {},\n enumerable: true\n },\n filters: {\n value: filters || {},\n enumerable: true\n },\n // writable properties\n fetchedDocument: {\n value: previous instanceof SearchResult ? documents.length + previous.fetchedDocument : documents.length,\n enumerable: true,\n writable: true\n }\n });\n\n // promisifying\n if (this.collection.kuzzle.bluebird) {\n return this.collection.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['fetchNext'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * @param {function} cb\n */\nSearchResult.prototype.fetchNext = function (cb) {\n var\n filters,\n options = Object.assign({}, this.options),\n self = this;\n \n options.previous = this;\n\n // retrieve next results with scroll if original search use it\n if (options.scrollId) {\n if (this.fetchedDocument >= this.getTotal()) {\n cb(null, null);\n return;\n }\n\n // from and size parameters are not valid for a scroll action\n if (typeof options.from !== 'undefined') {\n delete options.from;\n }\n\n if (options.size) {\n delete options.size;\n }\n\n this.collection.scroll(options.scrollId, options, this.filters || {}, cb);\n\n return;\n }\n\n // retrieve next results using ES's search_after\n if (options.size && this.filters.sort) {\n if (this.fetchedDocument >= this.getTotal()) {\n cb(null, null);\n return;\n }\n\n if (options.from) {\n delete options.from;\n }\n\n filters = Object.assign(this.filters, {search_after: []});\n\n filters.sort.forEach(function (sortRule) {\n filters.search_after.push(self.documents[self.documents.length - 1].content[Object.keys(sortRule)[0]]);\n });\n\n this.collection.search(filters, options, cb);\n\n return;\n }\n\n // retrieve next results with from/size if original search use it\n if (options.from !== undefined && options.size !== undefined) {\n filters = Object.assign({}, this.filters);\n\n // check if we need to do next request to fetch all matching documents\n options.from += options.size;\n\n if (options.from >= this.getTotal()) {\n cb(null, null);\n\n return;\n }\n\n this.collection.search(filters, options, cb);\n\n return;\n }\n\n cb(new Error('Unable to retrieve next results from search: missing scrollId or from/size params'));\n};\n\n/**\n * @returns {Document[]}\n */\nSearchResult.prototype.getDocuments = function () {\n return this.documents;\n};\n\n/**\n * @returns {number}\n */\nSearchResult.prototype.getTotal = function () {\n return this.total;\n};\n\n/**\n * @returns {object}\n */\nSearchResult.prototype.getAggregations = function () {\n return this.aggregations;\n};\n\n/**\n * @returns {Object}\n */\nSearchResult.prototype.getOptions = function() {\n return this.options;\n};\n\n/**\n * @returns {object}\n */\nSearchResult.prototype.getFilters = function() {\n return this.filters;\n};\n\n/**\n * @returns {object}\n */\nSearchResult.prototype.getCollection = function () {\n return this.collection;\n};\n\n/**\n * @returns {number}\n */\nSearchResult.prototype.getFetchedDocument = function () {\n return this.fetchedDocument;\n};\n\nmodule.exports = SearchResult;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/SearchResult.js\n// module id = 11\n// module chunks = 0","/**\n * Sugar-code handling the result of a Room.renew call\n * @constructor\n */\nfunction SubscribeResult() {\n this.cbs = [];\n this.error = null;\n this.room = null;\n}\n\n/**\n * Registers a callback to be called with a subscription result\n * @param {Function} cb\n */\nSubscribeResult.prototype.onDone = function (cb) {\n if (this.error || this.room) {\n cb(this.error, this.room);\n }\n else {\n this.cbs.push(cb);\n }\n\n return this;\n};\n\n/**\n * Calls all registered callbacks\n *\n * @param {Object} error object\n * @param {Room} room\n */\nSubscribeResult.prototype.done = function (error, room) {\n this.error = error;\n this.room = room;\n\n this.cbs.forEach(function (cb) {\n cb(error, room);\n });\n};\n\nmodule.exports = SubscribeResult;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/SubscribeResult.js\n// module id = 12\n// module chunks = 0","/**\n *\n * @param host\n * @param port\n * @param sslConnection\n * @returns {Object} tnstantiated WebSocket/Socket.IO object\n */\n\nfunction network(host, port, sslConnection) {\n // Web browser / NodeJS websocket handling\n if (typeof window !== 'undefined') {\n // use native websockets if the browser supports it\n if (typeof WebSocket !== 'undefined') {\n return new (require('./wrappers/websocket'))(host, port, sslConnection);\n }\n // otherwise fallback to socket.io, if available\n else if (window.io) {\n return new (require('./wrappers/socketio'))(host, port, sslConnection);\n }\n\n throw new Error('Aborting: no websocket support detected and no socket.io library loaded either.');\n }\n\n return new (require('./wrappers/websocket'))(host, port, sslConnection);\n}\n\nmodule.exports = network;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/networkWrapper/index.js\n// module id = 13\n// module chunks = 0","function SocketIO(host, port, ssl) {\n this.host = host;\n this.port = port;\n this.ssl = ssl;\n this.socket = null;\n this.wasConnected = false;\n this.forceDisconnect = false;\n this.handlers = {\n connect: [],\n reconnect: [],\n connectError: [],\n disconnect: []\n };\n this.retrying = false;\n\n /**\n * Creates a new socket from the provided arguments\n *\n * @constructor\n * @param {boolean} autoReconnect\n * @param {int} reconnectionDelay\n */\n this.connect = function (autoReconnect, reconnectionDelay) {\n var self = this;\n\n this.socket = window.io((this.ssl ? 'https://' : 'http://') + this.host + ':' + this.port, {\n reconnection: autoReconnect,\n reconnectionDelay: reconnectionDelay,\n forceNew: true\n });\n\n this.socket.on('connect', function() {\n if (self.wasConnected) {\n self.handlers.reconnect.forEach(function(handler) {\n handler();\n });\n }\n else {\n self.handlers.connect.forEach(function(handler) {\n handler();\n });\n }\n\n self.wasConnected = true;\n });\n\n this.socket.on('connect_error', function(error) {\n onClientNetworkError(self, autoReconnect, reconnectionDelay, error);\n });\n\n this.socket.on('disconnect', function() {\n var error;\n\n if (self.forceDisconnect) {\n self.handlers.disconnect.forEach(function(handler) {\n handler();\n });\n }\n else {\n error = new Error('An error occurred, this may due that kuzzle was not ready yet');\n error.status = 500;\n\n onClientNetworkError(self, autoReconnect, reconnectionDelay, error);\n }\n\n self.forceDisconnect = false;\n });\n };\n\n /**\n * Fires the provided callback whence a connection is established\n *\n * @param {function} callback\n */\n this.onConnect = function (callback) {\n if (this.handlers.connect.indexOf(callback) === -1) {\n this.handlers.connect.push(callback);\n }\n };\n\n /**\n * Fires the provided callback whenever a connection error is received\n * @param {function} callback\n */\n this.onConnectError = function (callback) {\n if (this.handlers.connectError.indexOf(callback) === -1) {\n this.handlers.connectError.push(callback);\n }\n };\n\n /**\n * Fires the provided callback whenever a disconnection occurred\n * @param {function} callback\n */\n this.onDisconnect = function (callback) {\n if (this.handlers.disconnect.indexOf(callback) === -1) {\n this.handlers.disconnect.push(callback);\n }\n };\n\n /**\n * Fires the provided callback whenever a connection has been reestablished\n * @param {function} callback\n */\n this.onReconnect = function (callback) {\n if (this.handlers.reconnect.indexOf(callback) === -1) {\n this.handlers.reconnect.push(callback);\n }\n };\n\n /**\n * Registers a callback on a room. Once 1 message is received, fires the\n * callback and unregister it afterward.\n *\n * @param {string} roomId\n * @param {function} callback\n */\n this.once = function (roomId, callback) {\n this.socket.once(roomId, callback);\n };\n\n /**\n * Registers a callback on a room.\n *\n * @param {string} roomId\n * @param {function} callback\n */\n this.on = function (roomId, callback) {\n this.socket.on(roomId, callback);\n };\n\n /**\n * Unregisters a callback from a room.\n *\n * @param {string} roomId\n * @param {function} callback\n */\n this.off = function (roomId, callback) {\n this.socket.off(roomId, callback);\n };\n\n\n /**\n * Sends a payload to the connected server\n *\n * @param {Object} payload\n */\n this.send = function (payload) {\n this.socket.emit('kuzzle', payload);\n };\n\n /**\n * Closes the connection\n */\n this.close = function () {\n this.forceDisconnect = true;\n\n this.socket.close();\n this.socket = null;\n };\n}\n\n/**\n * Called when the connection closes with an error state\n *\n * @param {SocketIO}\n * @param {boolean} autoReconnect\n * @param {number} reconnectionDelay\n * @param {Error} error\n */\nfunction onClientNetworkError(socketio, autoReconnect, reconnectionDelay, error) {\n if (autoReconnect && !socketio.retrying && !socketio.stopRetryingToConnect) {\n socketio.retrying = true;\n setTimeout(function () {\n socketio.retrying = false;\n socketio.connect(autoReconnect, reconnectionDelay);\n }, reconnectionDelay);\n }\n\n socketio.handlers.connectError.forEach(function(handler) {\n handler(error);\n });\n}\n\n\nmodule.exports = SocketIO;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/networkWrapper/wrappers/socketio.js\n// module id = 14\n// module chunks = 0","var SecurityDocument = require('./SecurityDocument');\n\nfunction Profile(Security, id, content, meta) {\n\n SecurityDocument.call(this, Security, id, content, meta);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteProfile'\n },\n updateActionName: {\n value: 'updateProfile'\n }\n });\n\n // promisifying\n if (Security.kuzzle.bluebird) {\n return Security.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['hydrate', 'save'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n}\n\nProfile.prototype = Object.create(SecurityDocument.prototype, {\n constructor: {\n value: Profile\n }\n});\n\n/**\n * Persist to the persistent layer the current profile\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Profile} this\n */\nProfile.prototype.save = function (options, cb) {\n var\n data,\n self = this;\n\n if (!this.content.policies) {\n throw new Error('Argument \"policies\" is mandatory in a profile. This argument contains an array of objects.');\n }\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = this.serialize();\n\n self.kuzzle.query(self.Security.buildQueryArgs('createOrReplaceProfile'), data, options, cb && function (error) {\n cb(error, error ? undefined : self);\n });\n\n return self;\n};\n\n\n/**\n * Add a policy in the policies list\n * @param {Object} policy - must be an object containing at least a \"roleId\" member which must be a string.\n *\n * @returns {Profile} this\n */\nProfile.prototype.addPolicy = function (policy) {\n\n if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n throw new Error('Parameter \"policies\" must be an object containing at least a \"roleId\" member which must be a string.');\n }\n\n if (!this.content.policies) {\n this.content.policies = [];\n }\n\n this.content.policies.push(policy);\n\n return this;\n};\n\n/**\n * Set policies list\n * @param {Array} policies - must be an array of objects containing at least a \"roleId\" member which must be a string\n *\n * @returns {Profile} this\n */\nProfile.prototype.setPolicies = function (policies) {\n\n if (!Array.isArray(policies)) {\n throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n }\n\n policies.map(function (policy) {\n if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n }\n });\n\n this.content.policies = policies;\n\n return this;\n};\n\n/**\n * Serialize this object into a JSON object\n *\n * @return {object} JSON object representing this securityDocument\n */\nProfile.prototype.serialize = function () {\n var\n data = {};\n\n if (this.id) {\n data._id = this.id;\n }\n\n data.body = this.content;\n data.meta = this.meta;\n\n return data;\n};\n\n/**\n * Returns the list of policies associated to this profile.\n * Each policy element is an array of objects containing at least a \"roleId\" member which must be a string\n *\n * @return {object} an array of policies\n */\nProfile.prototype.getPolicies = function () {\n return this.content.policies;\n};\n\nmodule.exports = Profile;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/security/Profile.js\n// module id = 15\n// module chunks = 0","var SecurityDocument = require('./SecurityDocument');\n\nfunction Role(Security, id, content, meta) {\n\n SecurityDocument.call(this, Security, id, content, meta);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteRole'\n },\n updateActionName: {\n value: 'updateRole'\n }\n });\n\n // promisifying\n if (Security.kuzzle.bluebird) {\n return Security.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['save'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n}\n\nRole.prototype = Object.create(SecurityDocument.prototype, {\n constructor: {\n value: Role\n }\n});\n\n/**\n * Saves this role into Kuzzle.\n *\n * If this is a new role, this function will create it in Kuzzle.\n * Otherwise, this method will replace the latest version of this role in Kuzzle by the current content\n * of this object.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Role} this object\n */\nRole.prototype.save = function (options, cb) {\n var\n data = this.serialize(),\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.Security.buildQueryArgs('createOrReplaceRole'), data, options, cb && function (error) {\n cb(error, error ? undefined : self);\n });\n\n return this;\n};\n\nmodule.exports = Role;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/security/Role.js\n// module id = 16\n// module chunks = 0","var\n Role = require('./Role'),\n Profile = require('./Profile'),\n User = require('./User');\n\n/**\n * Kuzzle security constructor\n *\n * @param kuzzle\n * @returns {Security}\n * @constructor\n */\nfunction Security(kuzzle) {\n\n Object.defineProperty(this, 'kuzzle', {\n value: kuzzle\n });\n\n Object.defineProperty(this, 'buildQueryArgs', {\n value: function (action) {\n return {\n controller: 'security',\n action: action\n };\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = ['role', 'profile', 'user', 'isActionAllowed'];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n\n/**\n * Retrieve a single Role using its unique role ID.\n *\n * @param {string} id\n * @param {object|responseCallback} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nSecurity.prototype.fetchRole = function (id, options, cb) {\n var\n data,\n self = this;\n\n if (!id) {\n throw new Error('Id parameter is mandatory for fetchRole function');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = {_id: id};\n\n self.kuzzle.callbackRequired('Security.fetchRole', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n cb(err, err ? undefined : new Role(self, response.result._id, response.result._source, response.result._meta));\n });\n};\n\n/**\n * Executes a search on roles according to a filter\n *\n * /!\\ There is a small delay between role creation and their existence in our persistent search layer,\n * usually a couple of seconds.\n * That means that a role that was just been created won’t be returned by this function.\n *\n * @param {Object} filters - this object can contains an array `indexes` with a list of index id, a integer `from` and a integer `size`\n * @param {object|responseCallback} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n *\n */\nSecurity.prototype.searchRoles = function (filters, options, cb) {\n var\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Security.searchRoles', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchRoles'), {body: filters}, options, function (error, result) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = result.result.hits.map(function (doc) {\n return new Role(self, doc._id, doc._source, doc._meta);\n });\n\n cb(null, { total: result.result.total, roles: documents });\n });\n};\n\n/**\n * Create a new role in Kuzzle.\n *\n * Takes an optional argument object with the following property:\n * - replaceIfExist (boolean, default: false):\n * If the same role already exists: throw an error if sets to false.\n * Replace the existing role otherwise\n *\n * @param {string} id - role identifier\n * @param {object} content - a plain javascript object representing the role\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nSecurity.prototype.createRole = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'createRole';\n\n if (!id || typeof id !== 'string') {\n throw new Error('Security.createRole: cannot create a role without a role ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n data.body = content;\n\n if (options) {\n action = options.replaceIfExist ? 'createOrReplaceRole' : 'createRole';\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new Role(self, res.result._id, res.result._source, res.result._meta));\n });\n};\n\n\n/**\n * Update a role in Kuzzle.\n *\n * @param {string} id - role identifier\n * @param {object} content - a plain javascript object representing the role's modification\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {Security} this object\n */\nSecurity.prototype.updateRole = function (id, content, options, cb) {\n var\n self = this,\n data = {_id: id, body: content},\n action = 'updateRole';\n\n if (!id || typeof id !== 'string') {\n throw new Error('Security.updateRole: cannot update a role without a role ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new Role(self, id, content, res.result._meta));\n });\n\n return this;\n};\n\n/**\n * Delete role.\n *\n * There is a small delay between role deletion and their deletion in our advanced search layer,\n * usually a couple of seconds.\n * That means that a role that was just been delete will be returned by this function\n *\n *\n * @param {string} id - Role id to delete\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Security} this object\n */\nSecurity.prototype.deleteRole = function (id, options, cb) {\n var data = {_id: id};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.buildQueryArgs('deleteRole'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result._id);\n });\n\n return this;\n};\n\n/**\n * Instantiate a new Role object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - role id\n * @param {object} content - role content\n * @param {object} meta - role metadata\n * @constructor\n */\nSecurity.prototype.role = function(id, content, meta) {\n return new Role(this, id, content, meta);\n};\n\n\n/**\n * Get a specific profile from kuzzle\n *\n *\n * @param {string} id\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nSecurity.prototype.fetchProfile = function (id, options, cb) {\n var\n data,\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!id || typeof id !== 'string') {\n throw new Error('Id parameter is mandatory for fetchProfile function');\n }\n\n\n data = {_id: id};\n\n self.kuzzle.callbackRequired('Security.fetchProfile', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n cb(error, error ? undefined : new Profile(self, response.result._id, response.result._source, response.result._meta));\n });\n};\n\n/**\n * Executes a search on profiles according to a filter\n *\n *\n * /!\\ There is a small delay between profile creation and their existence in our persistent search layer,\n * usually a couple of seconds.\n * That means that a profile that was just been created won’t be returned by this function.\n *\n * @param {Object} filters - this object can contains an array `roles` with a list of roles id, a integer `from` and a integer `size`\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nSecurity.prototype.searchProfiles = function (filters, options, cb) {\n var\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Security.searchProfiles', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n var\n documents,\n scrollId;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new Profile(self, doc._id, doc._source, doc._meta);\n });\n\n if (response.result.scrollId) {\n scrollId = response.result.scrollId;\n }\n\n cb(null, { total: response.result.total, profiles: documents, scrollId: scrollId });\n });\n};\n\n/**\n * Create a new profile in Kuzzle.\n *\n * Takes an optional argument object with the following property:\n * - replaceIfExist (boolean, default: false):\n * If the same profile already exists: throw an error if sets to false.\n * Replace the existing profile otherwise\n *\n * @param {string} id - profile identifier\n * @param {array} policies - list of policies to attach to the new profile\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nSecurity.prototype.createProfile = function (id, policies, options, cb) {\n var\n self = this,\n data = {},\n action = 'createProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('Security.createProfile: cannot create a profile without a profile ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n\n if (policies) {\n data.body = { policies: policies };\n }\n\n if (options) {\n action = options.replaceIfExist ? 'createOrReplaceProfile' : 'createProfile';\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new Profile(self, res.result._id, res.result._source, res.result._meta));\n });\n};\n\n\n/**\n * Update a profile in Kuzzle.\n *\n * @param {string} id - profile identifier\n * @param {array} policies - the list of policies to apply to this profile\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {Security} this object\n */\nSecurity.prototype.updateProfile = function (id, policies, options, cb) {\n var\n self = this,\n data = {},\n action = 'updateProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('Security.updateProfile: cannot update a profile without a profile ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n\n if (policies) {\n data.body = {policies: policies};\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n var updatedContent = {};\n\n if (err) {\n return cb(err);\n }\n\n Object.keys(res.result._source).forEach(function (property) {\n updatedContent[property] = res.result._source[property];\n });\n\n cb(null, new Profile(self, res.result._id, updatedContent, res.result._meta));\n });\n\n return this;\n};\n\n/**\n * Delete profile.\n *\n * There is a small delay between profile deletion and their deletion in our advanced search layer,\n * usually a couple of seconds.\n * That means that a profile that was just been delete will be returned by this function\n *\n *\n * @param {string} id - Profile id to delete\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Security} this object\n */\nSecurity.prototype.deleteProfile = function (id, options, cb) {\n var data = {_id: id};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.buildQueryArgs('deleteProfile'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result._id);\n });\n\n return this;\n};\n\n/**\n * @param {string} scrollId\n * @param {object} [options]\n * @param {responseCallback} cb\n */\nSecurity.prototype.scrollProfiles = function (scrollId, options, cb) {\n var\n request = {},\n self = this;\n\n if (!scrollId) {\n throw new Error('Security.scrollProfiles: scrollId is required');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n this.kuzzle.callbackRequired('Security.scrollProfiles', cb);\n\n request.scrollId = scrollId;\n\n if (options && options.scroll) {\n request.scroll = options.scroll;\n }\n\n this.kuzzle.query({controller: 'security', action: 'scrollProfiles'}, request, options, function (error, result) {\n var profiles = [];\n\n if (error) {\n return cb(error);\n }\n\n result.result.hits.forEach(function (profile) {\n var newProfile = new Profile(self, profile._id, profile._source, profile._meta);\n\n newProfile.version = profile._version;\n\n profiles.push(newProfile);\n });\n\n cb(null, {\n total: result.result.total,\n profiles: profiles,\n scrollId: scrollId\n });\n });\n};\n\n/**\n * Instantiate a new Profile object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - profile id\n * @param {object} content - profile content\n * @param {object} meta - profile metadata\n * @constructor\n */\nSecurity.prototype.profile = function(id, content, meta) {\n return new Profile(this, id, content, meta);\n};\n\n/**\n * Get a specific user from kuzzle using its unique ID\n *\n * @param {string} id\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nSecurity.prototype.fetchUser = function (id, options, cb) {\n var\n data = {_id: id},\n self = this;\n\n if (!id || typeof id !== 'string') {\n throw new Error('Id parameter is mandatory for fetchUser function');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Security.fetchUser', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n cb(err, err ? undefined : new User(self, response.result._id, response.result._source, response.result._meta));\n });\n};\n\n/**\n * Executes a search on user according to a filter\n *\n * /!\\ There is a small delay between user creation and their existence in our persistent search layer,\n * usually a couple of seconds.\n * That means that a user that was just been created won’t be returned by this function.\n *\n * @param {Object} filters - same filters as documents filters\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nSecurity.prototype.searchUsers = function (filters, options, cb) {\n var\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Security.searchUsers', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n var\n documents,\n scrollId = null;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new User(self, doc._id, doc._source, doc._meta);\n });\n\n if (response.result.scrollId) {\n scrollId = response.result.scrollId;\n }\n\n cb(null, { total: response.result.total, users: documents, scrollId: scrollId });\n });\n};\n\n/**\n * Create a new user in Kuzzle.\n *\n * @param {string} id - user identifier\n * @param {object} content - attribute `profileIds` in `content` must only contain an array of profile ids\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nSecurity.prototype.createUser = function (id, content, options, cb) {\n var\n self = this,\n data = {_id: id, body: content};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(self.buildQueryArgs('createUser'), data, null, cb && function (err, res) {\n cb(err, err ? undefined : new User(self, res.result._id, res.result._source, res.result._meta));\n });\n};\n\n/**\n * Replace an user in Kuzzle.\n *\n * @param {string} id - user identifier\n * @param {object} content - attribute `profileIds` in `content` must only contain an array of profile ids\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nSecurity.prototype.replaceUser = function (id, content, options, cb) {\n var\n self = this,\n data = {_id: id, body: content};\n\n if (!id || typeof id !== 'string') {\n throw new Error('Security.replaceUser: cannot replace a user without a user ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.buildQueryArgs('replaceUser'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new User(self, res.result._id, res.result._source, res.result._meta));\n });\n};\n\n/**\n * Create a new restricted user in Kuzzle.\n *\n * This function will create a new user. It is not usable to update an existing user.\n * This function allows anonymous users to create a \"restricted\" user with predefined rights.\n *\n * @param {string} id - user identifier\n * @param {object} content - attribute `profile` in `content` must only contains the profile id\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nSecurity.prototype.createRestrictedUser = function (id, content, options, cb) {\n var\n self = this,\n data = {_id: id, body: content};\n\n if (content.profileIds) {\n throw new Error('Security.createRestrictedUser: cannot provide profileIds');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.buildQueryArgs('createRestrictedUser'), data, null, cb && function (err, res) {\n cb(err, err ? undefined : new User(self, res.result._id, res.result._source));\n });\n};\n\n\n/**\n * Update an user in Kuzzle.\n *\n * @param {string} id - user identifier\n * @param {object} content - a plain javascript object representing the user's modification\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {Security} this object\n */\nSecurity.prototype.updateUser = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'updateUser';\n\n if (!id || typeof id !== 'string') {\n throw new Error('Security.updateUser: cannot update an user without an user ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n data.body = content;\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new User(self, res.result._id, res.result._source, res.result._meta));\n });\n\n return this;\n};\n\n/**\n * Delete user.\n *\n * There is a small delay between user deletion and their deletion in our advanced search layer,\n * usually a couple of seconds.\n * That means that a user that was just been delete will be returned by this function\n *\n *\n * @param {string} id - Profile id to delete\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Security} this object\n */\nSecurity.prototype.deleteUser = function (id, options, cb) {\n var data = {_id: id};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.buildQueryArgs('deleteUser'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result._id);\n });\n\n return this;\n};\n\n/**\n * @param {string} scrollId\n * @param {object} [options]\n * @param {responseCallback} cb\n */\nSecurity.prototype.scrollUsers = function (scrollId, options, cb) {\n var\n request = {},\n self = this;\n\n if (!scrollId) {\n throw new Error('Security.scrollUsers: scrollId is required');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n this.kuzzle.callbackRequired('Security.scrollUsers', cb);\n\n request.scrollId = scrollId;\n\n if (options && options.scroll) {\n request.scroll = options.scroll;\n }\n\n this.kuzzle.query({controller: 'security', action: 'scrollUsers'}, request, options, function (error, result) {\n var users = [];\n\n if (error) {\n return cb(error);\n }\n\n result.result.hits.forEach(function (user) {\n var newUser = new User(self, user._id, user._source, user._meta);\n\n newUser.version = user._version;\n\n users.push(newUser);\n });\n\n cb(null, {\n total: result.result.total,\n users: users,\n scrollId: scrollId\n });\n });\n\n return this;\n};\n\n/**\n * Instantiate a new User object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - user id\n * @param {object} content - user content\n * @param {object} meta - user metadata\n * @constructor\n */\nSecurity.prototype.user = function(id, content, meta) {\n return new User(this, id, content, meta);\n};\n\n/**\n * Tells whether an action is allowed, denied or conditional based on the rights\n * rights provided as the first argument. An action is defined as a couple of\n * action and controller (mandatory), plus an index and a collection(optional).\n *\n * @param {object} rights - The rights rights associated to a user\n * (see getMyrights and getUserrights).\n * @param {string} controller - The controller to check the action onto.\n * @param {string} action - The action to perform.\n * @param {string} index - (optional) The name of index to perform the action onto.\n * @param {string} collection - (optional) The name of the collection to perform the action onto.\n *\n * @returns {string} ['allowed', 'denied', 'conditional'] where conditional cases\n * correspond to rights containing closures.\n * See also http://kuzzle.io/guide/#roles-definition\n */\nSecurity.prototype.isActionAllowed = function(rights, controller, action, index, collection) {\n var filteredRights;\n\n if (!rights || typeof rights !== 'object') {\n throw new Error('rights parameter is mandatory for isActionAllowed function');\n }\n if (!controller || typeof controller !== 'string') {\n throw new Error('controller parameter is mandatory for isActionAllowed function');\n }\n if (!action || typeof action !== 'string') {\n throw new Error('action parameter is mandatory for isActionAllowed function');\n }\n\n // We filter in all the rights that match the request (including wildcards).\n filteredRights = rights\n .filter(function (right) {\n return right.controller === controller || right.controller === '*';\n })\n .filter(function (right) {\n return right.action === action || right.action === '*';\n })\n .filter(function (right) {\n return right.index === index || right.index === '*';\n })\n .filter(function (right) {\n return right.collection === collection || right.collection === '*';\n });\n\n // Then, if at least one right allows the action, we return 'allowed'\n if (filteredRights.some(function (item) { return item.value === 'allowed'; })) {\n return 'allowed';\n }\n // If no right allows the action, we check for conditionals.\n if (filteredRights.some(function (item) { return item.value === 'conditional'; })) {\n return 'conditional';\n }\n // Otherwise we return 'denied'.\n return 'denied';\n};\n\n\n/**\n * Gets the rights array of a given user.\n *\n * @param {string} userId The id of the user.\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {function} cb The callback containing the normalized array of rights.\n */\nSecurity.prototype.getUserRights = function (userId, options, cb) {\n var\n data = {_id: userId},\n self = this;\n\n if (!userId || typeof userId !== 'string') {\n throw new Error('userId parameter is mandatory for getUserRights function');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Kuzzle.getUserRights', cb);\n\n this.kuzzle.query(this.buildQueryArgs('getUserRights'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result.hits);\n });\n};\n\n/**\n * Create credentials of the specified for the user .\n *\n * @param strategy\n * @param kuid\n * @param credentials\n * @param options\n * @param cb\n * @returns {Security}\n */\nSecurity.prototype.createCredentials = function (strategy, kuid, credentials, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'createCredentials'}, {_id: kuid, strategy: strategy, body: credentials}, options, function(err, res) {\n if (!err) {\n cb && cb(null, res.result._source);\n } else {\n cb && cb(err);\n }\n });\n\n return this;\n};\n\n/**\n * Delete credentials of the specified for the user .\n *\n * @param strategy\n * @param kuid\n * @param options\n * @param cb\n * @returns {Security}\n */\nSecurity.prototype.deleteCredentials = function (strategy, kuid, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'deleteCredentials'}, {strategy: strategy, _id: kuid}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n\n return this;\n};\n\n/**\n * Retrieve a list of accepted fields per authentication strategy.\n *\n * @param options\n * @param cb\n */\nSecurity.prototype.getAllCredentialFields = function (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'getAllCredentialFields'}, {}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n};\n\n/**\n * Retrieve the list of accepted field names by the specified .\n *\n * @param strategy\n * @param options\n * @param cb\n */\nSecurity.prototype.getCredentialFields = function (strategy, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'getCredentialFields'}, {strategy: strategy}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n};\n\n/**\n * Get credential information of the specified for the user .\n *\n * @param strategy\n * @param kuid\n * @param options\n * @param cb\n */\nSecurity.prototype.getCredentials = function (strategy, kuid, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'getCredentials'}, {strategy: strategy, _id: kuid}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n};\n\n/**\n * Check the existence of the specified ’s credentials for the user .\n *\n * @param strategy\n * @param kuid\n * @param options\n * @param cb\n */\nSecurity.prototype.hasCredentials = function (strategy, kuid, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'hasCredentials'}, {strategy: strategy, _id: kuid}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n};\n\n/**\n * Updates credentials of the specified for the user .\n *\n * @param strategy\n * @param kuid\n * @param credentials\n * @param options\n * @param cb\n * @returns {Security}\n */\nSecurity.prototype.updateCredentials = function (strategy, kuid, credentials, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'updateCredentials'}, {strategy: strategy, _id: kuid, body: credentials}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n\n return this;\n};\n\n/**\n * Validate credentials of the specified for the user .\n *\n * @param strategy\n * @param kuid\n * @param credentials\n * @param options\n * @param cb\n */\nSecurity.prototype.validateCredentials = function (strategy, kuid, credentials, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'validateCredentials'}, {strategy: strategy, _id: kuid, body: credentials}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n};\n\nmodule.exports = Security;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/security/Security.js\n// module id = 17\n// module chunks = 0","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../~/events/events.js\n// module id = 18\n// module chunks = 0","/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nvar byteToHex = [];\nfor (var i = 0; i < 256; ++i) {\n byteToHex[i] = (i + 0x100).toString(16).substr(1);\n}\n\nfunction bytesToUuid(buf, offset) {\n var i = offset || 0;\n var bth = byteToHex;\n return bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]];\n}\n\nmodule.exports = bytesToUuid;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../~/uuid/lib/bytesToUuid.js\n// module id = 19\n// module chunks = 0","// Unique ID creation requires a high quality random # generator. In the\n// browser this is a little complicated due to unknown quality of Math.random()\n// and inconsistent support for the `crypto` API. We do the best we can via\n// feature-detection\nvar rng;\n\nvar crypto = global.crypto || global.msCrypto; // for IE 11\nif (crypto && crypto.getRandomValues) {\n // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto\n var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef\n rng = function whatwgRNG() {\n crypto.getRandomValues(rnds8);\n return rnds8;\n };\n}\n\nif (!rng) {\n // Math.random()-based (RNG)\n //\n // If all else fails, use Math.random(). It's fast, but is of unspecified\n // quality.\n var rnds = new Array(16);\n rng = function() {\n for (var i = 0, r; i < 16; i++) {\n if ((i & 0x03) === 0) r = Math.random() * 0x100000000;\n rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n }\n\n return rnds;\n };\n}\n\nmodule.exports = rng;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../~/uuid/lib/rng-browser.js\n// module id = 20\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///kuzzle.js","webpack:///webpack/bootstrap d2654b12cf08324a5af1","webpack:///./src/Kuzzle.js","webpack:///./src/eventEmitter/index.js","webpack:///./src/security/SecurityDocument.js","webpack:///./src/networkWrapper/protocols/abstract/realtime.js","webpack:///./src/Document.js","webpack:///./src/security/User.js","webpack:///./src/Room.js","webpack:///./src/networkWrapper/protocols/socketio.js","webpack:///./src/networkWrapper/protocols/websocket.js","webpack:///./src/Collection.js","webpack:///./src/CollectionMapping.js","webpack:///./src/MemoryStorage.js","webpack:///./src/SearchResult.js","webpack:///./src/networkWrapper/index.js","webpack:///./src/security/Profile.js","webpack:///./src/security/Role.js","webpack:///./src/security/Security.js","webpack:///./~/uuid/lib/bytesToUuid.js","webpack:///./~/uuid/lib/rng-browser.js","webpack:///./~/uuid/v4.js"],"names":["root","factory","exports","module","define","amd","this","modules","__webpack_require__","moduleId","installedModules","id","loaded","call","m","c","p","_classCallCheck","instance","Constructor","TypeError","_possibleConstructorReturn","self","ReferenceError","_inherits","subClass","superClass","prototype","Object","create","constructor","value","enumerable","writable","configurable","setPrototypeOf","__proto__","checkPropertyType","prop","typestr","wrongType","Array","isArray","_typeof","Error","Symbol","iterator","obj","_createClass","defineProperties","target","props","i","length","descriptor","defineProperty","key","protoProps","staticProps","_get","get","object","property","receiver","Function","desc","getOwnPropertyDescriptor","undefined","parent","getPrototypeOf","getter","uuidv4","KuzzleEventEmitter","Collection","Document","Security","MemoryStorage","User","networkWrapper","Kuzzle","_KuzzleEventEmitter","host","options","cb","_this","connectCB","eventActions","autoResubscribe","defaultIndex","jwt","protocol","sdkVersion","volatile","_iteratorNormalCompletion","_didIteratorError","_iteratorError","_step","_iterator","keys","next","done","opt","hasOwnProperty","err","return","room","opts","subscribeCB","_this2","requestId","controller","action","index","collection","body","filters","scope","state","users","notificationCB","data","type","unsetJwt","emit","copy","assign","document","result","_id","_source","_meta","notify","network","subscribe","unsubscribeCB","roomId","unsubscribe","channel","errorMessagePrefix","callback","eventTimeout","connected","timeout","error","disconnected","reconnected","tokenExpired","loginAttempt","autoQueue","set","autoReconnect","autoReplay","offlineQueue","offlineQueueLoader","port","queueFilter","queueMaxSize","queueTTL","replayInterval","reconnectionDelay","sslConnection","eumerable","ssl","addListener","query","connect","bluebird","_ret","promisifyAll","suffix","filter","name","func","passes","whitelist","indexOf","eventName","_get2","now","Date","protectedEvent","protectedEvents","lastEmitted","_len","arguments","payload","_key","apply","concat","_this3","connectionError","internal","disconnect","checkToken","res","valid","on","token","success","JSON","stringify","strategy","_this4","request","expiresIn","queuable","response","message","setJwt","credentials","_this5","callbackRequired","_this6","security","hits","content","event","listener","toString","timestamp","queryCB","startTime","collections","flushQueue","_len2","args","_key2","_iteratorNormalCompletion2","_didIteratorError2","_iteratorError2","_step2","_iterator2","arg","indexes","close","_iteratorNormalCompletion3","_didIteratorError3","_iteratorError3","_step3","_iterator3","serverInfo","_len3","_key3","_iteratorNormalCompletion4","_didIteratorError4","_iteratorError4","_step4","_iterator4","_len4","_key4","_iteratorNormalCompletion5","_didIteratorError5","_iteratorError5","_step5","_iterator5","autoRefresh","_len5","_key5","_iteratorNormalCompletion6","_didIteratorError6","_iteratorError6","_step6","_iterator6","queryArgs","_arr","_i","_iteratorNormalCompletion7","_didIteratorError7","_iteratorError7","_step7","_iterator7","attr","startQueuing","stopQueuing","playQueue","Listener","fn","once","_events","listeners","Boolean","find","map","listenerType","_exists","push","addOnceListener","prependListener","findIndex","l","splice","onceListeners","toDelete","removeListener","SecurityDocument","meta","kuzzle","setContent","serialize","delete","buildQueryArgs","deleteActionName","update","updateActionName","emitRequest","status","requestHistory","send","discardRequest","cleanQueue","lastDocumentIndex","forEach","ts","droppedRequest","dequeue","uniqueQueue","dequeuingProcess","shift","setTimeout","Math","max","additionalQueue","cleanHistory","RTWrapper","cleanHistoryTimer","queuing","offlineMode","wasConnected","stopRetryingToConnect","retrying","setInterval","clearHistoryTimer","fromSelf","removeAllListeners","clearInterval","documentId","dataCollection","version","_version","exists","refresh","newDocument","save","publish","replace","ids","values","KuzzleSecurityDocument","setProfiles","profileIds","setCredentials","addProfile","profileId","creationSerialize","saveRestricted","getProfileIds","getProfiles","fetchedProfiles","errored","fetchProfile","profile","Room","_roomId","roomstate","isListening","resubscribe","deactivate","resubscribeConditional","subscribeToSelf","count","onDone","SocketIO","_RTWrapper","socket","forceDisconnect","eventsWrapper","window","io","reconnection","forceNew","clientConnected","clientNetworkError","clientDisconnected","_addEventWrapper","size","off","wrapper","_event","Set","add","WebSocketClient","WSNode","WebSocket","e","code","client","lasturl","url","perMessageDeflate","onopen","onclose","closeEvent","reason","onerror","onmessage","parse","readyState","OPEN","blacklist","KuzzleSearchResult","CollectionMapping","createDocument","ifExist","doc","deleteDocument","deleteSpecifications","documentExists","fetchDocument","getMapping","kuzzleMapping","mCreateDocument","documents","mCreateOrReplaceDocument","mDeleteDocument","documentIds","mGetDocument","mReplaceDocument","mUpdateDocument","getSpecifications","publishMessage","replaceDocument","search","_scroll_id","scrollId","total","aggregations","previous","scroll","scrollSpecifications","searchSpecifications","evtName","truncate","updateDocument","retryOnConflict","updateSpecifications","specifications","validateSpecifications","collectionMapping","mapping","properties","mappings","field","assignParameter","assignGeoRadiusOptions","parsed","assignZrangeOptions","limit","mapGeoposResults","results","coords","latlon","parseFloat","mapGeoRadiusResults","point","coordinates","coord","distance","mapStringToArray","mapArrayStringToArrayInt","parseInt","mapNoResult","mapZrangeResults","buffer","mapped","member","score","mapScanResults","cursor","getId","required","getIdField","getKeys","getMember","getxScan","mapResults","getZrange","getZrangeBy","setId","setIdValue","commands","append","bitcount","bitop","bitpos","dbsize","decr","decrby","del","expire","expireat","flushdb","geoadd","geodist","geohash","geopos","georadius","georadiusbymember","getbit","getrange","getset","hdel","hexists","hget","hgetall","hincrby","hincrbyfloat","hkeys","hlen","hmget","hmset","hscan","hset","hsetnx","hstrlen","hvals","incr","incrby","incrbyfloat","lindex","linsert","llen","lpop","lpush","lpushx","lrange","lrem","lset","ltrim","mget","mset","msetnx","persist","pexpire","pexpireat","pfadd","pfcount","pfmerge","ping","psetex","pttl","randomkey","rename","renamenx","rpop","rpoplpush","rpush","rpushx","sadd","scan","scard","sdiff","sdiffstore","setex","setnx","sinter","sinterstore","sismember","smembers","smove","sort","spop","srandmember","srem","sscan","strlen","sunion","sunionstore","time","touch","ttl","zadd","zcard","zcount","zincrby","zinterstore","zlexcount","zrange","zrangebylex","zrevrangebylex","zrangebyscore","zrank","zrem","zremrangebylex","zremrangebyrank","zremrangebyscore","zrevrange","zrevrangebyscore","zrevrank","zscan","zscore","zunionstore","command","slice","pop","param","SearchResult","fetchedDocument","fetchNext","getTotal","from","search_after","sortRule","getDocuments","getAggregations","getOptions","getFilters","getCollection","getFetchedDocument","Profile","policies","addPolicy","policy","roleId","setPolicies","getPolicies","Role","fetchRole","searchRoles","roles","createRole","replaceIfExist","updateRole","deleteRole","role","searchProfiles","profiles","createProfile","updateProfile","updatedContent","deleteProfile","scrollProfiles","newProfile","fetchUser","searchUsers","createUser","replaceUser","createRestrictedUser","updateUser","deleteUser","scrollUsers","user","newUser","isActionAllowed","rights","filteredRights","right","some","item","getUserRights","userId","createCredentials","kuid","deleteCredentials","getAllCredentialFields","getCredentialFields","getCredentials","hasCredentials","updateCredentials","validateCredentials","bytesToUuid","buf","offset","bth","byteToHex","substr","rng","crypto","msCrypto","getRandomValues","rnds8","Uint8Array","rnds","r","random","v4","ii"],"mappings":";CAAA,SAAAA,EAAAC,GACA,gBAAAC,UAAA,gBAAAC,QACAA,OAAAD,QAAAD,IACA,kBAAAG,gBAAAC,IACAD,UAAAH,GACA,gBAAAC,SACAA,QAAA,OAAAD,IAEAD,EAAA,OAAAC,KACCK,KAAA,WACD,MCCgB,UAAUC,GCP1B,QAAAC,GAAAC,GAGA,GAAAC,EAAAD,GACA,MAAAC,GAAAD,GAAAP,OAGA,IAAAC,GAAAO,EAAAD,IACAP,WACAS,G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,UACAF,EAAArnB,GAAAsnB,MAAA,EAAAtnB,IAAA,MAGA,OAAAqnB,IAIAtqB,EAAAD,QAAAiqB,GpBu2NM,SAAUhqB,EAAQD,EAASM,GqBp4NjC,QAAAoqB,GAAA1lB,EAAA4kB,EAAAC,GACA,GAAA3mB,GAAA0mB,GAAAC,GAAA,CAEA,sBACAD,EAAA,UAAA5kB,EAAA,GAAAzC,OAAA,SACAyC,EAAA,MAEAA,OAEA,IAAAulB,GAAAvlB,EAAAylB,SAAAzlB,EAAAilB,SAOA,IAJAM,EAAA,MAAAA,EAAA,MACAA,EAAA,MAAAA,EAAA,OAGAX,EACA,OAAAe,GAAA,EAAoBA,EAAA,KAASA,EAC7Bf,EAAA1mB,EAAAynB,GAAAJ,EAAAI,EAIA,OAAAf,IAAAD,EAAAY,GAzBA,GAAAN,GAAA3pB,EAAA,IACAqpB,EAAArpB,EAAA,GA2BAL,GAAAD,QAAA0qB","file":"kuzzle.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Kuzzle\"] = factory();\n\telse\n\t\troot[\"Kuzzle\"] = factory();\n})(this, function() {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition","/*! Kuzzle javascript SDK version 5.0.10 */\n(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Kuzzle\"] = factory();\n\telse\n\t\troot[\"Kuzzle\"] = factory();\n})(this, function() {\nreturn /******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId])\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\texports: {},\n/******/ \t\t\tid: moduleId,\n/******/ \t\t\tloaded: false\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.loaded = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(0);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t'use strict';\n\t\n\tvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\t\n\tvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\t\n\tvar _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if (\"value\" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };\n\t\n\tfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\t\n\tfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\t\n\tfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\t\n\tvar uuidv4 = __webpack_require__(19),\n\t KuzzleEventEmitter = __webpack_require__(1),\n\t Collection = __webpack_require__(9),\n\t Document = __webpack_require__(4),\n\t Security = __webpack_require__(16),\n\t MemoryStorage = __webpack_require__(11),\n\t User = __webpack_require__(5),\n\t networkWrapper = __webpack_require__(13);\n\t\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t/**\n\t * Kuzzle object constructor.\n\t *\n\t * @constructor\n\t * @param host - Server name or IP Address to the Kuzzle instance\n\t * @param [options] - Connection options\n\t * @param {responseCallback} [cb] - Handles connection response\n\t */\n\t\n\tvar Kuzzle = function (_KuzzleEventEmitter) {\n\t _inherits(Kuzzle, _KuzzleEventEmitter);\n\t\n\t function Kuzzle(host, options, cb) {\n\t _classCallCheck(this, Kuzzle);\n\t\n\t var _this = _possibleConstructorReturn(this, (Kuzzle.__proto__ || Object.getPrototypeOf(Kuzzle)).call(this));\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!host || host === '') {\n\t throw new Error('host argument missing');\n\t }\n\t\n\t Object.defineProperties(_this, {\n\t // 'private' properties\n\t connectCB: {\n\t value: cb\n\t },\n\t eventActions: {\n\t value: ['connected', 'discarded', 'disconnected', 'loginAttempt', 'networkError', 'offlineQueuePush', 'offlineQueuePop', 'queryError', 'reconnected', 'tokenExpired']\n\t },\n\t // configuration properties\n\t autoResubscribe: {\n\t value: options && typeof options.autoResubscribe === 'boolean' ? options.autoResubscribe : true,\n\t enumerable: true\n\t },\n\t defaultIndex: {\n\t value: options && typeof options.defaultIndex === 'string' ? options.defaultIndex : undefined,\n\t writable: true,\n\t enumerable: true\n\t },\n\t jwt: {\n\t value: undefined,\n\t enumerable: true,\n\t writable: true\n\t },\n\t protocol: {\n\t value: options && typeof options.protocol === 'string' ? options.protocol : 'websocket',\n\t enumerable: true\n\t },\n\t sdkVersion: {\n\t value: false ? require('../package.json').version : (\"5.0.10\")\n\t },\n\t volatile: {\n\t value: {},\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t if (options) {\n\t var _iteratorNormalCompletion = true;\n\t var _didIteratorError = false;\n\t var _iteratorError = undefined;\n\t\n\t try {\n\t for (var _iterator = Object.keys(options)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n\t var opt = _step.value;\n\t\n\t if (_this.hasOwnProperty(opt) && Object.getOwnPropertyDescriptor(_this, opt).writable) {\n\t _this[opt] = options[opt];\n\t }\n\t }\n\t } catch (err) {\n\t _didIteratorError = true;\n\t _iteratorError = err;\n\t } finally {\n\t try {\n\t if (!_iteratorNormalCompletion && _iterator.return) {\n\t _iterator.return();\n\t }\n\t } finally {\n\t if (_didIteratorError) {\n\t throw _iteratorError;\n\t }\n\t }\n\t }\n\t }\n\t\n\t // Forward the subscribe query to the network wrapper\n\t Object.defineProperty(_this, 'subscribe', {\n\t value: function value(room, opts, subscribeCB) {\n\t var _this2 = this;\n\t\n\t var object = {\n\t requestId: uuidv4(),\n\t controller: 'realtime',\n\t action: 'subscribe',\n\t index: room.collection.index,\n\t collection: room.collection.collection,\n\t volatile: this.volatile,\n\t body: room.filters,\n\t scope: room.scope,\n\t state: room.state,\n\t users: room.users\n\t },\n\t notificationCB = function notificationCB(data) {\n\t if (data.type === 'TokenExpired') {\n\t _this2.unsetJwt();\n\t return _this2.emit('tokenExpired');\n\t }\n\t\n\t if (data.type === 'document') {\n\t var copy = Object.assign({}, data);\n\t copy.document = new Document(room.collection, data.result._id, data.result._source, data.result._meta);\n\t delete copy.result;\n\t return room.notify(copy);\n\t }\n\t\n\t room.notify(data);\n\t };\n\t\n\t if (this.jwt !== undefined) {\n\t object.jwt = this.jwt;\n\t }\n\t\n\t Object.assign(object.volatile, room.volatile, { sdkVersion: this.sdkVersion });\n\t\n\t this.network.subscribe(object, opts, notificationCB, subscribeCB);\n\t }\n\t });\n\t\n\t // Forward the unsubscribe query to the network wrapper\n\t Object.defineProperty(_this, 'unsubscribe', {\n\t value: function value(room, unsubscribeCB) {\n\t var object = {\n\t requestId: uuidv4(),\n\t controller: 'realtime',\n\t action: 'unsubscribe',\n\t volatile: _this.volatile,\n\t body: { roomId: room.roomId }\n\t };\n\t\n\t if (_this.jwt !== undefined) {\n\t object.jwt = _this.jwt;\n\t }\n\t\n\t Object.assign(object.volatile, room.volatile, { sdkVersion: _this.sdkVersion });\n\t\n\t _this.network.unsubscribe(object, room.channel, unsubscribeCB);\n\t }\n\t });\n\t\n\t /**\n\t * Some methods (mainly read queries) require a callback function. This function exists to avoid repetition of code,\n\t * and is called by these methods\n\t */\n\t Object.defineProperty(_this, 'callbackRequired', {\n\t value: function value(errorMessagePrefix, callback) {\n\t if (!callback || typeof callback !== 'function') {\n\t throw new Error(errorMessagePrefix + ': a callback argument is required for read queries');\n\t }\n\t }\n\t });\n\t\n\t /**\n\t * Create an attribute security that embed all methods to manage Role, Profile and User\n\t */\n\t Object.defineProperty(_this, 'security', {\n\t value: new Security(_this),\n\t enumerable: true\n\t });\n\t\n\t Object.defineProperty(_this, 'memoryStorage', {\n\t value: new MemoryStorage(_this),\n\t enumerable: true\n\t });\n\t\n\t Object.defineProperty(_this, 'collections', {\n\t value: {},\n\t writable: true\n\t });\n\t\n\t Object.defineProperty(_this, 'eventTimeout', {\n\t value: options && typeof options.eventTimeout === 'number' ? options.eventTimeout : 200\n\t });\n\t\n\t Object.defineProperty(_this, 'protectedEvents', {\n\t value: {\n\t connected: { timeout: _this.eventTimeout },\n\t error: { timeout: _this.eventTimeout },\n\t disconnected: { timeout: _this.eventTimeout },\n\t reconnected: { timeout: _this.eventTimeout },\n\t tokenExpired: { timeout: _this.eventTimeout },\n\t loginAttempt: { timeout: _this.eventTimeout }\n\t }\n\t });\n\t\n\t _this.network = networkWrapper(_this.protocol, host, options);\n\t\n\t // Properties related to the network layer\n\t // Accessing a property irrelevant for a given protocol\n\t // (e.g. \"autoReconnect\" for the HTTP layer) should\n\t // throw an exception\n\t Object.defineProperties(_this, {\n\t autoQueue: {\n\t enumerable: true,\n\t get: function get() {\n\t return _this.network.autoQueue;\n\t },\n\t set: function set(value) {\n\t checkPropertyType('autoQueue', 'boolean', value);\n\t _this.network.autoQueue = value;\n\t }\n\t },\n\t autoReconnect: {\n\t enumerable: true,\n\t get: function get() {\n\t return _this.network.autoReconnect;\n\t }\n\t },\n\t autoReplay: {\n\t enumerable: true,\n\t get: function get() {\n\t return _this.network.autoReplay;\n\t },\n\t set: function set(value) {\n\t checkPropertyType('autoReplay', 'boolean', value);\n\t _this.network.autoReplay = value;\n\t }\n\t },\n\t host: {\n\t enumerable: true,\n\t get: function get() {\n\t return _this.network.host;\n\t }\n\t },\n\t offlineQueue: {\n\t enumerable: true,\n\t get: function get() {\n\t return _this.network.offlineQueue;\n\t }\n\t },\n\t offlineQueueLoader: {\n\t enumerable: true,\n\t get: function get() {\n\t return _this.network.offlineQueueLoader;\n\t },\n\t set: function set(value) {\n\t if (value !== null) {\n\t checkPropertyType('offlineQueueLoader', 'function', value);\n\t }\n\t _this.network.offlineQueueLoader = value;\n\t }\n\t },\n\t port: {\n\t enumerable: true,\n\t get: function get() {\n\t return _this.network.port;\n\t }\n\t },\n\t queueFilter: {\n\t enumerable: true,\n\t get: function get() {\n\t return _this.network.queueFilter;\n\t },\n\t set: function set(value) {\n\t checkPropertyType('queueFilter', 'function', value);\n\t _this.network.queueFilter = value;\n\t }\n\t },\n\t queueMaxSize: {\n\t enumerable: true,\n\t get: function get() {\n\t return _this.network.queueMaxSize;\n\t },\n\t set: function set(value) {\n\t checkPropertyType('queueMaxSize', 'number', value);\n\t _this.network.queueMaxSize = value;\n\t }\n\t },\n\t queueTTL: {\n\t enumerable: true,\n\t get: function get() {\n\t return _this.network.queueTTL;\n\t },\n\t set: function set(value) {\n\t checkPropertyType('queueTTL', 'number', value);\n\t _this.network.queueTTL = value;\n\t }\n\t },\n\t replayInterval: {\n\t enumerable: true,\n\t get: function get() {\n\t return _this.network.replayInterval;\n\t },\n\t set: function set(value) {\n\t checkPropertyType('replayInterval', 'number', value);\n\t _this.network.replayInterval = value;\n\t }\n\t },\n\t reconnectionDelay: {\n\t enumerable: true,\n\t get: function get() {\n\t return _this.network.reconnectionDelay;\n\t }\n\t },\n\t sslConnection: {\n\t eumerable: true,\n\t get: function get() {\n\t return _this.network.ssl;\n\t }\n\t }\n\t });\n\t\n\t _this.network.addListener('offlineQueuePush', function (data) {\n\t return _this.emit('offlineQueuePush', data);\n\t });\n\t _this.network.addListener('offlineQueuePop', function (data) {\n\t return _this.emit('offlineQueuePop', data);\n\t });\n\t _this.network.addListener('queryError', function (err, query) {\n\t return _this.emit('queryError', err, query);\n\t });\n\t\n\t _this.network.addListener('tokenExpired', function () {\n\t _this.unsetJwt();\n\t _this.emit('tokenExpired');\n\t });\n\t\n\t if ((options && options.connect || 'auto') === 'auto') {\n\t _this.connect();\n\t }\n\t\n\t if (_this.bluebird) {\n\t var _ret;\n\t\n\t return _ret = _this.bluebird.promisifyAll(_this, {\n\t suffix: 'Promise',\n\t filter: function filter(name, func, target, passes) {\n\t var whitelist = ['getAllStatistics', 'getServerInfo', 'getStatistics', 'listCollections', 'listIndexes', 'login', 'logout', 'now', 'query', 'checkToken', 'whoAmI', 'updateSelf', 'getMyRights', 'getMyCredentials', 'createMyCredentials', 'deleteMyCredentials', 'updateMyCredentials', 'validateMyCredentials', 'createIndex', 'refreshIndex', 'getAutoRefresh', 'setAutoRefresh'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t }), _possibleConstructorReturn(_this, _ret);\n\t }\n\t return _this;\n\t }\n\t\n\t /**\n\t * Emit an event to all registered listeners\n\t * An event cannot be emitted multiple times before a timeout has been reached.\n\t */\n\t\n\t\n\t _createClass(Kuzzle, [{\n\t key: 'emit',\n\t value: function emit(eventName) {\n\t var _get2;\n\t\n\t var now = Date.now(),\n\t protectedEvent = this.protectedEvents[eventName];\n\t\n\t if (protectedEvent) {\n\t if (protectedEvent.lastEmitted && protectedEvent.lastEmitted > now - protectedEvent.timeout) {\n\t return false;\n\t }\n\t protectedEvent.lastEmitted = now;\n\t }\n\t\n\t for (var _len = arguments.length, payload = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n\t payload[_key - 1] = arguments[_key];\n\t }\n\t\n\t (_get2 = _get(Kuzzle.prototype.__proto__ || Object.getPrototypeOf(Kuzzle.prototype), 'emit', this)).call.apply(_get2, [this, eventName].concat(payload));\n\t }\n\t\n\t /**\n\t * Connects to a Kuzzle instance using the provided host name.\n\t * @returns {Object} this\n\t */\n\t\n\t }, {\n\t key: 'connect',\n\t value: function connect() {\n\t var _this3 = this;\n\t\n\t if (this.network.state !== 'offline') {\n\t if (this.connectCB) {\n\t this.connectCB(null, this);\n\t }\n\t return this;\n\t }\n\t\n\t this.network.connect();\n\t\n\t this.network.addListener('connect', function () {\n\t _this3.emit('connected');\n\t\n\t if (_this3.connectCB) {\n\t _this3.connectCB(null, _this3);\n\t }\n\t });\n\t\n\t this.network.addListener('networkError', function (error) {\n\t var connectionError = new Error('Unable to connect to kuzzle proxy server at ' + _this3.network.host + ':' + _this3.network.port);\n\t\n\t connectionError.internal = error;\n\t _this3.emit('networkError', connectionError);\n\t\n\t if (_this3.connectCB) {\n\t _this3.connectCB(connectionError);\n\t }\n\t });\n\t\n\t this.network.addListener('disconnect', function () {\n\t _this3.disconnect();\n\t _this3.emit('disconnected');\n\t });\n\t\n\t this.network.addListener('reconnect', function () {\n\t if (_this3.jwt) {\n\t _this3.checkToken(_this3.jwt, function (err, res) {\n\t // shouldn't obtain an error but let's invalidate the token anyway\n\t if (err || !res.valid) {\n\t _this3.unsetJwt();\n\t }\n\t\n\t _this3.emit('reconnected');\n\t });\n\t } else {\n\t _this3.emit('reconnected');\n\t }\n\t });\n\t\n\t this.network.on('discarded', function (data) {\n\t return _this3.emit('discarded', data);\n\t });\n\t\n\t return this;\n\t }\n\t\n\t /**\n\t * Set the jwt used to query kuzzle\n\t * @param token\n\t * @returns {Kuzzle}\n\t */\n\t\n\t }, {\n\t key: 'setJwt',\n\t value: function setJwt(token) {\n\t if (typeof token === 'string') {\n\t this.jwt = token;\n\t } else if ((typeof token === 'undefined' ? 'undefined' : _typeof(token)) === 'object') {\n\t if (token.result && token.result.jwt && typeof token.result.jwt === 'string') {\n\t this.jwt = token.result.jwt;\n\t } else {\n\t this.emit('loginAttempt', {\n\t success: false,\n\t error: 'Cannot find a valid JWT in the following object: ' + JSON.stringify(token)\n\t });\n\t\n\t return this;\n\t }\n\t } else {\n\t this.emit('loginAttempt', { success: false, error: 'Invalid token argument: ' + token });\n\t return this;\n\t }\n\t\n\t this.emit('loginAttempt', { success: true });\n\t return this;\n\t }\n\t\n\t /**\n\t * Unset the jwt used to query kuzzle\n\t * @returns {Kuzzle}\n\t */\n\t\n\t }, {\n\t key: 'unsetJwt',\n\t value: function unsetJwt() {\n\t this.jwt = undefined;\n\t return this;\n\t }\n\t\n\t /**\n\t * Get the jwt used by kuzzle\n\t * @returns {Kuzzle}\n\t */\n\t\n\t }, {\n\t key: 'getJwt',\n\t value: function getJwt() {\n\t return this.jwt;\n\t }\n\t\n\t /**\n\t * Send login request to kuzzle with credentials\n\t * If login success, store the jwt into kuzzle object\n\t *\n\t * @param strategy\n\t * @param credentials\n\t * @param expiresIn\n\t * @param cb\n\t */\n\t\n\t }, {\n\t key: 'login',\n\t value: function login(strategy) {\n\t var _this4 = this;\n\t\n\t if (!strategy || typeof strategy !== 'string') {\n\t throw new Error('Kuzzle.login: strategy required');\n\t }\n\t\n\t var request = {\n\t strategy: strategy,\n\t body: {}\n\t };\n\t\n\t var cb = null;\n\t\n\t // Handle arguments (credentials, expiresIn, cb)\n\t if (arguments.length <= 1 ? undefined : arguments[1]) {\n\t if (_typeof(arguments.length <= 1 ? undefined : arguments[1]) === 'object') {\n\t request.body = arguments.length <= 1 ? undefined : arguments[1];\n\t } else if (typeof (arguments.length <= 1 ? undefined : arguments[1]) === 'number' || typeof (arguments.length <= 1 ? undefined : arguments[1]) === 'string') {\n\t request.expiresIn = arguments.length <= 1 ? undefined : arguments[1];\n\t } else if (typeof (arguments.length <= 1 ? undefined : arguments[1]) === 'function') {\n\t cb = arguments.length <= 1 ? undefined : arguments[1];\n\t }\n\t }\n\t if (arguments.length <= 2 ? undefined : arguments[2]) {\n\t if (typeof (arguments.length <= 2 ? undefined : arguments[2]) === 'number' || typeof (arguments.length <= 2 ? undefined : arguments[2]) === 'string') {\n\t request.expiresIn = arguments.length <= 2 ? undefined : arguments[2];\n\t } else if (typeof (arguments.length <= 2 ? undefined : arguments[2]) === 'function') {\n\t cb = arguments.length <= 2 ? undefined : arguments[2];\n\t }\n\t }\n\t if ((arguments.length <= 3 ? undefined : arguments[3]) && typeof (arguments.length <= 3 ? undefined : arguments[3]) === 'function') {\n\t cb = arguments.length <= 3 ? undefined : arguments[3];\n\t }\n\t\n\t this.query({ controller: 'auth', action: 'login' }, request, { queuable: false }, function (error, response) {\n\t if (!error) {\n\t if (response.result.jwt) {\n\t _this4.setJwt(response.result.jwt);\n\t }\n\t\n\t cb && cb(null, response.result);\n\t } else {\n\t cb && cb(error);\n\t _this4.emit('loginAttempt', { success: false, error: error.message });\n\t }\n\t });\n\t }\n\t\n\t /**\n\t * Create credentials of the specified for the current user.\n\t *\n\t * @param credentials\n\t * @param strategy\n\t * @param options\n\t * @param cb\n\t * @returns {Kuzzle}\n\t */\n\t\n\t }, {\n\t key: 'createMyCredentials',\n\t value: function createMyCredentials(strategy, credentials, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.query({ controller: 'auth', action: 'createMyCredentials' }, { strategy: strategy, body: credentials }, options, function (err, res) {\n\t if (typeof cb === 'function') {\n\t cb(err, err ? undefined : res.result._source);\n\t }\n\t });\n\t\n\t return this;\n\t }\n\t\n\t /**\n\t * Delete credentials of the specified for the current user.\n\t *\n\t * @param strategy\n\t * @param options\n\t * @param cb\n\t * @returns {Kuzzle}\n\t */\n\t\n\t }, {\n\t key: 'deleteMyCredentials',\n\t value: function deleteMyCredentials(strategy, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.query({ controller: 'auth', action: 'deleteMyCredentials' }, { strategy: strategy }, options, function (err, res) {\n\t if (typeof cb === 'function') {\n\t cb(err, err ? undefined : res.result);\n\t }\n\t });\n\t\n\t return this;\n\t }\n\t\n\t /**\n\t * Get credential information of the specified for the current user.\n\t *\n\t * @param strategy\n\t * @param options\n\t * @param cb\n\t */\n\t\n\t }, {\n\t key: 'getMyCredentials',\n\t value: function getMyCredentials(strategy, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.query({ controller: 'auth', action: 'getMyCredentials' }, { strategy: strategy }, options, function (err, res) {\n\t if (typeof cb === 'function') {\n\t cb(err, err ? undefined : res.result);\n\t }\n\t });\n\t }\n\t\n\t /**\n\t * Update credentials of the specified for the current user.\n\t *\n\t * @param strategy\n\t * @param credentals\n\t * @param options\n\t * @param cb\n\t * @returns {Kuzzle}\n\t */\n\t\n\t }, {\n\t key: 'updateMyCredentials',\n\t value: function updateMyCredentials(strategy, credentials, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.query({ controller: 'auth', action: 'updateMyCredentials' }, { strategy: strategy, body: credentials }, options, function (err, res) {\n\t if (typeof cb === 'function') {\n\t cb(err, err ? undefined : res.result);\n\t }\n\t });\n\t\n\t return this;\n\t }\n\t\n\t /**\n\t * Validate credentials of the specified for the current user.\n\t *\n\t * @param strategy\n\t * @param credentials\n\t * @param options\n\t * @param cb\n\t */\n\t\n\t }, {\n\t key: 'validateMyCredentials',\n\t value: function validateMyCredentials(strategy, credentials, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.query({ controller: 'auth', action: 'validateMyCredentials' }, { strategy: strategy, body: credentials }, options, function (err, res) {\n\t if (typeof cb === 'function') {\n\t cb(err, err ? undefined : res.result);\n\t }\n\t });\n\t }\n\t\n\t /**\n\t * Create a kuzzle index\n\t *\n\t * @param {string} index\n\t * @param {object} [options]\n\t * @param {responseCallback} cb\n\t * @returns {Kuzzle}\n\t */\n\t\n\t }, {\n\t key: 'createIndex',\n\t value: function createIndex(index, options, cb) {\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.createIndex: index required');\n\t }\n\t index = this.defaultIndex;\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.query({ controller: 'index', action: 'create', index: index }, {}, options, function (err, res) {\n\t if (typeof cb === 'function') {\n\t cb(err, err ? undefined : res.result);\n\t }\n\t });\n\t\n\t return this;\n\t }\n\t\n\t /**\n\t * Send logout request to kuzzle with jwt.\n\t *\n\t * @param cb\n\t * @returns {Kuzzle}\n\t */\n\t\n\t }, {\n\t key: 'logout',\n\t value: function logout(cb) {\n\t var _this5 = this;\n\t\n\t var request = {\n\t action: 'logout',\n\t controller: 'auth',\n\t requestId: uuidv4(),\n\t body: {}\n\t };\n\t\n\t this.query({ controller: 'auth', action: 'logout' }, request, { queuable: false }, function (error) {\n\t if (typeof cb === 'function') {\n\t cb(error, _this5);\n\t }\n\t });\n\t\n\t return this.unsetJwt();\n\t }\n\t\n\t /**\n\t * Checks whether a given jwt token still represents a valid session in Kuzzle.\n\t *\n\t * @param {string} token The jwt token to check\n\t * @param {function} cb The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t */\n\t\n\t }, {\n\t key: 'checkToken',\n\t value: function checkToken(token, cb) {\n\t var request = {\n\t body: {\n\t token: token\n\t }\n\t };\n\t\n\t this.callbackRequired('Kuzzle.checkToken', cb);\n\t\n\t this.query({ controller: 'auth', action: 'checkToken' }, request, { queuable: false }, function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t }\n\t\n\t /**\n\t * Fetches the current user.\n\t *\n\t * @param {function} cb The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t */\n\t\n\t }, {\n\t key: 'whoAmI',\n\t value: function whoAmI(cb) {\n\t var _this6 = this;\n\t\n\t this.callbackRequired('Kuzzle.whoAmI', cb);\n\t\n\t this.query({ controller: 'auth', action: 'getCurrentUser' }, {}, {}, function (err, res) {\n\t cb(err, err ? undefined : new User(_this6.security, res.result._id, res.result._source, res.result._meta));\n\t });\n\t }\n\t\n\t /**\n\t * Gets the rights array of the currently logged user.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {function} cb The callback containing the normalized array of rights.\n\t */\n\t\n\t }, {\n\t key: 'getMyRights',\n\t value: function getMyRights(options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.getMyRights', cb);\n\t\n\t this.query({ controller: 'auth', action: 'getMyRights' }, {}, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.hits);\n\t });\n\t }\n\t\n\t /**\n\t * Update current user in Kuzzle.\n\t *\n\t * @param {object} content - a plain javascript object representing the user's modification\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {Kuzzle} this object\n\t */\n\t\n\t }, {\n\t key: 'updateSelf',\n\t value: function updateSelf(content, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.query({ controller: 'auth', action: 'updateSelf' }, { body: content }, options, function (err, res) {\n\t if (typeof cb === 'function') {\n\t cb(err, err ? undefined : res.result);\n\t }\n\t });\n\t\n\t return this;\n\t }\n\t\n\t /**\n\t * Adds a listener to a Kuzzle global event. When an event is fired, listeners are called in the order of their\n\t * insertion.\n\t *\n\t * @param {string} event - name of the global event to subscribe to\n\t * @param {function} listener - callback to invoke each time an event is fired\n\t */\n\t\n\t }, {\n\t key: 'addListener',\n\t value: function addListener(event, listener) {\n\t if (this.eventActions.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + this.eventActions.toString());\n\t }\n\t\n\t return _get(Kuzzle.prototype.__proto__ || Object.getPrototypeOf(Kuzzle.prototype), 'addListener', this).call(this, event, listener);\n\t }\n\t\n\t /**\n\t * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n\t * This method returns all available statistics from Kuzzle.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\t\n\t }, {\n\t key: 'getAllStatistics',\n\t value: function getAllStatistics(options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.getAllStatistics', cb);\n\t\n\t this.query({ controller: 'server', action: 'getAllStats' }, {}, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.hits);\n\t });\n\t }\n\t\n\t /**\n\t * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n\t * This method allows getting either the last statistics frame, or a set of frames starting from a provided timestamp.\n\t *\n\t * @param {number} [timestamp] - Epoch time. Starting time from which the frames are to be retrieved\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\t\n\t }, {\n\t key: 'getStatistics',\n\t value: function getStatistics(timestamp, options, cb) {\n\t if (!cb) {\n\t if (!options) {\n\t cb = timestamp;\n\t options = null;\n\t timestamp = null;\n\t } else {\n\t cb = options;\n\t if ((typeof timestamp === 'undefined' ? 'undefined' : _typeof(timestamp)) === 'object') {\n\t options = timestamp;\n\t timestamp = null;\n\t } else {\n\t options = null;\n\t }\n\t }\n\t }\n\t\n\t this.callbackRequired('Kuzzle.getStatistics', cb);\n\t\n\t var queryCB = function queryCB(err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, timestamp ? res.result.hits : [res.result]);\n\t },\n\t body = timestamp ? { body: { startTime: timestamp } } : {};\n\t\n\t this.query({ controller: 'server', action: timestamp ? 'getStats' : 'getLastStats' }, body, options, queryCB);\n\t }\n\t\n\t /**\n\t * Create a new instance of a Collection object.\n\t * If no index is specified, takes the default index.\n\t *\n\t * @param {string} collection - The name of the data collection you want to manipulate\n\t * @param {string} [index] - The name of the data index containing the data collection\n\t * @returns {Collection} A Collection instance\n\t */\n\t\n\t }, {\n\t key: 'collection',\n\t value: function collection(_collection, index) {\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Unable to create a new data collection object: no index specified');\n\t }\n\t\n\t index = this.defaultIndex;\n\t }\n\t\n\t if (typeof index !== 'string' || typeof _collection !== 'string') {\n\t throw new Error('Invalid index or collection argument: string expected');\n\t }\n\t\n\t if (!this.collections[index]) {\n\t this.collections[index] = {};\n\t }\n\t\n\t if (!this.collections[index][_collection]) {\n\t this.collections[index][_collection] = new Collection(this, _collection, index);\n\t }\n\t\n\t return this.collections[index][_collection];\n\t }\n\t\n\t /**\n\t * Empties the offline queue without replaying it.\n\t *\n\t * @returns {Kuzzle}\n\t */\n\t\n\t }, {\n\t key: 'flushQueue',\n\t value: function flushQueue() {\n\t this.network.flushQueue();\n\t return this;\n\t }\n\t\n\t /**\n\t * Returns the list of known persisted data collections.\n\t *\n\t * @param {string} [index] - Index containing collections to be listed\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\t\n\t }, {\n\t key: 'listCollections',\n\t value: function listCollections() {\n\t var index = void 0,\n\t options = void 0,\n\t cb = void 0;\n\t\n\t for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n\t args[_key2] = arguments[_key2];\n\t }\n\t\n\t var _iteratorNormalCompletion2 = true;\n\t var _didIteratorError2 = false;\n\t var _iteratorError2 = undefined;\n\t\n\t try {\n\t for (var _iterator2 = args[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n\t var arg = _step2.value;\n\t\n\t switch (typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t }\n\t } catch (err) {\n\t _didIteratorError2 = true;\n\t _iteratorError2 = err;\n\t } finally {\n\t try {\n\t if (!_iteratorNormalCompletion2 && _iterator2.return) {\n\t _iterator2.return();\n\t }\n\t } finally {\n\t if (_didIteratorError2) {\n\t throw _iteratorError2;\n\t }\n\t }\n\t }\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.listCollections: index required');\n\t }\n\t\n\t index = this.defaultIndex;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.listCollections', cb);\n\t\n\t var query = { type: options && options.type || 'all' };\n\t\n\t this.query({ index: index, controller: 'collection', action: 'list' }, query, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.collections);\n\t });\n\t }\n\t\n\t /**\n\t * Returns the list of existing indexes in Kuzzle\n\t *\n\t * @param {object} [options] - Optional arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\t\n\t }, {\n\t key: 'listIndexes',\n\t value: function listIndexes(options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.listIndexes', cb);\n\t\n\t this.query({ controller: 'index', action: 'list' }, {}, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.indexes);\n\t });\n\t }\n\t\n\t /**\n\t * Disconnects from Kuzzle and invalidate this instance.\n\t */\n\t\n\t }, {\n\t key: 'disconnect',\n\t value: function disconnect() {\n\t this.network.close();\n\t\n\t var _iteratorNormalCompletion3 = true;\n\t var _didIteratorError3 = false;\n\t var _iteratorError3 = undefined;\n\t\n\t try {\n\t for (var _iterator3 = Object.keys(this.collections)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {\n\t var collection = _step3.value;\n\t\n\t delete this.collections[collection];\n\t }\n\t } catch (err) {\n\t _didIteratorError3 = true;\n\t _iteratorError3 = err;\n\t } finally {\n\t try {\n\t if (!_iteratorNormalCompletion3 && _iterator3.return) {\n\t _iterator3.return();\n\t }\n\t } finally {\n\t if (_didIteratorError3) {\n\t throw _iteratorError3;\n\t }\n\t }\n\t }\n\t }\n\t\n\t /**\n\t * Returns the server informations\n\t *\n\t * @param {object} [options] - Optional arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\t\n\t }, {\n\t key: 'getServerInfo',\n\t value: function getServerInfo(options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.getServerInfo', cb);\n\t\n\t this.query({ controller: 'server', action: 'info' }, {}, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.serverInfo);\n\t });\n\t }\n\t\n\t /**\n\t * Forces an index refresh\n\t *\n\t * @param {string} index - The index to refresh. Defaults to Kuzzle.defaultIndex\n\t * @param {object} options - Optional arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t * @returns {Kuzzle}\n\t */\n\t\n\t }, {\n\t key: 'refreshIndex',\n\t value: function refreshIndex() {\n\t var index = void 0,\n\t options = void 0,\n\t cb = void 0;\n\t\n\t for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n\t args[_key3] = arguments[_key3];\n\t }\n\t\n\t var _iteratorNormalCompletion4 = true;\n\t var _didIteratorError4 = false;\n\t var _iteratorError4 = undefined;\n\t\n\t try {\n\t for (var _iterator4 = args[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {\n\t var arg = _step4.value;\n\t\n\t switch (typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t }\n\t } catch (err) {\n\t _didIteratorError4 = true;\n\t _iteratorError4 = err;\n\t } finally {\n\t try {\n\t if (!_iteratorNormalCompletion4 && _iterator4.return) {\n\t _iterator4.return();\n\t }\n\t } finally {\n\t if (_didIteratorError4) {\n\t throw _iteratorError4;\n\t }\n\t }\n\t }\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.refreshIndex: index required');\n\t }\n\t index = this.defaultIndex;\n\t }\n\t\n\t this.query({ index: index, controller: 'index', action: 'refresh' }, {}, options, cb);\n\t\n\t return this;\n\t }\n\t\n\t /**\n\t * Returns de current autoRefresh status for the given index\n\t *\n\t * @param {string} index - The index to get the status from. Defaults to Kuzzle.defaultIndex\n\t * @param {object} options - Optinal arguments\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\t\n\t }, {\n\t key: 'getAutoRefresh',\n\t value: function getAutoRefresh() {\n\t var index = void 0,\n\t options = void 0,\n\t cb = void 0;\n\t\n\t for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n\t args[_key4] = arguments[_key4];\n\t }\n\t\n\t var _iteratorNormalCompletion5 = true;\n\t var _didIteratorError5 = false;\n\t var _iteratorError5 = undefined;\n\t\n\t try {\n\t for (var _iterator5 = args[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {\n\t var arg = _step5.value;\n\t\n\t switch (typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t }\n\t } catch (err) {\n\t _didIteratorError5 = true;\n\t _iteratorError5 = err;\n\t } finally {\n\t try {\n\t if (!_iteratorNormalCompletion5 && _iterator5.return) {\n\t _iterator5.return();\n\t }\n\t } finally {\n\t if (_didIteratorError5) {\n\t throw _iteratorError5;\n\t }\n\t }\n\t }\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.getAutoRefresh: index required');\n\t }\n\t index = this.defaultIndex;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.getAutoRefresh', cb);\n\t this.query({ index: index, controller: 'index', action: 'getAutoRefresh' }, {}, options, cb);\n\t }\n\t\n\t /**\n\t * (Un)Sets the autoRefresh flag on the given index\n\t *\n\t * @param {string} index - the index to modify. Defaults to Kuzzle.defaultIndex\n\t * @param {boolean} autoRefresh - The autoRefresh value to set\n\t * @param {object} options - Optional arguments\n\t * @param {responseCallback} cb - Handles the query result\n\t * @returns {object} this\n\t */\n\t\n\t }, {\n\t key: 'setAutoRefresh',\n\t value: function setAutoRefresh() {\n\t var index, autoRefresh, options, cb;\n\t\n\t for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {\n\t args[_key5] = arguments[_key5];\n\t }\n\t\n\t var _iteratorNormalCompletion6 = true;\n\t var _didIteratorError6 = false;\n\t var _iteratorError6 = undefined;\n\t\n\t try {\n\t for (var _iterator6 = args[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {\n\t var arg = _step6.value;\n\t\n\t switch (typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) {\n\t case 'string':\n\t index = arg;\n\t break;\n\t case 'boolean':\n\t autoRefresh = arg;\n\t break;\n\t case 'object':\n\t options = arg;\n\t break;\n\t case 'function':\n\t cb = arg;\n\t break;\n\t }\n\t }\n\t } catch (err) {\n\t _didIteratorError6 = true;\n\t _iteratorError6 = err;\n\t } finally {\n\t try {\n\t if (!_iteratorNormalCompletion6 && _iterator6.return) {\n\t _iterator6.return();\n\t }\n\t } finally {\n\t if (_didIteratorError6) {\n\t throw _iteratorError6;\n\t }\n\t }\n\t }\n\t\n\t if (!index) {\n\t if (!this.defaultIndex) {\n\t throw new Error('Kuzzle.setAutoRefresh: index required');\n\t }\n\t index = this.defaultIndex;\n\t }\n\t\n\t if (autoRefresh === undefined) {\n\t throw new Error('Kuzzle.setAutoRefresh: autoRefresh value is required');\n\t }\n\t\n\t this.query({ index: index, controller: 'index', action: 'setAutoRefresh' }, { body: { autoRefresh: autoRefresh } }, options, cb);\n\t\n\t return this;\n\t }\n\t\n\t /**\n\t * Return the current Kuzzle's UTC Epoch time, in milliseconds\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\t\n\t }, {\n\t key: 'now',\n\t value: function now(options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.callbackRequired('Kuzzle.now', cb);\n\t\n\t this.query({ controller: 'server', action: 'now' }, {}, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.now);\n\t });\n\t }\n\t\n\t /**\n\t * This is a low-level method, exposed to allow advanced SDK users to bypass high-level methods.\n\t * Base method used to send read queries to Kuzzle\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} queryArgs - Query configuration\n\t * @param {object} query - The query data\n\t * @param {object} [options] - Optional arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\t\n\t }, {\n\t key: 'query',\n\t value: function query(queryArgs, _query, options, cb) {\n\t var object = {\n\t action: queryArgs.action,\n\t controller: queryArgs.controller,\n\t volatile: this.volatile\n\t };\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t } else if (!cb && !options && typeof _query === 'function') {\n\t cb = _query;\n\t _query = {};\n\t options = null;\n\t }\n\t\n\t if (options) {\n\t var _arr = ['refresh', 'from', 'size', 'scroll', 'scrollId'];\n\t\n\t for (var _i = 0; _i < _arr.length; _i++) {\n\t var prop = _arr[_i];\n\t if (options[prop] !== undefined) {\n\t object[prop] = options[prop];\n\t }\n\t }\n\t\n\t if (options.volatile && _typeof(options.volatile) === 'object') {\n\t Object.assign(object.volatile, options.volatile);\n\t }\n\t }\n\t\n\t if (!_query || (typeof _query === 'undefined' ? 'undefined' : _typeof(_query)) !== 'object' || Array.isArray(_query)) {\n\t throw new Error('Invalid query parameter: ' + _query);\n\t }\n\t\n\t Object.assign(object.volatile, _query.volatile, { sdkVersion: this.sdkVersion });\n\t\n\t var _iteratorNormalCompletion7 = true;\n\t var _didIteratorError7 = false;\n\t var _iteratorError7 = undefined;\n\t\n\t try {\n\t for (var _iterator7 = Object.keys(_query)[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {\n\t var attr = _step7.value;\n\t\n\t if (attr !== 'volatile') {\n\t object[attr] = _query[attr];\n\t }\n\t }\n\t\n\t /*\n\t * Do not add the token for the checkToken route, to avoid getting a token error when\n\t * a developer simply wish to verify his token\n\t */\n\t } catch (err) {\n\t _didIteratorError7 = true;\n\t _iteratorError7 = err;\n\t } finally {\n\t try {\n\t if (!_iteratorNormalCompletion7 && _iterator7.return) {\n\t _iterator7.return();\n\t }\n\t } finally {\n\t if (_didIteratorError7) {\n\t throw _iteratorError7;\n\t }\n\t }\n\t }\n\t\n\t if (this.jwt !== undefined && !(object.controller === 'auth' && object.action === 'checkToken')) {\n\t object.jwt = this.jwt;\n\t }\n\t\n\t if (queryArgs.collection) {\n\t object.collection = queryArgs.collection;\n\t }\n\t\n\t if (queryArgs.index) {\n\t object.index = queryArgs.index;\n\t }\n\t\n\t if (!object.requestId) {\n\t object.requestId = uuidv4();\n\t }\n\t\n\t this.network.query(object, options, cb);\n\t\n\t return this;\n\t }\n\t\n\t /**\n\t * Starts the requests queuing.\n\t */\n\t\n\t }, {\n\t key: 'startQueuing',\n\t value: function startQueuing() {\n\t this.network.startQueuing();\n\t return this;\n\t }\n\t\n\t /**\n\t * Stops the requests queuing.\n\t */\n\t\n\t }, {\n\t key: 'stopQueuing',\n\t value: function stopQueuing() {\n\t this.network.stopQueuing();\n\t return this;\n\t }\n\t\n\t /**\n\t * @DEPRECATED\n\t * See Kuzzle.prototype.playQueue();\n\t */\n\t\n\t }, {\n\t key: 'replayQueue',\n\t value: function replayQueue() {\n\t return this.playQueue();\n\t }\n\t\n\t /**\n\t * Plays the requests queued during offline mode.\n\t */\n\t\n\t }, {\n\t key: 'playQueue',\n\t value: function playQueue() {\n\t this.network.playQueue();\n\t return this;\n\t }\n\t\n\t /**\n\t * Sets the default Kuzzle index\n\t *\n\t * @param index\n\t * @returns this\n\t */\n\t\n\t }, {\n\t key: 'setDefaultIndex',\n\t value: function setDefaultIndex(index) {\n\t if (typeof index !== 'string') {\n\t throw new Error('Invalid default index: [' + index + '] (an index name is expected)');\n\t }\n\t\n\t if (index.length === 0) {\n\t throw new Error('Cannot set an empty index as the default index');\n\t }\n\t\n\t this.defaultIndex = index;\n\t\n\t return this;\n\t }\n\t }]);\n\t\n\t return Kuzzle;\n\t}(KuzzleEventEmitter);\n\t\n\tfunction checkPropertyType(prop, typestr, value) {\n\t var wrongType = typestr === 'array' ? !Array.isArray(value) : (typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== typestr;\n\t\n\t if (wrongType) {\n\t throw new Error('Can only assign a ' + typestr + ' value to property \"' + prop + '\"');\n\t }\n\t}\n\t\n\tmodule.exports = Kuzzle;\n\n/***/ }),\n/* 1 */\n/***/ (function(module, exports) {\n\n\t'use strict';\n\t\n\tvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\t\n\tvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\t\n\tfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\t\n\tvar Listener = function Listener(fn) {\n\t var once = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\t\n\t _classCallCheck(this, Listener);\n\t\n\t this.fn = fn;\n\t this.once = once;\n\t};\n\t\n\tvar KuzzleEventEmitter = function () {\n\t function KuzzleEventEmitter() {\n\t _classCallCheck(this, KuzzleEventEmitter);\n\t\n\t this._events = {};\n\t }\n\t\n\t _createClass(KuzzleEventEmitter, [{\n\t key: '_exists',\n\t value: function _exists(listeners, fn) {\n\t return Boolean(listeners.find(function (listener) {\n\t return listener.fn === fn;\n\t }));\n\t }\n\t }, {\n\t key: 'listeners',\n\t value: function listeners(eventName) {\n\t if (this._events[eventName] === undefined) {\n\t return [];\n\t }\n\t\n\t return this._events[eventName].map(function (listener) {\n\t return listener.fn;\n\t });\n\t }\n\t }, {\n\t key: 'addListener',\n\t value: function addListener(eventName, listener) {\n\t var once = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\t\n\t if (!eventName || !listener) {\n\t return this;\n\t }\n\t\n\t var listenerType = typeof listener === 'undefined' ? 'undefined' : _typeof(listener);\n\t\n\t if (listenerType !== 'function') {\n\t throw new Error('Invalid listener type: expected a function, got a ' + listenerType);\n\t }\n\t\n\t if (this._events[eventName] === undefined) {\n\t this._events[eventName] = [];\n\t }\n\t\n\t if (!this._exists(this._events[eventName], listener)) {\n\t this._events[eventName].push(new Listener(listener, once));\n\t }\n\t\n\t return this;\n\t }\n\t }, {\n\t key: 'on',\n\t value: function on(eventName, listener) {\n\t return this.addListener(eventName, listener);\n\t }\n\t }, {\n\t key: 'prependListener',\n\t value: function prependListener(eventName, listener) {\n\t var once = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\t\n\t if (!eventName || !listener) {\n\t return this;\n\t }\n\t\n\t if (this._events[eventName] === undefined) {\n\t this._events[eventName] = [];\n\t }\n\t\n\t if (!this._exists(this._events[eventName], listener)) {\n\t this._events[eventName] = [new Listener(listener, once)].concat(this._events[eventName]);\n\t }\n\t\n\t return this;\n\t }\n\t }, {\n\t key: 'addOnceListener',\n\t value: function addOnceListener(eventName, listener) {\n\t return this.addListener(eventName, listener, true);\n\t }\n\t }, {\n\t key: 'once',\n\t value: function once(eventName, listener) {\n\t return this.addOnceListener(eventName, listener);\n\t }\n\t }, {\n\t key: 'prependOnceListener',\n\t value: function prependOnceListener(eventName, listener) {\n\t return this.prependListener(eventName, listener, true);\n\t }\n\t }, {\n\t key: 'removeListener',\n\t value: function removeListener(eventName, listener) {\n\t var listeners = this._events[eventName];\n\t\n\t if (!listeners || !listeners.length) {\n\t return this;\n\t }\n\t\n\t var index = listeners.findIndex(function (l) {\n\t return l.fn === listener;\n\t });\n\t\n\t if (index !== -1) {\n\t listeners.splice(index, 1);\n\t }\n\t\n\t if (listeners.length === 0) {\n\t delete this._events[eventName];\n\t }\n\t\n\t return this;\n\t }\n\t }, {\n\t key: 'removeAllListeners',\n\t value: function removeAllListeners(eventName) {\n\t if (eventName) {\n\t delete this._events[eventName];\n\t } else {\n\t this._events = {};\n\t }\n\t\n\t return this;\n\t }\n\t }, {\n\t key: 'emit',\n\t value: function emit(eventName) {\n\t var listeners = this._events[eventName];\n\t\n\t if (listeners === undefined) {\n\t return false;\n\t }\n\t\n\t var onceListeners = [];\n\t\n\t for (var _len = arguments.length, payload = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n\t payload[_key - 1] = arguments[_key];\n\t }\n\t\n\t var _iteratorNormalCompletion = true;\n\t var _didIteratorError = false;\n\t var _iteratorError = undefined;\n\t\n\t try {\n\t for (var _iterator = listeners[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n\t var listener = _step.value;\n\t\n\t listener.fn.apply(listener, payload);\n\t\n\t if (listener.once) {\n\t onceListeners.push(listener.fn);\n\t }\n\t }\n\t } catch (err) {\n\t _didIteratorError = true;\n\t _iteratorError = err;\n\t } finally {\n\t try {\n\t if (!_iteratorNormalCompletion && _iterator.return) {\n\t _iterator.return();\n\t }\n\t } finally {\n\t if (_didIteratorError) {\n\t throw _iteratorError;\n\t }\n\t }\n\t }\n\t\n\t var _iteratorNormalCompletion2 = true;\n\t var _didIteratorError2 = false;\n\t var _iteratorError2 = undefined;\n\t\n\t try {\n\t for (var _iterator2 = onceListeners[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n\t var toDelete = _step2.value;\n\t\n\t this.removeListener(eventName, toDelete);\n\t }\n\t } catch (err) {\n\t _didIteratorError2 = true;\n\t _iteratorError2 = err;\n\t } finally {\n\t try {\n\t if (!_iteratorNormalCompletion2 && _iterator2.return) {\n\t _iterator2.return();\n\t }\n\t } finally {\n\t if (_didIteratorError2) {\n\t throw _iteratorError2;\n\t }\n\t }\n\t }\n\t\n\t return true;\n\t }\n\t }, {\n\t key: 'eventNames',\n\t value: function eventNames() {\n\t return Object.keys(this._events);\n\t }\n\t }, {\n\t key: 'listenerCount',\n\t value: function listenerCount(eventName) {\n\t return this._events[eventName] && this._events[eventName].length || 0;\n\t }\n\t }]);\n\t\n\t return KuzzleEventEmitter;\n\t}();\n\t\n\tmodule.exports = KuzzleEventEmitter;\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports) {\n\n\tfunction SecurityDocument(Security, id, content, meta) {\n\t\n\t if (!id) {\n\t throw new Error('A security document must have an id');\n\t }\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t kuzzle: {\n\t value: Security.kuzzle\n\t },\n\t Security: {\n\t value: Security\n\t },\n\t // read-only properties\n\t // writable properties\n\t id: {\n\t value: id,\n\t enumerable: true\n\t },\n\t content: {\n\t value: {},\n\t writable: true,\n\t enumerable: true\n\t },\n\t meta: {\n\t value: meta || {},\n\t writable: true,\n\t enumerable: true\n\t }\n\t });\n\t\n\t if (content) {\n\t this.setContent(content, true);\n\t }\n\t\n\t // promisifying\n\t if (Security.kuzzle.bluebird) {\n\t return Security.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['delete', 'update'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t}\n\t\n\t/**\n\t * Replaces the current content with new data.\n\t * Changes made by this function won’t be applied until the save method is called.\n\t *\n\t * @param {Object} data - New securityDocument content\n\t * @return {SecurityDocument} this\n\t */\n\tSecurityDocument.prototype.setContent = function (data) {\n\t this.content = data;\n\t return this;\n\t};\n\t\n\t/**\n\t * Serialize this object into a pojo\n\t *\n\t * @return {object} pojo representing this securityDocument\n\t */\n\tSecurityDocument.prototype.serialize = function () {\n\t var\n\t data = {};\n\t\n\t if (this.id) {\n\t data._id = this.id;\n\t }\n\t\n\t data.body = this.content;\n\t data.meta = this.meta;\n\t\n\t return data;\n\t};\n\t\n\t/**\n\t * Delete the current KuzzleSecurityDocument into Kuzzle.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tSecurityDocument.prototype.delete = function (options, cb) {\n\t var\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.Security.buildQueryArgs(this.deleteActionName), {_id: this.id}, options, function (error, res) {\n\t if (error) {\n\t return cb ? cb(error) : false;\n\t }\n\t\n\t if (cb) {\n\t cb(null, res.result._id);\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Update the current KuzzleSecurityDocument into Kuzzle.\n\t *\n\t * @param {object} content - Content to add to KuzzleSecurityDocument\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {SecurityDocument} this\n\t */\n\tSecurityDocument.prototype.update = function (content, options, cb) {\n\t var\n\t data = {},\n\t self = this;\n\t\n\t if (typeof content !== 'object') {\n\t throw new Error('Parameter \"content\" must be a object');\n\t }\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = self.id;\n\t data.body = content;\n\t\n\t self.kuzzle.query(this.Security.buildQueryArgs(this.updateActionName), data, options, function (error, response) {\n\t if (error) {\n\t return cb ? cb(error) : false;\n\t }\n\t\n\t self.setContent(response.result._source);\n\t\n\t if (cb) {\n\t cb(null, self);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\tmodule.exports = SecurityDocument;\n\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t'use strict';\n\t\n\tvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\t\n\tvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\t\n\tfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\t\n\tfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\t\n\tfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\t\n\tvar KuzzleEventEmitter = __webpack_require__(1);\n\t\n\tvar RTWrapper = function (_KuzzleEventEmitter) {\n\t _inherits(RTWrapper, _KuzzleEventEmitter);\n\t\n\t function RTWrapper(host, options) {\n\t _classCallCheck(this, RTWrapper);\n\t\n\t var _this = _possibleConstructorReturn(this, (RTWrapper.__proto__ || Object.getPrototypeOf(RTWrapper)).call(this));\n\t\n\t Object.defineProperties(_this, {\n\t cleanHistoryTimer: {\n\t value: null,\n\t writable: true\n\t },\n\t host: {\n\t value: host,\n\t enumerable: true\n\t },\n\t port: {\n\t value: options && typeof options.port === 'number' ? options.port : 7512,\n\t enumerable: true\n\t },\n\t ssl: {\n\t value: options && typeof options.sslConnection === 'boolean' ? options.sslConnection : false,\n\t enumerable: true\n\t },\n\t queuing: {\n\t value: false,\n\t writable: true\n\t },\n\t reconnectionDelay: {\n\t value: options && typeof options.reconnectionDelay === 'number' ? options.reconnectionDelay : 1000,\n\t enumerable: true\n\t },\n\t // configuration properties\n\t autoReconnect: {\n\t value: options && typeof options.autoReconnect === 'boolean' ? options.autoReconnect : true,\n\t enumerable: true\n\t },\n\t autoQueue: {\n\t value: false,\n\t enumerable: true,\n\t writable: true\n\t },\n\t autoReplay: {\n\t value: false,\n\t enumerable: true,\n\t writable: true\n\t },\n\t state: {\n\t value: 'offline',\n\t enumerable: true,\n\t writable: true\n\t },\n\t /*\n\t Offline queue use the following format:\n\t [\n\t {\n\t ts: ,\n\t query: 'query',\n\t cb: callbackFunction\n\t }\n\t ]\n\t */\n\t offlineQueue: {\n\t value: [],\n\t enumerable: true,\n\t writable: true\n\t },\n\t queueFilter: {\n\t value: null,\n\t enumerable: true,\n\t writable: true\n\t },\n\t queueMaxSize: {\n\t value: 500,\n\t enumerable: true,\n\t writable: true\n\t },\n\t queueTTL: {\n\t value: 120000,\n\t enumerable: true,\n\t writable: true\n\t },\n\t replayInterval: {\n\t value: 10,\n\t enumerable: true,\n\t writable: true\n\t },\n\t offlineQueueLoader: {\n\t value: null,\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t if (options) {\n\t Object.keys(options).forEach(function (opt) {\n\t if (_this.hasOwnProperty(opt) && Object.getOwnPropertyDescriptor(_this, opt).writable) {\n\t _this[opt] = options[opt];\n\t }\n\t });\n\t\n\t if (options.offlineMode === 'auto' && _this.autoReconnect) {\n\t _this.autoQueue = _this.autoReplay = true;\n\t }\n\t }\n\t\n\t Object.defineProperty(_this, 'requestHistory', {\n\t value: {},\n\t writable: true\n\t });\n\t\n\t _this.wasConnected = false;\n\t _this.stopRetryingToConnect = false;\n\t _this.retrying = false;\n\t return _this;\n\t }\n\t\n\t _createClass(RTWrapper, [{\n\t key: 'connect',\n\t value: function connect() {\n\t this.state = 'connecting';\n\t if (this.autoQueue) {\n\t this.startQueuing();\n\t }\n\t }\n\t\n\t /**\n\t * Called when the client's connection is established\n\t */\n\t\n\t }, {\n\t key: 'clientConnected',\n\t value: function clientConnected() {\n\t var _this2 = this;\n\t\n\t this.state = 'connected';\n\t this.emit(this.wasConnected && 'reconnect' || 'connect');\n\t this.wasConnected = true;\n\t this.stopRetryingToConnect = false;\n\t\n\t if (this.autoQueue) {\n\t this.stopQueuing();\n\t }\n\t\n\t if (this.autoReplay) {\n\t this.playQueue();\n\t }\n\t\n\t if (!this.cleanHistoryTimer) {\n\t this.cleanHistoryTimer = setInterval(function () {\n\t cleanHistory(_this2.requestHistory);\n\t }, 1000);\n\t }\n\t }\n\t\n\t /**\n\t * Called when the client's connection is closed\n\t */\n\t\n\t }, {\n\t key: 'clientDisconnected',\n\t value: function clientDisconnected() {\n\t this.state = 'offline';\n\t if (this.autoQueue) {\n\t this.startQueuing();\n\t }\n\t\n\t this.clearHistoryTimer();\n\t this.emit('disconnect');\n\t }\n\t\n\t /**\n\t * Called when the client's connection is closed with an error state\n\t *\n\t * @param {Error} error\n\t */\n\t\n\t }, {\n\t key: 'clientNetworkError',\n\t value: function clientNetworkError(error) {\n\t var _this3 = this;\n\t\n\t this.state = 'offline';\n\t if (this.autoQueue) {\n\t this.startQueuing();\n\t }\n\t\n\t this.clearHistoryTimer();\n\t\n\t this.emit('networkError', error);\n\t if (this.autoReconnect && !this.retrying && !this.stopRetryingToConnect) {\n\t this.retrying = true;\n\t setTimeout(function () {\n\t _this3.retrying = false;\n\t _this3.connect(_this3.host);\n\t }, this.reconnectionDelay);\n\t } else {\n\t this.emit('disconnect');\n\t }\n\t }\n\t\n\t /**\n\t * Empties the offline queue without replaying it.\n\t */\n\t\n\t }, {\n\t key: 'flushQueue',\n\t value: function flushQueue() {\n\t this.offlineQueue = [];\n\t }\n\t\n\t /**\n\t * Replays the requests queued during offline mode.\n\t */\n\t\n\t }, {\n\t key: 'playQueue',\n\t value: function playQueue() {\n\t if (this.state === 'connected') {\n\t cleanQueue(this);\n\t dequeue(this);\n\t }\n\t }\n\t\n\t /**\n\t * Starts the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n\t */\n\t\n\t }, {\n\t key: 'startQueuing',\n\t value: function startQueuing() {\n\t this.queuing = true;\n\t }\n\t\n\t /**\n\t * Stops the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n\t */\n\t\n\t }, {\n\t key: 'stopQueuing',\n\t value: function stopQueuing() {\n\t this.queuing = false;\n\t }\n\t }, {\n\t key: 'subscribe',\n\t value: function subscribe(object, options, notificationCB, cb) {\n\t var _this4 = this;\n\t\n\t if (this.state !== 'connected') {\n\t return cb(new Error('Not Connected'));\n\t }\n\t this.query(object, options, function (error, response) {\n\t if (error) {\n\t return cb(error);\n\t }\n\t _this4.on(response.result.channel, function (data) {\n\t data.fromSelf = _this4.requestHistory[data.requestId] !== undefined;\n\t notificationCB(data);\n\t });\n\t cb(null, response.result);\n\t });\n\t }\n\t }, {\n\t key: 'unsubscribe',\n\t value: function unsubscribe(object, channel, cb) {\n\t this.removeAllListeners(channel);\n\t this.query(object, null, function (err, res) {\n\t if (cb) {\n\t cb(err, err ? undefined : res.result);\n\t }\n\t });\n\t }\n\t }, {\n\t key: 'query',\n\t value: function query(object, options, cb) {\n\t var queuable = options && options.queuable !== false || true;\n\t\n\t if (this.queueFilter) {\n\t queuable = queuable && this.queueFilter(object);\n\t }\n\t\n\t if (this.queuing && queuable) {\n\t cleanQueue(this, object, cb);\n\t this.emit('offlineQueuePush', { query: object, cb: cb });\n\t return this.offlineQueue.push({ ts: Date.now(), query: object, cb: cb });\n\t }\n\t\n\t if (this.state === 'connected') {\n\t return emitRequest(this, object, cb);\n\t }\n\t\n\t return discardRequest(object, cb);\n\t }\n\t }, {\n\t key: 'clearHistoryTimer',\n\t value: function clearHistoryTimer() {\n\t if (this.cleanHistoryTimer) {\n\t clearInterval(this.cleanHistoryTimer);\n\t this.cleanHistoryTimer = null;\n\t }\n\t }\n\t }]);\n\t\n\t return RTWrapper;\n\t}(KuzzleEventEmitter);\n\t/**\n\t * Emit a request to Kuzzle\n\t *\n\t * @param {RTWrapper} network\n\t * @param {object} request\n\t * @param {responseCallback} [cb]\n\t */\n\t\n\t\n\tfunction emitRequest(network, request, cb) {\n\t if (request.jwt !== undefined || cb) {\n\t network.once(request.requestId, function (response) {\n\t var error = null;\n\t\n\t if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n\t network.emit('tokenExpired', request, cb);\n\t }\n\t\n\t if (response.error) {\n\t error = new Error(response.error.message);\n\t Object.assign(error, response.error);\n\t error.status = response.status;\n\t network.emit('queryError', error, request, cb);\n\t }\n\t\n\t if (cb) {\n\t cb(error, response);\n\t }\n\t });\n\t }\n\t // Track requests made to allow Room.subscribeToSelf to work\n\t network.requestHistory[request.requestId] = Date.now();\n\t network.send(request);\n\t}\n\t\n\tfunction discardRequest(object, cb) {\n\t if (cb) {\n\t cb(new Error('Unable to execute request: not connected to a Kuzzle server.\\nDiscarded request: ' + JSON.stringify(object)));\n\t }\n\t}\n\t\n\t/**\n\t * Clean up the queue, ensuring the queryTTL and queryMaxSize properties are respected\n\t * @param {RTWrapper} network\n\t */\n\tfunction cleanQueue(network) {\n\t var now = Date.now();\n\t var lastDocumentIndex = -1;\n\t\n\t if (network.queueTTL > 0) {\n\t network.offlineQueue.forEach(function (query, index) {\n\t if (query.ts < now - network.queueTTL) {\n\t lastDocumentIndex = index;\n\t }\n\t });\n\t\n\t if (lastDocumentIndex !== -1) {\n\t network.offlineQueue.splice(0, lastDocumentIndex + 1).forEach(function (droppedRequest) {\n\t network.emit('offlineQueuePop', droppedRequest.query);\n\t });\n\t }\n\t }\n\t\n\t if (network.queueMaxSize > 0 && network.offlineQueue.length > network.queueMaxSize) {\n\t network.offlineQueue.splice(0, network.offlineQueue.length - network.queueMaxSize).forEach(function (droppedRequest) {\n\t network.emit('offlineQueuePop', droppedRequest.query);\n\t });\n\t }\n\t}\n\t\n\t/**\n\t * Play all queued requests, in order.\n\t */\n\tfunction dequeue(network) {\n\t var uniqueQueue = {},\n\t dequeuingProcess = function dequeuingProcess() {\n\t if (network.offlineQueue.length > 0) {\n\t emitRequest(network, network.offlineQueue[0].query, network.offlineQueue[0].cb);\n\t network.emit('offlineQueuePop', network.offlineQueue.shift());\n\t\n\t setTimeout(function () {\n\t dequeuingProcess();\n\t }, Math.max(0, network.replayInterval));\n\t }\n\t };\n\t\n\t if (network.offlineQueueLoader) {\n\t if (typeof network.offlineQueueLoader !== 'function') {\n\t throw new Error('Invalid value for offlineQueueLoader property. Expected: function. Got: ' + _typeof(network.offlineQueueLoader));\n\t }\n\t\n\t var additionalQueue = network.offlineQueueLoader();\n\t if (Array.isArray(additionalQueue)) {\n\t network.offlineQueue = additionalQueue.concat(network.offlineQueue).filter(function (request) {\n\t // throws if the query object does not contain required attributes\n\t if (!request.query || request.query.requestId === undefined || !request.query.action || !request.query.controller) {\n\t throw new Error('Invalid offline queue request. One or more missing properties: requestId, action, controller.');\n\t }\n\t\n\t return uniqueQueue.hasOwnProperty(request.query.requestId) ? false : uniqueQueue[request.query.requestId] = true;\n\t });\n\t } else {\n\t throw new Error('Invalid value returned by the offlineQueueLoader function. Expected: array. Got: ' + (typeof additionalQueue === 'undefined' ? 'undefined' : _typeof(additionalQueue)));\n\t }\n\t }\n\t\n\t dequeuingProcess();\n\t}\n\t\n\t/**\n\t * Clean history from requests made more than 10s ago\n\t */\n\tfunction cleanHistory(requestHistory) {\n\t var now = Date.now();\n\t\n\t Object.keys(requestHistory).forEach(function (key) {\n\t if (requestHistory[key] < now - 10000) {\n\t delete requestHistory[key];\n\t }\n\t });\n\t}\n\t\n\tmodule.exports = RTWrapper;\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports) {\n\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t/**\n\t * Kuzzle handles documents either as realtime messages or as stored documents.\n\t * Document is the object representation of one of these documents.\n\t *\n\t * Notes:\n\t * - this constructor may be called either with a documentId, a content, neither or both.\n\t * - providing a documentID to the constructor will automatically call refresh, unless a content is also provided\n\t *\n\t *\n\t * @param {Collection} collection - an instanciated Collection object\n\t * @param {string} [documentId] - ID of an existing document\n\t * @param {object} [content] - Initializes this document with the provided content\n\t * @param {object} [meta] - Initializes this document with the provided meta\n\t * @constructor\n\t */\n\tfunction Document(collection, documentId, content, meta) {\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t collection: {\n\t value: collection.collection,\n\t enumerable: true\n\t },\n\t dataCollection: {\n\t value: collection,\n\t enumerable: false\n\t },\n\t kuzzle: {\n\t value: collection.kuzzle,\n\t enumerable: false\n\t },\n\t // writable properties\n\t id: {\n\t value: undefined,\n\t enumerable: true,\n\t writable: true\n\t },\n\t content: {\n\t value: {},\n\t writable: true,\n\t enumerable: true\n\t },\n\t version: {\n\t value: undefined,\n\t enumerable: true,\n\t writable: true\n\t },\n\t meta: {\n\t value: meta || {},\n\t enumerable: true,\n\t writable: false\n\t }\n\t });\n\t\n\t // handling provided arguments\n\t if (!content && documentId && typeof documentId === 'object') {\n\t content = documentId;\n\t documentId = null;\n\t }\n\t\n\t if (content) {\n\t if (content._version) {\n\t this.version = content._version;\n\t delete content._version;\n\t }\n\t this.setContent(content, true);\n\t }\n\t\n\t if (documentId) {\n\t Object.defineProperty(this, 'id', {\n\t value: documentId,\n\t enumerable: true\n\t });\n\t }\n\t\n\t // promisifying\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['delete', 'refresh', 'save'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * Serialize this object into a JSON object\n\t *\n\t * @return {object} JSON object representing this document\n\t */\n\tDocument.prototype.serialize = function () {\n\t var\n\t data = {};\n\t\n\t if (this.id) {\n\t data._id = this.id;\n\t }\n\t\n\t if (this.version) {\n\t data._version = this.version;\n\t }\n\t\n\t data.body = this.content;\n\t data.meta = this.meta;\n\t\n\t return data;\n\t};\n\t\n\t/**\n\t * Overrides the toString() method in order to return a serialized version of the document\n\t *\n\t * @return {string} serialized version of this object\n\t */\n\tDocument.prototype.toString = function () {\n\t return JSON.stringify(this.serialize());\n\t};\n\t\n\t/**\n\t * Deletes this document in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tDocument.prototype.delete = function (options, cb) {\n\t var self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!self.id) {\n\t throw new Error('Document.delete: cannot delete a document without a document ID');\n\t }\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('document', 'delete'), this.serialize(), options, cb && function (err) {\n\t cb(err, err ? undefined : self.id);\n\t });\n\t};\n\t\n\t/**\n\t * Checks if this document exists in Kuzzle.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tDocument.prototype.exists = function (options, cb) {\n\t var self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!self.id) {\n\t throw new Error('Document.exists: cannot check if the document exists if no id has been provided');\n\t }\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('document', 'exists'), this.serialize(), options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t};\n\t\n\t/**\n\t * Replaces the current content with the last version of this document stored in Kuzzle.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tDocument.prototype.refresh = function (options, cb) {\n\t var self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!self.id) {\n\t throw new Error('Document.refresh: cannot retrieve a document if no ID has been provided');\n\t }\n\t\n\t this.kuzzle.callbackRequired('Document.refresh', cb);\n\t\n\t self.kuzzle.query(self.dataCollection.buildQueryArgs('document', 'get'), {_id: self.id}, options, function (error, res) {\n\t var newDocument;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t newDocument = new Document(self.dataCollection, self.id, res.result._source, res.result._meta);\n\t newDocument.version = res.result._version;\n\t\n\t cb(null, newDocument);\n\t });\n\t};\n\t\n\t/**\n\t * Saves this document into Kuzzle.\n\t *\n\t * If this is a new document, this function will create it in Kuzzle and the id property will be made available.\n\t * Otherwise, this method will replace the latest version of this document in Kuzzle by the current content\n\t * of this object.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tDocument.prototype.save = function (options, cb) {\n\t var\n\t data = this.serialize(),\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.dataCollection.buildQueryArgs('document', 'createOrReplace'), data, options, function (error, res) {\n\t if (error) {\n\t return cb && cb(error);\n\t }\n\t\n\t self.id = res.result._id;\n\t self.version = res.result._version;\n\t\n\t if (cb) {\n\t cb(null, self);\n\t }\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Sends the content of this document as a realtime message.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @returns {*} this\n\t */\n\tDocument.prototype.publish = function (options) {\n\t var data = this.serialize();\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('realtime', 'publish'), data, options);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Replaces the current content with new data.\n\t * Changes made by this function won’t be applied until the save method is called.\n\t *\n\t * @param {object} data - New content\n\t * @param {boolean} replace - if true: replace this document content with the provided data\n\t */\n\tDocument.prototype.setContent = function (data, replace) {\n\t var self = this;\n\t\n\t if (replace) {\n\t this.content = data;\n\t }\n\t else {\n\t Object.keys(data).forEach(function (key) {\n\t self.content[key] = data[key];\n\t });\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Listens to events concerning this document. Has no effect if the document does not have an ID\n\t * (i.e. if the document has not yet been created as a persisted document).\n\t *\n\t * @param {object} [options] - subscription options\n\t * @param {responseCallback} cb - callback that will be called each time a change has been detected on this document\n\t */\n\tDocument.prototype.subscribe = function (options, cb) {\n\t var filters;\n\t\n\t if (options && !cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('Document.subscribe', cb);\n\t\n\t if (!this.id) {\n\t throw new Error('Document.subscribe: cannot subscribe to a document if no ID has been provided');\n\t }\n\t\n\t filters = { ids: { values: [this.id] } };\n\t\n\t return this.dataCollection.subscribe(filters, options, cb);\n\t};\n\t\n\tmodule.exports = Document;\n\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSecurityDocument = __webpack_require__(2);\n\t\n\t/**\n\t * @param {Security} Security\n\t * @param {string} id\n\t * @param {Object} content\n\t * @constructor\n\t */\n\tfunction User(Security, id, content, meta) {\n\t KuzzleSecurityDocument.call(this, Security, id, content, meta);\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t deleteActionName: {\n\t value: 'deleteUser'\n\t },\n\t updateActionName: {\n\t value: 'updateUser'\n\t },\n\t credentials: {\n\t value: {},\n\t writable: true,\n\t enumerable: true\n\t }\n\t });\n\t\n\t // promisifying\n\t if (Security.kuzzle.bluebird) {\n\t return Security.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['create', 'replace', 'saveRestricted', 'update', 'getProfiles'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t}\n\t\n\tUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: User\n\t }\n\t});\n\t\n\t/**\n\t * Set profiles in content\n\t * @param {array} profileIds - an array of profiles ids string\n\t *\n\t * @returns {User} this\n\t */\n\tUser.prototype.setProfiles = function (profileIds) {\n\t if (!Array.isArray(profileIds) || typeof profileIds[0] !== 'string') {\n\t throw new Error('Parameter \"profileIds\" must be an array of strings');\n\t }\n\t\n\t this.content.profileIds = profileIds;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * @param {object} credentials\n\t */\n\tUser.prototype.setCredentials = function (credentials) {\n\t if (typeof credentials !== 'object') {\n\t throw new Error('Parameter \"credentials\" must be a object');\n\t }\n\t\n\t this.credentials = credentials;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Add a profile\n\t * @param {string} profileId - a profile ids string\n\t *\n\t * @returns {User} this\n\t */\n\tUser.prototype.addProfile = function (profileId) {\n\t if (typeof profileId !== 'string') {\n\t throw new Error('Parameter \"profileId\" must be a string');\n\t }\n\t\n\t if (!this.content.profileIds) {\n\t this.content.profileIds = [];\n\t }\n\t\n\t if (this.content.profileIds.indexOf(profileId) === -1) {\n\t this.content.profileIds.push(profileId);\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Creates this user into Kuzzle\n\t *\n\t * @param {object|responseCallback} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {User} this\n\t */\n\tUser.prototype.create = function (options, cb) {\n\t var\n\t data = this.creationSerialize(),\n\t self = this;\n\t\n\t if (!this.content.profileIds) {\n\t throw new Error('Argument \"profileIds\" is mandatory in a user. This argument contains an array of profile identifiers.');\n\t }\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.Security.buildQueryArgs('createUser'), data, null, cb && function (err) {\n\t cb(err, err ? undefined : self);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t\n\t/**\n\t * Replaces the latest version of this user in Kuzzle by the current content of this object.\n\t *\n\t * @param {object|responseCallback} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {User} this\n\t */\n\tUser.prototype.replace = function (options, cb) {\n\t var\n\t data = this.serialize(),\n\t self = this;\n\t\n\t if (!this.content.profileIds) {\n\t throw new Error('Argument \"profileIds\" is mandatory in a user. This argument contains an array of profile identifiers.');\n\t }\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t\n\t this.kuzzle.query(this.Security.buildQueryArgs('replaceUser'), data, null, cb && function (err) {\n\t cb(err, err ? undefined : self);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Saves this user as restricted into Kuzzle.\n\t *\n\t * This function will create a new user. It is not usable to update an existing user.\n\t * The \"profileIds\" property must not be provided, or the request will be rejected by Kuzzle.\n\t * This function allows anonymous users to create a \"restricted\" user with predefined rights.\n\t *\n\t * @param {object|responseCallback} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {User} this\n\t */\n\tUser.prototype.saveRestricted = function (options, cb) {\n\t var\n\t data = this.serialize(),\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.Security.buildQueryArgs('createRestrictedUser'), data, options, cb && function (error) {\n\t cb(error, error ? undefined : self);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Serialize this object into a JSON object\n\t *\n\t * @return {object} JSON object representing this User\n\t */\n\tUser.prototype.serialize = function () {\n\t return {_id: this.id, body: this.content, meta: this.meta};\n\t};\n\t\n\t/**\n\t * Serialize this object into a JSON object\n\t *\n\t * @return {object} JSON object representing this User\n\t */\n\tUser.prototype.creationSerialize = function () {\n\t return {_id: this.id, body: {content: this.content, credentials: this.credentials, meta: this.meta}};\n\t};\n\t\n\t/**\n\t * Return the associated profiles IDs\n\t *\n\t * @return {array.} the associated profiles IDs\n\t */\n\tUser.prototype.getProfileIds = function () {\n\t return this.content.profileIds || [];\n\t};\n\t\n\t/**\n\t * Return the associated Profile objects\n\t *\n\t * @param {object|responseCallback} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tUser.prototype.getProfiles = function (options, cb) {\n\t var \n\t self = this,\n\t fetchedProfiles = [],\n\t errored = false;\n\t\n\t if (options && !cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.Security.kuzzle.callbackRequired('User.getProfiles', cb);\n\t\n\t if (!self.content.profileIds) {\n\t return cb(null, fetchedProfiles);\n\t }\n\t\n\t self.content.profileIds.forEach(function (profileId) {\n\t self.Security.fetchProfile(profileId, options, function (error, profile) {\n\t if (error) {\n\t if (errored) {\n\t return;\n\t }\n\t\n\t errored = true; // prevents multiple callback resolutions\n\t return cb(error);\n\t }\n\t\n\t fetchedProfiles.push(profile);\n\t\n\t if (fetchedProfiles.length === self.content.profileIds.length) {\n\t cb(null, fetchedProfiles);\n\t }\n\t });\n\t });\n\t};\n\t\n\tmodule.exports = User;\n\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t'use strict';\n\t\n\tvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\t\n\tfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\t\n\tfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\t\n\tfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\t\n\tvar KuzzleEventEmitter = __webpack_require__(1);\n\t\n\t/**\n\t * This object is the result of a subscription request, allowing to manipulate the subscription itself.\n\t *\n\t * In Kuzzle, you don’t exactly subscribe to a room or a topic but, instead, you subscribe to documents.\n\t *\n\t * What it means is that, to subscribe, you provide to Kuzzle a set of matching filters.\n\t * Once you have subscribed, if a pub/sub message is published matching your filters, or if a matching stored\n\t * document change (because it is created, updated or deleted), then you’ll receive a notification about it.\n\t *\n\t */\n\t\n\tvar Room = function (_KuzzleEventEmitter) {\n\t _inherits(Room, _KuzzleEventEmitter);\n\t\n\t /*\n\t * @constructor\n\t * @param {object} collection - an instantiated and valid kuzzle object\n\t * @param {object} [filters] - Filters in Kuzzle DSL format\n\t * @param {object} [options] - subscription optional configuration\n\t */\n\t function Room(collection, filters, options) {\n\t _classCallCheck(this, Room);\n\t\n\t var _this = _possibleConstructorReturn(this, (Room.__proto__ || Object.getPrototypeOf(Room)).call(this));\n\t\n\t var _roomId = null;\n\t\n\t // Define properties\n\t Object.defineProperties(_this, {\n\t // private properties\n\t roomstate: {\n\t // Values can be: inactive, subscribing, active\n\t value: 'inactive',\n\t writable: true\n\t },\n\t kuzzle: {\n\t value: collection.kuzzle\n\t },\n\t isListening: {\n\t value: false,\n\t writable: true\n\t },\n\t //listeners\n\t resubscribe: {\n\t value: function value() {\n\t _this.roomstate = 'inactive';\n\t _this.error = null;\n\t _this.subscribe();\n\t }\n\t },\n\t deactivate: {\n\t value: function value() {\n\t _this.roomstate = 'inactive';\n\t }\n\t },\n\t resubscribeConditional: {\n\t value: function value() {\n\t _this.roomstate = 'inactive';\n\t\n\t if (_this.autoResubscribe) {\n\t _this.subscribe();\n\t }\n\t }\n\t },\n\t //enumerables\n\t channel: {\n\t value: null,\n\t writable: true,\n\t enumerable: true\n\t },\n\t scope: {\n\t value: options && options.scope ? options.scope : 'all',\n\t enumerable: true\n\t },\n\t state: {\n\t value: options && options.state ? options.state : 'done',\n\t enumerable: true\n\t },\n\t users: {\n\t value: options && options.users ? options.users : 'none',\n\t enumerable: true\n\t },\n\t // read-only properties\n\t collection: {\n\t value: collection,\n\t enumerable: true\n\t },\n\t filters: {\n\t value: filters ? filters : {},\n\t enumerable: true\n\t },\n\t roomId: {\n\t enumerable: true,\n\t get: function get() {\n\t return _roomId;\n\t },\n\t set: function set(value) {\n\t if (!_roomId) {\n\t _roomId = value;\n\t }\n\t }\n\t },\n\t // writable properties\n\t volatile: {\n\t value: options && options.volatile ? options.volatile : {},\n\t enumerable: true,\n\t writable: true\n\t },\n\t subscribeToSelf: {\n\t value: options && typeof options.subscribeToSelf === 'boolean' ? options.subscribeToSelf : true,\n\t enumerable: true,\n\t writable: true\n\t },\n\t autoResubscribe: {\n\t value: options && typeof options.autoResubscribe === 'boolean' ? options.autoResubscribe : collection.kuzzle.autoResubscribe,\n\t enumerable: true\n\t }\n\t });\n\t\n\t if (_this.kuzzle.bluebird) {\n\t var _ret;\n\t\n\t return _ret = _this.kuzzle.bluebird.promisifyAll(_this, {\n\t suffix: 'Promise',\n\t filter: function filter(name, func, target, passes) {\n\t var whitelist = ['count', 'subscribe', 'unsubscribe', 'onDone'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t }), _possibleConstructorReturn(_this, _ret);\n\t }\n\t return _this;\n\t }\n\t\n\t /**\n\t * Returns the number of other subscriptions on that room.\n\t *\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\t\n\t\n\t _createClass(Room, [{\n\t key: 'count',\n\t value: function count(cb) {\n\t this.kuzzle.callbackRequired('Room.count', cb);\n\t\n\t var data = { body: { roomId: this.roomId } };\n\t\n\t if (this.roomstate !== 'active') {\n\t return cb(new Error('Cannot count subscriptions on an non-active room'));\n\t }\n\t\n\t this.kuzzle.query(this.collection.buildQueryArgs('realtime', 'count'), data, function (err, res) {\n\t cb(err, res && res.result.count);\n\t });\n\t }\n\t\n\t /**\n\t * Subscribes to Kuzzle \n\t * (do nothing if a subscription is active or underway)\n\t * \n\t * @param options\n\t * @param {responseCallback} cb - called when the subscription is ready.\n\t * @return {*} this\n\t */\n\t\n\t }, {\n\t key: 'subscribe',\n\t value: function subscribe(options, cb) {\n\t var _this2 = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (cb) {\n\t this.onDone(cb);\n\t }\n\t\n\t // If the room subscription is active, just call the callback.\n\t if (this.roomstate === 'active') {\n\t this.emit('done', null, this);\n\t return this;\n\t }\n\t\n\t // If the room is already subscribing, wait for its activation.\n\t if (this.roomstate === 'subscribing') {\n\t return this;\n\t }\n\t\n\t // If the room is still inactive, start the subscription.\n\t this.error = null;\n\t this.roomstate = 'subscribing';\n\t\n\t this.kuzzle.subscribe(this, options, function (error, result) {\n\t if (error) {\n\t if (error.message === 'Not Connected') {\n\t return _this2.kuzzle.once('connected', _this2.resubscribe);\n\t }\n\t\n\t _this2.roomstate = 'inactive';\n\t _this2.error = new Error('Error during Kuzzle subscription: ' + error.message);\n\t _this2.emit('done', _this2.error);\n\t return null;\n\t }\n\t\n\t _this2.roomId = result.roomId;\n\t _this2.channel = result.channel;\n\t _this2.roomstate = 'active';\n\t\n\t if (!_this2.isListening) {\n\t _this2.kuzzle.addListener('disconnected', _this2.deactivate);\n\t _this2.kuzzle.addListener('tokenExpired', _this2.deactivate);\n\t _this2.kuzzle.addListener('reconnected', _this2.resubscribeConditional);\n\t _this2.isListening = true;\n\t }\n\t\n\t _this2.emit('done', null, _this2);\n\t });\n\t\n\t return this;\n\t }\n\t\n\t /**\n\t * Unsubscribes from Kuzzle.\n\t *\n\t * Stop listening immediately.\n\t * @param {responseCallback} cb - Handles the query response\n\t * @return {*} this\n\t */\n\t\n\t }, {\n\t key: 'unsubscribe',\n\t value: function unsubscribe(cb) {\n\t if (this.roomstate === 'subscribing') {\n\t if (cb) {\n\t cb(new Error('Cannot unsubscribe a room while a subscription attempt is underway'));\n\t }\n\t\n\t return this;\n\t }\n\t\n\t if (this.isListening) {\n\t this.kuzzle.removeListener('disconnected', this.deactivate);\n\t this.kuzzle.removeListener('tokenExpired', this.deactivate);\n\t this.kuzzle.removeListener('reconnected', this.resubscribeConditional);\n\t this.isListening = false;\n\t }\n\t\n\t if (this.roomstate === 'active') {\n\t this.kuzzle.unsubscribe(this, cb);\n\t } else if (cb) {\n\t cb(null, this.roomId);\n\t }\n\t\n\t this.roomstate = 'inactive';\n\t\n\t return this;\n\t }\n\t\n\t /**\n\t * Notify listeners\n\t *\n\t * @param {Object} data - data to send. Must contain `data.type` as eventName.\n\t * @return {*} this\n\t */\n\t\n\t }, {\n\t key: 'notify',\n\t value: function notify(data) {\n\t if (data.type === undefined) {\n\t throw new Error('Room.notify: argument must match {type: }');\n\t }\n\t if (!data.fromSelf || this.subscribeToSelf) {\n\t this.emit(data.type, data);\n\t }\n\t return this;\n\t }\n\t\n\t /**\n\t * Registers a callback to be called with a subscription result\n\t * @param {Function} cb\n\t */\n\t\n\t }, {\n\t key: 'onDone',\n\t value: function onDone(cb) {\n\t if (!cb || typeof cb !== 'function') {\n\t throw new Error('Room.onDone: a callback argument is required.');\n\t }\n\t\n\t if (this.error) {\n\t cb(this.error);\n\t } else if (this.roomstate === 'active') {\n\t cb(null, this);\n\t } else {\n\t this.once('done', cb);\n\t }\n\t\n\t return this;\n\t }\n\t }]);\n\t\n\t return Room;\n\t}(KuzzleEventEmitter);\n\t\n\tmodule.exports = Room;\n\n/***/ }),\n/* 7 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t'use strict';\n\t\n\tvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\t\n\tvar _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if (\"value\" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };\n\t\n\tfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\t\n\tfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\t\n\tfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\t\n\tvar RTWrapper = __webpack_require__(3);\n\t\n\tvar SocketIO = function (_RTWrapper) {\n\t _inherits(SocketIO, _RTWrapper);\n\t\n\t function SocketIO(host, options) {\n\t _classCallCheck(this, SocketIO);\n\t\n\t var _this = _possibleConstructorReturn(this, (SocketIO.__proto__ || Object.getPrototypeOf(SocketIO)).call(this, host, options));\n\t\n\t _this.socket = null;\n\t _this.forceDisconnect = false;\n\t _this.eventsWrapper = {};\n\t return _this;\n\t }\n\t\n\t /**\n\t * Connect to the SocketIO server\n\t */\n\t\n\t\n\t _createClass(SocketIO, [{\n\t key: 'connect',\n\t value: function connect() {\n\t var _this2 = this;\n\t\n\t _get(SocketIO.prototype.__proto__ || Object.getPrototypeOf(SocketIO.prototype), 'connect', this).call(this);\n\t\n\t this.socket = window.io((this.ssl ? 'https://' : 'http://') + this.host + ':' + this.port, {\n\t reconnection: this.autoReconnect,\n\t reconnectionDelay: this.reconnectionDelay,\n\t forceNew: true\n\t });\n\t\n\t this.socket.on('connect', function () {\n\t return _this2.clientConnected();\n\t });\n\t this.socket.on('connect_error', function (error) {\n\t return _this2.clientNetworkError(error);\n\t });\n\t\n\t this.socket.on('disconnect', function () {\n\t if (_this2.forceDisconnect) {\n\t _this2.clientDisconnected();\n\t } else {\n\t var error = new Error('An error occurred, kuzzle may not be ready yet');\n\t error.status = 500;\n\t\n\t _this2.clientNetworkError(error);\n\t }\n\t\n\t _this2.forceDisconnect = false;\n\t });\n\t }\n\t\n\t /**\n\t * Registers a callback on an event. Once 1 message is received, fires the\n\t * callback and unregister it afterward.\n\t *\n\t * @param {string} event\n\t * @param {function} callback\n\t */\n\t\n\t }, {\n\t key: 'addOnceListener',\n\t value: function addOnceListener(event, callback) {\n\t return this.addListener(event, callback, true);\n\t }\n\t }, {\n\t key: 'once',\n\t value: function once(event, callback) {\n\t return this.addOnceListener(event, callback);\n\t }\n\t }, {\n\t key: 'prependOnceListener',\n\t value: function prependOnceListener(event, callback) {\n\t return this.prependListener(event, callback, true);\n\t }\n\t\n\t /**\n\t * Registers a callback on an event.\n\t *\n\t * @param {string} event\n\t * @param {function} callback\n\t */\n\t\n\t }, {\n\t key: 'addListener',\n\t value: function addListener(event, callback) {\n\t var once = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\t\n\t this._addEventWrapper(event, callback, once);\n\t _get(SocketIO.prototype.__proto__ || Object.getPrototypeOf(SocketIO.prototype), 'addListener', this).call(this, event, callback, once);\n\t\n\t return this;\n\t }\n\t }, {\n\t key: 'on',\n\t value: function on(event, callback) {\n\t return this.addListener(event, callback);\n\t }\n\t }, {\n\t key: 'prependListener',\n\t value: function prependListener(event, callback) {\n\t var once = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\t\n\t this._addEventWrapper(event, callback, once);\n\t return this.prependListener(event, callback, once);\n\t }\n\t\n\t /**\n\t * Unregisters a callback from an event.\n\t *\n\t * @param {string} event\n\t * @param {function} callback\n\t */\n\t\n\t }, {\n\t key: 'removeListener',\n\t value: function removeListener(event, callback) {\n\t if (this.eventsWrapper[event]) {\n\t this.eventsWrapper[event].listeners.delete(callback);\n\t\n\t if (this.eventsWrapper[event].listeners.size === 0) {\n\t this.socket.off(event, this.eventsWrapper[event].wrapper);\n\t delete this.eventsWrapper[event];\n\t }\n\t\n\t _get(SocketIO.prototype.__proto__ || Object.getPrototypeOf(SocketIO.prototype), 'removeListener', this).call(this, event, callback);\n\t }\n\t\n\t return this;\n\t }\n\t\n\t /**\n\t * Unregisters all listeners either from an event, or from all events\n\t *\n\t * @param {string} [event]\n\t */\n\t\n\t }, {\n\t key: 'removeAllListeners',\n\t value: function removeAllListeners(event) {\n\t if (event !== undefined && this.eventsWrapper[event] !== undefined) {\n\t var _iteratorNormalCompletion = true;\n\t var _didIteratorError = false;\n\t var _iteratorError = undefined;\n\t\n\t try {\n\t for (var _iterator = this.eventsWrapper[event].listeners[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n\t var listener = _step.value;\n\t\n\t this.removeListener(event, listener);\n\t }\n\t } catch (err) {\n\t _didIteratorError = true;\n\t _iteratorError = err;\n\t } finally {\n\t try {\n\t if (!_iteratorNormalCompletion && _iterator.return) {\n\t _iterator.return();\n\t }\n\t } finally {\n\t if (_didIteratorError) {\n\t throw _iteratorError;\n\t }\n\t }\n\t }\n\t } else {\n\t var _iteratorNormalCompletion2 = true;\n\t var _didIteratorError2 = false;\n\t var _iteratorError2 = undefined;\n\t\n\t try {\n\t for (var _iterator2 = Object.keys(this.eventsWrapper)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n\t var _event = _step2.value;\n\t\n\t this.removeAllListeners(_event);\n\t }\n\t } catch (err) {\n\t _didIteratorError2 = true;\n\t _iteratorError2 = err;\n\t } finally {\n\t try {\n\t if (!_iteratorNormalCompletion2 && _iterator2.return) {\n\t _iterator2.return();\n\t }\n\t } finally {\n\t if (_didIteratorError2) {\n\t throw _iteratorError2;\n\t }\n\t }\n\t }\n\t }\n\t\n\t return this;\n\t }\n\t\n\t /**\n\t * Sends a payload to the connected server\n\t *\n\t * @param {Object} payload\n\t */\n\t\n\t }, {\n\t key: 'send',\n\t value: function send(payload) {\n\t this.socket.emit('kuzzle', payload);\n\t }\n\t\n\t /**\n\t * Closes the connection\n\t */\n\t\n\t }, {\n\t key: 'close',\n\t value: function close() {\n\t this.forceDisconnect = true;\n\t this.state = 'offline';\n\t this.socket.close();\n\t this.socket = null;\n\t }\n\t }, {\n\t key: '_addEventWrapper',\n\t value: function _addEventWrapper(event, callback) {\n\t var _this3 = this;\n\t\n\t var once = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\t\n\t if (!this.eventsWrapper[event]) {\n\t var wrapper = function wrapper() {\n\t for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n\t args[_key] = arguments[_key];\n\t }\n\t\n\t return _this3.emit.apply(_this3, [event].concat(args));\n\t };\n\t\n\t this.eventsWrapper[event] = {\n\t wrapper: wrapper,\n\t listeners: new Set()\n\t };\n\t\n\t if (['connect', 'connect_error', 'disconnect'].indexOf(event) === -1) {\n\t if (once) {\n\t this.socket.once(event, wrapper);\n\t } else {\n\t this.socket.on(event, wrapper);\n\t }\n\t }\n\t }\n\t\n\t this.eventsWrapper[event].listeners.add(callback);\n\t }\n\t }]);\n\t\n\t return SocketIO;\n\t}(RTWrapper);\n\t\n\tmodule.exports = SocketIO;\n\n/***/ }),\n/* 8 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t'use strict';\n\t\n\tvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\t\n\tvar _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if (\"value\" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };\n\t\n\tfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\t\n\tfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\t\n\tfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\t\n\tvar RTWrapper = __webpack_require__(3);\n\t\n\tvar WebSocketClient = void 0;\n\t\n\tvar WSNode = function (_RTWrapper) {\n\t _inherits(WSNode, _RTWrapper);\n\t\n\t function WSNode(host, options) {\n\t _classCallCheck(this, WSNode);\n\t\n\t var _this = _possibleConstructorReturn(this, (WSNode.__proto__ || Object.getPrototypeOf(WSNode)).call(this, host, options));\n\t\n\t WebSocketClient = typeof WebSocket !== 'undefined' ? WebSocket : __webpack_require__(!(function webpackMissingModule() { var e = new Error(\"Cannot find module \\\"ws\\\"\"); e.code = 'MODULE_NOT_FOUND'; throw e; }()));\n\t _this.client = null;\n\t _this.lasturl = null;\n\t return _this;\n\t }\n\t\n\t /**\n\t * Connect to the websocket server\n\t */\n\t\n\t\n\t _createClass(WSNode, [{\n\t key: 'connect',\n\t value: function connect() {\n\t var _this2 = this;\n\t\n\t var url = (this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port,\n\t opts = typeof window !== 'undefined' ? undefined : { perMessageDeflate: false };\n\t\n\t _get(WSNode.prototype.__proto__ || Object.getPrototypeOf(WSNode.prototype), 'connect', this).call(this);\n\t\n\t if (url !== this.lasturl) {\n\t this.wasConnected = false;\n\t this.lasturl = url;\n\t }\n\t\n\t this.client = new WebSocketClient(url, opts);\n\t\n\t this.client.onopen = function () {\n\t _this2.clientConnected();\n\t };\n\t\n\t this.client.onclose = function (closeEvent, message) {\n\t var status = void 0,\n\t reason = message;\n\t\n\t if (typeof closeEvent === 'number') {\n\t status = closeEvent;\n\t } else {\n\t status = closeEvent.code;\n\t\n\t if (closeEvent.reason) {\n\t reason = closeEvent.reason;\n\t }\n\t }\n\t\n\t if (status === 1000) {\n\t _this2.clientDisconnected();\n\t }\n\t // do not forward a connection close error if no \n\t // connection has been previously established\n\t else if (_this2.wasConnected) {\n\t var error = new Error(reason);\n\t error.status = status;\n\t\n\t _this2.clientNetworkError(error);\n\t }\n\t };\n\t\n\t this.client.onerror = function (error) {\n\t var err = error instanceof Error && error || new Error(error);\n\t\n\t _this2.clientNetworkError(err);\n\t };\n\t\n\t this.client.onmessage = function (payload) {\n\t var data = JSON.parse(payload.data || payload);\n\t\n\t if (data.room) {\n\t _this2.emit(data.room, data);\n\t } else {\n\t _this2.emit('discarded', data);\n\t }\n\t };\n\t }\n\t\n\t /**\n\t * Sends a payload to the connected server\n\t *\n\t * @param {Object} payload\n\t */\n\t\n\t }, {\n\t key: 'send',\n\t value: function send(payload) {\n\t if (this.client && this.client.readyState === this.client.OPEN) {\n\t this.client.send(JSON.stringify(payload));\n\t }\n\t }\n\t\n\t /**\n\t * Closes the connection\n\t */\n\t\n\t }, {\n\t key: 'close',\n\t value: function close() {\n\t this.state = 'offline';\n\t this.removeAllListeners();\n\t this.wasConnected = false;\n\t if (this.client) {\n\t this.client.close();\n\t }\n\t this.client = null;\n\t this.stopRetryingToConnect = true;\n\t }\n\t }]);\n\t\n\t return WSNode;\n\t}(RTWrapper);\n\t\n\tmodule.exports = WSNode;\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSearchResult = __webpack_require__(12),\n\t Document = __webpack_require__(4),\n\t CollectionMapping = __webpack_require__(10),\n\t Room = __webpack_require__(6);\n\t\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t/**\n\t * A data collection is a set of data managed by Kuzzle. It acts like a data table for persistent documents,\n\t * or like a room for pub/sub messages.\n\t *\n\t * @property {string} collection\n\t * @property {string} index\n\t * @property {Kuzzle} kuzzle\n\t * @property {Array.} collection\n\t * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @param {string} collection - name of the data collection to handle\n\t * @param {string} index - Index containing the data collection\n\t * @constructor\n\t */\n\tfunction Collection(kuzzle, collection, index) {\n\t if (!index || !collection) {\n\t throw new Error('The Collection object constructor needs an index and a collection arguments');\n\t }\n\t\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t collection: {\n\t value: collection,\n\t enumerable: true\n\t },\n\t index: {\n\t value: index,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzle,\n\t enumerable: true\n\t }\n\t });\n\t\n\t Object.defineProperty(this, 'buildQueryArgs', {\n\t value: function (controller, action) {\n\t return {\n\t controller: controller,\n\t action: action,\n\t collection: this.collection,\n\t index: this.index\n\t };\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = ['subscribe'];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * Returns the number of documents matching the provided set of filters.\n\t *\n\t * There is a small delay between documents creation and their existence in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a document that was just been created won’t be returned by this function\n\t *\n\t * @param {object} filters - Filters in Elasticsearch Query DSL format\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tCollection.prototype.count = function (filters, options, cb) {\n\t var query = {body: filters};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('Collection.count', cb);\n\t\n\t this.kuzzle.query(this.buildQueryArgs('document', 'count'), query, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.count);\n\t });\n\t};\n\t\n\t/**\n\t * Create a new empty data collection, with no associated mapping.\n\t * Kuzzle automatically creates data collections when storing documents, but there are cases where we\n\t * want to create and prepare data collections before storing documents in it.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t * @returns {*} this\n\t */\n\tCollection.prototype.create = function (options, cb) {\n\t var data = {},\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('collection', 'create'), data, options, function(err) {\n\t cb(err, err ? undefined : self);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Create a new document in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t * - ifExist (string, allowed values: \"error\" (default), \"replace\"):\n\t * If the same document already exists:\n\t * - resolves with an error if set to \"error\".\n\t * - replaces the existing document if set to \"replace\"\n\t *\n\t * @param {string} [id] - (optional) document identifier\n\t * @param {object} document - either an instance of a Document object, or a document\n\t * @param {object} [options] - optional arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Object} this\n\t */\n\tCollection.prototype.createDocument = function (id, document, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'create';\n\t\n\t if (id && typeof id !== 'string') {\n\t cb = options;\n\t options = document;\n\t document = id;\n\t id = null;\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (document instanceof Document) {\n\t data = document.serialize();\n\t } else {\n\t data.body = document;\n\t }\n\t\n\t if (options && options.ifExist) {\n\t if (options.ifExist === 'replace') {\n\t action = 'createOrReplace';\n\t }\n\t else if (options.ifExist !== 'error') {\n\t throw new Error('Invalid value for the \"ifExist\" option: ' + options.ifExist);\n\t }\n\t }\n\t\n\t if (id) {\n\t data._id = id;\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', action), data, options, cb && function (err, res) {\n\t var doc;\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t doc = new Document(self, res.result._id, res.result._source, res.result._meta);\n\t doc.version = res.result._version;\n\t cb(null, doc);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete persistent documents.\n\t *\n\t * There is a small delay between documents creation and their existence in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a document that was just been created won’t be returned by this function\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {string|object} arg - Either a document ID (will delete only this particular document), or a set of filters\n\t * @param {object} [options] - optional arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Collection} this\n\t */\n\tCollection.prototype.deleteDocument = function (arg, options, cb) {\n\t var\n\t action,\n\t data = {};\n\t\n\t if (typeof arg === 'string') {\n\t data._id = arg;\n\t action = 'delete';\n\t } else {\n\t data.body = {query: arg};\n\t action = 'deleteByQuery';\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('document', action), data, options, cb && function (err, res) {\n\t if (err) {\n\t cb(err);\n\t }\n\t else {\n\t cb(null, (action === 'delete' ? [res.result._id] : res.result.ids));\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Deletes the current specifications of this collection\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @return {object} this\n\t */\n\tCollection.prototype.deleteSpecifications = function (options, cb) {\n\t var\n\t data = { index: this.index, collection: this.collection },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs('collection', 'deleteSpecifications'), data, options, function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Returns a boolean indicating whether or not a document with provided ID exists.\n\t *\n\t * @param {string} documentId - Unique document identifier\n\t * @param {object} options [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tCollection.prototype.documentExists = function (documentId, options, cb) {\n\t var\n\t data = {_id: documentId},\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.documentExists', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'exists'), data, options, function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t};\n\t\n\t/**\n\t * Retrieve a single stored document using its unique document ID.\n\t *\n\t * @param {string} documentId - Unique document identifier\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tCollection.prototype.fetchDocument = function (documentId, options, cb) {\n\t var\n\t data = {_id: documentId},\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.fetch', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'get'), data, options, function (err, res) {\n\t var document;\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t document = new Document(self, res.result._id, res.result._source, res.result._meta);\n\t document.version = res.result._version;\n\t cb(null, document);\n\t });\n\t};\n\t\n\t/**\n\t * Instantiates a CollectionMapping object containing the current mapping of this collection.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n\t */\n\tCollection.prototype.getMapping = function (options, cb) {\n\t var kuzzleMapping;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('Collection.getMapping', cb);\n\t\n\t kuzzleMapping = new CollectionMapping(this);\n\t kuzzleMapping.refresh(options, cb);\n\t};\n\t\n\t/**\n\t * Create the provided documents\n\t *\n\t * @param {Array.} documents - Array of documents to create\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n\t * @returns {object} this\n\t */\n\tCollection.prototype.mCreateDocument = function (documents, options, cb) {\n\t var data = {\n\t body: {},\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!Array.isArray(documents)) {\n\t return cb(new Error('Collection.mCreateDocument: documents parameter format is invalid (should be an array of documents)'));\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.mCreate', cb);\n\t\n\t data.body.documents = documents.map(function (doc) {\n\t return (doc instanceof Document) ? doc.serialize() : doc;\n\t });\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'mCreate'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Create or replace the provided documents\n\t *\n\t * @param {Array.} documents - Array of documents to create or replace\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n\t * @returns {object} this\n\t */\n\tCollection.prototype.mCreateOrReplaceDocument = function (documents, options, cb) {\n\t var data = {\n\t body: {},\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!Array.isArray(documents)) {\n\t return cb(new Error('Collection.mCreateOrReplaceDocument: documents parameter format is invalid (should be an array of documents)'));\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.mCreateOrReplace', cb);\n\t\n\t data.body.documents = documents.map(function (doc) {\n\t return (doc instanceof Document) ? doc.serialize() : doc;\n\t });\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'mCreateOrReplace'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Delete specific documents according to given IDs\n\t *\n\t * @param {Array.} documentIds - IDs of the documents to delete\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n\t * @returns {object} this\n\t */\n\tCollection.prototype.mDeleteDocument = function (documentIds, options, cb) {\n\t var data = {\n\t body: {\n\t ids: documentIds\n\t }\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!Array.isArray(documentIds)) {\n\t return cb(new Error('Collection.mDeleteDocument: documentIds parameter format is invalid (should be an array of IDs)'));\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.mDelete', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'mDelete'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Get specific documents according to given IDs\n\t *\n\t * @param {Array.} documentIds - IDs of the documents to retrieve\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n\t */\n\tCollection.prototype.mGetDocument = function (documentIds, options, cb) {\n\t var data = {\n\t body: {\n\t ids: documentIds\n\t }\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!Array.isArray(documentIds)) {\n\t return cb(new Error('Collection.mGetDocument: documentIds parameter format is invalid (should be an array of IDs)'));\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.mGet', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'mGet'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t};\n\t\n\t/**\n\t * Replace the provided documents\n\t *\n\t * @param {Array.} documents - Array of documents to replace\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n\t * @returns {object} this\n\t */\n\tCollection.prototype.mReplaceDocument = function (documents, options, cb) {\n\t var data = {\n\t body: {}\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!Array.isArray(documents)) {\n\t return cb(new Error('Collection.mReplaceDocument: documents parameter format is invalid (should be an array of documents)'));\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.mReplace', cb);\n\t\n\t data.body.documents = documents.map(function (doc) {\n\t return (doc instanceof Document) ? doc.serialize() : doc;\n\t });\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'mReplace'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Update the provided documents\n\t *\n\t * @param {Array.} documents - Array of documents to update\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n\t * @returns {object} this\n\t */\n\tCollection.prototype.mUpdateDocument = function (documents, options, cb) {\n\t var data = {\n\t body: {}\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!Array.isArray(documents)) {\n\t return cb(new Error('Collection.mUpdateDocument: documents parameter format is invalid (should be an array of documents)'));\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.mUpdate', cb);\n\t\n\t data.body.documents = documents.map(function (doc) {\n\t return (doc instanceof Document) ? doc.serialize() : doc;\n\t });\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'mUpdate'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Retrieves the current specifications of this collection\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tCollection.prototype.getSpecifications = function (options, cb) {\n\t var\n\t data = { index: this.index, collection: this.collection },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.getSpecifications', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('collection', 'getSpecifications'), data, options, function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t};\n\t\n\t/**\n\t * Publish a realtime message\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} document - either a Document instance or a JSON object\n\t * @param {object} [options] - optional arguments\n\t * @param {responseCallback} [cb] - Returns a raw Kuzzle response\n\t * @returns {*} this\n\t */\n\tCollection.prototype.publishMessage = function (document, options, cb) {\n\t var data = {};\n\t\n\t if (document instanceof Document) {\n\t data = document.serialize();\n\t } else {\n\t data.body = document;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('realtime', 'publish'), data, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Replace an existing document with a new one.\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {string} documentId - Unique document identifier of the document to replace\n\t * @param {object} content - JSON object representing the new document version\n\t * @param {object} [options] - additional arguments\n\t * @param {responseCallback} [cb] - Returns an instantiated Document object\n\t * @return {object} this\n\t */\n\tCollection.prototype.replaceDocument = function (documentId, content, options, cb) {\n\t var\n\t self = this,\n\t data = {\n\t _id: documentId,\n\t body: content\n\t };\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'createOrReplace'), data, options, cb && function (err, res) {\n\t var document;\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t document = new Document(self, res.result._id, res.result._source, res.result._meta);\n\t document.version = res.result._version;\n\t cb(null, document);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Executes an advanced search on the data collection.\n\t *\n\t * /!\\ There is a small delay between documents creation and their existence in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a document that was just been created won’t be returned by this function.\n\t *\n\t * @param {object} filters - Filters in Elasticsearch Query DSL format\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\t\n\tCollection.prototype.search = function (filters, options, cb) {\n\t var\n\t query = {body: filters},\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = {};\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.search', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'search'), query, options, function (error, result) {\n\t var documents = [];\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t result.result.hits.forEach(function (doc) {\n\t var newDocument = new Document(self, doc._id, doc._source, doc._meta);\n\t\n\t newDocument.version = doc._version;\n\t\n\t documents.push(newDocument);\n\t });\n\t\n\t if (result.result._scroll_id) {\n\t options.scrollId = result.result._scroll_id;\n\t }\n\t\n\t cb(null, new KuzzleSearchResult(\n\t self,\n\t result.result.total,\n\t documents,\n\t result.result.aggregations ? result.result.aggregations : {},\n\t options,\n\t filters,\n\t options.previous || null\n\t ));\n\t });\n\t};\n\t\n\t/**\n\t * A \"scroll\" option can be passed to search queries, creating persistent\n\t * paginated results.\n\t * This method can be used to manually get the next page of a search result,\n\t * instead of using KuzzleSearchResult.next()\n\t *\n\t * @param {string} scrollId\n\t * @param {object} [options]\n\t * @param {object} [filters]\n\t * @param {responseCallback} cb\n\t */\n\tCollection.prototype.scroll = function (scrollId, options, filters, cb) {\n\t var\n\t request = {},\n\t self = this;\n\t\n\t if (!scrollId) {\n\t throw new Error('Collection.scroll: scrollId is required');\n\t }\n\t\n\t if (!cb) {\n\t cb = filters;\n\t filters = null;\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = {};\n\t }\n\t\n\t this.kuzzle.callbackRequired('Collection.scroll', cb);\n\t\n\t request.scrollId = scrollId;\n\t\n\t this.kuzzle.query({controller: 'document', action: 'scroll'}, request, options, function (error, result) {\n\t var documents = [];\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t result.result.hits.forEach(function (doc) {\n\t var newDocument = new Document(self, doc._id, doc._source, doc._meta);\n\t\n\t newDocument.version = doc._version;\n\t\n\t documents.push(newDocument);\n\t });\n\t\n\t if (result.result._scroll_id) {\n\t options.scrollId = result.result._scroll_id;\n\t }\n\t\n\t cb(null, new KuzzleSearchResult(\n\t self,\n\t result.result.total,\n\t documents,\n\t {},\n\t options,\n\t filters,\n\t options.previous || null\n\t ));\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Retrieves next result of a search with scroll query.\n\t *\n\t * @param {string} scrollId\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tCollection.prototype.scrollSpecifications = function (scrollId, options, cb) {\n\t var\n\t data = { scrollId: scrollId };\n\t\n\t if (!scrollId) {\n\t throw new Error('Collection.scrollSpecifications: scrollId is required');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = {};\n\t }\n\t\n\t this.kuzzle.callbackRequired('Collection.scrollSpecifications', cb);\n\t\n\t this.kuzzle.query(\n\t { controller: 'collection', action: 'scrollSpecifications'},\n\t data,\n\t options,\n\t function (err, res) {\n\t cb (err, err ? undefined : res.result);\n\t }\n\t );\n\t};\n\t\n\t/**\n\t * Searches specifications across indexes/collections according to the provided filters\n\t *\n\t * @param {object} [filters] - Optional filters in ElasticSearch Query DSL format\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tCollection.prototype.searchSpecifications = function (filters, options, cb) {\n\t var\n\t data = { body: { query: filters } },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = {};\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.searchSpecifications', cb);\n\t\n\t self.kuzzle.query({ controller: 'collection', action: 'searchSpecifications' }, data, options, function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t};\n\t\n\t/**\n\t * Create a subscription room to this data collection with a set of filters.\n\t * To subscribe to the entire data collection, simply provide an empty filter.\n\t *\n\t * @param {object} filters - Filters in Kuzzle DSL format\n\t * @param {object} [options] - subscriptions options\n\t * @returns {*} KuzzleRoom object\n\t */\n\tCollection.prototype.room = function (filters, options) {\n\t return new Room(this, filters, options);\n\t};\n\t\n\t/**\n\t * Subscribes to this data collection with a set of filters.\n\t * To subscribe to the entire data collection, simply provide an empty filter.\n\t *\n\t * @param {object} filters - Filters in Kuzzle DSL format\n\t * @param {object} [options] - subscriptions options\n\t * @param {responseCallback} notificationCB - called for each new notification\n\t * @returns {*} KuzzleRoom object\n\t */\n\tCollection.prototype.subscribe = function (filters, options, notificationCB) {\n\t var\n\t evtName,\n\t room;\n\t\n\t if (!notificationCB && typeof options === 'function') {\n\t notificationCB = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.callbackRequired('Collection.subscribe', notificationCB);\n\t\n\t evtName = (options && options.users && options.users !== 'none') ? 'user' : 'document';\n\t room = new Room(this, filters, options);\n\t\n\t room.subscribe().on(evtName, notificationCB);\n\t return room;\n\t};\n\t\n\t/**\n\t * Truncate the data collection, removing all stored documents but keeping all associated mappings.\n\t * This method is a lot faster than removing all documents using a query.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t * @returns {*} this\n\t */\n\tCollection.prototype.truncate = function (options, cb) {\n\t var data = {};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('collection', 'truncate'), data, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t\n\t/**\n\t * Update parts of a document\n\t *\n\t * Takes an optional argument object with the following properties:\n\t * - volatile (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {string} documentId - Unique document identifier of the document to update\n\t * @param {object} content - JSON object containing changes to perform on the document\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Returns an instantiated Document object\n\t * @return {object} this\n\t */\n\tCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n\t var data = {\n\t _id: documentId,\n\t body: content\n\t },\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (options && options.retryOnConflict) {\n\t data.retryOnConflict = options.retryOnConflict;\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs('document', 'update'), data, options, cb && function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t (new Document(self, res.result._id)).refresh(cb);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Updates the current specifications of this collection\n\t *\n\t * @param {object} specifications - Specifications content\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @return {object} this\n\t */\n\tCollection.prototype.updateSpecifications = function (specifications, options, cb) {\n\t var\n\t collection = {},\n\t data = { body: {} },\n\t self = this;\n\t\n\t collection[this.collection] = specifications;\n\t data.body[this.index] = collection;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs('collection', 'updateSpecifications'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Validates the provided specifications\n\t *\n\t * @param {object} specifications - Specifications content\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t */\n\tCollection.prototype.validateSpecifications = function (specifications, options, cb) {\n\t var\n\t collection = {},\n\t data = { body: {} },\n\t self = this;\n\t\n\t collection[this.collection] = specifications;\n\t data.body[this.index] = collection;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Collection.validateSpecifications', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('collection', 'validateSpecifications'), data, options, function (err, res) {\n\t cb(err, err ? undefined : res.result.valid);\n\t });\n\t};\n\t\n\t/**\n\t * Instantiate a new Document object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - document id\n\t * @param {object} content - document content\n\t * @constructor\n\t */\n\tCollection.prototype.document = function (id, content) {\n\t return new Document(this, id, content);\n\t};\n\t\n\t/**\n\t * Instantiate a new CollectionMapping object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {object} [mapping] - mapping to instantiate the CollectionMapping object with\n\t * @constructor\n\t */\n\tCollection.prototype.collectionMapping = function (mapping) {\n\t return new CollectionMapping(this, mapping);\n\t};\n\t\n\tmodule.exports = Collection;\n\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports) {\n\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t\n\t/**\n\t * When creating a new data collection in the persistent data storage layer, Kuzzle uses a default mapping.\n\t * It means that, by default, you won’t be able to exploit the full capabilities of our persistent data storage layer\n\t * (currently handled by ElasticSearch), and your searches may suffer from below-average performances, depending on\n\t * the amount of data you stored in a collection and the complexity of your database.\n\t *\n\t * The CollectionMapping object allow to get the current mapping of a data collection and to modify it if needed.\n\t *\n\t * @param {object} collection - Instance of the inherited Collection object\n\t * @param {object} [mapping] - mappings\n\t * @constructor\n\t */\n\tfunction CollectionMapping(collection, mapping) {\n\t Object.defineProperties(this, {\n\t //read-only properties\n\t collection: {\n\t value: collection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: collection.kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t mapping: {\n\t value: mapping || {},\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = ['set'];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * Applies the new mapping to the data collection.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tCollectionMapping.prototype.apply = function (options, cb) {\n\t var\n\t self = this,\n\t data = {\n\t body: {\n\t properties: this.mapping\n\t }\n\t };\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.collection.buildQueryArgs('collection', 'updateMapping'), data, options, function (err) {\n\t if (err) {\n\t return cb && cb(err);\n\t }\n\t\n\t self.refresh(options, cb);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Replaces the current content with the mapping stored in Kuzzle\n\t *\n\t * Calling this function will discard any uncommited changes. You can commit changes by calling the “apply” function\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {*} this\n\t */\n\tCollectionMapping.prototype.refresh = function (options, cb) {\n\t var\n\t self = this,\n\t data = {};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.collection.buildQueryArgs('collection', 'getMapping'), data, options, function (err, res) {\n\t if (err) {\n\t return cb ? cb(err) : false;\n\t }\n\t\n\t if (res.result[self.collection.index]) {\n\t if (res.result[self.collection.index].mappings[self.collection.collection]) {\n\t self.mapping = res.result[self.collection.index].mappings[self.collection.collection].properties;\n\t\n\t // Mappings can be empty. The mapping property should never be \"undefined\"\n\t if (self.mapping === undefined) {\n\t self.mapping = {};\n\t }\n\t } else {\n\t return cb && cb(new Error('No mapping found for collection ' + self.collection.collection));\n\t }\n\t } else {\n\t return cb && cb(new Error('No mapping found for index ' + self.collection.index));\n\t }\n\t\n\t if (cb) {\n\t cb(null, self);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t\n\t/**\n\t * Adds or updates a field mapping.\n\t *\n\t * Changes made by this function won’t be applied until you call the apply method\n\t *\n\t * @param {string} field - Name of the field from which the mapping is to be added or updated\n\t * @param {object} mapping - corresponding field mapping\n\t * @returns {CollectionMapping}\n\t */\n\tCollectionMapping.prototype.set = function (field, mapping) {\n\t this.mapping[field] = mapping;\n\t\n\t return this;\n\t};\n\t\n\tmodule.exports = CollectionMapping;\n\n\n/***/ }),\n/* 11 */\n/***/ (function(module, exports) {\n\n\t// Parameter mutualization\n\tvar\n\t getId = {getter: true, required: ['_id']},\n\t getIdField = {getter: true, required: ['_id', 'field']},\n\t getKeys = {getter: true, required: ['keys']},\n\t getMember = {getter: true, required: ['_id', 'member']},\n\t getxScan = {\n\t getter: true, \n\t required: ['_id', 'cursor'], \n\t opts: ['match', 'count'],\n\t mapResults: mapScanResults\n\t },\n\t getZrange = {\n\t getter: true,\n\t required: ['_id', 'start', 'stop'],\n\t opts: assignZrangeOptions,\n\t mapResults: mapZrangeResults\n\t },\n\t getZrangeBy = {\n\t getter: true,\n\t required: ['_id', 'min', 'max'],\n\t opts: assignZrangeOptions,\n\t mapResults: mapZrangeResults\n\t },\n\t setId = {required: ['_id']},\n\t setIdValue = {required: ['_id', 'value']};\n\t\n\t// Redis commands\n\tvar\n\t commands = {\n\t append: setIdValue,\n\t bitcount: {getter: true, required: ['_id'], opts: ['start', 'end']},\n\t bitop: {required: ['_id', 'operation', 'keys']},\n\t bitpos: {getter: true, required: ['_id', 'bit'], opts: ['start', 'end']},\n\t dbsize: {getter: true},\n\t decr: setId,\n\t decrby: setIdValue,\n\t del: {required: ['keys']},\n\t exists: getKeys,\n\t expire: {required: ['_id', 'seconds'], mapResults: Boolean},\n\t expireat: {required: ['_id', 'timestamp'], mapResults: Boolean},\n\t flushdb: {mapResults: mapNoResult},\n\t geoadd: {required: ['_id', 'points']},\n\t geodist: {\n\t getter: true,\n\t required: ['_id', 'member1', 'member2'],\n\t opts: ['unit'],\n\t mapResults: parseFloat\n\t },\n\t geohash: {getter: true, required: ['_id', 'members']},\n\t geopos: {getter: true, required: ['_id', 'members'], mapResults: mapGeoposResults},\n\t georadius: {\n\t getter: true,\n\t required: ['_id', 'lon', 'lat', 'distance', 'unit'],\n\t opts: assignGeoRadiusOptions,\n\t mapResults: mapGeoRadiusResults\n\t },\n\t georadiusbymember: {\n\t getter: true,\n\t required: ['_id', 'member', 'distance', 'unit'],\n\t opts: assignGeoRadiusOptions,\n\t mapResults: mapGeoRadiusResults\n\t },\n\t get: getId,\n\t getbit: {getter: true, required: ['_id', 'offset']},\n\t getrange: {getter: true, required: ['_id', 'start', 'end']},\n\t getset: setIdValue,\n\t hdel: {required: ['_id', 'fields']},\n\t hexists: {getter: true, required: ['_id', 'field'], mapResults: Boolean},\n\t hget: getIdField,\n\t hgetall: {getter: true, required: ['_id']},\n\t hincrby: {required: ['_id', 'field', 'value']},\n\t hincrbyfloat: {required: ['_id', 'field', 'value'], mapResults: parseFloat},\n\t hkeys: getId,\n\t hlen: getId,\n\t hmget: {getter: true, required: ['_id', 'fields']},\n\t hmset: {required: ['_id', 'entries'], mapResults: mapNoResult},\n\t hscan: getxScan,\n\t hset: {required: ['_id', 'field', 'value'], mapResults: Boolean},\n\t hsetnx: {required: ['_id', 'field', 'value'], mapResults: Boolean},\n\t hstrlen: getIdField,\n\t hvals: getId,\n\t incr: setId,\n\t incrby: setIdValue,\n\t incrbyfloat: {required: ['_id', 'value'], mapResults: parseFloat},\n\t keys: {getter: true, required: ['pattern']},\n\t lindex: {getter: true, required: ['_id', 'idx']},\n\t linsert: {required: ['_id', 'position', 'pivot', 'value']},\n\t llen: getId,\n\t lpop: setId,\n\t lpush: {required: ['_id', 'values']},\n\t lpushx: setIdValue,\n\t lrange: {getter: true, required: ['_id', 'start', 'stop']},\n\t lrem: {required: ['_id', 'count', 'value']},\n\t lset: {required: ['_id', 'index', 'value'], mapResults: mapNoResult},\n\t ltrim: {required: ['_id', 'start', 'stop'], mapResults: mapNoResult},\n\t mget: getKeys,\n\t mset: {required: ['entries'], mapResults: mapNoResult},\n\t msetnx: {required: ['entries'], mapResults: Boolean},\n\t object: {getter: true, required: ['_id', 'subcommand']},\n\t persist: {required: ['_id'], mapResults: Boolean},\n\t pexpire: {required: ['_id', 'milliseconds'], mapResults: Boolean},\n\t pexpireat: {required: ['_id', 'timestamp'], mapResults: Boolean},\n\t pfadd: {required: ['_id', 'elements'], mapResults: Boolean},\n\t pfcount: getKeys,\n\t pfmerge: {required: ['_id', 'sources'], mapResults: mapNoResult},\n\t ping: {getter: true},\n\t psetex: {required: ['_id', 'value', 'milliseconds'], mapResults: mapNoResult},\n\t pttl: getId,\n\t randomkey: {getter: true},\n\t rename: {required: ['_id', 'newkey'], mapResults: mapNoResult},\n\t renamenx: {required: ['_id', 'newkey'], mapResults: Boolean},\n\t rpop: setId,\n\t rpoplpush: {required: ['source', 'destination']},\n\t rpush: {required: ['_id', 'values']},\n\t rpushx: setIdValue,\n\t sadd: {required: ['_id', 'members']},\n\t scan: {getter: true, required: ['cursor'], opts: ['match', 'count'], mapResults: mapScanResults},\n\t scard: getId,\n\t sdiff: {getter: true, required: ['_id', 'keys']},\n\t sdiffstore: {required: ['_id', 'keys', 'destination']},\n\t set: {required: ['_id', 'value'], opts: ['ex', 'px', 'nx', 'xx'], mapResults: mapNoResult},\n\t setex: {required: ['_id', 'value', 'seconds'], mapResults: mapNoResult},\n\t setnx: {required: ['_id', 'value'], mapResults: Boolean},\n\t sinter: getKeys,\n\t sinterstore: {required: ['destination', 'keys']},\n\t sismember: {getter: true, required: ['_id', 'member'], mapResults: Boolean},\n\t smembers: getId,\n\t smove: {required: ['_id', 'destination', 'member'], mapResults: Boolean},\n\t sort: {getter: true, required: ['_id'], opts: ['alpha', 'by', 'direction', 'get', 'limit']},\n\t spop: {required: ['_id'], opts: ['count'], mapResults: mapStringToArray },\n\t srandmember: {getter: true, required: ['_id'], opts: ['count'], mapResults: mapStringToArray},\n\t srem: {required: ['_id', 'members']},\n\t sscan: getxScan,\n\t strlen: getId,\n\t sunion: getKeys,\n\t sunionstore: {required: ['destination', 'keys']},\n\t time: {getter: true, mapResults: mapArrayStringToArrayInt},\n\t touch: {required: ['keys']},\n\t ttl: getId,\n\t type: getId,\n\t zadd: {required: ['_id', 'elements'], opts: ['nx', 'xx', 'ch', 'incr']},\n\t zcard: getId,\n\t zcount: {getter: true, required: ['_id', 'min', 'max']},\n\t zincrby: {required: ['_id', 'member', 'value']},\n\t zinterstore: {required: ['_id', 'keys'], opts: ['weights', 'aggregate']},\n\t zlexcount: {getter: true, required: ['_id', 'min', 'max']},\n\t zrange: getZrange,\n\t zrangebylex: {getter: true, required: ['_id', 'min', 'max'], opts: ['limit']},\n\t zrevrangebylex: {getter: true, required: ['_id', 'min', 'max'], opts: ['limit']},\n\t zrangebyscore: getZrangeBy,\n\t zrank: getMember,\n\t zrem: {required: ['_id', 'members']},\n\t zremrangebylex: {required: ['_id', 'min', 'max']},\n\t zremrangebyrank: {required: ['_id', 'start', 'stop']},\n\t zremrangebyscore: {required: ['_id', 'min', 'max']},\n\t zrevrange: getZrange,\n\t zrevrangebyscore: getZrangeBy,\n\t zrevrank: getMember,\n\t zscan: getxScan,\n\t zscore: {getter: true, required: ['_id', 'member'], mapResults: parseFloat},\n\t zunionstore: {required: ['_id', 'keys'], opts: ['weights', 'aggregate']}\n\t };\n\t\n\t/**\n\t * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n\t *\n\t * @callback responseCallback\n\t * @param {Object} err - Error object, NULL if the query is successful\n\t * @param {Object} [data] - The content of the query response\n\t */\n\t\n\t\n\t/**\n\t * Kuzzle's memory storage is a separate data store from the database layer.\n\t * It is internaly based on Redis. You can access most of Redis functions (all\n\t * lowercased), except functions falling in the following categories:\n\t *\n\t * - blocking functions\n\t * - cluster commands\n\t * - configuration commands\n\t * - cursor functions\n\t * - database administration commands\n\t * - debugging functions\n\t * - script based functions\n\t * - transaction functions\n\t *\n\t * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @constructor\n\t */\n\tfunction MemoryStorage(kuzzle) {\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t kuzzle: {\n\t value: kuzzle,\n\t enumerable: true\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = [];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t// Dynamically builds this class' prototypes using the \"commands\" global variable\n\t(function () {\n\t Object.keys(commands).forEach(function (command) {\n\t MemoryStorage.prototype[command] = function () {\n\t var\n\t args = Array.prototype.slice.call(arguments),\n\t options = null,\n\t cb,\n\t query = {\n\t controller: 'ms',\n\t action: command\n\t },\n\t data = {};\n\t\n\t if (args.length && typeof args[args.length - 1] === 'function') {\n\t cb = args.pop();\n\t }\n\t\n\t commands[command].getter && this.kuzzle.callbackRequired('MemoryStorage.' + command, cb);\n\t\n\t if (!commands[command].getter) {\n\t data.body = {};\n\t }\n\t\n\t if (commands[command].required) {\n\t commands[command].required.forEach(function (param) {\n\t var value = args.shift();\n\t\n\t if (value === undefined) {\n\t throw new Error('MemoryStorage.' + command + ': Missing parameter \"' + param + '\"');\n\t }\n\t\n\t assignParameter(data, commands[command].getter, param, value);\n\t });\n\t }\n\t\n\t if (args.length > 1) {\n\t throw new Error('MemoryStorage.' + command + ': Too many parameters provided');\n\t }\n\t\n\t if (args.length === 1 && typeof args[0] !== 'object' || Array.isArray(args[0])) {\n\t throw new Error('MemoryStorage.' + command + ': Invalid optional parameter (expected an object)');\n\t }\n\t\n\t if (args.length) {\n\t options = Object.assign({}, args[0]);\n\t\n\t if (Array.isArray(commands[command].opts)) {\n\t commands[command].opts.forEach(function (opt) {\n\t if (options[opt] !== null && options[opt] !== undefined) {\n\t assignParameter(data, commands[command].getter, opt, options[opt]);\n\t delete options[opt];\n\t }\n\t });\n\t }\n\t }\n\t\n\t /*\n\t Options function mapper does not necessarily need\n\t options to be passed by clients.\n\t */\n\t if (typeof commands[command].opts === 'function') {\n\t commands[command].opts(data, options || {});\n\t }\n\t\n\t this.kuzzle.query(query, data, options, cb && function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t if (commands[command].mapResults) {\n\t return cb(null, commands[command].mapResults(res.result));\n\t }\n\t\n\t cb(null, res.result);\n\t });\n\t\n\t if (!commands[command].getter) {\n\t return this;\n\t }\n\t };\n\t });\n\t})();\n\t\n\t/**\n\t *\n\t * @param {object} data - target data object\n\t * @param {boolean} getter - tells if the command is a getter one\n\t * @param {string} name - parameter name\n\t * @param {*} value - parameter value\n\t */\n\tfunction assignParameter(data, getter, name, value) {\n\t if (getter || name === '_id') {\n\t data[name] = value;\n\t }\n\t else {\n\t data.body[name] = value;\n\t }\n\t}\n\t\n\t/**\n\t * Assign the provided options for the georadius* redis functions\n\t * to the request object, as expected by Kuzzle API\n\t *\n\t * Mutates the provided data and options objects\n\t *\n\t * @param {object} data\n\t * @param {object} options\n\t */\n\tfunction assignGeoRadiusOptions(data, options) {\n\t var parsed = [];\n\t\n\t Object.keys(options)\n\t .filter(function (opt) {\n\t return options[opt] && ['withcoord', 'withdist', 'count', 'sort'].indexOf(opt) !== -1;\n\t })\n\t .forEach(function (opt) {\n\t if (opt === 'withcoord' || opt === 'withdist') {\n\t parsed.push(opt);\n\t delete options[opt];\n\t }\n\t else if (opt === 'count' || opt === 'sort') {\n\t if (opt === 'count') {\n\t parsed.push('count');\n\t }\n\t\n\t parsed.push(options[opt]);\n\t }\n\t\n\t delete options[opt];\n\t });\n\t\n\t if (parsed.length > 0) {\n\t data.options = parsed;\n\t }\n\t}\n\t\n\t/**\n\t * Force the WITHSCORES option on z*range* routes\n\t *\n\t * Mutates the provided data and options objects\n\t *\n\t * @param {object} data\n\t * @param {object} options\n\t */\n\tfunction assignZrangeOptions(data, options) {\n\t data.options = ['withscores'];\n\t\n\t if (options.limit) {\n\t data.limit = options.limit;\n\t delete options.limit;\n\t }\n\t}\n\t\n\t/**\n\t * Maps geopos results, from array> to array>\n\t *\n\t * @param {Array.>} results\n\t * @return {Array.>}\n\t */\n\tfunction mapGeoposResults(results) {\n\t return results.map(function (coords) {\n\t return coords.map(function (latlon) {\n\t return parseFloat(latlon);\n\t });\n\t });\n\t}\n\t\n\t\n\t/**\n\t * Maps georadius results to the format specified in the SDK documentation,\n\t * preventing different formats depending on the passed options\n\t *\n\t * Results can be either an array of point names, or an array\n\t * of arrays, each one of them containing the point name,\n\t * and additional informations depending on the passed options\n\t * (coordinates, distances)\n\t *\n\t * @param {Array} results\n\t * @return {Array.}\n\t */\n\tfunction mapGeoRadiusResults(results) {\n\t // Simple array of point names (no options provided)\n\t if (!Array.isArray(results[0])) {\n\t return results.map(function (point) {\n\t return {name: point};\n\t });\n\t }\n\t\n\t return results.map(function (point) {\n\t // The point id is always the first item\n\t var p = {\n\t name: point[0]\n\t },\n\t i;\n\t\n\t for (i = 1; i < point.length; i++) {\n\t // withcoord result are in an array...\n\t if (Array.isArray(point[i])) {\n\t p.coordinates = point[i].map(function (coord) {\n\t return parseFloat(coord);\n\t });\n\t }\n\t else {\n\t // ... and withdist are not\n\t p.distance = parseFloat(point[i]);\n\t }\n\t }\n\t\n\t return p;\n\t });\n\t}\n\t\n\t/**\n\t * Map a string result to an array of strings.\n\t * Used to uniformize polymorphic results from redis\n\t *\n\t * @param {Array|string} results\n\t * @return {Array.}\n\t */\n\tfunction mapStringToArray(results) {\n\t return Array.isArray(results) ? results : [results];\n\t}\n\t\n\t/**\n\t * Map an array of strings to an array of integers\n\t *\n\t * @param {Array.} results\n\t * @return {Array.}\n\t */\n\tfunction mapArrayStringToArrayInt(results) {\n\t return results.map(function (value) {\n\t return parseInt(value);\n\t });\n\t}\n\t\n\t/**\n\t * Disable results for routes like flushdb\n\t * @return {undefined}\n\t */\n\tfunction mapNoResult() {\n\t return undefined;\n\t}\n\t\n\t/**\n\t * Map zrange results with WITHSCORES:\n\t * [\n\t * \"member1\",\n\t * \"score of member1\",\n\t * \"member2\",\n\t * \"score of member2\"\n\t * ]\n\t *\n\t * into the following format:\n\t * [\n\t * {\"member\": \"member1\", \"score\": },\n\t * {\"member\": \"member2\", \"score\": },\n\t * ]\n\t *\n\t *\n\t * @param {Array.} results\n\t * @return {Array.}\n\t */\n\tfunction mapZrangeResults(results) {\n\t var\n\t buffer = null,\n\t mapped = [];\n\t\n\t results.forEach(function (value) {\n\t if (buffer === null) {\n\t buffer = value;\n\t }\n\t else {\n\t mapped.push({member: buffer, score: parseFloat(value)});\n\t buffer = null;\n\t }\n\t });\n\t\n\t return mapped;\n\t}\n\t\n\t/**\n\t * Map *scan calls results, from:\n\t * [\n\t * \"\",\n\t * [\n\t * \"value1\",\n\t * \"value2\", \n\t * \"...\"\n\t * ]\n\t * ]\n\t *\n\t * To:\n\t * {\n\t * cursor: ,\n\t * values: [\n\t * \"value1\",\n\t * \"value2\",\n\t * \"...\"\n\t * ]\n\t * }\n\t * \n\t * @param {array.} results \n\t * @return {object}\n\t */\n\tfunction mapScanResults(results) {\n\t return {\n\t cursor: results[0],\n\t values: results[1]\n\t };\n\t}\n\t\n\tmodule.exports = MemoryStorage;\n\n\n/***/ }),\n/* 12 */\n/***/ (function(module, exports) {\n\n\t/**\n\t * @param {Collection} collection\n\t * @param {int} total\n\t * @param {Document[]} documents\n\t * @param {object} aggregations\n\t * @param {object} options\n\t * @param {object} filters\n\t * @param {SearchResult} previous\n\t * @property {Collection} collection\n\t * @property {number} total\n\t * @property {Document[]} documents\n\t * @property {object} aggregations\n\t * @property {object} options\n\t * @property {object} filters\n\t * @property {number} fetchedDocument\n\t * @constructor\n\t */\n\tfunction SearchResult (collection, total, documents, aggregations, options, filters, previous) {\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t collection: {\n\t value: collection,\n\t enumerable: true\n\t },\n\t total: {\n\t value: total,\n\t enumerable: true\n\t },\n\t documents: {\n\t value: documents,\n\t enumerable: true\n\t },\n\t aggregations: {\n\t value: aggregations || {},\n\t enumerable: true\n\t },\n\t options: {\n\t value: options || {},\n\t enumerable: true\n\t },\n\t filters: {\n\t value: filters || {},\n\t enumerable: true\n\t },\n\t // writable properties\n\t fetchedDocument: {\n\t value: previous instanceof SearchResult ? documents.length + previous.fetchedDocument : documents.length,\n\t enumerable: true,\n\t writable: true\n\t }\n\t });\n\t\n\t // promisifying\n\t if (this.collection.kuzzle.bluebird) {\n\t return this.collection.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['fetchNext'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t/**\n\t * @param {function} cb\n\t */\n\tSearchResult.prototype.fetchNext = function (cb) {\n\t var\n\t filters,\n\t options = Object.assign({}, this.options),\n\t self = this;\n\t \n\t options.previous = this;\n\t\n\t // retrieve next results with scroll if original search use it\n\t if (options.scrollId) {\n\t if (this.fetchedDocument >= this.getTotal()) {\n\t cb(null, null);\n\t return;\n\t }\n\t\n\t // from and size parameters are not valid for a scroll action\n\t if (typeof options.from !== 'undefined') {\n\t delete options.from;\n\t }\n\t\n\t if (options.size) {\n\t delete options.size;\n\t }\n\t\n\t this.collection.scroll(options.scrollId, options, this.filters || {}, cb);\n\t\n\t return;\n\t }\n\t\n\t // retrieve next results using ES's search_after\n\t if (options.size && this.filters.sort) {\n\t if (this.fetchedDocument >= this.getTotal()) {\n\t cb(null, null);\n\t return;\n\t }\n\t\n\t if (options.from) {\n\t delete options.from;\n\t }\n\t\n\t filters = Object.assign(this.filters, {search_after: []});\n\t\n\t filters.sort.forEach(function (sortRule) {\n\t filters.search_after.push(self.documents[self.documents.length - 1].content[Object.keys(sortRule)[0]]);\n\t });\n\t\n\t this.collection.search(filters, options, cb);\n\t\n\t return;\n\t }\n\t\n\t // retrieve next results with from/size if original search use it\n\t if (options.from !== undefined && options.size !== undefined) {\n\t filters = Object.assign({}, this.filters);\n\t\n\t // check if we need to do next request to fetch all matching documents\n\t options.from += options.size;\n\t\n\t if (options.from >= this.getTotal()) {\n\t cb(null, null);\n\t\n\t return;\n\t }\n\t\n\t this.collection.search(filters, options, cb);\n\t\n\t return;\n\t }\n\t\n\t cb(new Error('Unable to retrieve next results from search: missing scrollId or from/size params'));\n\t};\n\t\n\t/**\n\t * @returns {Document[]}\n\t */\n\tSearchResult.prototype.getDocuments = function () {\n\t return this.documents;\n\t};\n\t\n\t/**\n\t * @returns {number}\n\t */\n\tSearchResult.prototype.getTotal = function () {\n\t return this.total;\n\t};\n\t\n\t/**\n\t * @returns {object}\n\t */\n\tSearchResult.prototype.getAggregations = function () {\n\t return this.aggregations;\n\t};\n\t\n\t/**\n\t * @returns {Object}\n\t */\n\tSearchResult.prototype.getOptions = function() {\n\t return this.options;\n\t};\n\t\n\t/**\n\t * @returns {object}\n\t */\n\tSearchResult.prototype.getFilters = function() {\n\t return this.filters;\n\t};\n\t\n\t/**\n\t * @returns {object}\n\t */\n\tSearchResult.prototype.getCollection = function () {\n\t return this.collection;\n\t};\n\t\n\t/**\n\t * @returns {number}\n\t */\n\tSearchResult.prototype.getFetchedDocument = function () {\n\t return this.fetchedDocument;\n\t};\n\t\n\tmodule.exports = SearchResult;\n\n\n/***/ }),\n/* 13 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/**\n\t *\n\t * @param protocol\n\t * @param host\n\t * @param options\n\t * @returns {Object} Instantiated WebSocket/Socket.IO object\n\t */\n\t\n\tfunction network(protocol, host, options) {\n\t switch (protocol) {\n\t case 'websocket':\n\t if (typeof window !== 'undefined' && typeof WebSocket === 'undefined') {\n\t throw new Error('Aborting: no websocket support detected.');\n\t }\n\t return new (__webpack_require__(8))(host, options);\n\t case 'socketio':\n\t if (!window.io) {\n\t throw new Error('Aborting: no socket.io library loaded.');\n\t }\n\t return new (__webpack_require__(7))(host, options);\n\t default:\n\t throw new Error('Aborting: unknown protocol \"' + protocol + '\" (only \"websocket\" and \"socketio\" are available).');\n\t }\n\t}\n\t\n\tmodule.exports = network;\n\n\n/***/ }),\n/* 14 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tvar SecurityDocument = __webpack_require__(2);\n\t\n\tfunction Profile(Security, id, content, meta) {\n\t\n\t SecurityDocument.call(this, Security, id, content, meta);\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t deleteActionName: {\n\t value: 'deleteProfile'\n\t },\n\t updateActionName: {\n\t value: 'updateProfile'\n\t }\n\t });\n\t\n\t // promisifying\n\t if (Security.kuzzle.bluebird) {\n\t return Security.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['hydrate', 'save'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t}\n\t\n\tProfile.prototype = Object.create(SecurityDocument.prototype, {\n\t constructor: {\n\t value: Profile\n\t }\n\t});\n\t\n\t/**\n\t * Persist to the persistent layer the current profile\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Profile} this\n\t */\n\tProfile.prototype.save = function (options, cb) {\n\t var\n\t data,\n\t self = this;\n\t\n\t if (!this.content.policies) {\n\t throw new Error('Argument \"policies\" is mandatory in a profile. This argument contains an array of objects.');\n\t }\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = this.serialize();\n\t\n\t self.kuzzle.query(self.Security.buildQueryArgs('createOrReplaceProfile'), data, options, cb && function (error) {\n\t cb(error, error ? undefined : self);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t\n\t/**\n\t * Add a policy in the policies list\n\t * @param {Object} policy - must be an object containing at least a \"roleId\" member which must be a string.\n\t *\n\t * @returns {Profile} this\n\t */\n\tProfile.prototype.addPolicy = function (policy) {\n\t\n\t if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n\t throw new Error('Parameter \"policies\" must be an object containing at least a \"roleId\" member which must be a string.');\n\t }\n\t\n\t if (!this.content.policies) {\n\t this.content.policies = [];\n\t }\n\t\n\t this.content.policies.push(policy);\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Set policies list\n\t * @param {Array} policies - must be an array of objects containing at least a \"roleId\" member which must be a string\n\t *\n\t * @returns {Profile} this\n\t */\n\tProfile.prototype.setPolicies = function (policies) {\n\t\n\t if (!Array.isArray(policies)) {\n\t throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n\t }\n\t\n\t policies.map(function (policy) {\n\t if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n\t throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n\t }\n\t });\n\t\n\t this.content.policies = policies;\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Serialize this object into a JSON object\n\t *\n\t * @return {object} JSON object representing this securityDocument\n\t */\n\tProfile.prototype.serialize = function () {\n\t var\n\t data = {};\n\t\n\t if (this.id) {\n\t data._id = this.id;\n\t }\n\t\n\t data.body = this.content;\n\t data.meta = this.meta;\n\t\n\t return data;\n\t};\n\t\n\t/**\n\t * Returns the list of policies associated to this profile.\n\t * Each policy element is an array of objects containing at least a \"roleId\" member which must be a string\n\t *\n\t * @return {object} an array of policies\n\t */\n\tProfile.prototype.getPolicies = function () {\n\t return this.content.policies;\n\t};\n\t\n\tmodule.exports = Profile;\n\n\n/***/ }),\n/* 15 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tvar SecurityDocument = __webpack_require__(2);\n\t\n\tfunction Role(Security, id, content, meta) {\n\t\n\t SecurityDocument.call(this, Security, id, content, meta);\n\t\n\t // Define properties\n\t Object.defineProperties(this, {\n\t // private properties\n\t deleteActionName: {\n\t value: 'deleteRole'\n\t },\n\t updateActionName: {\n\t value: 'updateRole'\n\t }\n\t });\n\t\n\t // promisifying\n\t if (Security.kuzzle.bluebird) {\n\t return Security.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var whitelist = ['save'];\n\t\n\t return passes && whitelist.indexOf(name) !== -1;\n\t }\n\t });\n\t }\n\t\n\t}\n\t\n\tRole.prototype = Object.create(SecurityDocument.prototype, {\n\t constructor: {\n\t value: Role\n\t }\n\t});\n\t\n\t/**\n\t * Saves this role into Kuzzle.\n\t *\n\t * If this is a new role, this function will create it in Kuzzle.\n\t * Otherwise, this method will replace the latest version of this role in Kuzzle by the current content\n\t * of this object.\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Role} this object\n\t */\n\tRole.prototype.save = function (options, cb) {\n\t var\n\t data = this.serialize(),\n\t self = this;\n\t\n\t if (options && cb === undefined && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.Security.buildQueryArgs('createOrReplaceRole'), data, options, cb && function (error) {\n\t cb(error, error ? undefined : self);\n\t });\n\t\n\t return this;\n\t};\n\t\n\tmodule.exports = Role;\n\n\n/***/ }),\n/* 16 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tvar\n\t Role = __webpack_require__(15),\n\t Profile = __webpack_require__(14),\n\t User = __webpack_require__(5);\n\t\n\t/**\n\t * Kuzzle security constructor\n\t *\n\t * @param kuzzle\n\t * @returns {Security}\n\t * @constructor\n\t */\n\tfunction Security(kuzzle) {\n\t\n\t Object.defineProperty(this, 'kuzzle', {\n\t value: kuzzle\n\t });\n\t\n\t Object.defineProperty(this, 'buildQueryArgs', {\n\t value: function (action) {\n\t return {\n\t controller: 'security',\n\t action: action\n\t };\n\t }\n\t });\n\t\n\t if (this.kuzzle.bluebird) {\n\t return this.kuzzle.bluebird.promisifyAll(this, {\n\t suffix: 'Promise',\n\t filter: function (name, func, target, passes) {\n\t var blacklist = ['role', 'profile', 'user', 'isActionAllowed'];\n\t\n\t return passes && blacklist.indexOf(name) === -1;\n\t }\n\t });\n\t }\n\t\n\t return this;\n\t}\n\t\n\t\n\t/**\n\t * Retrieve a single Role using its unique role ID.\n\t *\n\t * @param {string} id\n\t * @param {object|responseCallback} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tSecurity.prototype.fetchRole = function (id, options, cb) {\n\t var\n\t data,\n\t self = this;\n\t\n\t if (!id) {\n\t throw new Error('Id parameter is mandatory for fetchRole function');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data = {_id: id};\n\t\n\t self.kuzzle.callbackRequired('Security.fetchRole', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n\t cb(err, err ? undefined : new Role(self, response.result._id, response.result._source, response.result._meta));\n\t });\n\t};\n\t\n\t/**\n\t * Executes a search on roles according to a filter\n\t *\n\t * /!\\ There is a small delay between role creation and their existence in our persistent search layer,\n\t * usually a couple of seconds.\n\t * That means that a role that was just been created won’t be returned by this function.\n\t *\n\t * @param {Object} filters - this object can contains an array `indexes` with a list of index id, a integer `from` and a integer `size`\n\t * @param {object|responseCallback} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t *\n\t */\n\tSecurity.prototype.searchRoles = function (filters, options, cb) {\n\t var\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Security.searchRoles', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchRoles'), {body: filters}, options, function (error, result) {\n\t var documents;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t documents = result.result.hits.map(function (doc) {\n\t return new Role(self, doc._id, doc._source, doc._meta);\n\t });\n\t\n\t cb(null, { total: result.result.total, roles: documents });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new role in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following property:\n\t * - replaceIfExist (boolean, default: false):\n\t * If the same role already exists: throw an error if sets to false.\n\t * Replace the existing role otherwise\n\t *\n\t * @param {string} id - role identifier\n\t * @param {object} content - a plain javascript object representing the role\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tSecurity.prototype.createRole = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'createRole';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Security.createRole: cannot create a role without a role ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t data.body = content;\n\t\n\t if (options) {\n\t action = options.replaceIfExist ? 'createOrReplaceRole' : 'createRole';\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new Role(self, res.result._id, res.result._source, res.result._meta));\n\t });\n\t};\n\t\n\t\n\t/**\n\t * Update a role in Kuzzle.\n\t *\n\t * @param {string} id - role identifier\n\t * @param {object} content - a plain javascript object representing the role's modification\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {Security} this object\n\t */\n\tSecurity.prototype.updateRole = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {_id: id, body: content},\n\t action = 'updateRole';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Security.updateRole: cannot update a role without a role ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new Role(self, id, content, res.result._meta));\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete role.\n\t *\n\t * There is a small delay between role deletion and their deletion in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a role that was just been delete will be returned by this function\n\t *\n\t *\n\t * @param {string} id - Role id to delete\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Security} this object\n\t */\n\tSecurity.prototype.deleteRole = function (id, options, cb) {\n\t var data = {_id: id};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('deleteRole'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result._id);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Instantiate a new Role object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - role id\n\t * @param {object} content - role content\n\t * @param {object} meta - role metadata\n\t * @constructor\n\t */\n\tSecurity.prototype.role = function(id, content, meta) {\n\t return new Role(this, id, content, meta);\n\t};\n\t\n\t\n\t/**\n\t * Get a specific profile from kuzzle\n\t *\n\t *\n\t * @param {string} id\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tSecurity.prototype.fetchProfile = function (id, options, cb) {\n\t var\n\t data,\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Id parameter is mandatory for fetchProfile function');\n\t }\n\t\n\t\n\t data = {_id: id};\n\t\n\t self.kuzzle.callbackRequired('Security.fetchProfile', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n\t cb(error, error ? undefined : new Profile(self, response.result._id, response.result._source, response.result._meta));\n\t });\n\t};\n\t\n\t/**\n\t * Executes a search on profiles according to a filter\n\t *\n\t *\n\t * /!\\ There is a small delay between profile creation and their existence in our persistent search layer,\n\t * usually a couple of seconds.\n\t * That means that a profile that was just been created won’t be returned by this function.\n\t *\n\t * @param {Object} filters - this object can contains an array `roles` with a list of roles id, a integer `from` and a integer `size`\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tSecurity.prototype.searchProfiles = function (filters, options, cb) {\n\t var\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Security.searchProfiles', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n\t var\n\t documents,\n\t scrollId;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t documents = response.result.hits.map(function (doc) {\n\t return new Profile(self, doc._id, doc._source, doc._meta);\n\t });\n\t\n\t if (response.result.scrollId) {\n\t scrollId = response.result.scrollId;\n\t }\n\t\n\t cb(null, { total: response.result.total, profiles: documents, scrollId: scrollId });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new profile in Kuzzle.\n\t *\n\t * Takes an optional argument object with the following property:\n\t * - replaceIfExist (boolean, default: false):\n\t * If the same profile already exists: throw an error if sets to false.\n\t * Replace the existing profile otherwise\n\t *\n\t * @param {string} id - profile identifier\n\t * @param {array} policies - list of policies to attach to the new profile\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tSecurity.prototype.createProfile = function (id, policies, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'createProfile';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Security.createProfile: cannot create a profile without a profile ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t\n\t if (policies) {\n\t data.body = { policies: policies };\n\t }\n\t\n\t if (options) {\n\t action = options.replaceIfExist ? 'createOrReplaceProfile' : 'createProfile';\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new Profile(self, res.result._id, res.result._source, res.result._meta));\n\t });\n\t};\n\t\n\t\n\t/**\n\t * Update a profile in Kuzzle.\n\t *\n\t * @param {string} id - profile identifier\n\t * @param {array} policies - the list of policies to apply to this profile\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {Security} this object\n\t */\n\tSecurity.prototype.updateProfile = function (id, policies, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'updateProfile';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Security.updateProfile: cannot update a profile without a profile ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t\n\t if (policies) {\n\t data.body = {policies: policies};\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t var updatedContent = {};\n\t\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t Object.keys(res.result._source).forEach(function (property) {\n\t updatedContent[property] = res.result._source[property];\n\t });\n\t\n\t cb(null, new Profile(self, res.result._id, updatedContent, res.result._meta));\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete profile.\n\t *\n\t * There is a small delay between profile deletion and their deletion in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a profile that was just been delete will be returned by this function\n\t *\n\t *\n\t * @param {string} id - Profile id to delete\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Security} this object\n\t */\n\tSecurity.prototype.deleteProfile = function (id, options, cb) {\n\t var data = {_id: id};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('deleteProfile'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result._id);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * @param {string} scrollId\n\t * @param {object} [options]\n\t * @param {responseCallback} cb\n\t */\n\tSecurity.prototype.scrollProfiles = function (scrollId, options, cb) {\n\t var\n\t request = {},\n\t self = this;\n\t\n\t if (!scrollId) {\n\t throw new Error('Security.scrollProfiles: scrollId is required');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = {};\n\t }\n\t\n\t this.kuzzle.callbackRequired('Security.scrollProfiles', cb);\n\t\n\t request.scrollId = scrollId;\n\t\n\t if (options && options.scroll) {\n\t request.scroll = options.scroll;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'scrollProfiles'}, request, options, function (error, result) {\n\t var profiles = [];\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t result.result.hits.forEach(function (profile) {\n\t var newProfile = new Profile(self, profile._id, profile._source, profile._meta);\n\t\n\t newProfile.version = profile._version;\n\t\n\t profiles.push(newProfile);\n\t });\n\t\n\t cb(null, {\n\t total: result.result.total,\n\t profiles: profiles,\n\t scrollId: scrollId\n\t });\n\t });\n\t};\n\t\n\t/**\n\t * Instantiate a new Profile object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - profile id\n\t * @param {object} content - profile content\n\t * @param {object} meta - profile metadata\n\t * @constructor\n\t */\n\tSecurity.prototype.profile = function(id, content, meta) {\n\t return new Profile(this, id, content, meta);\n\t};\n\t\n\t/**\n\t * Get a specific user from kuzzle using its unique ID\n\t *\n\t * @param {string} id\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tSecurity.prototype.fetchUser = function (id, options, cb) {\n\t var\n\t data = {_id: id},\n\t self = this;\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Id parameter is mandatory for fetchUser function');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Security.fetchUser', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n\t cb(err, err ? undefined : new User(self, response.result._id, response.result._source, response.result._meta));\n\t });\n\t};\n\t\n\t/**\n\t * Executes a search on user according to a filter\n\t *\n\t * /!\\ There is a small delay between user creation and their existence in our persistent search layer,\n\t * usually a couple of seconds.\n\t * That means that a user that was just been created won’t be returned by this function.\n\t *\n\t * @param {Object} filters - same filters as documents filters\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tSecurity.prototype.searchUsers = function (filters, options, cb) {\n\t var\n\t self = this;\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Security.searchUsers', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n\t var\n\t documents,\n\t scrollId = null;\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t documents = response.result.hits.map(function (doc) {\n\t return new User(self, doc._id, doc._source, doc._meta);\n\t });\n\t\n\t if (response.result.scrollId) {\n\t scrollId = response.result.scrollId;\n\t }\n\t\n\t cb(null, { total: response.result.total, users: documents, scrollId: scrollId });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new user in Kuzzle.\n\t *\n\t * @param {string} id - user identifier\n\t * @param {object} content - attribute `profileIds` in `content` must only contain an array of profile ids\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tSecurity.prototype.createUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {_id: id, body: content};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(self.buildQueryArgs('createUser'), data, null, cb && function (err, res) {\n\t cb(err, err ? undefined : new User(self, res.result._id, res.result._source, res.result._meta));\n\t });\n\t};\n\t\n\t/**\n\t * Replace an user in Kuzzle.\n\t *\n\t * @param {string} id - user identifier\n\t * @param {object} content - attribute `profileIds` in `content` must only contain an array of profile ids\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tSecurity.prototype.replaceUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {_id: id, body: content};\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Security.replaceUser: cannot replace a user without a user ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs('replaceUser'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new User(self, res.result._id, res.result._source, res.result._meta));\n\t });\n\t};\n\t\n\t/**\n\t * Create a new restricted user in Kuzzle.\n\t *\n\t * This function will create a new user. It is not usable to update an existing user.\n\t * This function allows anonymous users to create a \"restricted\" user with predefined rights.\n\t *\n\t * @param {string} id - user identifier\n\t * @param {object} content - attribute `profile` in `content` must only contains the profile id\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tSecurity.prototype.createRestrictedUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {_id: id, body: content};\n\t\n\t if (content.profileIds) {\n\t throw new Error('Security.createRestrictedUser: cannot provide profileIds');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs('createRestrictedUser'), data, null, cb && function (err, res) {\n\t cb(err, err ? undefined : new User(self, res.result._id, res.result._source));\n\t });\n\t};\n\t\n\t\n\t/**\n\t * Update an user in Kuzzle.\n\t *\n\t * @param {string} id - user identifier\n\t * @param {object} content - a plain javascript object representing the user's modification\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t * @returns {Security} this object\n\t */\n\tSecurity.prototype.updateUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'updateUser';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Security.updateUser: cannot update an user without an user ID');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t data._id = id;\n\t data.body = content;\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : new User(self, res.result._id, res.result._source, res.result._meta));\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete user.\n\t *\n\t * There is a small delay between user deletion and their deletion in our advanced search layer,\n\t * usually a couple of seconds.\n\t * That means that a user that was just been delete will be returned by this function\n\t *\n\t *\n\t * @param {string} id - Profile id to delete\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @returns {Security} this object\n\t */\n\tSecurity.prototype.deleteUser = function (id, options, cb) {\n\t var data = {_id: id};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query(this.buildQueryArgs('deleteUser'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result._id);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * @param {string} scrollId\n\t * @param {object} [options]\n\t * @param {responseCallback} cb\n\t */\n\tSecurity.prototype.scrollUsers = function (scrollId, options, cb) {\n\t var\n\t request = {},\n\t self = this;\n\t\n\t if (!scrollId) {\n\t throw new Error('Security.scrollUsers: scrollId is required');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = {};\n\t }\n\t\n\t this.kuzzle.callbackRequired('Security.scrollUsers', cb);\n\t\n\t request.scrollId = scrollId;\n\t\n\t if (options && options.scroll) {\n\t request.scroll = options.scroll;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'scrollUsers'}, request, options, function (error, result) {\n\t var users = [];\n\t\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t result.result.hits.forEach(function (user) {\n\t var newUser = new User(self, user._id, user._source, user._meta);\n\t\n\t newUser.version = user._version;\n\t\n\t users.push(newUser);\n\t });\n\t\n\t cb(null, {\n\t total: result.result.total,\n\t users: users,\n\t scrollId: scrollId\n\t });\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Instantiate a new User object. Workaround to the module.exports limitation, preventing multiple\n\t * constructors to be exposed without having to use a factory or a composed object.\n\t *\n\t * @param {string} id - user id\n\t * @param {object} content - user content\n\t * @param {object} meta - user metadata\n\t * @constructor\n\t */\n\tSecurity.prototype.user = function(id, content, meta) {\n\t return new User(this, id, content, meta);\n\t};\n\t\n\t/**\n\t * Tells whether an action is allowed, denied or conditional based on the rights\n\t * rights provided as the first argument. An action is defined as a couple of\n\t * action and controller (mandatory), plus an index and a collection(optional).\n\t *\n\t * @param {object} rights - The rights rights associated to a user\n\t * (see getMyrights and getUserrights).\n\t * @param {string} controller - The controller to check the action onto.\n\t * @param {string} action - The action to perform.\n\t * @param {string} index - (optional) The name of index to perform the action onto.\n\t * @param {string} collection - (optional) The name of the collection to perform the action onto.\n\t *\n\t * @returns {string} ['allowed', 'denied', 'conditional'] where conditional cases\n\t * correspond to rights containing closures.\n\t * See also http://kuzzle.io/guide/#roles-definition\n\t */\n\tSecurity.prototype.isActionAllowed = function(rights, controller, action, index, collection) {\n\t var filteredRights;\n\t\n\t if (!rights || typeof rights !== 'object') {\n\t throw new Error('rights parameter is mandatory for isActionAllowed function');\n\t }\n\t if (!controller || typeof controller !== 'string') {\n\t throw new Error('controller parameter is mandatory for isActionAllowed function');\n\t }\n\t if (!action || typeof action !== 'string') {\n\t throw new Error('action parameter is mandatory for isActionAllowed function');\n\t }\n\t\n\t // We filter in all the rights that match the request (including wildcards).\n\t filteredRights = rights\n\t .filter(function (right) {\n\t return right.controller === controller || right.controller === '*';\n\t })\n\t .filter(function (right) {\n\t return right.action === action || right.action === '*';\n\t })\n\t .filter(function (right) {\n\t return right.index === index || right.index === '*';\n\t })\n\t .filter(function (right) {\n\t return right.collection === collection || right.collection === '*';\n\t });\n\t\n\t // Then, if at least one right allows the action, we return 'allowed'\n\t if (filteredRights.some(function (item) { return item.value === 'allowed'; })) {\n\t return 'allowed';\n\t }\n\t // If no right allows the action, we check for conditionals.\n\t if (filteredRights.some(function (item) { return item.value === 'conditional'; })) {\n\t return 'conditional';\n\t }\n\t // Otherwise we return 'denied'.\n\t return 'denied';\n\t};\n\t\n\t\n\t/**\n\t * Gets the rights array of a given user.\n\t *\n\t * @param {string} userId The id of the user.\n\t * @param {object|responseCallback} [options] - (optional) arguments\n\t * @param {function} cb The callback containing the normalized array of rights.\n\t */\n\tSecurity.prototype.getUserRights = function (userId, options, cb) {\n\t var\n\t data = {_id: userId},\n\t self = this;\n\t\n\t if (!userId || typeof userId !== 'string') {\n\t throw new Error('userId parameter is mandatory for getUserRights function');\n\t }\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('Kuzzle.getUserRights', cb);\n\t\n\t this.kuzzle.query(this.buildQueryArgs('getUserRights'), data, options, cb && function (err, res) {\n\t cb(err, err ? undefined : res.result.hits);\n\t });\n\t};\n\t\n\t/**\n\t * Create credentials of the specified for the user .\n\t *\n\t * @param strategy\n\t * @param kuid\n\t * @param credentials\n\t * @param options\n\t * @param cb\n\t * @returns {Security}\n\t */\n\tSecurity.prototype.createCredentials = function (strategy, kuid, credentials, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'createCredentials'}, {_id: kuid, strategy: strategy, body: credentials}, options, function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result._source);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Delete credentials of the specified for the user .\n\t *\n\t * @param strategy\n\t * @param kuid\n\t * @param options\n\t * @param cb\n\t * @returns {Security}\n\t */\n\tSecurity.prototype.deleteCredentials = function (strategy, kuid, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'deleteCredentials'}, {strategy: strategy, _id: kuid}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Retrieve a list of accepted fields per authentication strategy.\n\t *\n\t * @param options\n\t * @param cb\n\t */\n\tSecurity.prototype.getAllCredentialFields = function (options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'getAllCredentialFields'}, {}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Retrieve the list of accepted field names by the specified .\n\t *\n\t * @param strategy\n\t * @param options\n\t * @param cb\n\t */\n\tSecurity.prototype.getCredentialFields = function (strategy, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'getCredentialFields'}, {strategy: strategy}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Get credential information of the specified for the user .\n\t *\n\t * @param strategy\n\t * @param kuid\n\t * @param options\n\t * @param cb\n\t */\n\tSecurity.prototype.getCredentials = function (strategy, kuid, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'getCredentials'}, {strategy: strategy, _id: kuid}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Check the existence of the specified ’s credentials for the user .\n\t *\n\t * @param strategy\n\t * @param kuid\n\t * @param options\n\t * @param cb\n\t */\n\tSecurity.prototype.hasCredentials = function (strategy, kuid, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'hasCredentials'}, {strategy: strategy, _id: kuid}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t};\n\t\n\t/**\n\t * Updates credentials of the specified for the user .\n\t *\n\t * @param strategy\n\t * @param kuid\n\t * @param credentials\n\t * @param options\n\t * @param cb\n\t * @returns {Security}\n\t */\n\tSecurity.prototype.updateCredentials = function (strategy, kuid, credentials, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'updateCredentials'}, {strategy: strategy, _id: kuid, body: credentials}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Validate credentials of the specified for the user .\n\t *\n\t * @param strategy\n\t * @param kuid\n\t * @param credentials\n\t * @param options\n\t * @param cb\n\t */\n\tSecurity.prototype.validateCredentials = function (strategy, kuid, credentials, options, cb) {\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t this.kuzzle.query({controller: 'security', action: 'validateCredentials'}, {strategy: strategy, _id: kuid, body: credentials}, options, typeof cb !== 'function' ? null : function(err, res) {\n\t if (!err) {\n\t cb && cb(null, res.result);\n\t } else {\n\t cb && cb(err);\n\t }\n\t });\n\t};\n\t\n\tmodule.exports = Security;\n\n\n/***/ }),\n/* 17 */\n/***/ (function(module, exports) {\n\n\t/**\n\t * Convert array of 16 byte values to UUID string format of the form:\n\t * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n\t */\n\tvar byteToHex = [];\n\tfor (var i = 0; i < 256; ++i) {\n\t byteToHex[i] = (i + 0x100).toString(16).substr(1);\n\t}\n\t\n\tfunction bytesToUuid(buf, offset) {\n\t var i = offset || 0;\n\t var bth = byteToHex;\n\t return bth[buf[i++]] + bth[buf[i++]] +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] + '-' +\n\t bth[buf[i++]] + bth[buf[i++]] +\n\t bth[buf[i++]] + bth[buf[i++]] +\n\t bth[buf[i++]] + bth[buf[i++]];\n\t}\n\t\n\tmodule.exports = bytesToUuid;\n\n\n/***/ }),\n/* 18 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t// Unique ID creation requires a high quality random # generator. In the\n\t// browser this is a little complicated due to unknown quality of Math.random()\n\t// and inconsistent support for the `crypto` API. We do the best we can via\n\t// feature-detection\n\tvar rng;\n\t\n\tvar crypto = (window).crypto || (window).msCrypto; // for IE 11\n\tif (crypto && crypto.getRandomValues) {\n\t // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto\n\t var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef\n\t rng = function whatwgRNG() {\n\t crypto.getRandomValues(rnds8);\n\t return rnds8;\n\t };\n\t}\n\t\n\tif (!rng) {\n\t // Math.random()-based (RNG)\n\t //\n\t // If all else fails, use Math.random(). It's fast, but is of unspecified\n\t // quality.\n\t var rnds = new Array(16);\n\t rng = function() {\n\t for (var i = 0, r; i < 16; i++) {\n\t if ((i & 0x03) === 0) r = Math.random() * 0x100000000;\n\t rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n\t }\n\t\n\t return rnds;\n\t };\n\t}\n\t\n\tmodule.exports = rng;\n\n\n/***/ }),\n/* 19 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tvar rng = __webpack_require__(18);\n\tvar bytesToUuid = __webpack_require__(17);\n\t\n\tfunction v4(options, buf, offset) {\n\t var i = buf && offset || 0;\n\t\n\t if (typeof(options) == 'string') {\n\t buf = options == 'binary' ? new Array(16) : null;\n\t options = null;\n\t }\n\t options = options || {};\n\t\n\t var rnds = options.random || (options.rng || rng)();\n\t\n\t // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\t rnds[6] = (rnds[6] & 0x0f) | 0x40;\n\t rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\t\n\t // Copy bytes to buffer, if provided\n\t if (buf) {\n\t for (var ii = 0; ii < 16; ++ii) {\n\t buf[i + ii] = rnds[ii];\n\t }\n\t }\n\t\n\t return buf || bytesToUuid(rnds);\n\t}\n\t\n\tmodule.exports = v4;\n\n\n/***/ })\n/******/ ])\n});\n;\n\n\n// WEBPACK FOOTER //\n// kuzzle.js"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap d2654b12cf08324a5af1","const\n uuidv4 = require('uuid/v4'),\n KuzzleEventEmitter = require('./eventEmitter'),\n Collection = require('./Collection.js'),\n Document = require('./Document.js'),\n Security = require('./security/Security'),\n MemoryStorage = require('./MemoryStorage'),\n User = require('./security/User'),\n networkWrapper = require('./networkWrapper');\n\n/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n/**\n * Kuzzle object constructor.\n *\n * @constructor\n * @param host - Server name or IP Address to the Kuzzle instance\n * @param [options] - Connection options\n * @param {responseCallback} [cb] - Handles connection response\n */\nclass Kuzzle extends KuzzleEventEmitter {\n constructor(host, options, cb) {\n super();\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!host || host === '') {\n throw new Error('host argument missing');\n }\n\n Object.defineProperties(this, {\n // 'private' properties\n connectCB: {\n value: cb\n },\n eventActions: {\n value: [\n 'connected',\n 'discarded',\n 'disconnected',\n 'loginAttempt',\n 'networkError',\n 'offlineQueuePush',\n 'offlineQueuePop',\n 'queryError',\n 'reconnected',\n 'tokenExpired'\n ]\n },\n // configuration properties\n autoResubscribe: {\n value: options && typeof options.autoResubscribe === 'boolean' ? options.autoResubscribe : true,\n enumerable: true\n },\n defaultIndex: {\n value: (options && typeof options.defaultIndex === 'string') ? options.defaultIndex : undefined,\n writable: true,\n enumerable: true\n },\n jwt: {\n value: undefined,\n enumerable: true,\n writable: true\n },\n protocol: {\n value: (options && typeof options.protocol === 'string') ? options.protocol : 'websocket',\n enumerable: true\n },\n sdkVersion: {\n value: (typeof SDKVERSION === 'undefined') ? require('../package.json').version : SDKVERSION\n },\n volatile: {\n value: {},\n enumerable: true,\n writable: true\n }\n });\n\n if (options) {\n for (const opt of Object.keys(options)) {\n if (this.hasOwnProperty(opt) && Object.getOwnPropertyDescriptor(this, opt).writable) {\n this[opt] = options[opt];\n }\n }\n }\n\n // Forward the subscribe query to the network wrapper\n Object.defineProperty(this, 'subscribe', {\n value: function(room, opts, subscribeCB) {\n const\n object = {\n requestId: uuidv4(),\n controller: 'realtime',\n action: 'subscribe',\n index: room.collection.index,\n collection: room.collection.collection,\n volatile: this.volatile,\n body: room.filters,\n scope: room.scope,\n state: room.state,\n users: room.users\n },\n notificationCB = data => {\n if (data.type === 'TokenExpired') {\n this.unsetJwt();\n return this.emit('tokenExpired');\n }\n\n if (data.type === 'document') {\n const copy = Object.assign({}, data);\n copy.document = new Document(room.collection, data.result._id, data.result._source, data.result._meta);\n delete copy.result;\n return room.notify(copy);\n }\n\n room.notify(data);\n };\n\n if (this.jwt !== undefined) {\n object.jwt = this.jwt;\n }\n\n Object.assign(object.volatile, room.volatile, {sdkVersion: this.sdkVersion});\n\n this.network.subscribe(object, opts, notificationCB, subscribeCB);\n }\n });\n\n // Forward the unsubscribe query to the network wrapper\n Object.defineProperty(this, 'unsubscribe', {\n value: (room, unsubscribeCB) => {\n const\n object = {\n requestId: uuidv4(),\n controller: 'realtime',\n action: 'unsubscribe',\n volatile: this.volatile,\n body: {roomId: room.roomId}\n };\n\n if (this.jwt !== undefined) {\n object.jwt = this.jwt;\n }\n\n Object.assign(object.volatile, room.volatile, {sdkVersion: this.sdkVersion});\n\n this.network.unsubscribe(object, room.channel, unsubscribeCB);\n }\n });\n\n /**\n * Some methods (mainly read queries) require a callback function. This function exists to avoid repetition of code,\n * and is called by these methods\n */\n Object.defineProperty(this, 'callbackRequired', {\n value: (errorMessagePrefix, callback) => {\n if (!callback || typeof callback !== 'function') {\n throw new Error(`${errorMessagePrefix}: a callback argument is required for read queries`);\n }\n }\n });\n\n /**\n * Create an attribute security that embed all methods to manage Role, Profile and User\n */\n Object.defineProperty(this, 'security', {\n value: new Security(this),\n enumerable: true\n });\n\n Object.defineProperty(this, 'memoryStorage', {\n value: new MemoryStorage(this),\n enumerable: true\n });\n\n Object.defineProperty(this, 'collections',{\n value: {},\n writable: true\n });\n\n Object.defineProperty(this, 'eventTimeout',{\n value: options && typeof options.eventTimeout === 'number' ? options.eventTimeout : 200\n });\n\n Object.defineProperty(this, 'protectedEvents', {\n value: {\n connected: {timeout: this.eventTimeout},\n error: {timeout: this.eventTimeout},\n disconnected: {timeout: this.eventTimeout},\n reconnected: {timeout: this.eventTimeout},\n tokenExpired: {timeout: this.eventTimeout},\n loginAttempt: {timeout: this.eventTimeout}\n }\n });\n\n this.network = networkWrapper(this.protocol, host, options);\n\n // Properties related to the network layer\n // Accessing a property irrelevant for a given protocol\n // (e.g. \"autoReconnect\" for the HTTP layer) should\n // throw an exception\n Object.defineProperties(this, {\n autoQueue: {\n enumerable: true,\n get: () => this.network.autoQueue,\n set: value => {\n checkPropertyType('autoQueue', 'boolean', value);\n this.network.autoQueue = value;\n }\n },\n autoReconnect: {\n enumerable: true,\n get: () => this.network.autoReconnect\n },\n autoReplay: {\n enumerable: true,\n get: () => this.network.autoReplay,\n set: value => {\n checkPropertyType('autoReplay', 'boolean', value);\n this.network.autoReplay = value;\n }\n },\n host: {\n enumerable: true,\n get: () => this.network.host\n },\n offlineQueue: {\n enumerable: true,\n get: () => this.network.offlineQueue\n },\n offlineQueueLoader: {\n enumerable: true,\n get: () => this.network.offlineQueueLoader,\n set: value => {\n if (value !== null) {\n checkPropertyType('offlineQueueLoader', 'function', value);\n }\n this.network.offlineQueueLoader = value;\n }\n },\n port: {\n enumerable: true,\n get: () => this.network.port\n },\n queueFilter: {\n enumerable: true,\n get: () => this.network.queueFilter,\n set: value => {\n checkPropertyType('queueFilter', 'function', value);\n this.network.queueFilter = value;\n }\n },\n queueMaxSize: {\n enumerable: true,\n get: () => this.network.queueMaxSize,\n set: value => {\n checkPropertyType('queueMaxSize', 'number', value);\n this.network.queueMaxSize = value;\n }\n },\n queueTTL: {\n enumerable: true,\n get: () => this.network.queueTTL,\n set: value => {\n checkPropertyType('queueTTL', 'number', value);\n this.network.queueTTL = value;\n }\n },\n replayInterval: {\n enumerable: true,\n get: () => this.network.replayInterval,\n set: value => {\n checkPropertyType('replayInterval', 'number', value);\n this.network.replayInterval = value;\n }\n },\n reconnectionDelay: {\n enumerable: true,\n get: () => this.network.reconnectionDelay\n },\n sslConnection: {\n eumerable: true,\n get: () => this.network.ssl\n }\n });\n\n this.network.addListener('offlineQueuePush', data => this.emit('offlineQueuePush', data));\n this.network.addListener('offlineQueuePop', data => this.emit('offlineQueuePop', data));\n this.network.addListener('queryError', (err, query) => this.emit('queryError', err, query));\n\n this.network.addListener('tokenExpired', () => {\n this.unsetJwt();\n this.emit('tokenExpired');\n });\n\n if ((options && options.connect || 'auto') === 'auto') {\n this.connect();\n }\n\n if (this.bluebird) {\n return this.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n const whitelist = ['getAllStatistics', 'getServerInfo', 'getStatistics',\n 'listCollections', 'listIndexes', 'login', 'logout', 'now', 'query',\n 'checkToken', 'whoAmI', 'updateSelf', 'getMyRights', 'getMyCredentials',\n 'createMyCredentials', 'deleteMyCredentials', 'updateMyCredentials', 'validateMyCredentials',\n 'createIndex', 'refreshIndex', 'getAutoRefresh', 'setAutoRefresh'\n ];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n }\n\n /**\n * Emit an event to all registered listeners\n * An event cannot be emitted multiple times before a timeout has been reached.\n */\n emit (eventName, ...payload) {\n const\n now = Date.now(),\n protectedEvent = this.protectedEvents[eventName];\n\n if (protectedEvent) {\n if (protectedEvent.lastEmitted && protectedEvent.lastEmitted > now - protectedEvent.timeout) {\n return false;\n }\n protectedEvent.lastEmitted = now;\n }\n\n super.emit(eventName, ...payload);\n }\n\n\n /**\n * Connects to a Kuzzle instance using the provided host name.\n * @returns {Object} this\n */\n connect () {\n if (this.network.state !== 'offline') {\n if (this.connectCB) {\n this.connectCB(null, this);\n }\n return this;\n }\n\n this.network.connect();\n\n this.network.addListener('connect', () => {\n this.emit('connected');\n\n if (this.connectCB) {\n this.connectCB(null, this);\n }\n });\n\n this.network.addListener('networkError', error => {\n const connectionError = new Error(`Unable to connect to kuzzle proxy server at ${this.network.host}:${this.network.port}`);\n\n connectionError.internal = error;\n this.emit('networkError', connectionError);\n\n if (this.connectCB) {\n this.connectCB(connectionError);\n }\n });\n\n this.network.addListener('disconnect', () => {\n this.disconnect();\n this.emit('disconnected');\n });\n\n this.network.addListener('reconnect', () => {\n if (this.jwt) {\n this.checkToken(this.jwt, (err, res) => {\n // shouldn't obtain an error but let's invalidate the token anyway\n if (err || !res.valid) {\n this.unsetJwt();\n }\n\n this.emit('reconnected');\n });\n } else {\n this.emit('reconnected');\n }\n });\n\n this.network.on('discarded', data => this.emit('discarded', data));\n\n return this;\n }\n\n /**\n * Set the jwt used to query kuzzle\n * @param token\n * @returns {Kuzzle}\n */\n setJwt (token) {\n if (typeof token === 'string') {\n this.jwt = token;\n } else if (typeof token === 'object') {\n if (token.result && token.result.jwt && typeof token.result.jwt === 'string') {\n this.jwt = token.result.jwt;\n } else {\n this.emit('loginAttempt', {\n success: false,\n error: 'Cannot find a valid JWT in the following object: ' + JSON.stringify(token)\n });\n\n return this;\n }\n } else {\n this.emit('loginAttempt', {success: false, error: 'Invalid token argument: ' + token});\n return this;\n }\n\n this.emit('loginAttempt', {success: true});\n return this;\n }\n\n /**\n * Unset the jwt used to query kuzzle\n * @returns {Kuzzle}\n */\n unsetJwt () {\n this.jwt = undefined;\n return this;\n }\n\n /**\n * Get the jwt used by kuzzle\n * @returns {Kuzzle}\n */\n getJwt () {\n return this.jwt;\n }\n\n /**\n * Send login request to kuzzle with credentials\n * If login success, store the jwt into kuzzle object\n *\n * @param strategy\n * @param credentials\n * @param expiresIn\n * @param cb\n */\n login (strategy, ...args) {\n if (!strategy || typeof strategy !== 'string') {\n throw new Error('Kuzzle.login: strategy required');\n }\n\n const \n request = {\n strategy,\n body: {}\n };\n\n let cb = null;\n\n // Handle arguments (credentials, expiresIn, cb)\n if (args[0]) {\n if (typeof args[0] === 'object') {\n request.body = args[0];\n } else if (typeof args[0] === 'number' || typeof args[0] === 'string') {\n request.expiresIn = args[0];\n } else if (typeof args[0] === 'function') {\n cb = args[0];\n }\n }\n if (args[1]) {\n if (typeof args[1] === 'number' || typeof args[1] === 'string') {\n request.expiresIn = args[1];\n } else if (typeof args[1] === 'function') {\n cb = args[1];\n }\n }\n if (args[2] && typeof args[2] === 'function') {\n cb = args[2];\n }\n\n this.query({controller: 'auth', action: 'login'}, request, {queuable: false}, (error, response) => {\n if (!error) {\n if (response.result.jwt) {\n this.setJwt(response.result.jwt);\n }\n\n cb && cb(null, response.result);\n }\n else {\n cb && cb(error);\n this.emit('loginAttempt', {success: false, error: error.message});\n }\n });\n }\n\n /**\n * Create credentials of the specified for the current user.\n *\n * @param credentials\n * @param strategy\n * @param options\n * @param cb\n * @returns {Kuzzle}\n */\n createMyCredentials (strategy, credentials, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.query({controller: 'auth', action: 'createMyCredentials'}, {strategy, body: credentials}, options, (err, res) => {\n if (typeof cb === 'function') {\n cb(err, err ? undefined : res.result._source);\n }\n });\n\n return this;\n }\n\n /**\n * Delete credentials of the specified for the current user.\n *\n * @param strategy\n * @param options\n * @param cb\n * @returns {Kuzzle}\n */\n deleteMyCredentials (strategy, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.query({controller: 'auth', action: 'deleteMyCredentials'}, {strategy}, options, (err, res) => {\n if (typeof cb === 'function') {\n cb(err, err ? undefined : res.result);\n }\n });\n\n return this;\n }\n\n /**\n * Get credential information of the specified for the current user.\n *\n * @param strategy\n * @param options\n * @param cb\n */\n getMyCredentials (strategy, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.query({controller: 'auth', action: 'getMyCredentials'}, {strategy}, options, (err, res) => {\n if (typeof cb === 'function') {\n cb(err, err ? undefined : res.result);\n }\n });\n }\n\n /**\n * Update credentials of the specified for the current user.\n *\n * @param strategy\n * @param credentals\n * @param options\n * @param cb\n * @returns {Kuzzle}\n */\n updateMyCredentials (strategy, credentials, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.query({controller: 'auth', action: 'updateMyCredentials'}, {strategy, body: credentials}, options, (err, res) => {\n if (typeof cb === 'function') {\n cb(err, err ? undefined : res.result);\n }\n });\n\n return this;\n }\n\n /**\n * Validate credentials of the specified for the current user.\n *\n * @param strategy\n * @param credentials\n * @param options\n * @param cb\n */\n validateMyCredentials (strategy, credentials, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.query({controller: 'auth', action: 'validateMyCredentials'}, {strategy, body: credentials}, options, (err, res) => {\n if (typeof cb === 'function') {\n cb(err, err ? undefined : res.result);\n }\n });\n }\n\n /**\n * Create a kuzzle index\n *\n * @param {string} index\n * @param {object} [options]\n * @param {responseCallback} cb\n * @returns {Kuzzle}\n */\n createIndex (index, options, cb) {\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.createIndex: index required');\n }\n index = this.defaultIndex;\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.query({controller: 'index', action: 'create', index}, {}, options, (err, res) => {\n if (typeof cb === 'function') {\n cb(err, err ? undefined : res.result);\n }\n });\n\n return this;\n }\n\n /**\n * Send logout request to kuzzle with jwt.\n *\n * @param cb\n * @returns {Kuzzle}\n */\n logout (cb) {\n const\n request = {\n action: 'logout',\n controller: 'auth',\n requestId: uuidv4(),\n body: {}\n };\n\n this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, error => {\n if (typeof cb === 'function') {\n cb(error, this);\n }\n });\n\n return this.unsetJwt();\n }\n\n /**\n * Checks whether a given jwt token still represents a valid session in Kuzzle.\n *\n * @param {string} token The jwt token to check\n * @param {function} cb The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n */\n checkToken (token, cb) {\n const\n request = {\n body: {\n token\n }\n };\n\n this.callbackRequired('Kuzzle.checkToken', cb);\n\n this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, (err, res) => {\n cb(err, err ? undefined : res.result);\n });\n }\n\n /**\n * Fetches the current user.\n *\n * @param {function} cb The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n */\n whoAmI (cb) {\n this.callbackRequired('Kuzzle.whoAmI', cb);\n\n this.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, (err, res) => {\n cb(err, err ? undefined : new User(this.security, res.result._id, res.result._source, res.result._meta));\n });\n }\n\n /**\n * Gets the rights array of the currently logged user.\n *\n * @param {object} [options] - Optional parameters\n * @param {function} cb The callback containing the normalized array of rights.\n */\n getMyRights (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.getMyRights', cb);\n\n this.query({controller: 'auth', action:'getMyRights'}, {}, options, (err, res) => {\n cb(err, err ? undefined : res.result.hits);\n });\n }\n\n /**\n * Update current user in Kuzzle.\n *\n * @param {object} content - a plain javascript object representing the user's modification\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {Kuzzle} this object\n */\n updateSelf (content, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.query({controller: 'auth', action: 'updateSelf'}, {body: content}, options, (err, res) => {\n if (typeof cb === 'function') {\n cb(err, err ? undefined : res.result);\n }\n });\n\n return this;\n }\n\n /**\n * Adds a listener to a Kuzzle global event. When an event is fired, listeners are called in the order of their\n * insertion.\n *\n * @param {string} event - name of the global event to subscribe to\n * @param {function} listener - callback to invoke each time an event is fired\n */\n addListener (event, listener) {\n if (this.eventActions.indexOf(event) === -1) {\n throw new Error(`[${event}] is not a known event. Known events: ${this.eventActions.toString()}`);\n }\n\n return super.addListener(event, listener);\n }\n\n /**\n * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n * This method returns all available statistics from Kuzzle.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\n getAllStatistics (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.getAllStatistics', cb);\n\n this.query({controller:'server', action: 'getAllStats'}, {}, options, (err, res) => {\n cb(err, err ? undefined : res.result.hits);\n });\n }\n\n /**\n * Kuzzle monitors active connections, and ongoing/completed/failed requests.\n * This method allows getting either the last statistics frame, or a set of frames starting from a provided timestamp.\n *\n * @param {number} [timestamp] - Epoch time. Starting time from which the frames are to be retrieved\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\n getStatistics (timestamp, options, cb) {\n if (!cb) {\n if (!options) {\n cb = timestamp;\n options = null;\n timestamp = null;\n } else {\n cb = options;\n if (typeof timestamp === 'object') {\n options = timestamp;\n timestamp = null;\n } else {\n options = null;\n }\n }\n }\n\n this.callbackRequired('Kuzzle.getStatistics', cb);\n\n const \n queryCB = (err, res) => {\n if (err) {\n return cb(err);\n }\n\n cb(null, timestamp ? res.result.hits : [res.result]);\n },\n body = timestamp ? {body: {startTime: timestamp}} : {};\n\n this.query({controller: 'server', action: timestamp ? 'getStats' : 'getLastStats'}, body, options, queryCB);\n }\n\n /**\n * Create a new instance of a Collection object.\n * If no index is specified, takes the default index.\n *\n * @param {string} collection - The name of the data collection you want to manipulate\n * @param {string} [index] - The name of the data index containing the data collection\n * @returns {Collection} A Collection instance\n */\n collection (collection, index) {\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Unable to create a new data collection object: no index specified');\n }\n\n index = this.defaultIndex;\n }\n\n if (typeof index !== 'string' || typeof collection !== 'string') {\n throw new Error('Invalid index or collection argument: string expected');\n }\n\n if (!this.collections[index]) {\n this.collections[index] = {};\n }\n\n if (!this.collections[index][collection]) {\n this.collections[index][collection] = new Collection(this, collection, index);\n }\n\n return this.collections[index][collection];\n }\n\n /**\n * Empties the offline queue without replaying it.\n *\n * @returns {Kuzzle}\n */\n flushQueue () {\n this.network.flushQueue();\n return this;\n }\n\n /**\n * Returns the list of known persisted data collections.\n *\n * @param {string} [index] - Index containing collections to be listed\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\n listCollections (...args) {\n let\n index,\n options,\n cb;\n\n for (const arg of args) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n }\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.listCollections: index required');\n }\n\n index = this.defaultIndex;\n }\n\n this.callbackRequired('Kuzzle.listCollections', cb);\n\n const query = {type: options && options.type || 'all'};\n\n this.query({index, controller: 'collection', action: 'list'}, query, options, (err, res) => {\n cb(err, err ? undefined : res.result.collections);\n });\n }\n\n /**\n * Returns the list of existing indexes in Kuzzle\n *\n * @param {object} [options] - Optional arguments\n * @param {responseCallback} cb - Handles the query response\n */\n listIndexes (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.listIndexes', cb);\n\n this.query({controller: 'index', action: 'list'}, {}, options, (err, res) => {\n cb(err, err ? undefined : res.result.indexes);\n });\n }\n\n /**\n * Disconnects from Kuzzle and invalidate this instance.\n */\n disconnect () {\n this.network.close();\n\n for (const collection of Object.keys(this.collections)) {\n delete this.collections[collection];\n }\n }\n\n /**\n * Returns the server informations\n *\n * @param {object} [options] - Optional arguments\n * @param {responseCallback} cb - Handles the query response\n */\n getServerInfo (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.getServerInfo', cb);\n\n this.query({controller: 'server', action: 'info'}, {}, options, (err, res) => {\n cb(err, err ? undefined : res.result.serverInfo);\n });\n }\n\n /**\n * Forces an index refresh\n *\n * @param {string} index - The index to refresh. Defaults to Kuzzle.defaultIndex\n * @param {object} options - Optional arguments\n * @param {responseCallback} cb - Handles the query response\n * @returns {Kuzzle}\n */\n refreshIndex (...args) {\n let\n index,\n options,\n cb;\n\n for (const arg of args) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n }\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.refreshIndex: index required');\n }\n index = this.defaultIndex;\n }\n\n this.query({index, controller: 'index', action: 'refresh'}, {}, options, cb);\n\n return this;\n }\n\n /**\n * Returns de current autoRefresh status for the given index\n *\n * @param {string} index - The index to get the status from. Defaults to Kuzzle.defaultIndex\n * @param {object} options - Optinal arguments\n * @param {responseCallback} cb - Handles the query response\n */\n getAutoRefresh (...args) {\n let\n index,\n options,\n cb;\n\n for (const arg of args) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n }\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.getAutoRefresh: index required');\n }\n index = this.defaultIndex;\n }\n\n this.callbackRequired('Kuzzle.getAutoRefresh', cb);\n this.query({index, controller: 'index', action: 'getAutoRefresh'}, {}, options, cb);\n }\n\n /**\n * (Un)Sets the autoRefresh flag on the given index\n *\n * @param {string} index - the index to modify. Defaults to Kuzzle.defaultIndex\n * @param {boolean} autoRefresh - The autoRefresh value to set\n * @param {object} options - Optional arguments\n * @param {responseCallback} cb - Handles the query result\n * @returns {object} this\n */\n setAutoRefresh (...args) {\n var\n index,\n autoRefresh,\n options,\n cb;\n\n for (const arg of args) {\n switch (typeof arg) {\n case 'string':\n index = arg;\n break;\n case 'boolean':\n autoRefresh = arg;\n break;\n case 'object':\n options = arg;\n break;\n case 'function':\n cb = arg;\n break;\n }\n }\n\n if (!index) {\n if (!this.defaultIndex) {\n throw new Error('Kuzzle.setAutoRefresh: index required');\n }\n index = this.defaultIndex;\n }\n\n if (autoRefresh === undefined) {\n throw new Error('Kuzzle.setAutoRefresh: autoRefresh value is required');\n }\n\n this.query({index, controller: 'index', action: 'setAutoRefresh'}, {body: {autoRefresh}}, options, cb);\n\n return this;\n }\n\n /**\n * Return the current Kuzzle's UTC Epoch time, in milliseconds\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\n now (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.callbackRequired('Kuzzle.now', cb);\n\n this.query({controller: 'server', action: 'now'}, {}, options, (err, res) => {\n cb(err, err ? undefined : res.result.now);\n });\n }\n\n /**\n * This is a low-level method, exposed to allow advanced SDK users to bypass high-level methods.\n * Base method used to send read queries to Kuzzle\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} queryArgs - Query configuration\n * @param {object} query - The query data\n * @param {object} [options] - Optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\n query (queryArgs, query, options, cb) {\n const\n object = {\n action: queryArgs.action,\n controller: queryArgs.controller,\n volatile: this.volatile\n };\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n } else if (!cb && !options && typeof query === 'function') {\n cb = query;\n query = {};\n options = null;\n }\n\n if (options) {\n for (const prop of ['refresh', 'from', 'size', 'scroll', 'scrollId']) {\n if (options[prop] !== undefined) {\n object[prop] = options[prop];\n }\n }\n\n if (options.volatile && typeof options.volatile === 'object') {\n Object.assign(object.volatile, options.volatile);\n }\n }\n\n if (!query || typeof query !== 'object' || Array.isArray(query)) {\n throw new Error('Invalid query parameter: ' + query);\n }\n\n Object.assign(object.volatile, query.volatile, {sdkVersion: this.sdkVersion});\n\n for (const attr of Object.keys(query)) {\n if (attr !== 'volatile') {\n object[attr] = query[attr];\n }\n }\n\n /*\n * Do not add the token for the checkToken route, to avoid getting a token error when\n * a developer simply wish to verify his token\n */\n if (this.jwt !== undefined && !(object.controller === 'auth' && object.action === 'checkToken')) {\n object.jwt = this.jwt;\n }\n\n if (queryArgs.collection) {\n object.collection = queryArgs.collection;\n }\n\n if (queryArgs.index) {\n object.index = queryArgs.index;\n }\n\n if (!object.requestId) {\n object.requestId = uuidv4();\n }\n\n this.network.query(object, options, cb);\n\n return this;\n }\n\n /**\n * Starts the requests queuing.\n */\n startQueuing () {\n this.network.startQueuing();\n return this;\n }\n\n /**\n * Stops the requests queuing.\n */\n stopQueuing () {\n this.network.stopQueuing();\n return this;\n }\n\n /**\n * @DEPRECATED\n * See Kuzzle.prototype.playQueue();\n */\n replayQueue () {\n return this.playQueue();\n }\n\n /**\n * Plays the requests queued during offline mode.\n */\n playQueue () {\n this.network.playQueue();\n return this;\n }\n\n /**\n * Sets the default Kuzzle index\n *\n * @param index\n * @returns this\n */\n setDefaultIndex (index) {\n if (typeof index !== 'string') {\n throw new Error(`Invalid default index: [${index}] (an index name is expected)`);\n }\n\n if (index.length === 0) {\n throw new Error('Cannot set an empty index as the default index');\n }\n\n this.defaultIndex = index;\n\n return this;\n }\n}\n\nfunction checkPropertyType(prop, typestr, value) {\n const wrongType = typestr === 'array' ? !Array.isArray(value) : typeof value !== typestr;\n\n if (wrongType) {\n throw new Error(`Can only assign a ${typestr} value to property \"${prop}\"`);\n }\n}\n\nmodule.exports = Kuzzle;\n\n\n\n// WEBPACK FOOTER //\n// ./src/Kuzzle.js","class Listener {\n constructor(fn, once = false) {\n this.fn = fn;\n this.once = once;\n }\n}\n\nclass KuzzleEventEmitter {\n constructor() {\n this._events = {};\n }\n\n _exists (listeners, fn) {\n return Boolean(listeners.find(listener => listener.fn === fn));\n }\n\n listeners (eventName) {\n if (this._events[eventName] === undefined) {\n return [];\n }\n\n return this._events[eventName].map(listener => listener.fn);\n }\n\n addListener (eventName, listener, once = false) {\n if (!eventName || !listener) {\n return this;\n }\n\n const listenerType = typeof listener;\n\n if (listenerType !== 'function') {\n throw new Error(`Invalid listener type: expected a function, got a ${listenerType}`);\n }\n\n if (this._events[eventName] === undefined) {\n this._events[eventName] = [];\n }\n\n if (!this._exists(this._events[eventName], listener)) {\n this._events[eventName].push(new Listener(listener, once));\n }\n\n return this;\n }\n\n on (eventName, listener) {\n return this.addListener(eventName, listener);\n }\n\n prependListener (eventName, listener, once = false) {\n if (!eventName || !listener) {\n return this;\n }\n\n if (this._events[eventName] === undefined) {\n this._events[eventName] = [];\n }\n\n if (!this._exists(this._events[eventName], listener)) {\n this._events[eventName] = [new Listener(listener, once)].concat(this._events[eventName]);\n }\n\n return this;\n }\n\n addOnceListener (eventName, listener) {\n return this.addListener(eventName, listener, true);\n }\n\n once (eventName, listener) {\n return this.addOnceListener(eventName, listener);\n }\n\n prependOnceListener (eventName, listener) {\n return this.prependListener(eventName, listener, true);\n }\n\n removeListener (eventName, listener) {\n const listeners = this._events[eventName];\n\n if (!listeners || !listeners.length) {\n return this;\n }\n\n const index = listeners.findIndex(l => l.fn === listener);\n\n if (index !== -1) {\n listeners.splice(index, 1);\n }\n\n if (listeners.length === 0) {\n delete this._events[eventName];\n }\n\n return this;\n }\n\n removeAllListeners (eventName) {\n if (eventName) {\n delete this._events[eventName];\n } else {\n this._events = {};\n }\n\n return this;\n }\n\n emit (eventName, ...payload) {\n const listeners = this._events[eventName];\n\n if (listeners === undefined) {\n return false;\n }\n\n const onceListeners = [];\n\n for (const listener of listeners) {\n listener.fn(...payload);\n\n if (listener.once) {\n onceListeners.push(listener.fn);\n }\n }\n\n for (const toDelete of onceListeners) {\n this.removeListener(eventName, toDelete);\n }\n\n return true;\n }\n\n eventNames () {\n return Object.keys(this._events);\n }\n\n listenerCount (eventName) {\n return this._events[eventName] && this._events[eventName].length || 0;\n }\n}\n\nmodule.exports = KuzzleEventEmitter;\n\n\n\n// WEBPACK FOOTER //\n// ./src/eventEmitter/index.js","function SecurityDocument(Security, id, content, meta) {\n\n if (!id) {\n throw new Error('A security document must have an id');\n }\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n kuzzle: {\n value: Security.kuzzle\n },\n Security: {\n value: Security\n },\n // read-only properties\n // writable properties\n id: {\n value: id,\n enumerable: true\n },\n content: {\n value: {},\n writable: true,\n enumerable: true\n },\n meta: {\n value: meta || {},\n writable: true,\n enumerable: true\n }\n });\n\n if (content) {\n this.setContent(content, true);\n }\n\n // promisifying\n if (Security.kuzzle.bluebird) {\n return Security.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['delete', 'update'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n}\n\n/**\n * Replaces the current content with new data.\n * Changes made by this function won’t be applied until the save method is called.\n *\n * @param {Object} data - New securityDocument content\n * @return {SecurityDocument} this\n */\nSecurityDocument.prototype.setContent = function (data) {\n this.content = data;\n return this;\n};\n\n/**\n * Serialize this object into a pojo\n *\n * @return {object} pojo representing this securityDocument\n */\nSecurityDocument.prototype.serialize = function () {\n var\n data = {};\n\n if (this.id) {\n data._id = this.id;\n }\n\n data.body = this.content;\n data.meta = this.meta;\n\n return data;\n};\n\n/**\n * Delete the current KuzzleSecurityDocument into Kuzzle.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n */\nSecurityDocument.prototype.delete = function (options, cb) {\n var\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.Security.buildQueryArgs(this.deleteActionName), {_id: this.id}, options, function (error, res) {\n if (error) {\n return cb ? cb(error) : false;\n }\n\n if (cb) {\n cb(null, res.result._id);\n }\n });\n};\n\n/**\n * Update the current KuzzleSecurityDocument into Kuzzle.\n *\n * @param {object} content - Content to add to KuzzleSecurityDocument\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {SecurityDocument} this\n */\nSecurityDocument.prototype.update = function (content, options, cb) {\n var\n data = {},\n self = this;\n\n if (typeof content !== 'object') {\n throw new Error('Parameter \"content\" must be a object');\n }\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = self.id;\n data.body = content;\n\n self.kuzzle.query(this.Security.buildQueryArgs(this.updateActionName), data, options, function (error, response) {\n if (error) {\n return cb ? cb(error) : false;\n }\n\n self.setContent(response.result._source);\n\n if (cb) {\n cb(null, self);\n }\n });\n\n return this;\n};\n\nmodule.exports = SecurityDocument;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/security/SecurityDocument.js\n// module id = 2\n// module chunks = 0","'use strict';\n\nconst\n KuzzleEventEmitter = require('../../../eventEmitter');\n\nclass RTWrapper extends KuzzleEventEmitter {\n\n constructor (host, options) {\n super();\n\n Object.defineProperties(this, {\n cleanHistoryTimer: {\n value: null,\n writable: true\n },\n host: {\n value: host,\n enumerable: true\n },\n port: {\n value: (options && typeof options.port === 'number') ? options.port : 7512,\n enumerable: true\n },\n ssl: {\n value: (options && typeof options.sslConnection === 'boolean') ? options.sslConnection : false,\n enumerable: true\n },\n queuing: {\n value: false,\n writable: true\n },\n reconnectionDelay: {\n value: (options && typeof options.reconnectionDelay === 'number') ? options.reconnectionDelay : 1000,\n enumerable: true\n },\n // configuration properties\n autoReconnect: {\n value: (options && typeof options.autoReconnect === 'boolean') ? options.autoReconnect : true,\n enumerable: true\n },\n autoQueue: {\n value: false,\n enumerable: true,\n writable: true\n },\n autoReplay: {\n value: false,\n enumerable: true,\n writable: true\n },\n state: {\n value: 'offline',\n enumerable: true,\n writable: true\n },\n /*\n Offline queue use the following format:\n [\n {\n ts: ,\n query: 'query',\n cb: callbackFunction\n }\n ]\n */\n offlineQueue: {\n value: [],\n enumerable: true,\n writable: true\n },\n queueFilter: {\n value: null,\n enumerable: true,\n writable: true\n },\n queueMaxSize: {\n value: 500,\n enumerable: true,\n writable: true\n },\n queueTTL: {\n value: 120000,\n enumerable: true,\n writable: true\n },\n replayInterval: {\n value: 10,\n enumerable: true,\n writable: true\n },\n offlineQueueLoader: {\n value: null,\n enumerable: true,\n writable: true\n }\n });\n\n if (options) {\n Object.keys(options).forEach(opt => {\n if (this.hasOwnProperty(opt) && Object.getOwnPropertyDescriptor(this, opt).writable) {\n this[opt] = options[opt];\n }\n });\n\n if (options.offlineMode === 'auto' && this.autoReconnect) {\n this.autoQueue = this.autoReplay = true;\n }\n }\n\n Object.defineProperty(this, 'requestHistory', {\n value: {},\n writable: true\n });\n\n this.wasConnected = false;\n this.stopRetryingToConnect = false;\n this.retrying = false;\n }\n\n connect() {\n this.state = 'connecting';\n if (this.autoQueue) {\n this.startQueuing();\n }\n }\n\n /**\n * Called when the client's connection is established\n */\n clientConnected() {\n this.state = 'connected';\n this.emit(this.wasConnected && 'reconnect' || 'connect');\n this.wasConnected = true;\n this.stopRetryingToConnect = false;\n\n if (this.autoQueue) {\n this.stopQueuing();\n }\n\n if (this.autoReplay) {\n this.playQueue();\n }\n\n if (!this.cleanHistoryTimer) {\n this.cleanHistoryTimer = setInterval(() => { \n cleanHistory(this.requestHistory); \n }, 1000);\n }\n }\n\n /**\n * Called when the client's connection is closed\n */\n clientDisconnected() {\n this.state = 'offline';\n if (this.autoQueue) {\n this.startQueuing();\n }\n\n this.clearHistoryTimer();\n this.emit('disconnect');\n }\n\n /**\n * Called when the client's connection is closed with an error state\n *\n * @param {Error} error\n */\n clientNetworkError(error) {\n this.state = 'offline';\n if (this.autoQueue) {\n this.startQueuing();\n }\n\n this.clearHistoryTimer();\n\n this.emit('networkError', error);\n if (this.autoReconnect && !this.retrying && !this.stopRetryingToConnect) {\n this.retrying = true;\n setTimeout(() => {\n this.retrying = false;\n this.connect(this.host);\n }, this.reconnectionDelay);\n } else {\n this.emit('disconnect');\n }\n }\n\n /**\n * Empties the offline queue without replaying it.\n */\n flushQueue() {\n this.offlineQueue = [];\n }\n\n /**\n * Replays the requests queued during offline mode.\n */\n playQueue() {\n if (this.state === 'connected') {\n cleanQueue(this);\n dequeue(this);\n }\n }\n\n /**\n * Starts the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n */\n startQueuing() {\n this.queuing = true;\n }\n\n /**\n * Stops the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.\n */\n stopQueuing() {\n this.queuing = false;\n }\n\n subscribe(object, options, notificationCB, cb) {\n if (this.state !== 'connected') {\n return cb(new Error('Not Connected'));\n }\n this.query(object, options, (error, response) => {\n if (error) {\n return cb(error);\n }\n this.on(response.result.channel, data => {\n data.fromSelf = this.requestHistory[data.requestId] !== undefined;\n notificationCB(data);\n });\n cb(null, response.result);\n });\n }\n\n unsubscribe(object, channel, cb) {\n this.removeAllListeners(channel);\n this.query(object, null, (err, res) => {\n if (cb) {\n cb(err, err ? undefined : res.result);\n }\n });\n }\n\n query(object, options, cb) {\n let queuable = options && (options.queuable !== false) || true;\n\n if (this.queueFilter) {\n queuable = queuable && this.queueFilter(object);\n }\n\n if (this.queuing && queuable) {\n cleanQueue(this, object, cb);\n this.emit('offlineQueuePush', {query: object, cb: cb});\n return this.offlineQueue.push({ts: Date.now(), query: object, cb: cb});\n }\n\n if (this.state === 'connected') {\n return emitRequest(this, object, cb);\n }\n\n return discardRequest(object, cb);\n }\n\n clearHistoryTimer() {\n if (this.cleanHistoryTimer) {\n clearInterval(this.cleanHistoryTimer);\n this.cleanHistoryTimer = null;\n }\n }\n}\n/**\n * Emit a request to Kuzzle\n *\n * @param {RTWrapper} network\n * @param {object} request\n * @param {responseCallback} [cb]\n */\nfunction emitRequest (network, request, cb) {\n if (request.jwt !== undefined || cb) {\n network.once(request.requestId, response => {\n let error = null;\n\n if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n network.emit('tokenExpired', request, cb);\n }\n\n if (response.error) {\n error = new Error(response.error.message);\n Object.assign(error, response.error);\n error.status = response.status;\n network.emit('queryError', error, request, cb);\n }\n\n if (cb) {\n cb(error, response);\n }\n });\n }\n // Track requests made to allow Room.subscribeToSelf to work\n network.requestHistory[request.requestId] = Date.now();\n network.send(request);\n}\n\nfunction discardRequest(object, cb) {\n if (cb) {\n cb(new Error('Unable to execute request: not connected to a Kuzzle server.\\nDiscarded request: ' + JSON.stringify(object)));\n }\n}\n\n/**\n * Clean up the queue, ensuring the queryTTL and queryMaxSize properties are respected\n * @param {RTWrapper} network\n */\nfunction cleanQueue (network) {\n const now = Date.now();\n let lastDocumentIndex = -1;\n\n if (network.queueTTL > 0) {\n network.offlineQueue.forEach((query, index) => {\n if (query.ts < now - network.queueTTL) {\n lastDocumentIndex = index;\n }\n });\n\n if (lastDocumentIndex !== -1) {\n network.offlineQueue\n .splice(0, lastDocumentIndex + 1)\n .forEach(droppedRequest => {\n network.emit('offlineQueuePop', droppedRequest.query);\n });\n }\n }\n\n if (network.queueMaxSize > 0 && network.offlineQueue.length > network.queueMaxSize) {\n network.offlineQueue\n .splice(0, network.offlineQueue.length - network.queueMaxSize)\n .forEach(droppedRequest => {\n network.emit('offlineQueuePop', droppedRequest.query);\n });\n }\n}\n\n/**\n * Play all queued requests, in order.\n */\nfunction dequeue (network) {\n const\n uniqueQueue = {},\n dequeuingProcess = () => {\n if (network.offlineQueue.length > 0) {\n emitRequest(network, network.offlineQueue[0].query, network.offlineQueue[0].cb);\n network.emit('offlineQueuePop', network.offlineQueue.shift());\n\n setTimeout(() => {\n dequeuingProcess();\n }, Math.max(0, network.replayInterval));\n }\n };\n\n if (network.offlineQueueLoader) {\n if (typeof network.offlineQueueLoader !== 'function') {\n throw new Error('Invalid value for offlineQueueLoader property. Expected: function. Got: ' + typeof network.offlineQueueLoader);\n }\n\n const additionalQueue = network.offlineQueueLoader();\n if (Array.isArray(additionalQueue)) {\n network.offlineQueue = additionalQueue\n .concat(network.offlineQueue)\n .filter(request => {\n // throws if the query object does not contain required attributes\n if (!request.query || request.query.requestId === undefined || !request.query.action || !request.query.controller) {\n throw new Error('Invalid offline queue request. One or more missing properties: requestId, action, controller.');\n }\n\n return uniqueQueue.hasOwnProperty(request.query.requestId) ? false : (uniqueQueue[request.query.requestId] = true);\n });\n } else {\n throw new Error('Invalid value returned by the offlineQueueLoader function. Expected: array. Got: ' + typeof additionalQueue);\n }\n }\n\n dequeuingProcess();\n}\n\n/**\n * Clean history from requests made more than 10s ago\n */\nfunction cleanHistory (requestHistory) {\n var\n now = Date.now();\n\n Object.keys(requestHistory).forEach(function (key) {\n if (requestHistory[key] < now - 10000) {\n delete requestHistory[key];\n }\n });\n}\n\nmodule.exports = RTWrapper;\n\n\n\n// WEBPACK FOOTER //\n// ./src/networkWrapper/protocols/abstract/realtime.js","/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n/**\n * Kuzzle handles documents either as realtime messages or as stored documents.\n * Document is the object representation of one of these documents.\n *\n * Notes:\n * - this constructor may be called either with a documentId, a content, neither or both.\n * - providing a documentID to the constructor will automatically call refresh, unless a content is also provided\n *\n *\n * @param {Collection} collection - an instanciated Collection object\n * @param {string} [documentId] - ID of an existing document\n * @param {object} [content] - Initializes this document with the provided content\n * @param {object} [meta] - Initializes this document with the provided meta\n * @constructor\n */\nfunction Document(collection, documentId, content, meta) {\n Object.defineProperties(this, {\n // read-only properties\n collection: {\n value: collection.collection,\n enumerable: true\n },\n dataCollection: {\n value: collection,\n enumerable: false\n },\n kuzzle: {\n value: collection.kuzzle,\n enumerable: false\n },\n // writable properties\n id: {\n value: undefined,\n enumerable: true,\n writable: true\n },\n content: {\n value: {},\n writable: true,\n enumerable: true\n },\n version: {\n value: undefined,\n enumerable: true,\n writable: true\n },\n meta: {\n value: meta || {},\n enumerable: true,\n writable: false\n }\n });\n\n // handling provided arguments\n if (!content && documentId && typeof documentId === 'object') {\n content = documentId;\n documentId = null;\n }\n\n if (content) {\n if (content._version) {\n this.version = content._version;\n delete content._version;\n }\n this.setContent(content, true);\n }\n\n if (documentId) {\n Object.defineProperty(this, 'id', {\n value: documentId,\n enumerable: true\n });\n }\n\n // promisifying\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['delete', 'refresh', 'save'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * Serialize this object into a JSON object\n *\n * @return {object} JSON object representing this document\n */\nDocument.prototype.serialize = function () {\n var\n data = {};\n\n if (this.id) {\n data._id = this.id;\n }\n\n if (this.version) {\n data._version = this.version;\n }\n\n data.body = this.content;\n data.meta = this.meta;\n\n return data;\n};\n\n/**\n * Overrides the toString() method in order to return a serialized version of the document\n *\n * @return {string} serialized version of this object\n */\nDocument.prototype.toString = function () {\n return JSON.stringify(this.serialize());\n};\n\n/**\n * Deletes this document in Kuzzle.\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nDocument.prototype.delete = function (options, cb) {\n var self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!self.id) {\n throw new Error('Document.delete: cannot delete a document without a document ID');\n }\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('document', 'delete'), this.serialize(), options, cb && function (err) {\n cb(err, err ? undefined : self.id);\n });\n};\n\n/**\n * Checks if this document exists in Kuzzle.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nDocument.prototype.exists = function (options, cb) {\n var self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!self.id) {\n throw new Error('Document.exists: cannot check if the document exists if no id has been provided');\n }\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('document', 'exists'), this.serialize(), options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n};\n\n/**\n * Replaces the current content with the last version of this document stored in Kuzzle.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nDocument.prototype.refresh = function (options, cb) {\n var self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!self.id) {\n throw new Error('Document.refresh: cannot retrieve a document if no ID has been provided');\n }\n\n this.kuzzle.callbackRequired('Document.refresh', cb);\n\n self.kuzzle.query(self.dataCollection.buildQueryArgs('document', 'get'), {_id: self.id}, options, function (error, res) {\n var newDocument;\n\n if (error) {\n return cb(error);\n }\n\n newDocument = new Document(self.dataCollection, self.id, res.result._source, res.result._meta);\n newDocument.version = res.result._version;\n\n cb(null, newDocument);\n });\n};\n\n/**\n * Saves this document into Kuzzle.\n *\n * If this is a new document, this function will create it in Kuzzle and the id property will be made available.\n * Otherwise, this method will replace the latest version of this document in Kuzzle by the current content\n * of this object.\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nDocument.prototype.save = function (options, cb) {\n var\n data = this.serialize(),\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.dataCollection.buildQueryArgs('document', 'createOrReplace'), data, options, function (error, res) {\n if (error) {\n return cb && cb(error);\n }\n\n self.id = res.result._id;\n self.version = res.result._version;\n\n if (cb) {\n cb(null, self);\n }\n });\n\n return self;\n};\n\n/**\n * Sends the content of this document as a realtime message.\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @returns {*} this\n */\nDocument.prototype.publish = function (options) {\n var data = this.serialize();\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('realtime', 'publish'), data, options);\n\n return this;\n};\n\n/**\n * Replaces the current content with new data.\n * Changes made by this function won’t be applied until the save method is called.\n *\n * @param {object} data - New content\n * @param {boolean} replace - if true: replace this document content with the provided data\n */\nDocument.prototype.setContent = function (data, replace) {\n var self = this;\n\n if (replace) {\n this.content = data;\n }\n else {\n Object.keys(data).forEach(function (key) {\n self.content[key] = data[key];\n });\n }\n\n return this;\n};\n\n/**\n * Listens to events concerning this document. Has no effect if the document does not have an ID\n * (i.e. if the document has not yet been created as a persisted document).\n *\n * @param {object} [options] - subscription options\n * @param {responseCallback} cb - callback that will be called each time a change has been detected on this document\n */\nDocument.prototype.subscribe = function (options, cb) {\n var filters;\n\n if (options && !cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('Document.subscribe', cb);\n\n if (!this.id) {\n throw new Error('Document.subscribe: cannot subscribe to a document if no ID has been provided');\n }\n\n filters = { ids: { values: [this.id] } };\n\n return this.dataCollection.subscribe(filters, options, cb);\n};\n\nmodule.exports = Document;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/Document.js\n// module id = 4\n// module chunks = 0","var\n KuzzleSecurityDocument = require('./SecurityDocument');\n\n/**\n * @param {Security} Security\n * @param {string} id\n * @param {Object} content\n * @constructor\n */\nfunction User(Security, id, content, meta) {\n KuzzleSecurityDocument.call(this, Security, id, content, meta);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteUser'\n },\n updateActionName: {\n value: 'updateUser'\n },\n credentials: {\n value: {},\n writable: true,\n enumerable: true\n }\n });\n\n // promisifying\n if (Security.kuzzle.bluebird) {\n return Security.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['create', 'replace', 'saveRestricted', 'update', 'getProfiles'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n}\n\nUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: User\n }\n});\n\n/**\n * Set profiles in content\n * @param {array} profileIds - an array of profiles ids string\n *\n * @returns {User} this\n */\nUser.prototype.setProfiles = function (profileIds) {\n if (!Array.isArray(profileIds) || typeof profileIds[0] !== 'string') {\n throw new Error('Parameter \"profileIds\" must be an array of strings');\n }\n\n this.content.profileIds = profileIds;\n\n return this;\n};\n\n/**\n * @param {object} credentials\n */\nUser.prototype.setCredentials = function (credentials) {\n if (typeof credentials !== 'object') {\n throw new Error('Parameter \"credentials\" must be a object');\n }\n\n this.credentials = credentials;\n\n return this;\n};\n\n/**\n * Add a profile\n * @param {string} profileId - a profile ids string\n *\n * @returns {User} this\n */\nUser.prototype.addProfile = function (profileId) {\n if (typeof profileId !== 'string') {\n throw new Error('Parameter \"profileId\" must be a string');\n }\n\n if (!this.content.profileIds) {\n this.content.profileIds = [];\n }\n\n if (this.content.profileIds.indexOf(profileId) === -1) {\n this.content.profileIds.push(profileId);\n }\n\n return this;\n};\n\n/**\n * Creates this user into Kuzzle\n *\n * @param {object|responseCallback} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {User} this\n */\nUser.prototype.create = function (options, cb) {\n var\n data = this.creationSerialize(),\n self = this;\n\n if (!this.content.profileIds) {\n throw new Error('Argument \"profileIds\" is mandatory in a user. This argument contains an array of profile identifiers.');\n }\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.Security.buildQueryArgs('createUser'), data, null, cb && function (err) {\n cb(err, err ? undefined : self);\n });\n\n return this;\n};\n\n\n/**\n * Replaces the latest version of this user in Kuzzle by the current content of this object.\n *\n * @param {object|responseCallback} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {User} this\n */\nUser.prototype.replace = function (options, cb) {\n var\n data = this.serialize(),\n self = this;\n\n if (!this.content.profileIds) {\n throw new Error('Argument \"profileIds\" is mandatory in a user. This argument contains an array of profile identifiers.');\n }\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n\n this.kuzzle.query(this.Security.buildQueryArgs('replaceUser'), data, null, cb && function (err) {\n cb(err, err ? undefined : self);\n });\n\n return this;\n};\n\n/**\n * Saves this user as restricted into Kuzzle.\n *\n * This function will create a new user. It is not usable to update an existing user.\n * The \"profileIds\" property must not be provided, or the request will be rejected by Kuzzle.\n * This function allows anonymous users to create a \"restricted\" user with predefined rights.\n *\n * @param {object|responseCallback} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {User} this\n */\nUser.prototype.saveRestricted = function (options, cb) {\n var\n data = this.serialize(),\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.Security.buildQueryArgs('createRestrictedUser'), data, options, cb && function (error) {\n cb(error, error ? undefined : self);\n });\n\n return self;\n};\n\n/**\n * Serialize this object into a JSON object\n *\n * @return {object} JSON object representing this User\n */\nUser.prototype.serialize = function () {\n return {_id: this.id, body: this.content, meta: this.meta};\n};\n\n/**\n * Serialize this object into a JSON object\n *\n * @return {object} JSON object representing this User\n */\nUser.prototype.creationSerialize = function () {\n return {_id: this.id, body: {content: this.content, credentials: this.credentials, meta: this.meta}};\n};\n\n/**\n * Return the associated profiles IDs\n *\n * @return {array.} the associated profiles IDs\n */\nUser.prototype.getProfileIds = function () {\n return this.content.profileIds || [];\n};\n\n/**\n * Return the associated Profile objects\n *\n * @param {object|responseCallback} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nUser.prototype.getProfiles = function (options, cb) {\n var \n self = this,\n fetchedProfiles = [],\n errored = false;\n\n if (options && !cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.Security.kuzzle.callbackRequired('User.getProfiles', cb);\n\n if (!self.content.profileIds) {\n return cb(null, fetchedProfiles);\n }\n\n self.content.profileIds.forEach(function (profileId) {\n self.Security.fetchProfile(profileId, options, function (error, profile) {\n if (error) {\n if (errored) {\n return;\n }\n\n errored = true; // prevents multiple callback resolutions\n return cb(error);\n }\n\n fetchedProfiles.push(profile);\n\n if (fetchedProfiles.length === self.content.profileIds.length) {\n cb(null, fetchedProfiles);\n }\n });\n });\n};\n\nmodule.exports = User;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/security/User.js\n// module id = 5\n// module chunks = 0","'use strict';\n\nconst\n KuzzleEventEmitter = require('./eventEmitter');\n\n/**\n * This object is the result of a subscription request, allowing to manipulate the subscription itself.\n *\n * In Kuzzle, you don’t exactly subscribe to a room or a topic but, instead, you subscribe to documents.\n *\n * What it means is that, to subscribe, you provide to Kuzzle a set of matching filters.\n * Once you have subscribed, if a pub/sub message is published matching your filters, or if a matching stored\n * document change (because it is created, updated or deleted), then you’ll receive a notification about it.\n *\n */\nclass Room extends KuzzleEventEmitter {\n /*\n * @constructor\n * @param {object} collection - an instantiated and valid kuzzle object\n * @param {object} [filters] - Filters in Kuzzle DSL format\n * @param {object} [options] - subscription optional configuration\n */\n constructor(collection, filters, options) {\n super();\n\n let _roomId = null;\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n roomstate: {\n // Values can be: inactive, subscribing, active\n value: 'inactive',\n writable: true\n },\n kuzzle: {\n value: collection.kuzzle\n },\n isListening: {\n value: false,\n writable: true\n },\n //listeners\n resubscribe: {\n value: () => {\n this.roomstate = 'inactive';\n this.error = null;\n this.subscribe();\n }\n },\n deactivate: {\n value: () => {\n this.roomstate = 'inactive';\n }\n },\n resubscribeConditional: {\n value: () => {\n this.roomstate = 'inactive';\n \n if (this.autoResubscribe) {\n this.subscribe();\n }\n }\n },\n //enumerables\n channel: {\n value: null,\n writable: true,\n enumerable: true\n },\n scope: {\n value: options && options.scope ? options.scope : 'all',\n enumerable: true\n },\n state: {\n value: options && options.state ? options.state : 'done',\n enumerable: true\n },\n users: {\n value: options && options.users ? options.users : 'none',\n enumerable: true\n },\n // read-only properties\n collection: {\n value: collection,\n enumerable: true\n },\n filters: {\n value: filters ? filters : {},\n enumerable: true,\n },\n roomId: {\n enumerable: true,\n get: () => _roomId,\n set: value => {\n if (!_roomId) {\n _roomId = value;\n }\n }\n },\n // writable properties\n volatile: {\n value: (options && options.volatile) ? options.volatile : {},\n enumerable: true,\n writable: true\n },\n subscribeToSelf: {\n value: options && typeof options.subscribeToSelf === 'boolean' ? options.subscribeToSelf : true,\n enumerable: true,\n writable: true\n },\n autoResubscribe: {\n value: options && typeof options.autoResubscribe === 'boolean' ? options.autoResubscribe : collection.kuzzle.autoResubscribe,\n enumerable: true\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n const whitelist = ['count', 'subscribe', 'unsubscribe', 'onDone'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n }\n\n /**\n * Returns the number of other subscriptions on that room.\n *\n * @param {responseCallback} cb - Handles the query response\n */\n count(cb) {\n this.kuzzle.callbackRequired('Room.count', cb);\n\n const data = {body: {roomId: this.roomId}};\n\n if (this.roomstate !== 'active') {\n return cb(new Error('Cannot count subscriptions on an non-active room'));\n }\n\n this.kuzzle.query(this.collection.buildQueryArgs('realtime', 'count'), data, function (err, res) {\n cb(err, res && res.result.count);\n });\n }\n\n /**\n * Subscribes to Kuzzle \n * (do nothing if a subscription is active or underway)\n * \n * @param options\n * @param {responseCallback} cb - called when the subscription is ready.\n * @return {*} this\n */\n subscribe(options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (cb) {\n this.onDone(cb);\n }\n\n // If the room subscription is active, just call the callback.\n if (this.roomstate === 'active') {\n this.emit('done', null, this);\n return this;\n }\n\n // If the room is already subscribing, wait for its activation.\n if (this.roomstate === 'subscribing') {\n return this;\n }\n\n // If the room is still inactive, start the subscription.\n this.error = null;\n this.roomstate = 'subscribing';\n\n this.kuzzle.subscribe(this, options, (error, result) => {\n if (error) {\n if (error.message === 'Not Connected') {\n return this.kuzzle.once('connected', this.resubscribe);\n }\n\n this.roomstate = 'inactive';\n this.error = new Error('Error during Kuzzle subscription: ' + error.message);\n this.emit('done', this.error);\n return null;\n }\n\n this.roomId = result.roomId;\n this.channel = result.channel;\n this.roomstate = 'active';\n\n if (!this.isListening) {\n this.kuzzle.addListener('disconnected', this.deactivate);\n this.kuzzle.addListener('tokenExpired', this.deactivate);\n this.kuzzle.addListener('reconnected', this.resubscribeConditional);\n this.isListening = true;\n }\n\n this.emit('done', null, this);\n });\n\n return this;\n }\n\n /**\n * Unsubscribes from Kuzzle.\n *\n * Stop listening immediately.\n * @param {responseCallback} cb - Handles the query response\n * @return {*} this\n */\n unsubscribe(cb) {\n if (this.roomstate === 'subscribing') {\n if (cb) {\n cb(new Error('Cannot unsubscribe a room while a subscription attempt is underway'));\n }\n\n return this;\n }\n\n if (this.isListening) {\n this.kuzzle.removeListener('disconnected', this.deactivate);\n this.kuzzle.removeListener('tokenExpired', this.deactivate);\n this.kuzzle.removeListener('reconnected', this.resubscribeConditional);\n this.isListening = false;\n }\n\n if (this.roomstate === 'active') {\n this.kuzzle.unsubscribe(this, cb);\n }\n else if (cb) {\n cb(null, this.roomId);\n }\n\n this.roomstate = 'inactive';\n\n return this;\n }\n\n /**\n * Notify listeners\n *\n * @param {Object} data - data to send. Must contain `data.type` as eventName.\n * @return {*} this\n */\n notify(data) {\n if (data.type === undefined) {\n throw new Error('Room.notify: argument must match {type: }');\n }\n if (!data.fromSelf || this.subscribeToSelf) {\n this.emit(data.type, data);\n }\n return this;\n }\n\n /**\n * Registers a callback to be called with a subscription result\n * @param {Function} cb\n */\n onDone(cb) {\n if (!cb || typeof cb !== 'function') {\n throw new Error('Room.onDone: a callback argument is required.');\n }\n\n if (this.error) {\n cb(this.error);\n }\n else if (this.roomstate === 'active') {\n cb(null, this);\n }\n else {\n this.once('done', cb);\n }\n\n return this;\n }\n}\n\nmodule.exports = Room;\n\n\n\n// WEBPACK FOOTER //\n// ./src/Room.js","'use strict';\n\nconst\n RTWrapper = require('./abstract/realtime');\n\nclass SocketIO extends RTWrapper {\n\n constructor(host, options) {\n super(host, options);\n\n this.socket = null;\n this.forceDisconnect = false;\n this.eventsWrapper = {};\n }\n\n /**\n * Connect to the SocketIO server\n */\n connect() {\n super.connect();\n\n this.socket = window.io((this.ssl ? 'https://' : 'http://') + this.host + ':' + this.port, {\n reconnection: this.autoReconnect,\n reconnectionDelay: this.reconnectionDelay,\n forceNew: true\n });\n\n this.socket.on('connect', () => this.clientConnected());\n this.socket.on('connect_error', error => this.clientNetworkError(error));\n\n this.socket.on('disconnect', () => {\n if (this.forceDisconnect) {\n this.clientDisconnected();\n } else {\n const error = new Error('An error occurred, kuzzle may not be ready yet');\n error.status = 500;\n\n this.clientNetworkError(error);\n }\n\n this.forceDisconnect = false;\n });\n }\n\n /**\n * Registers a callback on an event. Once 1 message is received, fires the\n * callback and unregister it afterward.\n *\n * @param {string} event\n * @param {function} callback\n */\n addOnceListener(event, callback) {\n return this.addListener(event, callback, true);\n }\n\n once(event, callback) {\n return this.addOnceListener(event, callback);\n }\n\n prependOnceListener(event, callback) {\n return this.prependListener(event, callback, true);\n }\n\n /**\n * Registers a callback on an event.\n *\n * @param {string} event\n * @param {function} callback\n */\n addListener(event, callback, once = false) {\n this._addEventWrapper(event, callback, once);\n super.addListener(event, callback, once);\n\n return this;\n }\n\n on(event, callback) {\n return this.addListener(event, callback);\n }\n\n prependListener(event, callback, once = false) {\n this._addEventWrapper(event, callback, once);\n return this.prependListener(event, callback, once);\n }\n\n /**\n * Unregisters a callback from an event.\n *\n * @param {string} event\n * @param {function} callback\n */\n removeListener(event, callback) {\n if (this.eventsWrapper[event]) {\n this.eventsWrapper[event].listeners.delete(callback);\n\n if (this.eventsWrapper[event].listeners.size === 0) {\n this.socket.off(event, this.eventsWrapper[event].wrapper);\n delete this.eventsWrapper[event];\n }\n\n super.removeListener(event, callback);\n }\n\n return this;\n }\n\n /**\n * Unregisters all listeners either from an event, or from all events\n *\n * @param {string} [event]\n */\n removeAllListeners(event) {\n if (event !== undefined && this.eventsWrapper[event] !== undefined) {\n for (const listener of this.eventsWrapper[event].listeners) {\n this.removeListener(event, listener);\n }\n } else {\n for (const _event of Object.keys(this.eventsWrapper)) {\n this.removeAllListeners(_event);\n }\n }\n\n return this;\n }\n\n /**\n * Sends a payload to the connected server\n *\n * @param {Object} payload\n */\n send(payload) {\n this.socket.emit('kuzzle', payload);\n }\n\n /**\n * Closes the connection\n */\n close() {\n this.forceDisconnect = true;\n this.state = 'offline';\n this.socket.close();\n this.socket = null;\n }\n\n _addEventWrapper(event, callback, once = false) {\n if (!this.eventsWrapper[event]) {\n const wrapper = (...args) => this.emit(event, ...args);\n\n this.eventsWrapper[event] = {\n wrapper,\n listeners: new Set()\n };\n\n if (['connect', 'connect_error', 'disconnect'].indexOf(event) === -1) {\n if (once) {\n this.socket.once(event, wrapper);\n } else {\n this.socket.on(event, wrapper);\n }\n }\n }\n\n this.eventsWrapper[event].listeners.add(callback);\n }\n}\n\nmodule.exports = SocketIO;\n\n\n\n// WEBPACK FOOTER //\n// ./src/networkWrapper/protocols/socketio.js","'use strict';\n\nconst\n RTWrapper = require('./abstract/realtime');\n\nlet WebSocketClient;\n\nclass WSNode extends RTWrapper {\n\n constructor(host, options) {\n super(host, options);\n\n WebSocketClient = typeof WebSocket !== 'undefined' ? WebSocket : require('ws');\n this.client = null;\n this.lasturl = null;\n }\n\n /**\n * Connect to the websocket server\n */\n connect () {\n const\n url = (this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port,\n opts = typeof window !== 'undefined' ? undefined : {perMessageDeflate: false};\n\n super.connect();\n\n if (url !== this.lasturl) {\n this.wasConnected = false;\n this.lasturl = url;\n }\n\n this.client = new WebSocketClient(url, opts);\n\n this.client.onopen = () => {\n this.clientConnected();\n };\n\n this.client.onclose = (closeEvent, message) => {\n let\n status,\n reason = message;\n\n if (typeof closeEvent === 'number') {\n status = closeEvent;\n }\n else {\n status = closeEvent.code;\n\n if (closeEvent.reason) {\n reason = closeEvent.reason;\n }\n }\n\n if (status === 1000) {\n this.clientDisconnected();\n }\n // do not forward a connection close error if no \n // connection has been previously established\n else if (this.wasConnected) {\n const error = new Error(reason);\n error.status = status;\n\n this.clientNetworkError(error);\n }\n };\n\n this.client.onerror = error => {\n const err = (error instanceof Error) && error || new Error(error);\n\n this.clientNetworkError(err);\n };\n\n this.client.onmessage = payload => {\n const data = JSON.parse(payload.data || payload);\n\n if (data.room) {\n this.emit(data.room, data);\n }\n else {\n this.emit('discarded', data);\n }\n };\n }\n\n /**\n * Sends a payload to the connected server\n *\n * @param {Object} payload\n */\n send (payload) {\n if (this.client && this.client.readyState === this.client.OPEN) {\n this.client.send(JSON.stringify(payload));\n }\n }\n\n /**\n * Closes the connection\n */\n close () {\n this.state = 'offline';\n this.removeAllListeners();\n this.wasConnected = false;\n if (this.client) {\n this.client.close();\n }\n this.client = null;\n this.stopRetryingToConnect = true;\n }\n}\n\nmodule.exports = WSNode;\n\n\n\n// WEBPACK FOOTER //\n// ./src/networkWrapper/protocols/websocket.js","var\n KuzzleSearchResult = require('./SearchResult'),\n Document = require('./Document'),\n CollectionMapping = require('./CollectionMapping'),\n Room = require('./Room');\n\n/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n/**\n * A data collection is a set of data managed by Kuzzle. It acts like a data table for persistent documents,\n * or like a room for pub/sub messages.\n *\n * @property {string} collection\n * @property {string} index\n * @property {Kuzzle} kuzzle\n * @property {Array.} collection\n * @param {object} kuzzle - Kuzzle instance to inherit from\n * @param {string} collection - name of the data collection to handle\n * @param {string} index - Index containing the data collection\n * @constructor\n */\nfunction Collection(kuzzle, collection, index) {\n if (!index || !collection) {\n throw new Error('The Collection object constructor needs an index and a collection arguments');\n }\n\n Object.defineProperties(this, {\n // read-only properties\n collection: {\n value: collection,\n enumerable: true\n },\n index: {\n value: index,\n enumerable: true\n },\n kuzzle: {\n value: kuzzle,\n enumerable: true\n }\n });\n\n Object.defineProperty(this, 'buildQueryArgs', {\n value: function (controller, action) {\n return {\n controller: controller,\n action: action,\n collection: this.collection,\n index: this.index\n };\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = ['subscribe'];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * Returns the number of documents matching the provided set of filters.\n *\n * There is a small delay between documents creation and their existence in our advanced search layer,\n * usually a couple of seconds.\n * That means that a document that was just been created won’t be returned by this function\n *\n * @param {object} filters - Filters in Elasticsearch Query DSL format\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nCollection.prototype.count = function (filters, options, cb) {\n var query = {body: filters};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('Collection.count', cb);\n\n this.kuzzle.query(this.buildQueryArgs('document', 'count'), query, options, function (err, res) {\n cb(err, err ? undefined : res.result.count);\n });\n};\n\n/**\n * Create a new empty data collection, with no associated mapping.\n * Kuzzle automatically creates data collections when storing documents, but there are cases where we\n * want to create and prepare data collections before storing documents in it.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n * @returns {*} this\n */\nCollection.prototype.create = function (options, cb) {\n var data = {},\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.buildQueryArgs('collection', 'create'), data, options, function(err) {\n cb(err, err ? undefined : self);\n });\n\n return this;\n};\n\n/**\n * Create a new document in Kuzzle.\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n * - ifExist (string, allowed values: \"error\" (default), \"replace\"):\n * If the same document already exists:\n * - resolves with an error if set to \"error\".\n * - replaces the existing document if set to \"replace\"\n *\n * @param {string} [id] - (optional) document identifier\n * @param {object} document - either an instance of a Document object, or a document\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Object} this\n */\nCollection.prototype.createDocument = function (id, document, options, cb) {\n var\n self = this,\n data = {},\n action = 'create';\n\n if (id && typeof id !== 'string') {\n cb = options;\n options = document;\n document = id;\n id = null;\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (document instanceof Document) {\n data = document.serialize();\n } else {\n data.body = document;\n }\n\n if (options && options.ifExist) {\n if (options.ifExist === 'replace') {\n action = 'createOrReplace';\n }\n else if (options.ifExist !== 'error') {\n throw new Error('Invalid value for the \"ifExist\" option: ' + options.ifExist);\n }\n }\n\n if (id) {\n data._id = id;\n }\n\n self.kuzzle.query(this.buildQueryArgs('document', action), data, options, cb && function (err, res) {\n var doc;\n\n if (err) {\n return cb(err);\n }\n\n doc = new Document(self, res.result._id, res.result._source, res.result._meta);\n doc.version = res.result._version;\n cb(null, doc);\n });\n\n return this;\n};\n\n/**\n * Delete persistent documents.\n *\n * There is a small delay between documents creation and their existence in our advanced search layer,\n * usually a couple of seconds.\n * That means that a document that was just been created won’t be returned by this function\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {string|object} arg - Either a document ID (will delete only this particular document), or a set of filters\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Collection} this\n */\nCollection.prototype.deleteDocument = function (arg, options, cb) {\n var\n action,\n data = {};\n\n if (typeof arg === 'string') {\n data._id = arg;\n action = 'delete';\n } else {\n data.body = {query: arg};\n action = 'deleteByQuery';\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.buildQueryArgs('document', action), data, options, cb && function (err, res) {\n if (err) {\n cb(err);\n }\n else {\n cb(null, (action === 'delete' ? [res.result._id] : res.result.ids));\n }\n });\n\n return this;\n};\n\n/**\n * Deletes the current specifications of this collection\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @return {object} this\n */\nCollection.prototype.deleteSpecifications = function (options, cb) {\n var\n data = { index: this.index, collection: this.collection },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.buildQueryArgs('collection', 'deleteSpecifications'), data, options, function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return self;\n};\n\n/**\n * Returns a boolean indicating whether or not a document with provided ID exists.\n *\n * @param {string} documentId - Unique document identifier\n * @param {object} options [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nCollection.prototype.documentExists = function (documentId, options, cb) {\n var\n data = {_id: documentId},\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Collection.documentExists', cb);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'exists'), data, options, function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n};\n\n/**\n * Retrieve a single stored document using its unique document ID.\n *\n * @param {string} documentId - Unique document identifier\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nCollection.prototype.fetchDocument = function (documentId, options, cb) {\n var\n data = {_id: documentId},\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Collection.fetch', cb);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'get'), data, options, function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new Document(self, res.result._id, res.result._source, res.result._meta);\n document.version = res.result._version;\n cb(null, document);\n });\n};\n\n/**\n * Instantiates a CollectionMapping object containing the current mapping of this collection.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n */\nCollection.prototype.getMapping = function (options, cb) {\n var kuzzleMapping;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('Collection.getMapping', cb);\n\n kuzzleMapping = new CollectionMapping(this);\n kuzzleMapping.refresh(options, cb);\n};\n\n/**\n * Create the provided documents\n *\n * @param {Array.} documents - Array of documents to create\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n * @returns {object} this\n */\nCollection.prototype.mCreateDocument = function (documents, options, cb) {\n var data = {\n body: {},\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!Array.isArray(documents)) {\n return cb(new Error('Collection.mCreateDocument: documents parameter format is invalid (should be an array of documents)'));\n }\n\n self.kuzzle.callbackRequired('Collection.mCreate', cb);\n\n data.body.documents = documents.map(function (doc) {\n return (doc instanceof Document) ? doc.serialize() : doc;\n });\n\n self.kuzzle.query(this.buildQueryArgs('document', 'mCreate'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return self;\n};\n\n/**\n * Create or replace the provided documents\n *\n * @param {Array.} documents - Array of documents to create or replace\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n * @returns {object} this\n */\nCollection.prototype.mCreateOrReplaceDocument = function (documents, options, cb) {\n var data = {\n body: {},\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!Array.isArray(documents)) {\n return cb(new Error('Collection.mCreateOrReplaceDocument: documents parameter format is invalid (should be an array of documents)'));\n }\n\n self.kuzzle.callbackRequired('Collection.mCreateOrReplace', cb);\n\n data.body.documents = documents.map(function (doc) {\n return (doc instanceof Document) ? doc.serialize() : doc;\n });\n\n self.kuzzle.query(this.buildQueryArgs('document', 'mCreateOrReplace'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return self;\n};\n\n/**\n * Delete specific documents according to given IDs\n *\n * @param {Array.} documentIds - IDs of the documents to delete\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n * @returns {object} this\n */\nCollection.prototype.mDeleteDocument = function (documentIds, options, cb) {\n var data = {\n body: {\n ids: documentIds\n }\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!Array.isArray(documentIds)) {\n return cb(new Error('Collection.mDeleteDocument: documentIds parameter format is invalid (should be an array of IDs)'));\n }\n\n self.kuzzle.callbackRequired('Collection.mDelete', cb);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'mDelete'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return self;\n};\n\n/**\n * Get specific documents according to given IDs\n *\n * @param {Array.} documentIds - IDs of the documents to retrieve\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n */\nCollection.prototype.mGetDocument = function (documentIds, options, cb) {\n var data = {\n body: {\n ids: documentIds\n }\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!Array.isArray(documentIds)) {\n return cb(new Error('Collection.mGetDocument: documentIds parameter format is invalid (should be an array of IDs)'));\n }\n\n self.kuzzle.callbackRequired('Collection.mGet', cb);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'mGet'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n};\n\n/**\n * Replace the provided documents\n *\n * @param {Array.} documents - Array of documents to replace\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n * @returns {object} this\n */\nCollection.prototype.mReplaceDocument = function (documents, options, cb) {\n var data = {\n body: {}\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!Array.isArray(documents)) {\n return cb(new Error('Collection.mReplaceDocument: documents parameter format is invalid (should be an array of documents)'));\n }\n\n self.kuzzle.callbackRequired('Collection.mReplace', cb);\n\n data.body.documents = documents.map(function (doc) {\n return (doc instanceof Document) ? doc.serialize() : doc;\n });\n\n self.kuzzle.query(this.buildQueryArgs('document', 'mReplace'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return self;\n};\n\n/**\n * Update the provided documents\n *\n * @param {Array.} documents - Array of documents to update\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated CollectionMapping object\n * @returns {object} this\n */\nCollection.prototype.mUpdateDocument = function (documents, options, cb) {\n var data = {\n body: {}\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!Array.isArray(documents)) {\n return cb(new Error('Collection.mUpdateDocument: documents parameter format is invalid (should be an array of documents)'));\n }\n\n self.kuzzle.callbackRequired('Collection.mUpdate', cb);\n\n data.body.documents = documents.map(function (doc) {\n return (doc instanceof Document) ? doc.serialize() : doc;\n });\n\n self.kuzzle.query(this.buildQueryArgs('document', 'mUpdate'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return self;\n};\n\n/**\n * Retrieves the current specifications of this collection\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nCollection.prototype.getSpecifications = function (options, cb) {\n var\n data = { index: this.index, collection: this.collection },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Collection.getSpecifications', cb);\n\n self.kuzzle.query(this.buildQueryArgs('collection', 'getSpecifications'), data, options, function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n};\n\n/**\n * Publish a realtime message\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} document - either a Document instance or a JSON object\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Returns a raw Kuzzle response\n * @returns {*} this\n */\nCollection.prototype.publishMessage = function (document, options, cb) {\n var data = {};\n\n if (document instanceof Document) {\n data = document.serialize();\n } else {\n data.body = document;\n }\n\n this.kuzzle.query(this.buildQueryArgs('realtime', 'publish'), data, options, cb);\n\n return this;\n};\n\n/**\n * Replace an existing document with a new one.\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {string} documentId - Unique document identifier of the document to replace\n * @param {object} content - JSON object representing the new document version\n * @param {object} [options] - additional arguments\n * @param {responseCallback} [cb] - Returns an instantiated Document object\n * @return {object} this\n */\nCollection.prototype.replaceDocument = function (documentId, content, options, cb) {\n var\n self = this,\n data = {\n _id: documentId,\n body: content\n };\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.buildQueryArgs('document', 'createOrReplace'), data, options, cb && function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new Document(self, res.result._id, res.result._source, res.result._meta);\n document.version = res.result._version;\n cb(null, document);\n });\n\n return this;\n};\n\n/**\n * Executes an advanced search on the data collection.\n *\n * /!\\ There is a small delay between documents creation and their existence in our advanced search layer,\n * usually a couple of seconds.\n * That means that a document that was just been created won’t be returned by this function.\n *\n * @param {object} filters - Filters in Elasticsearch Query DSL format\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\n\nCollection.prototype.search = function (filters, options, cb) {\n var\n query = {body: filters},\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n self.kuzzle.callbackRequired('Collection.search', cb);\n\n self.kuzzle.query(this.buildQueryArgs('document', 'search'), query, options, function (error, result) {\n var documents = [];\n\n if (error) {\n return cb(error);\n }\n\n result.result.hits.forEach(function (doc) {\n var newDocument = new Document(self, doc._id, doc._source, doc._meta);\n\n newDocument.version = doc._version;\n\n documents.push(newDocument);\n });\n\n if (result.result._scroll_id) {\n options.scrollId = result.result._scroll_id;\n }\n\n cb(null, new KuzzleSearchResult(\n self,\n result.result.total,\n documents,\n result.result.aggregations ? result.result.aggregations : {},\n options,\n filters,\n options.previous || null\n ));\n });\n};\n\n/**\n * A \"scroll\" option can be passed to search queries, creating persistent\n * paginated results.\n * This method can be used to manually get the next page of a search result,\n * instead of using KuzzleSearchResult.next()\n *\n * @param {string} scrollId\n * @param {object} [options]\n * @param {object} [filters]\n * @param {responseCallback} cb\n */\nCollection.prototype.scroll = function (scrollId, options, filters, cb) {\n var\n request = {},\n self = this;\n\n if (!scrollId) {\n throw new Error('Collection.scroll: scrollId is required');\n }\n\n if (!cb) {\n cb = filters;\n filters = null;\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n this.kuzzle.callbackRequired('Collection.scroll', cb);\n\n request.scrollId = scrollId;\n\n this.kuzzle.query({controller: 'document', action: 'scroll'}, request, options, function (error, result) {\n var documents = [];\n\n if (error) {\n return cb(error);\n }\n\n result.result.hits.forEach(function (doc) {\n var newDocument = new Document(self, doc._id, doc._source, doc._meta);\n\n newDocument.version = doc._version;\n\n documents.push(newDocument);\n });\n\n if (result.result._scroll_id) {\n options.scrollId = result.result._scroll_id;\n }\n\n cb(null, new KuzzleSearchResult(\n self,\n result.result.total,\n documents,\n {},\n options,\n filters,\n options.previous || null\n ));\n });\n\n return this;\n};\n\n/**\n * Retrieves next result of a search with scroll query.\n *\n * @param {string} scrollId\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nCollection.prototype.scrollSpecifications = function (scrollId, options, cb) {\n var\n data = { scrollId: scrollId };\n\n if (!scrollId) {\n throw new Error('Collection.scrollSpecifications: scrollId is required');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n this.kuzzle.callbackRequired('Collection.scrollSpecifications', cb);\n\n this.kuzzle.query(\n { controller: 'collection', action: 'scrollSpecifications'},\n data,\n options,\n function (err, res) {\n cb (err, err ? undefined : res.result);\n }\n );\n};\n\n/**\n * Searches specifications across indexes/collections according to the provided filters\n *\n * @param {object} [filters] - Optional filters in ElasticSearch Query DSL format\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nCollection.prototype.searchSpecifications = function (filters, options, cb) {\n var\n data = { body: { query: filters } },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n self.kuzzle.callbackRequired('Collection.searchSpecifications', cb);\n\n self.kuzzle.query({ controller: 'collection', action: 'searchSpecifications' }, data, options, function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n};\n\n/**\n * Create a subscription room to this data collection with a set of filters.\n * To subscribe to the entire data collection, simply provide an empty filter.\n *\n * @param {object} filters - Filters in Kuzzle DSL format\n * @param {object} [options] - subscriptions options\n * @returns {*} KuzzleRoom object\n */\nCollection.prototype.room = function (filters, options) {\n return new Room(this, filters, options);\n};\n\n/**\n * Subscribes to this data collection with a set of filters.\n * To subscribe to the entire data collection, simply provide an empty filter.\n *\n * @param {object} filters - Filters in Kuzzle DSL format\n * @param {object} [options] - subscriptions options\n * @param {responseCallback} notificationCB - called for each new notification\n * @returns {*} KuzzleRoom object\n */\nCollection.prototype.subscribe = function (filters, options, notificationCB) {\n var\n evtName,\n room;\n\n if (!notificationCB && typeof options === 'function') {\n notificationCB = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('Collection.subscribe', notificationCB);\n\n evtName = (options && options.users && options.users !== 'none') ? 'user' : 'document';\n room = new Room(this, filters, options);\n\n room.subscribe().on(evtName, notificationCB);\n return room;\n};\n\n/**\n * Truncate the data collection, removing all stored documents but keeping all associated mappings.\n * This method is a lot faster than removing all documents using a query.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n * @returns {*} this\n */\nCollection.prototype.truncate = function (options, cb) {\n var data = {};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.buildQueryArgs('collection', 'truncate'), data, options, cb);\n\n return this;\n};\n\n\n/**\n * Update parts of a document\n *\n * Takes an optional argument object with the following properties:\n * - volatile (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {string} documentId - Unique document identifier of the document to update\n * @param {object} content - JSON object containing changes to perform on the document\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Returns an instantiated Document object\n * @return {object} this\n */\nCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n var data = {\n _id: documentId,\n body: content\n },\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (options && options.retryOnConflict) {\n data.retryOnConflict = options.retryOnConflict;\n }\n\n self.kuzzle.query(this.buildQueryArgs('document', 'update'), data, options, cb && function (err, res) {\n if (err) {\n return cb(err);\n }\n\n (new Document(self, res.result._id)).refresh(cb);\n });\n\n return self;\n};\n\n/**\n * Updates the current specifications of this collection\n *\n * @param {object} specifications - Specifications content\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @return {object} this\n */\nCollection.prototype.updateSpecifications = function (specifications, options, cb) {\n var\n collection = {},\n data = { body: {} },\n self = this;\n\n collection[this.collection] = specifications;\n data.body[this.index] = collection;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.buildQueryArgs('collection', 'updateSpecifications'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result);\n });\n\n return self;\n};\n\n/**\n * Validates the provided specifications\n *\n * @param {object} specifications - Specifications content\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n */\nCollection.prototype.validateSpecifications = function (specifications, options, cb) {\n var\n collection = {},\n data = { body: {} },\n self = this;\n\n collection[this.collection] = specifications;\n data.body[this.index] = collection;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Collection.validateSpecifications', cb);\n\n self.kuzzle.query(this.buildQueryArgs('collection', 'validateSpecifications'), data, options, function (err, res) {\n cb(err, err ? undefined : res.result.valid);\n });\n};\n\n/**\n * Instantiate a new Document object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - document id\n * @param {object} content - document content\n * @constructor\n */\nCollection.prototype.document = function (id, content) {\n return new Document(this, id, content);\n};\n\n/**\n * Instantiate a new CollectionMapping object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {object} [mapping] - mapping to instantiate the CollectionMapping object with\n * @constructor\n */\nCollection.prototype.collectionMapping = function (mapping) {\n return new CollectionMapping(this, mapping);\n};\n\nmodule.exports = Collection;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/Collection.js\n// module id = 9\n// module chunks = 0","/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n\n/**\n * When creating a new data collection in the persistent data storage layer, Kuzzle uses a default mapping.\n * It means that, by default, you won’t be able to exploit the full capabilities of our persistent data storage layer\n * (currently handled by ElasticSearch), and your searches may suffer from below-average performances, depending on\n * the amount of data you stored in a collection and the complexity of your database.\n *\n * The CollectionMapping object allow to get the current mapping of a data collection and to modify it if needed.\n *\n * @param {object} collection - Instance of the inherited Collection object\n * @param {object} [mapping] - mappings\n * @constructor\n */\nfunction CollectionMapping(collection, mapping) {\n Object.defineProperties(this, {\n //read-only properties\n collection: {\n value: collection,\n enumerable: true\n },\n kuzzle: {\n value: collection.kuzzle,\n enumerable: true\n },\n // writable properties\n mapping: {\n value: mapping || {},\n enumerable: true,\n writable: true\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = ['set'];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * Applies the new mapping to the data collection.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n */\nCollectionMapping.prototype.apply = function (options, cb) {\n var\n self = this,\n data = {\n body: {\n properties: this.mapping\n }\n };\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.collection.buildQueryArgs('collection', 'updateMapping'), data, options, function (err) {\n if (err) {\n return cb && cb(err);\n }\n\n self.refresh(options, cb);\n });\n\n return this;\n};\n\n/**\n * Replaces the current content with the mapping stored in Kuzzle\n *\n * Calling this function will discard any uncommited changes. You can commit changes by calling the “apply” function\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {*} this\n */\nCollectionMapping.prototype.refresh = function (options, cb) {\n var\n self = this,\n data = {};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.collection.buildQueryArgs('collection', 'getMapping'), data, options, function (err, res) {\n if (err) {\n return cb ? cb(err) : false;\n }\n\n if (res.result[self.collection.index]) {\n if (res.result[self.collection.index].mappings[self.collection.collection]) {\n self.mapping = res.result[self.collection.index].mappings[self.collection.collection].properties;\n\n // Mappings can be empty. The mapping property should never be \"undefined\"\n if (self.mapping === undefined) {\n self.mapping = {};\n }\n } else {\n return cb && cb(new Error('No mapping found for collection ' + self.collection.collection));\n }\n } else {\n return cb && cb(new Error('No mapping found for index ' + self.collection.index));\n }\n\n if (cb) {\n cb(null, self);\n }\n });\n\n return this;\n};\n\n\n/**\n * Adds or updates a field mapping.\n *\n * Changes made by this function won’t be applied until you call the apply method\n *\n * @param {string} field - Name of the field from which the mapping is to be added or updated\n * @param {object} mapping - corresponding field mapping\n * @returns {CollectionMapping}\n */\nCollectionMapping.prototype.set = function (field, mapping) {\n this.mapping[field] = mapping;\n\n return this;\n};\n\nmodule.exports = CollectionMapping;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/CollectionMapping.js\n// module id = 10\n// module chunks = 0","// Parameter mutualization\nvar\n getId = {getter: true, required: ['_id']},\n getIdField = {getter: true, required: ['_id', 'field']},\n getKeys = {getter: true, required: ['keys']},\n getMember = {getter: true, required: ['_id', 'member']},\n getxScan = {\n getter: true, \n required: ['_id', 'cursor'], \n opts: ['match', 'count'],\n mapResults: mapScanResults\n },\n getZrange = {\n getter: true,\n required: ['_id', 'start', 'stop'],\n opts: assignZrangeOptions,\n mapResults: mapZrangeResults\n },\n getZrangeBy = {\n getter: true,\n required: ['_id', 'min', 'max'],\n opts: assignZrangeOptions,\n mapResults: mapZrangeResults\n },\n setId = {required: ['_id']},\n setIdValue = {required: ['_id', 'value']};\n\n// Redis commands\nvar\n commands = {\n append: setIdValue,\n bitcount: {getter: true, required: ['_id'], opts: ['start', 'end']},\n bitop: {required: ['_id', 'operation', 'keys']},\n bitpos: {getter: true, required: ['_id', 'bit'], opts: ['start', 'end']},\n dbsize: {getter: true},\n decr: setId,\n decrby: setIdValue,\n del: {required: ['keys']},\n exists: getKeys,\n expire: {required: ['_id', 'seconds'], mapResults: Boolean},\n expireat: {required: ['_id', 'timestamp'], mapResults: Boolean},\n flushdb: {mapResults: mapNoResult},\n geoadd: {required: ['_id', 'points']},\n geodist: {\n getter: true,\n required: ['_id', 'member1', 'member2'],\n opts: ['unit'],\n mapResults: parseFloat\n },\n geohash: {getter: true, required: ['_id', 'members']},\n geopos: {getter: true, required: ['_id', 'members'], mapResults: mapGeoposResults},\n georadius: {\n getter: true,\n required: ['_id', 'lon', 'lat', 'distance', 'unit'],\n opts: assignGeoRadiusOptions,\n mapResults: mapGeoRadiusResults\n },\n georadiusbymember: {\n getter: true,\n required: ['_id', 'member', 'distance', 'unit'],\n opts: assignGeoRadiusOptions,\n mapResults: mapGeoRadiusResults\n },\n get: getId,\n getbit: {getter: true, required: ['_id', 'offset']},\n getrange: {getter: true, required: ['_id', 'start', 'end']},\n getset: setIdValue,\n hdel: {required: ['_id', 'fields']},\n hexists: {getter: true, required: ['_id', 'field'], mapResults: Boolean},\n hget: getIdField,\n hgetall: {getter: true, required: ['_id']},\n hincrby: {required: ['_id', 'field', 'value']},\n hincrbyfloat: {required: ['_id', 'field', 'value'], mapResults: parseFloat},\n hkeys: getId,\n hlen: getId,\n hmget: {getter: true, required: ['_id', 'fields']},\n hmset: {required: ['_id', 'entries'], mapResults: mapNoResult},\n hscan: getxScan,\n hset: {required: ['_id', 'field', 'value'], mapResults: Boolean},\n hsetnx: {required: ['_id', 'field', 'value'], mapResults: Boolean},\n hstrlen: getIdField,\n hvals: getId,\n incr: setId,\n incrby: setIdValue,\n incrbyfloat: {required: ['_id', 'value'], mapResults: parseFloat},\n keys: {getter: true, required: ['pattern']},\n lindex: {getter: true, required: ['_id', 'idx']},\n linsert: {required: ['_id', 'position', 'pivot', 'value']},\n llen: getId,\n lpop: setId,\n lpush: {required: ['_id', 'values']},\n lpushx: setIdValue,\n lrange: {getter: true, required: ['_id', 'start', 'stop']},\n lrem: {required: ['_id', 'count', 'value']},\n lset: {required: ['_id', 'index', 'value'], mapResults: mapNoResult},\n ltrim: {required: ['_id', 'start', 'stop'], mapResults: mapNoResult},\n mget: getKeys,\n mset: {required: ['entries'], mapResults: mapNoResult},\n msetnx: {required: ['entries'], mapResults: Boolean},\n object: {getter: true, required: ['_id', 'subcommand']},\n persist: {required: ['_id'], mapResults: Boolean},\n pexpire: {required: ['_id', 'milliseconds'], mapResults: Boolean},\n pexpireat: {required: ['_id', 'timestamp'], mapResults: Boolean},\n pfadd: {required: ['_id', 'elements'], mapResults: Boolean},\n pfcount: getKeys,\n pfmerge: {required: ['_id', 'sources'], mapResults: mapNoResult},\n ping: {getter: true},\n psetex: {required: ['_id', 'value', 'milliseconds'], mapResults: mapNoResult},\n pttl: getId,\n randomkey: {getter: true},\n rename: {required: ['_id', 'newkey'], mapResults: mapNoResult},\n renamenx: {required: ['_id', 'newkey'], mapResults: Boolean},\n rpop: setId,\n rpoplpush: {required: ['source', 'destination']},\n rpush: {required: ['_id', 'values']},\n rpushx: setIdValue,\n sadd: {required: ['_id', 'members']},\n scan: {getter: true, required: ['cursor'], opts: ['match', 'count'], mapResults: mapScanResults},\n scard: getId,\n sdiff: {getter: true, required: ['_id', 'keys']},\n sdiffstore: {required: ['_id', 'keys', 'destination']},\n set: {required: ['_id', 'value'], opts: ['ex', 'px', 'nx', 'xx'], mapResults: mapNoResult},\n setex: {required: ['_id', 'value', 'seconds'], mapResults: mapNoResult},\n setnx: {required: ['_id', 'value'], mapResults: Boolean},\n sinter: getKeys,\n sinterstore: {required: ['destination', 'keys']},\n sismember: {getter: true, required: ['_id', 'member'], mapResults: Boolean},\n smembers: getId,\n smove: {required: ['_id', 'destination', 'member'], mapResults: Boolean},\n sort: {getter: true, required: ['_id'], opts: ['alpha', 'by', 'direction', 'get', 'limit']},\n spop: {required: ['_id'], opts: ['count'], mapResults: mapStringToArray },\n srandmember: {getter: true, required: ['_id'], opts: ['count'], mapResults: mapStringToArray},\n srem: {required: ['_id', 'members']},\n sscan: getxScan,\n strlen: getId,\n sunion: getKeys,\n sunionstore: {required: ['destination', 'keys']},\n time: {getter: true, mapResults: mapArrayStringToArrayInt},\n touch: {required: ['keys']},\n ttl: getId,\n type: getId,\n zadd: {required: ['_id', 'elements'], opts: ['nx', 'xx', 'ch', 'incr']},\n zcard: getId,\n zcount: {getter: true, required: ['_id', 'min', 'max']},\n zincrby: {required: ['_id', 'member', 'value']},\n zinterstore: {required: ['_id', 'keys'], opts: ['weights', 'aggregate']},\n zlexcount: {getter: true, required: ['_id', 'min', 'max']},\n zrange: getZrange,\n zrangebylex: {getter: true, required: ['_id', 'min', 'max'], opts: ['limit']},\n zrevrangebylex: {getter: true, required: ['_id', 'min', 'max'], opts: ['limit']},\n zrangebyscore: getZrangeBy,\n zrank: getMember,\n zrem: {required: ['_id', 'members']},\n zremrangebylex: {required: ['_id', 'min', 'max']},\n zremrangebyrank: {required: ['_id', 'start', 'stop']},\n zremrangebyscore: {required: ['_id', 'min', 'max']},\n zrevrange: getZrange,\n zrevrangebyscore: getZrangeBy,\n zrevrank: getMember,\n zscan: getxScan,\n zscore: {getter: true, required: ['_id', 'member'], mapResults: parseFloat},\n zunionstore: {required: ['_id', 'keys'], opts: ['weights', 'aggregate']}\n };\n\n/**\n * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.\n *\n * @callback responseCallback\n * @param {Object} err - Error object, NULL if the query is successful\n * @param {Object} [data] - The content of the query response\n */\n\n\n/**\n * Kuzzle's memory storage is a separate data store from the database layer.\n * It is internaly based on Redis. You can access most of Redis functions (all\n * lowercased), except functions falling in the following categories:\n *\n * - blocking functions\n * - cluster commands\n * - configuration commands\n * - cursor functions\n * - database administration commands\n * - debugging functions\n * - script based functions\n * - transaction functions\n *\n * @param {object} kuzzle - Kuzzle instance to inherit from\n * @constructor\n */\nfunction MemoryStorage(kuzzle) {\n Object.defineProperties(this, {\n // read-only properties\n kuzzle: {\n value: kuzzle,\n enumerable: true\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = [];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n// Dynamically builds this class' prototypes using the \"commands\" global variable\n(function () {\n Object.keys(commands).forEach(function (command) {\n MemoryStorage.prototype[command] = function () {\n var\n args = Array.prototype.slice.call(arguments),\n options = null,\n cb,\n query = {\n controller: 'ms',\n action: command\n },\n data = {};\n\n if (args.length && typeof args[args.length - 1] === 'function') {\n cb = args.pop();\n }\n\n commands[command].getter && this.kuzzle.callbackRequired('MemoryStorage.' + command, cb);\n\n if (!commands[command].getter) {\n data.body = {};\n }\n\n if (commands[command].required) {\n commands[command].required.forEach(function (param) {\n var value = args.shift();\n\n if (value === undefined) {\n throw new Error('MemoryStorage.' + command + ': Missing parameter \"' + param + '\"');\n }\n\n assignParameter(data, commands[command].getter, param, value);\n });\n }\n\n if (args.length > 1) {\n throw new Error('MemoryStorage.' + command + ': Too many parameters provided');\n }\n\n if (args.length === 1 && typeof args[0] !== 'object' || Array.isArray(args[0])) {\n throw new Error('MemoryStorage.' + command + ': Invalid optional parameter (expected an object)');\n }\n\n if (args.length) {\n options = Object.assign({}, args[0]);\n\n if (Array.isArray(commands[command].opts)) {\n commands[command].opts.forEach(function (opt) {\n if (options[opt] !== null && options[opt] !== undefined) {\n assignParameter(data, commands[command].getter, opt, options[opt]);\n delete options[opt];\n }\n });\n }\n }\n\n /*\n Options function mapper does not necessarily need\n options to be passed by clients.\n */\n if (typeof commands[command].opts === 'function') {\n commands[command].opts(data, options || {});\n }\n\n this.kuzzle.query(query, data, options, cb && function (err, res) {\n if (err) {\n return cb(err);\n }\n\n if (commands[command].mapResults) {\n return cb(null, commands[command].mapResults(res.result));\n }\n\n cb(null, res.result);\n });\n\n if (!commands[command].getter) {\n return this;\n }\n };\n });\n})();\n\n/**\n *\n * @param {object} data - target data object\n * @param {boolean} getter - tells if the command is a getter one\n * @param {string} name - parameter name\n * @param {*} value - parameter value\n */\nfunction assignParameter(data, getter, name, value) {\n if (getter || name === '_id') {\n data[name] = value;\n }\n else {\n data.body[name] = value;\n }\n}\n\n/**\n * Assign the provided options for the georadius* redis functions\n * to the request object, as expected by Kuzzle API\n *\n * Mutates the provided data and options objects\n *\n * @param {object} data\n * @param {object} options\n */\nfunction assignGeoRadiusOptions(data, options) {\n var parsed = [];\n\n Object.keys(options)\n .filter(function (opt) {\n return options[opt] && ['withcoord', 'withdist', 'count', 'sort'].indexOf(opt) !== -1;\n })\n .forEach(function (opt) {\n if (opt === 'withcoord' || opt === 'withdist') {\n parsed.push(opt);\n delete options[opt];\n }\n else if (opt === 'count' || opt === 'sort') {\n if (opt === 'count') {\n parsed.push('count');\n }\n\n parsed.push(options[opt]);\n }\n\n delete options[opt];\n });\n\n if (parsed.length > 0) {\n data.options = parsed;\n }\n}\n\n/**\n * Force the WITHSCORES option on z*range* routes\n *\n * Mutates the provided data and options objects\n *\n * @param {object} data\n * @param {object} options\n */\nfunction assignZrangeOptions(data, options) {\n data.options = ['withscores'];\n\n if (options.limit) {\n data.limit = options.limit;\n delete options.limit;\n }\n}\n\n/**\n * Maps geopos results, from array> to array>\n *\n * @param {Array.>} results\n * @return {Array.>}\n */\nfunction mapGeoposResults(results) {\n return results.map(function (coords) {\n return coords.map(function (latlon) {\n return parseFloat(latlon);\n });\n });\n}\n\n\n/**\n * Maps georadius results to the format specified in the SDK documentation,\n * preventing different formats depending on the passed options\n *\n * Results can be either an array of point names, or an array\n * of arrays, each one of them containing the point name,\n * and additional informations depending on the passed options\n * (coordinates, distances)\n *\n * @param {Array} results\n * @return {Array.}\n */\nfunction mapGeoRadiusResults(results) {\n // Simple array of point names (no options provided)\n if (!Array.isArray(results[0])) {\n return results.map(function (point) {\n return {name: point};\n });\n }\n\n return results.map(function (point) {\n // The point id is always the first item\n var p = {\n name: point[0]\n },\n i;\n\n for (i = 1; i < point.length; i++) {\n // withcoord result are in an array...\n if (Array.isArray(point[i])) {\n p.coordinates = point[i].map(function (coord) {\n return parseFloat(coord);\n });\n }\n else {\n // ... and withdist are not\n p.distance = parseFloat(point[i]);\n }\n }\n\n return p;\n });\n}\n\n/**\n * Map a string result to an array of strings.\n * Used to uniformize polymorphic results from redis\n *\n * @param {Array|string} results\n * @return {Array.}\n */\nfunction mapStringToArray(results) {\n return Array.isArray(results) ? results : [results];\n}\n\n/**\n * Map an array of strings to an array of integers\n *\n * @param {Array.} results\n * @return {Array.}\n */\nfunction mapArrayStringToArrayInt(results) {\n return results.map(function (value) {\n return parseInt(value);\n });\n}\n\n/**\n * Disable results for routes like flushdb\n * @return {undefined}\n */\nfunction mapNoResult() {\n return undefined;\n}\n\n/**\n * Map zrange results with WITHSCORES:\n * [\n * \"member1\",\n * \"score of member1\",\n * \"member2\",\n * \"score of member2\"\n * ]\n *\n * into the following format:\n * [\n * {\"member\": \"member1\", \"score\": },\n * {\"member\": \"member2\", \"score\": },\n * ]\n *\n *\n * @param {Array.} results\n * @return {Array.}\n */\nfunction mapZrangeResults(results) {\n var\n buffer = null,\n mapped = [];\n\n results.forEach(function (value) {\n if (buffer === null) {\n buffer = value;\n }\n else {\n mapped.push({member: buffer, score: parseFloat(value)});\n buffer = null;\n }\n });\n\n return mapped;\n}\n\n/**\n * Map *scan calls results, from:\n * [\n * \"\",\n * [\n * \"value1\",\n * \"value2\", \n * \"...\"\n * ]\n * ]\n *\n * To:\n * {\n * cursor: ,\n * values: [\n * \"value1\",\n * \"value2\",\n * \"...\"\n * ]\n * }\n * \n * @param {array.} results \n * @return {object}\n */\nfunction mapScanResults(results) {\n return {\n cursor: results[0],\n values: results[1]\n };\n}\n\nmodule.exports = MemoryStorage;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/MemoryStorage.js\n// module id = 11\n// module chunks = 0","/**\n * @param {Collection} collection\n * @param {int} total\n * @param {Document[]} documents\n * @param {object} aggregations\n * @param {object} options\n * @param {object} filters\n * @param {SearchResult} previous\n * @property {Collection} collection\n * @property {number} total\n * @property {Document[]} documents\n * @property {object} aggregations\n * @property {object} options\n * @property {object} filters\n * @property {number} fetchedDocument\n * @constructor\n */\nfunction SearchResult (collection, total, documents, aggregations, options, filters, previous) {\n Object.defineProperties(this, {\n // read-only properties\n collection: {\n value: collection,\n enumerable: true\n },\n total: {\n value: total,\n enumerable: true\n },\n documents: {\n value: documents,\n enumerable: true\n },\n aggregations: {\n value: aggregations || {},\n enumerable: true\n },\n options: {\n value: options || {},\n enumerable: true\n },\n filters: {\n value: filters || {},\n enumerable: true\n },\n // writable properties\n fetchedDocument: {\n value: previous instanceof SearchResult ? documents.length + previous.fetchedDocument : documents.length,\n enumerable: true,\n writable: true\n }\n });\n\n // promisifying\n if (this.collection.kuzzle.bluebird) {\n return this.collection.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['fetchNext'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n return this;\n}\n\n/**\n * @param {function} cb\n */\nSearchResult.prototype.fetchNext = function (cb) {\n var\n filters,\n options = Object.assign({}, this.options),\n self = this;\n \n options.previous = this;\n\n // retrieve next results with scroll if original search use it\n if (options.scrollId) {\n if (this.fetchedDocument >= this.getTotal()) {\n cb(null, null);\n return;\n }\n\n // from and size parameters are not valid for a scroll action\n if (typeof options.from !== 'undefined') {\n delete options.from;\n }\n\n if (options.size) {\n delete options.size;\n }\n\n this.collection.scroll(options.scrollId, options, this.filters || {}, cb);\n\n return;\n }\n\n // retrieve next results using ES's search_after\n if (options.size && this.filters.sort) {\n if (this.fetchedDocument >= this.getTotal()) {\n cb(null, null);\n return;\n }\n\n if (options.from) {\n delete options.from;\n }\n\n filters = Object.assign(this.filters, {search_after: []});\n\n filters.sort.forEach(function (sortRule) {\n filters.search_after.push(self.documents[self.documents.length - 1].content[Object.keys(sortRule)[0]]);\n });\n\n this.collection.search(filters, options, cb);\n\n return;\n }\n\n // retrieve next results with from/size if original search use it\n if (options.from !== undefined && options.size !== undefined) {\n filters = Object.assign({}, this.filters);\n\n // check if we need to do next request to fetch all matching documents\n options.from += options.size;\n\n if (options.from >= this.getTotal()) {\n cb(null, null);\n\n return;\n }\n\n this.collection.search(filters, options, cb);\n\n return;\n }\n\n cb(new Error('Unable to retrieve next results from search: missing scrollId or from/size params'));\n};\n\n/**\n * @returns {Document[]}\n */\nSearchResult.prototype.getDocuments = function () {\n return this.documents;\n};\n\n/**\n * @returns {number}\n */\nSearchResult.prototype.getTotal = function () {\n return this.total;\n};\n\n/**\n * @returns {object}\n */\nSearchResult.prototype.getAggregations = function () {\n return this.aggregations;\n};\n\n/**\n * @returns {Object}\n */\nSearchResult.prototype.getOptions = function() {\n return this.options;\n};\n\n/**\n * @returns {object}\n */\nSearchResult.prototype.getFilters = function() {\n return this.filters;\n};\n\n/**\n * @returns {object}\n */\nSearchResult.prototype.getCollection = function () {\n return this.collection;\n};\n\n/**\n * @returns {number}\n */\nSearchResult.prototype.getFetchedDocument = function () {\n return this.fetchedDocument;\n};\n\nmodule.exports = SearchResult;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/SearchResult.js\n// module id = 12\n// module chunks = 0","/**\n *\n * @param protocol\n * @param host\n * @param options\n * @returns {Object} Instantiated WebSocket/Socket.IO object\n */\n\nfunction network(protocol, host, options) {\n switch (protocol) {\n case 'websocket':\n if (typeof window !== 'undefined' && typeof WebSocket === 'undefined') {\n throw new Error('Aborting: no websocket support detected.');\n }\n return new (require('./protocols/websocket'))(host, options);\n case 'socketio':\n if (!window.io) {\n throw new Error('Aborting: no socket.io library loaded.');\n }\n return new (require('./protocols/socketio'))(host, options);\n default:\n throw new Error('Aborting: unknown protocol \"' + protocol + '\" (only \"websocket\" and \"socketio\" are available).');\n }\n}\n\nmodule.exports = network;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/networkWrapper/index.js\n// module id = 13\n// module chunks = 0","var SecurityDocument = require('./SecurityDocument');\n\nfunction Profile(Security, id, content, meta) {\n\n SecurityDocument.call(this, Security, id, content, meta);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteProfile'\n },\n updateActionName: {\n value: 'updateProfile'\n }\n });\n\n // promisifying\n if (Security.kuzzle.bluebird) {\n return Security.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['hydrate', 'save'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n}\n\nProfile.prototype = Object.create(SecurityDocument.prototype, {\n constructor: {\n value: Profile\n }\n});\n\n/**\n * Persist to the persistent layer the current profile\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Profile} this\n */\nProfile.prototype.save = function (options, cb) {\n var\n data,\n self = this;\n\n if (!this.content.policies) {\n throw new Error('Argument \"policies\" is mandatory in a profile. This argument contains an array of objects.');\n }\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = this.serialize();\n\n self.kuzzle.query(self.Security.buildQueryArgs('createOrReplaceProfile'), data, options, cb && function (error) {\n cb(error, error ? undefined : self);\n });\n\n return self;\n};\n\n\n/**\n * Add a policy in the policies list\n * @param {Object} policy - must be an object containing at least a \"roleId\" member which must be a string.\n *\n * @returns {Profile} this\n */\nProfile.prototype.addPolicy = function (policy) {\n\n if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n throw new Error('Parameter \"policies\" must be an object containing at least a \"roleId\" member which must be a string.');\n }\n\n if (!this.content.policies) {\n this.content.policies = [];\n }\n\n this.content.policies.push(policy);\n\n return this;\n};\n\n/**\n * Set policies list\n * @param {Array} policies - must be an array of objects containing at least a \"roleId\" member which must be a string\n *\n * @returns {Profile} this\n */\nProfile.prototype.setPolicies = function (policies) {\n\n if (!Array.isArray(policies)) {\n throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n }\n\n policies.map(function (policy) {\n if (typeof policy !== 'object' || typeof policy.roleId !== 'string') {\n throw new Error('Parameter \"policies\" must be an array of objects containing at least a \"roleId\" member which must be a string');\n }\n });\n\n this.content.policies = policies;\n\n return this;\n};\n\n/**\n * Serialize this object into a JSON object\n *\n * @return {object} JSON object representing this securityDocument\n */\nProfile.prototype.serialize = function () {\n var\n data = {};\n\n if (this.id) {\n data._id = this.id;\n }\n\n data.body = this.content;\n data.meta = this.meta;\n\n return data;\n};\n\n/**\n * Returns the list of policies associated to this profile.\n * Each policy element is an array of objects containing at least a \"roleId\" member which must be a string\n *\n * @return {object} an array of policies\n */\nProfile.prototype.getPolicies = function () {\n return this.content.policies;\n};\n\nmodule.exports = Profile;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/security/Profile.js\n// module id = 14\n// module chunks = 0","var SecurityDocument = require('./SecurityDocument');\n\nfunction Role(Security, id, content, meta) {\n\n SecurityDocument.call(this, Security, id, content, meta);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteRole'\n },\n updateActionName: {\n value: 'updateRole'\n }\n });\n\n // promisifying\n if (Security.kuzzle.bluebird) {\n return Security.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var whitelist = ['save'];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n\n}\n\nRole.prototype = Object.create(SecurityDocument.prototype, {\n constructor: {\n value: Role\n }\n});\n\n/**\n * Saves this role into Kuzzle.\n *\n * If this is a new role, this function will create it in Kuzzle.\n * Otherwise, this method will replace the latest version of this role in Kuzzle by the current content\n * of this object.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Role} this object\n */\nRole.prototype.save = function (options, cb) {\n var\n data = this.serialize(),\n self = this;\n\n if (options && cb === undefined && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.Security.buildQueryArgs('createOrReplaceRole'), data, options, cb && function (error) {\n cb(error, error ? undefined : self);\n });\n\n return this;\n};\n\nmodule.exports = Role;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/security/Role.js\n// module id = 15\n// module chunks = 0","var\n Role = require('./Role'),\n Profile = require('./Profile'),\n User = require('./User');\n\n/**\n * Kuzzle security constructor\n *\n * @param kuzzle\n * @returns {Security}\n * @constructor\n */\nfunction Security(kuzzle) {\n\n Object.defineProperty(this, 'kuzzle', {\n value: kuzzle\n });\n\n Object.defineProperty(this, 'buildQueryArgs', {\n value: function (action) {\n return {\n controller: 'security',\n action: action\n };\n }\n });\n\n if (this.kuzzle.bluebird) {\n return this.kuzzle.bluebird.promisifyAll(this, {\n suffix: 'Promise',\n filter: function (name, func, target, passes) {\n var blacklist = ['role', 'profile', 'user', 'isActionAllowed'];\n\n return passes && blacklist.indexOf(name) === -1;\n }\n });\n }\n\n return this;\n}\n\n\n/**\n * Retrieve a single Role using its unique role ID.\n *\n * @param {string} id\n * @param {object|responseCallback} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nSecurity.prototype.fetchRole = function (id, options, cb) {\n var\n data,\n self = this;\n\n if (!id) {\n throw new Error('Id parameter is mandatory for fetchRole function');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data = {_id: id};\n\n self.kuzzle.callbackRequired('Security.fetchRole', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n cb(err, err ? undefined : new Role(self, response.result._id, response.result._source, response.result._meta));\n });\n};\n\n/**\n * Executes a search on roles according to a filter\n *\n * /!\\ There is a small delay between role creation and their existence in our persistent search layer,\n * usually a couple of seconds.\n * That means that a role that was just been created won’t be returned by this function.\n *\n * @param {Object} filters - this object can contains an array `indexes` with a list of index id, a integer `from` and a integer `size`\n * @param {object|responseCallback} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n *\n */\nSecurity.prototype.searchRoles = function (filters, options, cb) {\n var\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Security.searchRoles', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchRoles'), {body: filters}, options, function (error, result) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = result.result.hits.map(function (doc) {\n return new Role(self, doc._id, doc._source, doc._meta);\n });\n\n cb(null, { total: result.result.total, roles: documents });\n });\n};\n\n/**\n * Create a new role in Kuzzle.\n *\n * Takes an optional argument object with the following property:\n * - replaceIfExist (boolean, default: false):\n * If the same role already exists: throw an error if sets to false.\n * Replace the existing role otherwise\n *\n * @param {string} id - role identifier\n * @param {object} content - a plain javascript object representing the role\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nSecurity.prototype.createRole = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'createRole';\n\n if (!id || typeof id !== 'string') {\n throw new Error('Security.createRole: cannot create a role without a role ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n data.body = content;\n\n if (options) {\n action = options.replaceIfExist ? 'createOrReplaceRole' : 'createRole';\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new Role(self, res.result._id, res.result._source, res.result._meta));\n });\n};\n\n\n/**\n * Update a role in Kuzzle.\n *\n * @param {string} id - role identifier\n * @param {object} content - a plain javascript object representing the role's modification\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {Security} this object\n */\nSecurity.prototype.updateRole = function (id, content, options, cb) {\n var\n self = this,\n data = {_id: id, body: content},\n action = 'updateRole';\n\n if (!id || typeof id !== 'string') {\n throw new Error('Security.updateRole: cannot update a role without a role ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new Role(self, id, content, res.result._meta));\n });\n\n return this;\n};\n\n/**\n * Delete role.\n *\n * There is a small delay between role deletion and their deletion in our advanced search layer,\n * usually a couple of seconds.\n * That means that a role that was just been delete will be returned by this function\n *\n *\n * @param {string} id - Role id to delete\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Security} this object\n */\nSecurity.prototype.deleteRole = function (id, options, cb) {\n var data = {_id: id};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.buildQueryArgs('deleteRole'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result._id);\n });\n\n return this;\n};\n\n/**\n * Instantiate a new Role object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - role id\n * @param {object} content - role content\n * @param {object} meta - role metadata\n * @constructor\n */\nSecurity.prototype.role = function(id, content, meta) {\n return new Role(this, id, content, meta);\n};\n\n\n/**\n * Get a specific profile from kuzzle\n *\n *\n * @param {string} id\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nSecurity.prototype.fetchProfile = function (id, options, cb) {\n var\n data,\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (!id || typeof id !== 'string') {\n throw new Error('Id parameter is mandatory for fetchProfile function');\n }\n\n\n data = {_id: id};\n\n self.kuzzle.callbackRequired('Security.fetchProfile', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n cb(error, error ? undefined : new Profile(self, response.result._id, response.result._source, response.result._meta));\n });\n};\n\n/**\n * Executes a search on profiles according to a filter\n *\n *\n * /!\\ There is a small delay between profile creation and their existence in our persistent search layer,\n * usually a couple of seconds.\n * That means that a profile that was just been created won’t be returned by this function.\n *\n * @param {Object} filters - this object can contains an array `roles` with a list of roles id, a integer `from` and a integer `size`\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nSecurity.prototype.searchProfiles = function (filters, options, cb) {\n var\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Security.searchProfiles', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n var\n documents,\n scrollId;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new Profile(self, doc._id, doc._source, doc._meta);\n });\n\n if (response.result.scrollId) {\n scrollId = response.result.scrollId;\n }\n\n cb(null, { total: response.result.total, profiles: documents, scrollId: scrollId });\n });\n};\n\n/**\n * Create a new profile in Kuzzle.\n *\n * Takes an optional argument object with the following property:\n * - replaceIfExist (boolean, default: false):\n * If the same profile already exists: throw an error if sets to false.\n * Replace the existing profile otherwise\n *\n * @param {string} id - profile identifier\n * @param {array} policies - list of policies to attach to the new profile\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nSecurity.prototype.createProfile = function (id, policies, options, cb) {\n var\n self = this,\n data = {},\n action = 'createProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('Security.createProfile: cannot create a profile without a profile ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n\n if (policies) {\n data.body = { policies: policies };\n }\n\n if (options) {\n action = options.replaceIfExist ? 'createOrReplaceProfile' : 'createProfile';\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new Profile(self, res.result._id, res.result._source, res.result._meta));\n });\n};\n\n\n/**\n * Update a profile in Kuzzle.\n *\n * @param {string} id - profile identifier\n * @param {array} policies - the list of policies to apply to this profile\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {Security} this object\n */\nSecurity.prototype.updateProfile = function (id, policies, options, cb) {\n var\n self = this,\n data = {},\n action = 'updateProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('Security.updateProfile: cannot update a profile without a profile ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n\n if (policies) {\n data.body = {policies: policies};\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n var updatedContent = {};\n\n if (err) {\n return cb(err);\n }\n\n Object.keys(res.result._source).forEach(function (property) {\n updatedContent[property] = res.result._source[property];\n });\n\n cb(null, new Profile(self, res.result._id, updatedContent, res.result._meta));\n });\n\n return this;\n};\n\n/**\n * Delete profile.\n *\n * There is a small delay between profile deletion and their deletion in our advanced search layer,\n * usually a couple of seconds.\n * That means that a profile that was just been delete will be returned by this function\n *\n *\n * @param {string} id - Profile id to delete\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Security} this object\n */\nSecurity.prototype.deleteProfile = function (id, options, cb) {\n var data = {_id: id};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.buildQueryArgs('deleteProfile'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result._id);\n });\n\n return this;\n};\n\n/**\n * @param {string} scrollId\n * @param {object} [options]\n * @param {responseCallback} cb\n */\nSecurity.prototype.scrollProfiles = function (scrollId, options, cb) {\n var\n request = {},\n self = this;\n\n if (!scrollId) {\n throw new Error('Security.scrollProfiles: scrollId is required');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n this.kuzzle.callbackRequired('Security.scrollProfiles', cb);\n\n request.scrollId = scrollId;\n\n if (options && options.scroll) {\n request.scroll = options.scroll;\n }\n\n this.kuzzle.query({controller: 'security', action: 'scrollProfiles'}, request, options, function (error, result) {\n var profiles = [];\n\n if (error) {\n return cb(error);\n }\n\n result.result.hits.forEach(function (profile) {\n var newProfile = new Profile(self, profile._id, profile._source, profile._meta);\n\n newProfile.version = profile._version;\n\n profiles.push(newProfile);\n });\n\n cb(null, {\n total: result.result.total,\n profiles: profiles,\n scrollId: scrollId\n });\n });\n};\n\n/**\n * Instantiate a new Profile object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - profile id\n * @param {object} content - profile content\n * @param {object} meta - profile metadata\n * @constructor\n */\nSecurity.prototype.profile = function(id, content, meta) {\n return new Profile(this, id, content, meta);\n};\n\n/**\n * Get a specific user from kuzzle using its unique ID\n *\n * @param {string} id\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nSecurity.prototype.fetchUser = function (id, options, cb) {\n var\n data = {_id: id},\n self = this;\n\n if (!id || typeof id !== 'string') {\n throw new Error('Id parameter is mandatory for fetchUser function');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Security.fetchUser', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n cb(err, err ? undefined : new User(self, response.result._id, response.result._source, response.result._meta));\n });\n};\n\n/**\n * Executes a search on user according to a filter\n *\n * /!\\ There is a small delay between user creation and their existence in our persistent search layer,\n * usually a couple of seconds.\n * That means that a user that was just been created won’t be returned by this function.\n *\n * @param {Object} filters - same filters as documents filters\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nSecurity.prototype.searchUsers = function (filters, options, cb) {\n var\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Security.searchUsers', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n var\n documents,\n scrollId = null;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new User(self, doc._id, doc._source, doc._meta);\n });\n\n if (response.result.scrollId) {\n scrollId = response.result.scrollId;\n }\n\n cb(null, { total: response.result.total, users: documents, scrollId: scrollId });\n });\n};\n\n/**\n * Create a new user in Kuzzle.\n *\n * @param {string} id - user identifier\n * @param {object} content - attribute `profileIds` in `content` must only contain an array of profile ids\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nSecurity.prototype.createUser = function (id, content, options, cb) {\n var\n self = this,\n data = {_id: id, body: content};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(self.buildQueryArgs('createUser'), data, null, cb && function (err, res) {\n cb(err, err ? undefined : new User(self, res.result._id, res.result._source, res.result._meta));\n });\n};\n\n/**\n * Replace an user in Kuzzle.\n *\n * @param {string} id - user identifier\n * @param {object} content - attribute `profileIds` in `content` must only contain an array of profile ids\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nSecurity.prototype.replaceUser = function (id, content, options, cb) {\n var\n self = this,\n data = {_id: id, body: content};\n\n if (!id || typeof id !== 'string') {\n throw new Error('Security.replaceUser: cannot replace a user without a user ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.buildQueryArgs('replaceUser'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new User(self, res.result._id, res.result._source, res.result._meta));\n });\n};\n\n/**\n * Create a new restricted user in Kuzzle.\n *\n * This function will create a new user. It is not usable to update an existing user.\n * This function allows anonymous users to create a \"restricted\" user with predefined rights.\n *\n * @param {string} id - user identifier\n * @param {object} content - attribute `profile` in `content` must only contains the profile id\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nSecurity.prototype.createRestrictedUser = function (id, content, options, cb) {\n var\n self = this,\n data = {_id: id, body: content};\n\n if (content.profileIds) {\n throw new Error('Security.createRestrictedUser: cannot provide profileIds');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.query(this.buildQueryArgs('createRestrictedUser'), data, null, cb && function (err, res) {\n cb(err, err ? undefined : new User(self, res.result._id, res.result._source));\n });\n};\n\n\n/**\n * Update an user in Kuzzle.\n *\n * @param {string} id - user identifier\n * @param {object} content - a plain javascript object representing the user's modification\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n * @returns {Security} this object\n */\nSecurity.prototype.updateUser = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'updateUser';\n\n if (!id || typeof id !== 'string') {\n throw new Error('Security.updateUser: cannot update an user without an user ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n data._id = id;\n data.body = content;\n\n self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) {\n cb(err, err ? undefined : new User(self, res.result._id, res.result._source, res.result._meta));\n });\n\n return this;\n};\n\n/**\n * Delete user.\n *\n * There is a small delay between user deletion and their deletion in our advanced search layer,\n * usually a couple of seconds.\n * That means that a user that was just been delete will be returned by this function\n *\n *\n * @param {string} id - Profile id to delete\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Security} this object\n */\nSecurity.prototype.deleteUser = function (id, options, cb) {\n var data = {_id: id};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query(this.buildQueryArgs('deleteUser'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result._id);\n });\n\n return this;\n};\n\n/**\n * @param {string} scrollId\n * @param {object} [options]\n * @param {responseCallback} cb\n */\nSecurity.prototype.scrollUsers = function (scrollId, options, cb) {\n var\n request = {},\n self = this;\n\n if (!scrollId) {\n throw new Error('Security.scrollUsers: scrollId is required');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n this.kuzzle.callbackRequired('Security.scrollUsers', cb);\n\n request.scrollId = scrollId;\n\n if (options && options.scroll) {\n request.scroll = options.scroll;\n }\n\n this.kuzzle.query({controller: 'security', action: 'scrollUsers'}, request, options, function (error, result) {\n var users = [];\n\n if (error) {\n return cb(error);\n }\n\n result.result.hits.forEach(function (user) {\n var newUser = new User(self, user._id, user._source, user._meta);\n\n newUser.version = user._version;\n\n users.push(newUser);\n });\n\n cb(null, {\n total: result.result.total,\n users: users,\n scrollId: scrollId\n });\n });\n\n return this;\n};\n\n/**\n * Instantiate a new User object. Workaround to the module.exports limitation, preventing multiple\n * constructors to be exposed without having to use a factory or a composed object.\n *\n * @param {string} id - user id\n * @param {object} content - user content\n * @param {object} meta - user metadata\n * @constructor\n */\nSecurity.prototype.user = function(id, content, meta) {\n return new User(this, id, content, meta);\n};\n\n/**\n * Tells whether an action is allowed, denied or conditional based on the rights\n * rights provided as the first argument. An action is defined as a couple of\n * action and controller (mandatory), plus an index and a collection(optional).\n *\n * @param {object} rights - The rights rights associated to a user\n * (see getMyrights and getUserrights).\n * @param {string} controller - The controller to check the action onto.\n * @param {string} action - The action to perform.\n * @param {string} index - (optional) The name of index to perform the action onto.\n * @param {string} collection - (optional) The name of the collection to perform the action onto.\n *\n * @returns {string} ['allowed', 'denied', 'conditional'] where conditional cases\n * correspond to rights containing closures.\n * See also http://kuzzle.io/guide/#roles-definition\n */\nSecurity.prototype.isActionAllowed = function(rights, controller, action, index, collection) {\n var filteredRights;\n\n if (!rights || typeof rights !== 'object') {\n throw new Error('rights parameter is mandatory for isActionAllowed function');\n }\n if (!controller || typeof controller !== 'string') {\n throw new Error('controller parameter is mandatory for isActionAllowed function');\n }\n if (!action || typeof action !== 'string') {\n throw new Error('action parameter is mandatory for isActionAllowed function');\n }\n\n // We filter in all the rights that match the request (including wildcards).\n filteredRights = rights\n .filter(function (right) {\n return right.controller === controller || right.controller === '*';\n })\n .filter(function (right) {\n return right.action === action || right.action === '*';\n })\n .filter(function (right) {\n return right.index === index || right.index === '*';\n })\n .filter(function (right) {\n return right.collection === collection || right.collection === '*';\n });\n\n // Then, if at least one right allows the action, we return 'allowed'\n if (filteredRights.some(function (item) { return item.value === 'allowed'; })) {\n return 'allowed';\n }\n // If no right allows the action, we check for conditionals.\n if (filteredRights.some(function (item) { return item.value === 'conditional'; })) {\n return 'conditional';\n }\n // Otherwise we return 'denied'.\n return 'denied';\n};\n\n\n/**\n * Gets the rights array of a given user.\n *\n * @param {string} userId The id of the user.\n * @param {object|responseCallback} [options] - (optional) arguments\n * @param {function} cb The callback containing the normalized array of rights.\n */\nSecurity.prototype.getUserRights = function (userId, options, cb) {\n var\n data = {_id: userId},\n self = this;\n\n if (!userId || typeof userId !== 'string') {\n throw new Error('userId parameter is mandatory for getUserRights function');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('Kuzzle.getUserRights', cb);\n\n this.kuzzle.query(this.buildQueryArgs('getUserRights'), data, options, cb && function (err, res) {\n cb(err, err ? undefined : res.result.hits);\n });\n};\n\n/**\n * Create credentials of the specified for the user .\n *\n * @param strategy\n * @param kuid\n * @param credentials\n * @param options\n * @param cb\n * @returns {Security}\n */\nSecurity.prototype.createCredentials = function (strategy, kuid, credentials, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'createCredentials'}, {_id: kuid, strategy: strategy, body: credentials}, options, function(err, res) {\n if (!err) {\n cb && cb(null, res.result._source);\n } else {\n cb && cb(err);\n }\n });\n\n return this;\n};\n\n/**\n * Delete credentials of the specified for the user .\n *\n * @param strategy\n * @param kuid\n * @param options\n * @param cb\n * @returns {Security}\n */\nSecurity.prototype.deleteCredentials = function (strategy, kuid, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'deleteCredentials'}, {strategy: strategy, _id: kuid}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n\n return this;\n};\n\n/**\n * Retrieve a list of accepted fields per authentication strategy.\n *\n * @param options\n * @param cb\n */\nSecurity.prototype.getAllCredentialFields = function (options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'getAllCredentialFields'}, {}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n};\n\n/**\n * Retrieve the list of accepted field names by the specified .\n *\n * @param strategy\n * @param options\n * @param cb\n */\nSecurity.prototype.getCredentialFields = function (strategy, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'getCredentialFields'}, {strategy: strategy}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n};\n\n/**\n * Get credential information of the specified for the user .\n *\n * @param strategy\n * @param kuid\n * @param options\n * @param cb\n */\nSecurity.prototype.getCredentials = function (strategy, kuid, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'getCredentials'}, {strategy: strategy, _id: kuid}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n};\n\n/**\n * Check the existence of the specified ’s credentials for the user .\n *\n * @param strategy\n * @param kuid\n * @param options\n * @param cb\n */\nSecurity.prototype.hasCredentials = function (strategy, kuid, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'hasCredentials'}, {strategy: strategy, _id: kuid}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n};\n\n/**\n * Updates credentials of the specified for the user .\n *\n * @param strategy\n * @param kuid\n * @param credentials\n * @param options\n * @param cb\n * @returns {Security}\n */\nSecurity.prototype.updateCredentials = function (strategy, kuid, credentials, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'updateCredentials'}, {strategy: strategy, _id: kuid, body: credentials}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n\n return this;\n};\n\n/**\n * Validate credentials of the specified for the user .\n *\n * @param strategy\n * @param kuid\n * @param credentials\n * @param options\n * @param cb\n */\nSecurity.prototype.validateCredentials = function (strategy, kuid, credentials, options, cb) {\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.query({controller: 'security', action: 'validateCredentials'}, {strategy: strategy, _id: kuid, body: credentials}, options, typeof cb !== 'function' ? null : function(err, res) {\n if (!err) {\n cb && cb(null, res.result);\n } else {\n cb && cb(err);\n }\n });\n};\n\nmodule.exports = Security;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/security/Security.js\n// module id = 16\n// module chunks = 0","/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nvar byteToHex = [];\nfor (var i = 0; i < 256; ++i) {\n byteToHex[i] = (i + 0x100).toString(16).substr(1);\n}\n\nfunction bytesToUuid(buf, offset) {\n var i = offset || 0;\n var bth = byteToHex;\n return bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]];\n}\n\nmodule.exports = bytesToUuid;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/uuid/lib/bytesToUuid.js\n// module id = 17\n// module chunks = 0","// Unique ID creation requires a high quality random # generator. In the\n// browser this is a little complicated due to unknown quality of Math.random()\n// and inconsistent support for the `crypto` API. We do the best we can via\n// feature-detection\nvar rng;\n\nvar crypto = global.crypto || global.msCrypto; // for IE 11\nif (crypto && crypto.getRandomValues) {\n // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto\n var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef\n rng = function whatwgRNG() {\n crypto.getRandomValues(rnds8);\n return rnds8;\n };\n}\n\nif (!rng) {\n // Math.random()-based (RNG)\n //\n // If all else fails, use Math.random(). It's fast, but is of unspecified\n // quality.\n var rnds = new Array(16);\n rng = function() {\n for (var i = 0, r; i < 16; i++) {\n if ((i & 0x03) === 0) r = Math.random() * 0x100000000;\n rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n }\n\n return rnds;\n };\n}\n\nmodule.exports = rng;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/uuid/lib/rng-browser.js\n// module id = 18\n// module chunks = 0","var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\nfunction v4(options, buf, offset) {\n var i = buf && offset || 0;\n\n if (typeof(options) == 'string') {\n buf = options == 'binary' ? new Array(16) : null;\n options = null;\n }\n options = options || {};\n\n var rnds = options.random || (options.rng || rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n for (var ii = 0; ii < 16; ++ii) {\n buf[i + ii] = rnds[ii];\n }\n }\n\n return buf || bytesToUuid(rnds);\n}\n\nmodule.exports = v4;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/uuid/v4.js\n// module id = 19\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/src/Kuzzle.js b/src/Kuzzle.js index fcb0ffe62..3b8712a61 100644 --- a/src/Kuzzle.js +++ b/src/Kuzzle.js @@ -1,4 +1,4 @@ -var +const uuidv4 = require('uuid/v4'), KuzzleEventEmitter = require('./eventEmitter'), Collection = require('./Collection.js'), @@ -24,1335 +24,1230 @@ var * @param [options] - Connection options * @param {responseCallback} [cb] - Handles connection response */ -function Kuzzle (host, options, cb) { - var self = this; +class Kuzzle extends KuzzleEventEmitter { + constructor(host, options) { + super(); - if (!(this instanceof Kuzzle)) { - return new Kuzzle(host, options, cb); - } - KuzzleEventEmitter.call(this); - - if (!cb && typeof options === 'function') { - cb = options; - options = null; - } - - if (!host || host === '') { - throw new Error('host argument missing'); - } - - Object.defineProperties(this, { - // 'private' properties - connectCB: { - value: cb - }, - eventActions: { - value: [ - 'connected', - 'discarded', - 'disconnected', - 'loginAttempt', - 'networkError', - 'offlineQueuePush', - 'offlineQueuePop', - 'queryError', - 'reconnected', - 'tokenExpired' - ] - }, - // configuration properties - autoResubscribe: { - value: options && typeof options.autoResubscribe === 'boolean' ? options.autoResubscribe : true, - enumerable: true - }, - defaultIndex: { - value: (options && typeof options.defaultIndex === 'string') ? options.defaultIndex : undefined, - writable: true, - enumerable: true - }, - jwt: { - value: undefined, - enumerable: true, - writable: true - }, - protocol: { - value: (options && typeof options.protocol === 'string') ? options.protocol : 'websocket', - enumerable: true - }, - sdkVersion: { - value: (typeof SDKVERSION === 'undefined') ? require('../package.json').version : SDKVERSION - }, - volatile: { - value: {}, - enumerable: true, - writable: true + if (!host || host === '') { + throw new Error('host argument missing'); } - }); - if (options) { - Object.keys(options).forEach(function (opt) { - if (self.hasOwnProperty(opt) && Object.getOwnPropertyDescriptor(self, opt).writable) { - self[opt] = options[opt]; + Object.defineProperties(this, { + // 'private' properties + eventActions: { + value: [ + 'connected', + 'discarded', + 'disconnected', + 'loginAttempt', + 'networkError', + 'offlineQueuePush', + 'offlineQueuePop', + 'queryError', + 'reconnected', + 'tokenExpired' + ] + }, + // configuration properties + autoResubscribe: { + value: options && typeof options.autoResubscribe === 'boolean' ? options.autoResubscribe : true, + enumerable: true + }, + defaultIndex: { + value: (options && typeof options.defaultIndex === 'string') ? options.defaultIndex : undefined, + writable: true, + enumerable: true + }, + jwt: { + value: undefined, + enumerable: true, + writable: true + }, + protocol: { + value: (options && typeof options.protocol === 'string') ? options.protocol : 'websocket', + enumerable: true + }, + sdkVersion: { + value: (typeof SDKVERSION === 'undefined') ? require('../package.json').version : SDKVERSION + }, + volatile: { + value: {}, + enumerable: true, + writable: true } }); - } - // Forward the subscribe query to the network wrapper - Object.defineProperty(this, 'subscribe', { - value: function(room, opts, subscribeCB) { - var - object = { - requestId: uuidv4(), - controller: 'realtime', - action: 'subscribe', - index: room.collection.index, - collection: room.collection.collection, - volatile: this.volatile, - body: room.filters, - scope: room.scope, - state: room.state, - users: room.users - }, - notificationCB = function(data) { - var copy; - - if (data.type === 'TokenExpired') { - self.unsetJwt(); - return self.emitEvent('tokenExpired'); - } + if (options) { + for (const opt of Object.keys(options)) { + if (this.hasOwnProperty(opt) && Object.getOwnPropertyDescriptor(this, opt).writable) { + this[opt] = options[opt]; + } + } + } - if (data.type === 'document') { - copy = Object.assign({}, data); - copy.document = new Document(room.collection, data.result._id, data.result._source, data.result._meta); - delete copy.result; - return room.notify(copy); - } + // Forward the subscribe query to the network wrapper + Object.defineProperty(this, 'subscribe', { + value: function(room, opts, subscribeCB) { + const + object = { + requestId: uuidv4(), + controller: 'realtime', + action: 'subscribe', + index: room.collection.index, + collection: room.collection.collection, + volatile: this.volatile, + body: room.filters, + scope: room.scope, + state: room.state, + users: room.users + }, + notificationCB = data => { + if (data.type === 'TokenExpired') { + this.unsetJwt(); + return this.emit('tokenExpired'); + } + + if (data.type === 'document') { + const copy = Object.assign({}, data); + copy.document = new Document(room.collection, data.result._id, data.result._source, data.result._meta); + delete copy.result; + return room.notify(copy); + } + + room.notify(data); + }; + + if (this.jwt !== undefined) { + object.jwt = this.jwt; + } - room.notify(data); - }; + Object.assign(object.volatile, room.volatile, {sdkVersion: this.sdkVersion}); - if (this.jwt !== undefined) { - object.jwt = this.jwt; + this.network.subscribe(object, opts, notificationCB, subscribeCB); } + }); - Object.assign(object.volatile, room.volatile, {sdkVersion: this.sdkVersion}); + // Forward the unsubscribe query to the network wrapper + Object.defineProperty(this, 'unsubscribe', { + value: (room, unsubscribeCB) => { + const + object = { + requestId: uuidv4(), + controller: 'realtime', + action: 'unsubscribe', + volatile: this.volatile, + body: {roomId: room.roomId} + }; + + if (this.jwt !== undefined) { + object.jwt = this.jwt; + } - this.network.subscribe(object, opts, notificationCB, subscribeCB); - } - }); - - // Forward the unsubscribe query to the network wrapper - Object.defineProperty(this, 'unsubscribe', { - value: function(room, unsubscribeCB) { - var - object = { - requestId: uuidv4(), - controller: 'realtime', - action: 'unsubscribe', - volatile: this.volatile, - body: {roomId: room.roomId} - }; - - if (this.jwt !== undefined) { - object.jwt = this.jwt; + Object.assign(object.volatile, room.volatile, {sdkVersion: this.sdkVersion}); + + this.network.unsubscribe(object, room.channel, unsubscribeCB); } + }); - Object.assign(object.volatile, room.volatile, {sdkVersion: this.sdkVersion}); - if (room.volatile) { - Object.keys(room.volatile).forEach(function (meta) { - object.volatile[meta] = room.volatile[meta]; - }); + /** + * Some methods (mainly read queries) require a callback function. This function exists to avoid repetition of code, + * and is called by these methods + */ + Object.defineProperty(this, 'callbackRequired', { + value: (errorMessagePrefix, callback) => { + if (!callback || typeof callback !== 'function') { + throw new Error(`${errorMessagePrefix}: a callback argument is required for read queries`); + } } - object.volatile.sdkVersion = this.sdkVersion; + }); - this.network.unsubscribe(object, room.channel, unsubscribeCB); - } - }); + /** + * Create an attribute security that embed all methods to manage Role, Profile and User + */ + Object.defineProperty(this, 'security', { + value: new Security(this), + enumerable: true + }); - /** - * Some methods (mainly read queries) require a callback function. This function exists to avoid repetition of code, - * and is called by these methods - */ - Object.defineProperty(this, 'callbackRequired', { - value: function (errorMessagePrefix, callback) { - if (!callback || typeof callback !== 'function') { - throw new Error(errorMessagePrefix + ': a callback argument is required for read queries'); + Object.defineProperty(this, 'memoryStorage', { + value: new MemoryStorage(this), + enumerable: true + }); + + Object.defineProperty(this, 'collections',{ + value: {}, + writable: true + }); + + Object.defineProperty(this, 'eventTimeout',{ + value: options && typeof options.eventTimeout === 'number' ? options.eventTimeout : 200 + }); + + Object.defineProperty(this, 'protectedEvents', { + value: { + connected: {timeout: this.eventTimeout}, + error: {timeout: this.eventTimeout}, + disconnected: {timeout: this.eventTimeout}, + reconnected: {timeout: this.eventTimeout}, + tokenExpired: {timeout: this.eventTimeout}, + loginAttempt: {timeout: this.eventTimeout} } - } - }); + }); - /** - * Create an attribute security that embed all methods to manage Role, Profile and User - */ - Object.defineProperty(this, 'security', { - value: new Security(this), - enumerable: true - }); - - Object.defineProperty(this, 'memoryStorage', { - value: new MemoryStorage(this), - enumerable: true - }); - - Object.defineProperty(this, 'collections',{ - value: {}, - writable: true - }); - - Object.defineProperty(this, 'eventTimeout',{ - value: options && typeof options.eventTimeout === 'number' ? options.eventTimeout : 200 - }); - - Object.defineProperty(this, 'protectedEvents', { - value: { - connected: {timeout: this.eventTimeout}, - error: {timeout: this.eventTimeout}, - disconnected: {timeout: this.eventTimeout}, - reconnected: {timeout: this.eventTimeout}, - tokenExpired: {timeout: this.eventTimeout}, - loginAttempt: {timeout: this.eventTimeout} - } - }); - - this.network = networkWrapper(this.protocol, host, options); - - // Properties related to the network layer - // Accessing a property irrelevant for a given protocol - // (e.g. "autoReconnect" for the HTTP layer) should - // throw an exception - Object.defineProperties(this, { - autoQueue: { - enumerable: true, - get: function() { - return self.network.autoQueue; + this.network = networkWrapper(this.protocol, host, options); + + // Properties related to the network layer + // Accessing a property irrelevant for a given protocol + // (e.g. "autoReconnect" for the HTTP layer) should + // throw an exception + Object.defineProperties(this, { + autoQueue: { + enumerable: true, + get: () => this.network.autoQueue, + set: value => { + checkPropertyType('autoQueue', 'boolean', value); + this.network.autoQueue = value; + } }, - set: function(value) { - checkPropertyType('autoQueue', 'boolean', value); - self.network.autoQueue = value; - } - }, - autoReconnect: { - enumerable: true, - get: function() { - return self.network.autoReconnect; - } - }, - autoReplay: { - enumerable: true, - get: function() { - return self.network.autoReplay; + autoReconnect: { + enumerable: true, + get: () => this.network.autoReconnect }, - set: function(value) { - checkPropertyType('autoReplay', 'boolean', value); - self.network.autoReplay = value; - } - }, - host: { - enumerable: true, - get: function() { - return self.network.host; - } - }, - offlineQueue: { - enumerable: true, - get: function() { - return self.network.offlineQueue; - } - }, - offlineQueueLoader: { - enumerable: true, - get: function() { - return self.network.offlineQueueLoader; + autoReplay: { + enumerable: true, + get: () => this.network.autoReplay, + set: value => { + checkPropertyType('autoReplay', 'boolean', value); + this.network.autoReplay = value; + } }, - set: function(value) { - if (value !== null) { - checkPropertyType('offlineQueueLoader', 'function', value); + host: { + enumerable: true, + get: () => this.network.host + }, + offlineQueue: { + enumerable: true, + get: () => this.network.offlineQueue + }, + offlineQueueLoader: { + enumerable: true, + get: () => this.network.offlineQueueLoader, + set: value => { + if (value !== null) { + checkPropertyType('offlineQueueLoader', 'function', value); + } + this.network.offlineQueueLoader = value; } - self.network.offlineQueueLoader = value; - } - }, - port: { - enumerable: true, - get: function() { - return self.network.port; - } - }, - queueFilter: { - enumerable: true, - get: function() { - return self.network.queueFilter; }, - set: function(value) { - if (typeof value !== 'function') { - throw new Error('Can only assign a function to the "queueFilter" property'); + port: { + enumerable: true, + get: () => this.network.port + }, + queueFilter: { + enumerable: true, + get: () => this.network.queueFilter, + set: value => { + checkPropertyType('queueFilter', 'function', value); + this.network.queueFilter = value; } - self.network.queueFilter = value; - } - }, - queueMaxSize: { - enumerable: true, - get: function() { - return self.network.queueMaxSize; }, - set: function(value) { - checkPropertyType('queueMaxSize', 'number', value); - self.network.queueMaxSize = value; - } - }, - queueTTL: { - enumerable: true, - get: function() { - return self.network.queueTTL; + queueMaxSize: { + enumerable: true, + get: () => this.network.queueMaxSize, + set: value => { + checkPropertyType('queueMaxSize', 'number', value); + this.network.queueMaxSize = value; + } }, - set: function(value) { - checkPropertyType('queueTTL', 'number', value); - self.network.queueTTL = value; - } - }, - replayInterval: { - enumerable: true, - get: function() { - return self.network.replayInterval; + queueTTL: { + enumerable: true, + get: () => this.network.queueTTL, + set: value => { + checkPropertyType('queueTTL', 'number', value); + this.network.queueTTL = value; + } }, - set: function(value) { - checkPropertyType('replayInterval', 'number', value); - self.network.replayInterval = value; - } - }, - reconnectionDelay: { - enumerable: true, - get: function() { - return self.network.reconnectionDelay; - } - }, - sslConnection: { - eumerable: true, - get: function() { - return self.network.ssl; + replayInterval: { + enumerable: true, + get: () => this.network.replayInterval, + set: value => { + checkPropertyType('replayInterval', 'number', value); + this.network.replayInterval = value; + } + }, + reconnectionDelay: { + enumerable: true, + get: () => this.network.reconnectionDelay + }, + sslConnection: { + eumerable: true, + get: () => this.network.ssl } - } - }); - - this.network.addListener('offlineQueuePush', function(data) { - self.emitEvent('offlineQueuePush', data); - }); - - this.network.addListener('offlineQueuePop', function(data) { - self.emitEvent('offlineQueuePop', data); - }); + }); - this.network.addListener('queryError', function(err, query) { - self.emitEvent('queryError', err, query); - }); + this.network.addListener('offlineQueuePush', data => this.emit('offlineQueuePush', data)); + this.network.addListener('offlineQueuePop', data => this.emit('offlineQueuePop', data)); + this.network.addListener('queryError', (err, query) => this.emit('queryError', err, query)); - this.network.addListener('tokenExpired', function() { - self.unsetJwt(); - self.emitEvent('tokenExpired'); - }); + this.network.addListener('tokenExpired', () => { + this.unsetJwt(); + this.emit('tokenExpired'); + }); - if ((options && options.connect || 'auto') === 'auto') { - this.connect(); + if (this.bluebird) { + return this.bluebird.promisifyAll(this, { + suffix: 'Promise', + filter: function (name, func, target, passes) { + const whitelist = ['getAllStatistics', 'getServerInfo', 'getStatistics', + 'listCollections', 'listIndexes', 'login', 'logout', 'now', 'query', + 'checkToken', 'whoAmI', 'updateSelf', 'getMyRights', 'getMyCredentials', + 'createMyCredentials', 'deleteMyCredentials', 'updateMyCredentials', 'validateMyCredentials', + 'createIndex', 'refreshIndex', 'getAutoRefresh', 'setAutoRefresh', 'connect' + ]; + + return passes && whitelist.indexOf(name) !== -1; + } + }); + } } - if (this.bluebird) { - return this.bluebird.promisifyAll(this, { - suffix: 'Promise', - filter: function (name, func, target, passes) { - var whitelist = ['getAllStatistics', 'getServerInfo', 'getStatistics', - 'listCollections', 'listIndexes', 'login', 'logout', 'now', 'query', - 'checkToken', 'whoAmI', 'updateSelf', 'getMyRights', 'getMyCredentials', - 'createMyCredentials', 'deleteMyCredentials', 'updateMyCredentials', 'validateMyCredentials', - 'createIndex', 'refreshIndex', 'getAutoRefresh', 'setAutoRefresh' - ]; - - return passes && whitelist.indexOf(name) !== -1; + /** + * Emit an event to all registered listeners + * An event cannot be emitted multiple times before a timeout has been reached. + */ + emit (eventName, ...payload) { + const + now = Date.now(), + protectedEvent = this.protectedEvents[eventName]; + + if (protectedEvent) { + if (protectedEvent.lastEmitted && protectedEvent.lastEmitted > now - protectedEvent.timeout) { + return false; } - }); - } -} -Kuzzle.prototype = Object.create(KuzzleEventEmitter.prototype); -Kuzzle.prototype.constructor = Kuzzle; - -/** -* Emit an event to all registered listeners -* An event cannot be emitted multiple times before a timeout has been reached. -*/ -Kuzzle.prototype.emit = function(eventName) { - var - now = Date.now(), - protectedEvent = this.protectedEvents[eventName]; - - if (protectedEvent) { - if (protectedEvent.lastEmitted && protectedEvent.lastEmitted > now - protectedEvent.timeout) { - return false; + protectedEvent.lastEmitted = now; } - protectedEvent.lastEmitted = now; + + super.emit(eventName, ...payload); } - KuzzleEventEmitter.prototype.emit.apply(this, arguments); -}; -Kuzzle.prototype.emitEvent = Kuzzle.prototype.emit; -/** - * Connects to a Kuzzle instance using the provided host name. - * @returns {Object} this - */ -Kuzzle.prototype.connect = function () { - var self = this; - if (this.network.state !== 'offline') { - if (this.connectCB) { - this.connectCB(null, self); + /** + * Connects to a Kuzzle instance using the provided host name + * @param {function} [cb] Connection callback + */ + connect (cb) { + if (this.network.state !== 'offline') { + if (cb) { + cb(null, this); + } + return; } - return self; - } - this.network.connect(); + this.network.connect(); - this.network.addListener('connect', function () { - self.emitEvent('connected'); + this.network.addListener('connect', () => { + this.emit('connected'); - if (self.connectCB) { - self.connectCB(null, self); - } - }); + if (cb) { + cb(null, this); + } + }); - this.network.addListener('networkError', function (error) { - const connectionError = new Error(`Unable to connect to kuzzle proxy server at ${self.network.host}:${self.network.port}`); + this.network.addListener('networkError', error => { + const connectionError = new Error(`Unable to connect to kuzzle proxy server at ${this.network.host}:${this.network.port}`); - connectionError.internal = error; - self.emitEvent('networkError', connectionError); + connectionError.internal = error; + this.emit('networkError', connectionError); - if (self.connectCB) { - self.connectCB(connectionError); - } - }); - - this.network.addListener('disconnect', function () { - self.disconnect(); - self.emitEvent('disconnected'); - }); - - this.network.addListener('reconnect', function () { - if (self.jwt) { - self.checkToken(self.jwt, function (err, res) { - // shouldn't obtain an error but let's invalidate the token anyway - if (err || !res.valid) { - self.unsetJwt(); - } + if (cb) { + cb(connectionError); + } + }); - self.emitEvent('reconnected'); - }); - } else { - self.emitEvent('reconnected'); - } - }); + this.network.addListener('disconnect', () => { + this.disconnect(); + this.emit('disconnected'); + }); - this.network.on('discarded', function (data) { - self.emitEvent('discarded', data); - }); + this.network.addListener('reconnect', () => { + if (this.jwt) { + this.checkToken(this.jwt, (err, res) => { + // shouldn't obtain an error but let's invalidate the token anyway + if (err || !res.valid) { + this.unsetJwt(); + } - return this; -}; + this.emit('reconnected'); + }); + } else { + this.emit('reconnected'); + } + }); -/** - * Set the jwt used to query kuzzle - * @param token - * @returns {Kuzzle} - */ -Kuzzle.prototype.setJwt = function(token) { - if (typeof token === 'string') { - this.jwt = token; - } else if (typeof token === 'object') { - if (token.result && token.result.jwt && typeof token.result.jwt === 'string') { - this.jwt = token.result.jwt; - } else { - this.emitEvent('loginAttempt', { - success: false, - error: 'Cannot find a valid JWT in the following object: ' + JSON.stringify(token) - }); + this.network.on('discarded', data => this.emit('discarded', data)); + } + + /** + * Set the jwt used to query kuzzle + * @param token + * @returns {Kuzzle} + */ + setJwt (token) { + if (typeof token === 'string') { + this.jwt = token; + } else if (typeof token === 'object') { + if (token.result && token.result.jwt && typeof token.result.jwt === 'string') { + this.jwt = token.result.jwt; + } else { + this.emit('loginAttempt', { + success: false, + error: 'Cannot find a valid JWT in the following object: ' + JSON.stringify(token) + }); + return this; + } + } else { + this.emit('loginAttempt', {success: false, error: 'Invalid token argument: ' + token}); return this; } - } else { - this.emitEvent('loginAttempt', {success: false, error: 'Invalid token argument: ' + token}); + + this.emit('loginAttempt', {success: true}); return this; } - this.emitEvent('loginAttempt', {success: true}); - return this; -}; - -/** - * Unset the jwt used to query kuzzle - * @returns {Kuzzle} - */ -Kuzzle.prototype.unsetJwt = function() { - this.jwt = undefined; - return this; -}; - -/** - * Get the jwt used by kuzzle - * @returns {Kuzzle} - */ -Kuzzle.prototype.getJwt = function() { - return this.jwt; -}; - -/** - * Send login request to kuzzle with credentials - * If login success, store the jwt into kuzzle object - * - * @param strategy - * @param credentials - * @param expiresIn - * @param cb - */ -Kuzzle.prototype.login = function (strategy) { - var - self = this, - request = { - body: {}, - strategy: strategy - }, - cb = null; - - if (!strategy || typeof strategy !== 'string') { - throw new Error('Kuzzle.login: strategy required'); + /** + * Unset the jwt used to query kuzzle + * @returns {Kuzzle} + */ + unsetJwt () { + this.jwt = undefined; + return this; } - // Handle arguments (credentials, expiresIn, cb) - if (arguments[1]) { - if (typeof arguments[1] === 'object') { - request.body = arguments[1]; - } else if (typeof arguments[1] === 'number' || typeof arguments[1] === 'string') { - request.expiresIn = arguments[1]; - } else if (typeof arguments[1] === 'function') { - cb = arguments[1]; - } + /** + * Get the jwt used by kuzzle + * @returns {Kuzzle} + */ + getJwt () { + return this.jwt; } - if (arguments[2]) { - if (typeof arguments[2] === 'number' || typeof arguments[2] === 'string') { - request.expiresIn = arguments[2]; - } else if (typeof arguments[2] === 'function') { - cb = arguments[2]; + + /** + * Send login request to kuzzle with credentials + * If login success, store the jwt into kuzzle object + * + * @param strategy + * @param credentials + * @param expiresIn + * @param cb + */ + login (strategy, ...args) { + if (!strategy || typeof strategy !== 'string') { + throw new Error('Kuzzle.login: strategy required'); } - } - if (arguments[3] && typeof arguments[3] === 'function') { - cb = arguments[3]; - } - this.query({controller: 'auth', action: 'login'}, request, {queuable: false}, function(error, response) { - if (!error) { - if (response.result.jwt) { - self.setJwt(response.result.jwt); + const + request = { + strategy, + body: {} + }; + + let cb = null; + + // Handle arguments (credentials, expiresIn, cb) + if (args[0]) { + if (typeof args[0] === 'object') { + request.body = args[0]; + } else if (typeof args[0] === 'number' || typeof args[0] === 'string') { + request.expiresIn = args[0]; + } else if (typeof args[0] === 'function') { + cb = args[0]; } - - cb && cb(null, response.result); } - else { - cb && cb(error); - self.emitEvent('loginAttempt', {success: false, error: error.message}); + if (args[1]) { + if (typeof args[1] === 'number' || typeof args[1] === 'string') { + request.expiresIn = args[1]; + } else if (typeof args[1] === 'function') { + cb = args[1]; + } + } + if (args[2] && typeof args[2] === 'function') { + cb = args[2]; } - }); -}; -/** - * Create credentials of the specified for the current user. - * - * @param credentials - * @param strategy - * @param options - * @param cb - * @returns {Kuzzle} - */ -Kuzzle.prototype.createMyCredentials = function (strategy, credentials, options, cb) { - if (!cb && typeof options === 'function') { - cb = options; - options = null; + this.query({controller: 'auth', action: 'login'}, request, {queuable: false}, (error, response) => { + if (!error) { + if (response.result.jwt) { + this.setJwt(response.result.jwt); + } + + cb && cb(null, response.result); + } + else { + cb && cb(error); + this.emit('loginAttempt', {success: false, error: error.message}); + } + }); } - this.query({controller: 'auth', action: 'createMyCredentials'}, {strategy: strategy, body: credentials}, options, function(err, res) { - if (!err) { - cb && cb(null, res.result._source); - } else { - cb && cb(err); + /** + * Create credentials of the specified for the current user. + * + * @param credentials + * @param strategy + * @param options + * @param cb + * @returns {Kuzzle} + */ + createMyCredentials (strategy, credentials, options, cb) { + if (!cb && typeof options === 'function') { + cb = options; + options = null; } - }); - return this; -}; + this.query({controller: 'auth', action: 'createMyCredentials'}, {strategy, body: credentials}, options, (err, res) => { + if (typeof cb === 'function') { + cb(err, err ? undefined : res.result._source); + } + }); -/** - * Delete credentials of the specified for the current user. - * - * @param strategy - * @param options - * @param cb - * @returns {Kuzzle} - */ -Kuzzle.prototype.deleteMyCredentials = function (strategy, options, cb) { - if (!cb && typeof options === 'function') { - cb = options; - options = null; + return this; } - this.query({controller: 'auth', action: 'deleteMyCredentials'}, {strategy: strategy}, options, typeof cb !== 'function' ? null : function(err, res) { - if (!err) { - cb && cb(null, res.result); - } else { - cb && cb(err); + /** + * Delete credentials of the specified for the current user. + * + * @param strategy + * @param options + * @param cb + * @returns {Kuzzle} + */ + deleteMyCredentials (strategy, options, cb) { + if (!cb && typeof options === 'function') { + cb = options; + options = null; } - }); - return this; -}; + this.query({controller: 'auth', action: 'deleteMyCredentials'}, {strategy}, options, (err, res) => { + if (typeof cb === 'function') { + cb(err, err ? undefined : res.result); + } + }); -/** - * Get credential information of the specified for the current user. - * - * @param strategy - * @param options - * @param cb - */ -Kuzzle.prototype.getMyCredentials = function (strategy, options, cb) { - if (!cb && typeof options === 'function') { - cb = options; - options = null; + return this; } - this.query({controller: 'auth', action: 'getMyCredentials'}, {strategy: strategy}, options, typeof cb !== 'function' ? null : function(err, res) { - if (!err) { - cb && cb(null, res.result); - } else { - cb && cb(err); + /** + * Get credential information of the specified for the current user. + * + * @param strategy + * @param options + * @param cb + */ + getMyCredentials (strategy, options, cb) { + if (!cb && typeof options === 'function') { + cb = options; + options = null; } - }); -}; -/** - * Update credentials of the specified for the current user. - * - * @param strategy - * @param credentals - * @param options - * @param cb - * @returns {Kuzzle} - */ -Kuzzle.prototype.updateMyCredentials = function (strategy, credentials, options, cb) { - if (!cb && typeof options === 'function') { - cb = options; - options = null; + this.query({controller: 'auth', action: 'getMyCredentials'}, {strategy}, options, (err, res) => { + if (typeof cb === 'function') { + cb(err, err ? undefined : res.result); + } + }); } - this.query({controller: 'auth', action: 'updateMyCredentials'}, {strategy: strategy, body: credentials}, options, typeof cb !== 'function' ? null : function(err, res) { - if (!err) { - cb && cb(null, res.result); - } else { - cb && cb(err); + /** + * Update credentials of the specified for the current user. + * + * @param strategy + * @param credentals + * @param options + * @param cb + * @returns {Kuzzle} + */ + updateMyCredentials (strategy, credentials, options, cb) { + if (!cb && typeof options === 'function') { + cb = options; + options = null; } - }); - return this; -}; + this.query({controller: 'auth', action: 'updateMyCredentials'}, {strategy, body: credentials}, options, (err, res) => { + if (typeof cb === 'function') { + cb(err, err ? undefined : res.result); + } + }); -/** - * Validate credentials of the specified for the current user. - * - * @param strategy - * @param credentials - * @param options - * @param cb - */ -Kuzzle.prototype.validateMyCredentials = function (strategy, credentials, options, cb) { - if (!cb && typeof options === 'function') { - cb = options; - options = null; + return this; } - this.query({controller: 'auth', action: 'validateMyCredentials'}, {strategy: strategy, body: credentials}, options, typeof cb !== 'function' ? null : function(err, res) { - if (!err) { - cb && cb(null, res.result); - } else { - cb && cb(err); - } - }); -}; - -/** - * Create a kuzzle index - * - * @param {string} index - * @param {object} [options] - * @param {responseCallback} cb - * @returns {Kuzzle} - */ -Kuzzle.prototype.createIndex = function (index, options, cb) { - if (!index) { - if (!this.defaultIndex) { - throw new Error('Kuzzle.createIndex: index required'); + /** + * Validate credentials of the specified for the current user. + * + * @param strategy + * @param credentials + * @param options + * @param cb + */ + validateMyCredentials (strategy, credentials, options, cb) { + if (!cb && typeof options === 'function') { + cb = options; + options = null; } - index = this.defaultIndex; - } - if (!cb && typeof options === 'function') { - cb = options; - options = null; + this.query({controller: 'auth', action: 'validateMyCredentials'}, {strategy, body: credentials}, options, (err, res) => { + if (typeof cb === 'function') { + cb(err, err ? undefined : res.result); + } + }); } - this.query({controller: 'index', action: 'create', index: index}, {}, options, typeof cb !== 'function' ? null : function (err, res) { - cb(err, err ? undefined : res.result); - }); - - return this; -}; - -/** - * Send logout request to kuzzle with jwt. - * - * @param cb - * @returns {Kuzzle} - */ -Kuzzle.prototype.logout = function (cb) { - var - self = this, - request = { - action: 'logout', - controller: 'auth', - requestId: uuidv4(), - body: {} - }; + /** + * Create a kuzzle index + * + * @param {string} index + * @param {object} [options] + * @param {responseCallback} cb + * @returns {Kuzzle} + */ + createIndex (index, options, cb) { + if (!index) { + if (!this.defaultIndex) { + throw new Error('Kuzzle.createIndex: index required'); + } + index = this.defaultIndex; + } - this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, typeof cb !== 'function' ? null : function(error) { - cb(error, self); - }); + if (!cb && typeof options === 'function') { + cb = options; + options = null; + } - self.unsetJwt(); + this.query({controller: 'index', action: 'create', index}, {}, options, (err, res) => { + if (typeof cb === 'function') { + cb(err, err ? undefined : res.result); + } + }); - return self; -}; + return this; + } -/** - * Checks whether a given jwt token still represents a valid session in Kuzzle. - * - * @param {string} token The jwt token to check - * @param {function} cb The callback to be called when the response is - * available. The signature is `function(error, response)`. - */ -Kuzzle.prototype.checkToken = function (token, cb) { - var - request = { - body: { - token: token + /** + * Send logout request to kuzzle with jwt. + * + * @param cb + * @returns {Kuzzle} + */ + logout (cb) { + const + request = { + action: 'logout', + controller: 'auth', + requestId: uuidv4(), + body: {} + }; + + this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, error => { + if (typeof cb === 'function') { + cb(error, this); } - }; - - this.callbackRequired('Kuzzle.checkToken', cb); + }); - this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, function (err, res) { - cb(err, err ? undefined : res.result); - }); -}; + return this.unsetJwt(); + } -/** - * Fetches the current user. - * - * @param {function} cb The callback to be called when the response is - * available. The signature is `function(error, response)`. - */ -Kuzzle.prototype.whoAmI = function (cb) { - var self = this; + /** + * Checks whether a given jwt token still represents a valid session in Kuzzle. + * + * @param {string} token The jwt token to check + * @param {function} cb The callback to be called when the response is + * available. The signature is `function(error, response)`. + */ + checkToken (token, cb) { + const + request = { + body: { + token + } + }; - self.callbackRequired('Kuzzle.whoAmI', cb); + this.callbackRequired('Kuzzle.checkToken', cb); - self.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, function (err, res) { - cb(err, err ? undefined : new User(self.security, res.result._id, res.result._source, res.result._meta)); - }); -}; + this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, (err, res) => { + cb(err, err ? undefined : res.result); + }); + } -/** - * Gets the rights array of the currently logged user. - * - * @param {object} [options] - Optional parameters - * @param {function} cb The callback containing the normalized array of rights. - */ -Kuzzle.prototype.getMyRights = function (options, cb) { - var self = this; + /** + * Fetches the current user. + * + * @param {function} cb The callback to be called when the response is + * available. The signature is `function(error, response)`. + */ + whoAmI (cb) { + this.callbackRequired('Kuzzle.whoAmI', cb); - if (!cb && typeof options === 'function') { - cb = options; - options = null; + this.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, (err, res) => { + cb(err, err ? undefined : new User(this.security, res.result._id, res.result._source, res.result._meta)); + }); } - self.callbackRequired('Kuzzle.getMyRights', cb); + /** + * Gets the rights array of the currently logged user. + * + * @param {object} [options] - Optional parameters + * @param {function} cb The callback containing the normalized array of rights. + */ + getMyRights (options, cb) { + if (!cb && typeof options === 'function') { + cb = options; + options = null; + } - self.query({controller: 'auth', action:'getMyRights'}, {}, options, function (err, res) { - cb(err, err ? undefined : res.result.hits); - }); -}; + this.callbackRequired('Kuzzle.getMyRights', cb); -/** - * Update current user in Kuzzle. - * - * @param {object} content - a plain javascript object representing the user's modification - * @param {object} [options] - (optional) arguments - * @param {responseCallback} [cb] - (optional) Handles the query response - * @returns {Kuzzle} this object - */ -Kuzzle.prototype.updateSelf = function (content, options, cb) { - var - self = this, - data = {}, - queryArgs = {controller: 'auth', action: 'updateSelf'}; - - if (!cb && typeof options === 'function') { - cb = options; - options = null; + this.query({controller: 'auth', action:'getMyRights'}, {}, options, (err, res) => { + cb(err, err ? undefined : res.result.hits); + }); } - data.body = content; - - self.query(queryArgs, data, options, cb && function (err, res) { - cb(err, err ? undefined : res.result); - }); + /** + * Update current user in Kuzzle. + * + * @param {object} content - a plain javascript object representing the user's modification + * @param {object} [options] - (optional) arguments + * @param {responseCallback} [cb] - (optional) Handles the query response + * @returns {Kuzzle} this object + */ + updateSelf (content, options, cb) { + if (!cb && typeof options === 'function') { + cb = options; + options = null; + } - return this; -}; + this.query({controller: 'auth', action: 'updateSelf'}, {body: content}, options, (err, res) => { + if (typeof cb === 'function') { + cb(err, err ? undefined : res.result); + } + }); -/** - * Adds a listener to a Kuzzle global event. When an event is fired, listeners are called in the order of their - * insertion. - * - * @param {string} event - name of the global event to subscribe to - * @param {function} listener - callback to invoke each time an event is fired - */ -Kuzzle.prototype.addListener = function(event, listener) { - if (this.eventActions.indexOf(event) === -1) { - throw new Error('[' + event + '] is not a known event. Known events: ' + this.eventActions.toString()); + return this; } - return KuzzleEventEmitter.prototype.addListener.call(this, event, listener); -}; + /** + * Adds a listener to a Kuzzle global event. When an event is fired, listeners are called in the order of their + * insertion. + * + * @param {string} event - name of the global event to subscribe to + * @param {function} listener - callback to invoke each time an event is fired + */ + addListener (event, listener) { + if (this.eventActions.indexOf(event) === -1) { + throw new Error(`[${event}] is not a known event. Known events: ${this.eventActions.toString()}`); + } -/** - * Kuzzle monitors active connections, and ongoing/completed/failed requests. - * This method returns all available statistics from Kuzzle. - * - * @param {object} [options] - Optional parameters - * @param {responseCallback} cb - Handles the query response - */ -Kuzzle.prototype.getAllStatistics = function (options, cb) { - if (!cb && typeof options === 'function') { - cb = options; - options = null; + return super.addListener(event, listener); } - this.callbackRequired('Kuzzle.getAllStatistics', cb); + /** + * Kuzzle monitors active connections, and ongoing/completed/failed requests. + * This method returns all available statistics from Kuzzle. + * + * @param {object} [options] - Optional parameters + * @param {responseCallback} cb - Handles the query response + */ + getAllStatistics (options, cb) { + if (!cb && typeof options === 'function') { + cb = options; + options = null; + } - this.query({controller:'server', action: 'getAllStats'}, {}, options, function (err, res) { - cb(err, err ? undefined : res.result.hits); - }); -}; + this.callbackRequired('Kuzzle.getAllStatistics', cb); -/** - * Kuzzle monitors active connections, and ongoing/completed/failed requests. - * This method allows getting either the last statistics frame, or a set of frames starting from a provided timestamp. - * - * @param {number} startTime - Epoch time. Starting time from which the frames are to be retrieved - * @param {number} stopTime - Epoch time. End time from which the frames are to be retrieved - * @param {object} [options] - Optional parameters - * @param {responseCallback} cb - Handles the query response - */ -Kuzzle.prototype.getStatistics = function (startTime, stopTime, options, cb) { - var - queryCB, - query = {}; + this.query({controller:'server', action: 'getAllStats'}, {}, options, (err, res) => { + cb(err, err ? undefined : res.result.hits); + }); + } - if (!cb) { - switch (arguments.length) { + /** + * Kuzzle monitors active connections, and ongoing/completed/failed requests. + * This method allows getting either the last statistics frame, or a set of frames starting from a provided timestamp. + * + * @param {number} startTime - Epoch time. Starting time from which the frames are to be retrieved + * @param {number} stopTime - Epoch time. End time from which the frames are to be retrieved + * @param {object} [options] - Optional parameters + * @param {responseCallback} cb - Handles the query response + */ + getStatistics (...args) { + let + startTime, + stopTime, + options, + cb; + + switch (args.length) { case 1: - cb = arguments[0]; + cb = args[0]; startTime = null; stopTime = null; options = null; break; case 2: - cb = arguments[1]; - stopTime = null; - if (typeof arguments[0] === 'object') { - options = arguments[0]; - startTime = null; + if (typeof args[0] === 'object') { + [options, cb] = args; + } else { + [startTime, cb] = args; } break; case 3: - cb = arguments[2]; - options = null; - if (typeof arguments[1] === 'object') { - options = arguments[1]; - stopTime = null; + if (typeof args[1] === 'object') { + [startTime, options, cb] = args; + } else { + [startTime, stopTime, cb] = args; } break; + case 4: + [startTime, stopTime, options, cb] = args; + break; default: throw new Error('Bad arguments list. Usage: kuzzle.getStatistics([startTime,] [stopTime,] [options,] callback)'); } - } - queryCB = function (err, res) { - if (err) { - return cb(err); - } + this.callbackRequired('Kuzzle.getStatistics', cb); - cb(null, startTime ? res.result.hits : [res.result]); - }; + const queryCB = (err, res) => { + if (err) { + return cb(err); + } - this.callbackRequired('Kuzzle.getStatistics', cb); + cb(null, startTime ? res.result.hits : [res.result]); + }; + + let query = {}; + if (startTime) { + query = stopTime ? {startTime, stopTime} : {startTime}; + } - if (startTime) { - query = stopTime ? {startTime, stopTime} : {startTime}; + this.query({controller: 'server', action: startTime ? 'getStats' : 'getLastStats'}, query, options, queryCB); } - this.query({controller: 'server', action: startTime ? 'getStats' : 'getLastStats'}, query, options, queryCB); -}; + /** + * Create a new instance of a Collection object. + * If no index is specified, takes the default index. + * + * @param {string} collection - The name of the data collection you want to manipulate + * @param {string} [index] - The name of the data index containing the data collection + * @returns {Collection} A Collection instance + */ + collection (collection, index) { + if (!index) { + if (!this.defaultIndex) { + throw new Error('Unable to create a new data collection object: no index specified'); + } -/** - * Create a new instance of a Collection object. - * If no index is specified, takes the default index. - * - * @param {string} collection - The name of the data collection you want to manipulate - * @param {string} [index] - The name of the data index containing the data collection - * @returns {Collection} A Collection instance - */ -Kuzzle.prototype.collection = function(collection, index) { - if (!index) { - if (!this.defaultIndex) { - throw new Error('Unable to create a new data collection object: no index specified'); + index = this.defaultIndex; } - index = this.defaultIndex; - } + if (typeof index !== 'string' || typeof collection !== 'string') { + throw new Error('Invalid index or collection argument: string expected'); + } - if (typeof index !== 'string' || typeof collection !== 'string') { - throw new Error('Invalid index or collection argument: string expected'); - } + if (!this.collections[index]) { + this.collections[index] = {}; + } - if (!this.collections[index]) { - this.collections[index] = {}; - } + if (!this.collections[index][collection]) { + this.collections[index][collection] = new Collection(this, collection, index); + } - if (!this.collections[index][collection]) { - this.collections[index][collection] = new Collection(this, collection, index); + return this.collections[index][collection]; } - return this.collections[index][collection]; -}; - -/** - * Empties the offline queue without replaying it. - * - * @returns {Kuzzle} - */ -Kuzzle.prototype.flushQueue = function () { - this.network.flushQueue(); - return this; -}; - -/** - * Returns the list of known persisted data collections. - * - * @param {string} [index] - Index containing collections to be listed - * @param {object} [options] - Optional parameters - * @param {responseCallback} cb - Handles the query response - */ -Kuzzle.prototype.listCollections = function () { - var - index, - options, - cb, - args = Array.prototype.slice.call(arguments), - query; - - args.forEach(function(arg) { - switch (typeof arg) { - case 'string': - index = arg; - break; - case 'object': - options = arg; - break; - case 'function': - cb = arg; - break; - } - }); + /** + * Empties the offline queue without replaying it. + * + * @returns {Kuzzle} + */ + flushQueue () { + this.network.flushQueue(); + return this; + } - if (!index) { - if (!this.defaultIndex) { - throw new Error('Kuzzle.listCollections: index required'); + /** + * Returns the list of known persisted data collections. + * + * @param {string} [index] - Index containing collections to be listed + * @param {object} [options] - Optional parameters + * @param {responseCallback} cb - Handles the query response + */ + listCollections (...args) { + let + index, + options, + cb; + + for (const arg of args) { + switch (typeof arg) { + case 'string': + index = arg; + break; + case 'object': + options = arg; + break; + case 'function': + cb = arg; + break; + } } - index = this.defaultIndex; - } + if (!index) { + if (!this.defaultIndex) { + throw new Error('Kuzzle.listCollections: index required'); + } - this.callbackRequired('Kuzzle.listCollections', cb); + index = this.defaultIndex; + } - query = {type: options && options.type || 'all'}; + this.callbackRequired('Kuzzle.listCollections', cb); - this.query({index: index, controller: 'collection', action: 'list'}, query, options, function (err, res) { - cb(err, err ? undefined : res.result.collections); - }); -}; + const query = {type: options && options.type || 'all'}; -/** - * Returns the list of existing indexes in Kuzzle - * - * @param {object} [options] - Optional arguments - * @param {responseCallback} cb - Handles the query response - */ -Kuzzle.prototype.listIndexes = function (options, cb) { - if (!cb && typeof options === 'function') { - cb = options; - options = null; + this.query({index, controller: 'collection', action: 'list'}, query, options, (err, res) => { + cb(err, err ? undefined : res.result.collections); + }); } - this.callbackRequired('Kuzzle.listIndexes', cb); + /** + * Returns the list of existing indexes in Kuzzle + * + * @param {object} [options] - Optional arguments + * @param {responseCallback} cb - Handles the query response + */ + listIndexes (options, cb) { + if (!cb && typeof options === 'function') { + cb = options; + options = null; + } - this.query({controller: 'index', action: 'list'}, {}, options, function (err, res) { - cb(err, err ? undefined : res.result.indexes); - }); -}; + this.callbackRequired('Kuzzle.listIndexes', cb); -/** - * Disconnects from Kuzzle and invalidate this instance. - */ -Kuzzle.prototype.disconnect = function () { - var collection; + this.query({controller: 'index', action: 'list'}, {}, options, (err, res) => { + cb(err, err ? undefined : res.result.indexes); + }); + } - this.network.close(); + /** + * Disconnects from Kuzzle and invalidate this instance. + */ + disconnect () { + this.network.close(); - for (collection in this.collections) { - if (this.collections.hasOwnProperty(collection)) { + for (const collection of Object.keys(this.collections)) { delete this.collections[collection]; } } -}; -/** - * Returns the server informations - * - * @param {object} [options] - Optional arguments - * @param {responseCallback} cb - Handles the query response - */ -Kuzzle.prototype.getServerInfo = function (options, cb) { - if (!cb && typeof options === 'function') { - cb = options; - options = null; - } + /** + * Returns the server informations + * + * @param {object} [options] - Optional arguments + * @param {responseCallback} cb - Handles the query response + */ + getServerInfo (options, cb) { + if (!cb && typeof options === 'function') { + cb = options; + options = null; + } - this.callbackRequired('Kuzzle.getServerInfo', cb); + this.callbackRequired('Kuzzle.getServerInfo', cb); - this.query({controller: 'server', action: 'info'}, {}, options, function (err, res) { - cb(err, err ? undefined : res.result.serverInfo); - }); -}; + this.query({controller: 'server', action: 'info'}, {}, options, (err, res) => { + cb(err, err ? undefined : res.result.serverInfo); + }); + } -/** - * Forces an index refresh - * - * @param {string} index - The index to refresh. Defaults to Kuzzle.defaultIndex - * @param {object} options - Optional arguments - * @param {responseCallback} cb - Handles the query response - * @returns {Kuzzle} - */ -Kuzzle.prototype.refreshIndex = function () { - var - index, - options, - cb; - - Array.prototype.slice.call(arguments).forEach(function(arg) { - switch (typeof arg) { - case 'string': - index = arg; - break; - case 'object': - options = arg; - break; - case 'function': - cb = arg; - break; + /** + * Forces an index refresh + * + * @param {string} index - The index to refresh. Defaults to Kuzzle.defaultIndex + * @param {object} options - Optional arguments + * @param {responseCallback} cb - Handles the query response + * @returns {Kuzzle} + */ + refreshIndex (...args) { + let + index, + options, + cb; + + for (const arg of args) { + switch (typeof arg) { + case 'string': + index = arg; + break; + case 'object': + options = arg; + break; + case 'function': + cb = arg; + break; + } } - }); - if (!index) { - if (!this.defaultIndex) { - throw new Error('Kuzzle.refreshIndex: index required'); + if (!index) { + if (!this.defaultIndex) { + throw new Error('Kuzzle.refreshIndex: index required'); + } + index = this.defaultIndex; } - index = this.defaultIndex; - } - this.query({ index: index, controller: 'index', action: 'refresh'}, {}, options, cb); + this.query({index, controller: 'index', action: 'refresh'}, {}, options, cb); - return this; -}; + return this; + } -/** - * Returns de current autoRefresh status for the given index - * - * @param {string} index - The index to get the status from. Defaults to Kuzzle.defaultIndex - * @param {object} options - Optinal arguments - * @param {responseCallback} cb - Handles the query response - */ -Kuzzle.prototype.getAutoRefresh = function () { - var - index, - options, - cb; - - Array.prototype.slice.call(arguments).forEach(function (arg) { - switch (typeof arg) { - case 'string': - index = arg; - break; - case 'object': - options = arg; - break; - case 'function': - cb = arg; - break; + /** + * Returns de current autoRefresh status for the given index + * + * @param {string} index - The index to get the status from. Defaults to Kuzzle.defaultIndex + * @param {object} options - Optinal arguments + * @param {responseCallback} cb - Handles the query response + */ + getAutoRefresh (...args) { + let + index, + options, + cb; + + for (const arg of args) { + switch (typeof arg) { + case 'string': + index = arg; + break; + case 'object': + options = arg; + break; + case 'function': + cb = arg; + break; + } } - }); - if (!index) { - if (!this.defaultIndex) { - throw new Error('Kuzzle.getAutoRefresh: index required'); + if (!index) { + if (!this.defaultIndex) { + throw new Error('Kuzzle.getAutoRefresh: index required'); + } + index = this.defaultIndex; } - index = this.defaultIndex; + + this.callbackRequired('Kuzzle.getAutoRefresh', cb); + this.query({index, controller: 'index', action: 'getAutoRefresh'}, {}, options, cb); } - this.callbackRequired('Kuzzle.getAutoRefresh', cb); - this.query({ index: index, controller: 'index', action: 'getAutoRefresh'}, {}, options, cb); -}; + /** + * (Un)Sets the autoRefresh flag on the given index + * + * @param {string} index - the index to modify. Defaults to Kuzzle.defaultIndex + * @param {boolean} autoRefresh - The autoRefresh value to set + * @param {object} options - Optional arguments + * @param {responseCallback} cb - Handles the query result + * @returns {object} this + */ + setAutoRefresh (...args) { + var + index, + autoRefresh, + options, + cb; + + for (const arg of args) { + switch (typeof arg) { + case 'string': + index = arg; + break; + case 'boolean': + autoRefresh = arg; + break; + case 'object': + options = arg; + break; + case 'function': + cb = arg; + break; + } + } -/** - * (Un)Sets the autoRefresh flag on the given index - * - * @param {string} index - the index to modify. Defaults to Kuzzle.defaultIndex - * @param {boolean} autoRefresh - The autoRefresh value to set - * @param {object} options - Optional arguments - * @param {responseCallback} cb - Handles the query result - * @returns {object} this - */ -Kuzzle.prototype.setAutoRefresh = function () { - var - index, - autoRefresh, - options, - cb; - - Array.prototype.slice.call(arguments).forEach(function (arg) { - switch (typeof arg) { - case 'string': - index = arg; - break; - case 'boolean': - autoRefresh = arg; - break; - case 'object': - options = arg; - break; - case 'function': - cb = arg; - break; + if (!index) { + if (!this.defaultIndex) { + throw new Error('Kuzzle.setAutoRefresh: index required'); + } + index = this.defaultIndex; } - }); - if (!index) { - if (!this.defaultIndex) { - throw new Error('Kuzzle.setAutoRefresh: index required'); + if (autoRefresh === undefined) { + throw new Error('Kuzzle.setAutoRefresh: autoRefresh value is required'); } - index = this.defaultIndex; - } - if (autoRefresh === undefined) { - throw new Error('Kuzzle.setAutoRefresh: autoRefresh value is required'); + this.query({index, controller: 'index', action: 'setAutoRefresh'}, {body: {autoRefresh}}, options, cb); + + return this; } - this.query({ index: index, controller: 'index', action: 'setAutoRefresh'}, { body: { autoRefresh: autoRefresh }}, options, cb); + /** + * Return the current Kuzzle's UTC Epoch time, in milliseconds + * @param {object} [options] - Optional parameters + * @param {responseCallback} cb - Handles the query response + */ + now (options, cb) { + if (!cb && typeof options === 'function') { + cb = options; + options = null; + } - return this; -}; + this.callbackRequired('Kuzzle.now', cb); -/** - * Return the current Kuzzle's UTC Epoch time, in milliseconds - * @param {object} [options] - Optional parameters - * @param {responseCallback} cb - Handles the query response - */ -Kuzzle.prototype.now = function (options, cb) { - if (!cb && typeof options === 'function') { - cb = options; - options = null; + this.query({controller: 'server', action: 'now'}, {}, options, (err, res) => { + cb(err, err ? undefined : res.result.now); + }); } - this.callbackRequired('Kuzzle.now', cb); - - this.query({controller: 'server', action: 'now'}, {}, options, function (err, res) { - cb(err, err ? undefined : res.result.now); - }); -}; - -/** - * This is a low-level method, exposed to allow advanced SDK users to bypass high-level methods. - * Base method used to send read queries to Kuzzle - * - * Takes an optional argument object with the following properties: - * - volatile (object, default: null): - * Additional information passed to notifications to other users - * - * @param {object} queryArgs - Query configuration - * @param {object} query - The query data - * @param {object} [options] - Optional arguments - * @param {responseCallback} [cb] - Handles the query response - */ -Kuzzle.prototype.query = function (queryArgs, query, options, cb) { - var - attr, - object = { - action: queryArgs.action, - controller: queryArgs.controller, - volatile: this.volatile - }; + /** + * This is a low-level method, exposed to allow advanced SDK users to bypass high-level methods. + * Base method used to send read queries to Kuzzle + * + * Takes an optional argument object with the following properties: + * - volatile (object, default: null): + * Additional information passed to notifications to other users + * + * @param {object} queryArgs - Query configuration + * @param {object} query - The query data + * @param {object} [options] - Optional arguments + * @param {responseCallback} [cb] - Handles the query response + */ + query (queryArgs, query, options, cb) { + const + object = { + action: queryArgs.action, + controller: queryArgs.controller, + volatile: this.volatile + }; + + if (!cb && typeof options === 'function') { + cb = options; + options = null; + } else if (!cb && !options && typeof query === 'function') { + cb = query; + query = {}; + options = null; + } - if (!cb && typeof options === 'function') { - cb = options; - options = null; - } else if (!cb && !options && typeof query === 'function') { - cb = query; - query = {}; - options = null; - } + if (options) { + for (const prop of ['refresh', 'from', 'size', 'scroll', 'scrollId']) { + if (options[prop] !== undefined) { + object[prop] = options[prop]; + } + } - if (options) { - if (options.refresh) { - object.refresh = options.refresh; + if (options.volatile && typeof options.volatile === 'object') { + Object.assign(object.volatile, options.volatile); + } } - if (typeof options.from !== 'undefined' && options.from !== null) { - object.from = options.from; + if (!query || typeof query !== 'object' || Array.isArray(query)) { + throw new Error('Invalid query parameter: ' + query); } - if (options.size) { - object.size = options.size; + Object.assign(object.volatile, query.volatile, {sdkVersion: this.sdkVersion}); + + for (const attr of Object.keys(query)) { + if (attr !== 'volatile') { + object[attr] = query[attr]; + } } - if (options.scroll) { - object.scroll = options.scroll; + /* + * Do not add the token for the checkToken route, to avoid getting a token error when + * a developer simply wish to verify his token + */ + if (this.jwt !== undefined && !(object.controller === 'auth' && object.action === 'checkToken')) { + object.jwt = this.jwt; } - if (options.scrollId) { - object.scrollId = options.scrollId; + if (queryArgs.collection) { + object.collection = queryArgs.collection; } - if (options.volatile) { - Object.keys(options.volatile).forEach(function (meta) { - object.volatile[meta] = options.volatile[meta]; - }); + if (queryArgs.index) { + object.index = queryArgs.index; } - } - if (!query || typeof query !== 'object' || Array.isArray(query)) { - throw new Error('Invalid query parameter: ' + query); - } + if (!object.requestId) { + object.requestId = uuidv4(); + } - Object.assign(object.volatile, query.volatile, {sdkVersion: this.sdkVersion}); + this.network.query(object, options, cb); - for (attr in query) { - if (attr !== 'volatile' && query.hasOwnProperty(attr)) { - object[attr] = query[attr]; - } + return this; } - /* - * Do not add the token for the checkToken route, to avoid getting a token error when - * a developer simply wish to verify his token + /** + * Starts the requests queuing. */ - if (this.jwt !== undefined && !(object.controller === 'auth' && object.action === 'checkToken')) { - object.jwt = this.jwt; + startQueuing () { + this.network.startQueuing(); + return this; } - if (queryArgs.collection) { - object.collection = queryArgs.collection; + /** + * Stops the requests queuing. + */ + stopQueuing () { + this.network.stopQueuing(); + return this; } - if (queryArgs.index) { - object.index = queryArgs.index; + /** + * @DEPRECATED + * See Kuzzle.prototype.playQueue(); + */ + replayQueue () { + return this.playQueue(); } - if (!object.requestId) { - object.requestId = uuidv4(); + /** + * Plays the requests queued during offline mode. + */ + playQueue () { + this.network.playQueue(); + return this; } - this.network.query(object, options, cb); - - return this; -}; - -/** - * Starts the requests queuing. - */ -Kuzzle.prototype.startQueuing = function () { - this.network.startQueuing(); - return this; -}; - -/** - * Stops the requests queuing. - */ -Kuzzle.prototype.stopQueuing = function () { - this.network.stopQueuing(); - return this; -}; - -/** - * @DEPRECATED - * See Kuzzle.prototype.playQueue(); - */ -Kuzzle.prototype.replayQueue = function () { - return this.playQueue(); -}; + /** + * Sets the default Kuzzle index + * + * @param index + * @returns this + */ + setDefaultIndex (index) { + if (typeof index !== 'string') { + throw new Error(`Invalid default index: [${index}] (an index name is expected)`); + } -/** - * Plays the requests queued during offline mode. - */ -Kuzzle.prototype.playQueue = function () { - this.network.playQueue(); - return this; -}; + if (index.length === 0) { + throw new Error('Cannot set an empty index as the default index'); + } -/** - * Sets the default Kuzzle index - * - * @param index - * @returns this - */ -Kuzzle.prototype.setDefaultIndex = function (index) { - if (typeof index !== 'string') { - throw new Error('Invalid default index: [' + index + '] (an index name is expected)'); - } + this.defaultIndex = index; - if (index.length === 0) { - throw new Error('Cannot set an empty index as the default index'); + return this; } - - this.defaultIndex = index; - - return this; -}; +} function checkPropertyType(prop, typestr, value) { - var wrongType = typestr === 'array' ? !Array.isArray(value) : typeof value !== typestr; + const wrongType = typestr === 'array' ? !Array.isArray(value) : typeof value !== typestr; if (wrongType) { - throw new Error('Can only assign a ' + typestr + ' value to property "' + prop + '"'); + throw new Error(`Can only assign a ${typestr} value to property "${prop}"`); } } diff --git a/src/eventEmitter/index.js b/src/eventEmitter/index.js index dfac2fcc2..981d26f86 100644 --- a/src/eventEmitter/index.js +++ b/src/eventEmitter/index.js @@ -1,186 +1,142 @@ -function KuzzleEventEmitter() { - if (typeof window !== 'undefined') { - this._events = {}; - this._onceEvents = {}; +class Listener { + constructor(fn, once = false) { + this.fn = fn; + this.once = once; } } -if (typeof window === 'undefined') { - KuzzleEventEmitter.prototype = require('events').prototype; - KuzzleEventEmitter.prototype.constructor = KuzzleEventEmitter; -} else { +class KuzzleEventEmitter { + constructor() { + this._events = {}; + } - KuzzleEventEmitter.prototype.on = function(eventName, listener) { - var - listenerType = typeof listener, - listeners; + _exists (listeners, fn) { + return Boolean(listeners.find(listener => listener.fn === fn)); + } - if (!eventName || !listener) { - return; + listeners (eventName) { + if (this._events[eventName] === undefined) { + return []; } - if (listenerType !== 'function') { - throw new Error('Invalid listener type: expected a function, got a ' + listenerType); - } + return this._events[eventName].map(listener => listener.fn); + } - listeners = this.listeners(eventName); - // only add once - if (listeners.indexOf(listener) === -1) { - listeners.push(listener); + addListener (eventName, listener, once = false) { + if (!eventName || !listener) { + return this; } - // Handles `newListener` event (see https://nodejs.org/api/events.html#events_event_newlistener) - this.emit('newListener', eventName, listener); - - return this; - }; - KuzzleEventEmitter.prototype.addListener = KuzzleEventEmitter.prototype.on; - - KuzzleEventEmitter.prototype.prependListener = function(eventName, listener) { - var listeners; + const listenerType = typeof listener; - if (!eventName || !listener) { - return; + if (listenerType !== 'function') { + throw new Error(`Invalid listener type: expected a function, got a ${listenerType}`); } - listeners = this.listeners(eventName); - // only add once - if (listeners.indexOf(listener) === -1) { - this._events[eventName] = new Array(listener).concat(listeners); + if (this._events[eventName] === undefined) { + this._events[eventName] = []; } - // Handles `newListener` event (see https://nodejs.org/api/events.html#events_event_newlistener) - this.emit('newListener', eventName, listener); + if (!this._exists(this._events[eventName], listener)) { + this._events[eventName].push(new Listener(listener, once)); + } return this; - }; + } - KuzzleEventEmitter.prototype.once = function(eventName, listener) { - var onceListeners; + on (eventName, listener) { + return this.addListener(eventName, listener); + } + prependListener (eventName, listener, once = false) { if (!eventName || !listener) { - return; + return this; } + if (this._events[eventName] === undefined) { + this._events[eventName] = []; + } - this.on(eventName, listener); - onceListeners = this._onceEvents[eventName] = this._onceEvents[eventName] || {}; - onceListeners[listener] = true; + if (!this._exists(this._events[eventName], listener)) { + this._events[eventName] = [new Listener(listener, once)].concat(this._events[eventName]); + } return this; - }; + } - KuzzleEventEmitter.prototype.prependOnceListener = function(eventName, listener) { - var onceListeners; + addOnceListener (eventName, listener) { + return this.addListener(eventName, listener, true); + } - if (!eventName || !listener) { - return; - } - this.prependListener(eventName, listener); - onceListeners = this._onceEvents[eventName] = this._onceEvents[eventName] || {}; - onceListeners[listener] = true; + once (eventName, listener) { + return this.addOnceListener(eventName, listener); + } - return this; - }; + prependOnceListener (eventName, listener) { + return this.prependListener(eventName, listener, true); + } - KuzzleEventEmitter.prototype.removeListener = function(eventName, listener) { - var - index, - listeners = this._events[eventName]; + removeListener (eventName, listener) { + const listeners = this._events[eventName]; if (!listeners || !listeners.length) { - return; + return this; } - index = listeners.indexOf(listener); + const index = listeners.findIndex(l => l.fn === listener); + if (index !== -1) { listeners.splice(index, 1); } + if (listeners.length === 0) { delete this._events[eventName]; } - // Handles `removeListener` event (see https://nodejs.org/api/events.html#events_event_removeListener) - this.emit('removeListener', eventName, listener); - return this; - }; + } - KuzzleEventEmitter.prototype.removeAllListeners = function(eventName) { + removeAllListeners (eventName) { if (eventName) { delete this._events[eventName]; - delete this._onceEvents[eventName]; } else { - this._events = []; - this._onceEvents = []; + this._events = {}; } return this; - }; - - KuzzleEventEmitter.prototype.emit = function(eventName) { - var - i = 0, - listeners, - args, - onceListeners, - notifyList; + } - listeners = this._events && this._events[eventName]; + emit (eventName, ...payload) { + const listeners = this._events[eventName]; - if (!listeners || !listeners.length) { + if (listeners === undefined) { return false; } - args = Array.prototype.slice.call(arguments, 1); - // once stuff - onceListeners = this._onceEvents && this._onceEvents[eventName] || {}; - - notifyList = new Array(); - - listener = listeners[i]; - while (listener) { - // trigger listener - notifyList.push(listener); - // get next listener - if (onceListeners[listener]) { - // remove listener - this.removeListener(eventName,listener); - // unset once flag - delete onceListeners[listener]; - } else { - i++; + const onceListeners = []; + + for (const listener of listeners) { + listener.fn(...payload); + + if (listener.once) { + onceListeners.push(listener.fn); } - listener = listeners[i]; } - for (item in notifyList) { - // trigger listener - if (notifyList[item] !== undefined) { - notifyList[item].apply(this, args); - } + + for (const toDelete of onceListeners) { + this.removeListener(eventName, toDelete); } return true; - }; + } - KuzzleEventEmitter.prototype.eventNames = function () { + eventNames () { return Object.keys(this._events); - }; + } - KuzzleEventEmitter.prototype.listenerCount = function (eventName) { + listenerCount (eventName) { return this._events[eventName] && this._events[eventName].length || 0; - }; - - KuzzleEventEmitter.prototype.listeners = function (eventName) { - if (this._events[eventName] === undefined) { - this._events[eventName] = []; - } - return this._events[eventName]; - }; - + } } -// Aliases: -KuzzleEventEmitter.prototype.emitEvent = KuzzleEventEmitter.prototype.emit; -KuzzleEventEmitter.prototype.off = KuzzleEventEmitter.prototype.removeListener; module.exports = KuzzleEventEmitter; diff --git a/src/networkWrapper/protocols/abstract/realtime.js b/src/networkWrapper/protocols/abstract/realtime.js index eff50b047..ef69b1019 100644 --- a/src/networkWrapper/protocols/abstract/realtime.js +++ b/src/networkWrapper/protocols/abstract/realtime.js @@ -129,7 +129,7 @@ class RTWrapper extends KuzzleEventEmitter { */ clientConnected() { this.state = 'connected'; - this.emitEvent(this.wasConnected && 'reconnect' || 'connect'); + this.emit(this.wasConnected && 'reconnect' || 'connect'); this.wasConnected = true; this.stopRetryingToConnect = false; @@ -158,7 +158,7 @@ class RTWrapper extends KuzzleEventEmitter { } this.clearHistoryTimer(); - this.emitEvent('disconnect'); + this.emit('disconnect'); } /** @@ -174,7 +174,7 @@ class RTWrapper extends KuzzleEventEmitter { this.clearHistoryTimer(); - this.emitEvent('networkError', error); + this.emit('networkError', error); if (this.autoReconnect && !this.retrying && !this.stopRetryingToConnect) { this.retrying = true; setTimeout(() => { @@ -182,7 +182,7 @@ class RTWrapper extends KuzzleEventEmitter { this.connect(this.host); }, this.reconnectionDelay); } else { - this.emitEvent('disconnect'); + this.emit('disconnect'); } } @@ -251,7 +251,7 @@ class RTWrapper extends KuzzleEventEmitter { if (this.queuing && queuable) { cleanQueue(this, object, cb); - this.emitEvent('offlineQueuePush', {query: object, cb: cb}); + this.emit('offlineQueuePush', {query: object, cb: cb}); return this.offlineQueue.push({ts: Date.now(), query: object, cb: cb}); } @@ -282,14 +282,14 @@ function emitRequest (network, request, cb) { let error = null; if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') { - network.emitEvent('tokenExpired', request, cb); + network.emit('tokenExpired', request, cb); } if (response.error) { error = new Error(response.error.message); Object.assign(error, response.error); error.status = response.status; - network.emitEvent('queryError', error, request, cb); + network.emit('queryError', error, request, cb); } if (cb) { @@ -327,7 +327,7 @@ function cleanQueue (network) { network.offlineQueue .splice(0, lastDocumentIndex + 1) .forEach(droppedRequest => { - network.emitEvent('offlineQueuePop', droppedRequest.query); + network.emit('offlineQueuePop', droppedRequest.query); }); } } @@ -336,7 +336,7 @@ function cleanQueue (network) { network.offlineQueue .splice(0, network.offlineQueue.length - network.queueMaxSize) .forEach(droppedRequest => { - network.emitEvent('offlineQueuePop', droppedRequest.query); + network.emit('offlineQueuePop', droppedRequest.query); }); } } @@ -350,7 +350,7 @@ function dequeue (network) { dequeuingProcess = () => { if (network.offlineQueue.length > 0) { emitRequest(network, network.offlineQueue[0].query, network.offlineQueue[0].cb); - network.emitEvent('offlineQueuePop', network.offlineQueue.shift()); + network.emit('offlineQueuePop', network.offlineQueue.shift()); setTimeout(() => { dequeuingProcess(); diff --git a/src/networkWrapper/protocols/socketio.js b/src/networkWrapper/protocols/socketio.js index 04bc9efd7..ee11bec35 100644 --- a/src/networkWrapper/protocols/socketio.js +++ b/src/networkWrapper/protocols/socketio.js @@ -10,11 +10,11 @@ class SocketIO extends RTWrapper { this.socket = null; this.forceDisconnect = false; + this.eventsWrapper = {}; } /** * Connect to the SocketIO server - * */ connect() { super.connect(); @@ -25,20 +25,14 @@ class SocketIO extends RTWrapper { forceNew: true }); - this.socket.on('connect', () => { - this.clientConnected(); - }); - - this.socket.on('connect_error', error => { - this.clientNetworkError(error); - }); + this.socket.on('connect', () => this.clientConnected()); + this.socket.on('connect_error', error => this.clientNetworkError(error)); this.socket.on('disconnect', () => { if (this.forceDisconnect) { this.clientDisconnected(); - } - else { - const error = new Error('An error occurred, this may due that kuzzle was not ready yet'); + } else { + const error = new Error('An error occurred, kuzzle may not be ready yet'); error.status = 500; this.clientNetworkError(error); @@ -49,36 +43,64 @@ class SocketIO extends RTWrapper { } /** - * Registers a callback on a room. Once 1 message is received, fires the - * callback and unregister it afterward. + * Registers a callback on an event. * - * @param {string} roomId + * @param {string} event * @param {function} callback */ - once(roomId, callback) { - this.socket.once(roomId, callback); + addListener(event, callback, once = false) { + this._addEventWrapper(event, callback, once); + super.addListener(event, callback, once); + + return this; + } + + prependListener(event, callback, once = false) { + this._addEventWrapper(event, callback, once); + return super.prependListener(event, callback, once); } /** - * Registers a callback on a room. + * Unregisters a callback from an event. * - * @param {string} roomId + * @param {string} event * @param {function} callback */ - on(roomId, callback) { - this.socket.on(roomId, callback); + removeListener(event, callback) { + if (this.eventsWrapper[event]) { + this.eventsWrapper[event].listeners.delete(callback); + + if (this.eventsWrapper[event].listeners.size === 0) { + this.socket.off(event, this.eventsWrapper[event].wrapper); + delete this.eventsWrapper[event]; + } + + super.removeListener(event, callback); + } + + return this; } /** - * Unregisters a callback from a room. + * Unregisters all listeners either from an event, or from all events * - * @param {string} roomId - * @param {function} callback + * @param {string} [event] */ - off(roomId, callback) { - this.socket.off(roomId, callback); - } + removeAllListeners(event) { + if (event !== undefined) { + if (this.eventsWrapper[event] !== undefined) { + for (const listener of this.eventsWrapper[event].listeners) { + this.removeListener(event, listener); + } + } + } else { + for (const _event of Object.keys(this.eventsWrapper)) { + this.removeAllListeners(_event); + } + } + return this; + } /** * Sends a payload to the connected server @@ -98,6 +120,27 @@ class SocketIO extends RTWrapper { this.socket.close(); this.socket = null; } + + _addEventWrapper(event, callback, once = false) { + if (!this.eventsWrapper[event]) { + const wrapper = (...args) => this.emit(event, ...args); + + this.eventsWrapper[event] = { + wrapper, + listeners: new Set() + }; + + if (['connect', 'connect_error', 'disconnect'].indexOf(event) === -1) { + if (once) { + this.socket.once(event, wrapper); + } else { + this.socket.on(event, wrapper); + } + } + } + + this.eventsWrapper[event].listeners.add(callback); + } } module.exports = SocketIO; diff --git a/src/networkWrapper/protocols/websocket.js b/src/networkWrapper/protocols/websocket.js index 3ffd56f3d..35c85b4b6 100644 --- a/src/networkWrapper/protocols/websocket.js +++ b/src/networkWrapper/protocols/websocket.js @@ -75,10 +75,10 @@ class WSNode extends RTWrapper { const data = JSON.parse(payload.data || payload); if (data.room) { - this.emitEvent(data.room, data); + this.emit(data.room, data); } else { - this.emitEvent('discarded', data); + this.emit('discarded', data); } }; } diff --git a/test/Collection/constructor.test.js b/test/Collection/constructor.test.js index d73f0b1de..d39bae7df 100644 --- a/test/Collection/constructor.test.js +++ b/test/Collection/constructor.test.js @@ -7,7 +7,7 @@ var describe('Collection constructor', function () { it('should initialize properties and return a valid Collection object', function () { var - kuzzle = new Kuzzle('foo', {connect: 'manual'}), + kuzzle = new Kuzzle('foo'), index = 'barfoo', collectionName = 'foobar', c; @@ -29,7 +29,7 @@ describe('Collection constructor', function () { collection; Kuzzle.prototype.bluebird = bluebird; - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); collection = new Collection(kuzzle, 'bar', 'foo'); should.exist(collection.countPromise); @@ -59,7 +59,7 @@ describe('Collection constructor', function () { }); it('should throw an error if no collection or no index is provided', function () { - var kuzzle = new Kuzzle('foo', {connect: 'manual'}); + var kuzzle = new Kuzzle('foo'); should((function () { new Collection(kuzzle);})).throw(); should((function () { new Collection(kuzzle, 'foo');})).throw(); diff --git a/test/Collection/methods.test.js b/test/Collection/methods.test.js index 1bf950228..2caa2eb75 100644 --- a/test/Collection/methods.test.js +++ b/test/Collection/methods.test.js @@ -18,7 +18,7 @@ describe('Collection methods', function () { kuzzle; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); kuzzle.bluebird = Bluebird; kuzzle.query = sinon.stub(); kuzzle.subscribe = sinon.stub(); diff --git a/test/CollectionMapping/constructor.test.js b/test/CollectionMapping/constructor.test.js index a08cf8575..3445855ab 100644 --- a/test/CollectionMapping/constructor.test.js +++ b/test/CollectionMapping/constructor.test.js @@ -10,7 +10,7 @@ describe('CollectionMapping constructor', function () { collection; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual', defaultIndex: 'bar'}); + kuzzle = new Kuzzle('foo', {defaultIndex: 'bar'}); collection = kuzzle.collection('foo'); }); diff --git a/test/CollectionMapping/methods.test.js b/test/CollectionMapping/methods.test.js index 9ce782314..924672314 100644 --- a/test/CollectionMapping/methods.test.js +++ b/test/CollectionMapping/methods.test.js @@ -12,7 +12,7 @@ describe('CollectionMapping methods', function () { collection; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); kuzzle.query = sinon.stub(); collection = kuzzle.collection('foo', 'bar'); }); diff --git a/test/Document/constructor.test.js b/test/Document/constructor.test.js index b2b371073..055573667 100644 --- a/test/Document/constructor.test.js +++ b/test/Document/constructor.test.js @@ -11,7 +11,7 @@ describe('Document constructor', function () { beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual', defaultIndex: 'bar'}); + kuzzle = new Kuzzle('foo', {defaultIndex: 'bar'}); kuzzle.bluebird = bluebird; collection = kuzzle.collection('foo'); }); diff --git a/test/Document/methods.test.js b/test/Document/methods.test.js index d01403ecf..6a61c3308 100644 --- a/test/Document/methods.test.js +++ b/test/Document/methods.test.js @@ -14,7 +14,7 @@ describe('Document methods', function () { collection; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); kuzzle.query = sinon.stub(); collection = new Collection(kuzzle, 'foo', 'bar'); }); diff --git a/test/MemoryStorage/constructor.test.js b/test/MemoryStorage/constructor.test.js index 4f40e9a83..df9f367f1 100644 --- a/test/MemoryStorage/constructor.test.js +++ b/test/MemoryStorage/constructor.test.js @@ -7,7 +7,7 @@ var describe('MemoryStorage constructor', function () { it('should initialize properties and return a valid MemoryStorage object', function () { var - kuzzle = new Kuzzle('foo', {connect: 'manual'}), + kuzzle = new Kuzzle('foo'), ms; ms = new MemoryStorage(kuzzle); @@ -24,7 +24,7 @@ describe('MemoryStorage constructor', function () { Kuzzle.prototype.bluebird = bluebird; - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); ms = new MemoryStorage(kuzzle); functions = Object.getOwnPropertyNames(Object.getPrototypeOf(ms)).filter(function (p) { @@ -43,7 +43,7 @@ describe('MemoryStorage constructor', function () { it('auto-generated functions should throw if the wrong number of parameters is provided', function () { var emptyFunc = function () {}, - kuzzle = new Kuzzle('foo', {connect: 'manual'}), + kuzzle = new Kuzzle('foo'), ms = new MemoryStorage(kuzzle); should(function () {ms.dbsize('foo', {}, emptyFunc);}).throw('MemoryStorage.dbsize: Too many parameters provided'); diff --git a/test/MemoryStorage/methods.test.js b/test/MemoryStorage/methods.test.js index d78f19286..a37074ea1 100644 --- a/test/MemoryStorage/methods.test.js +++ b/test/MemoryStorage/methods.test.js @@ -11,7 +11,7 @@ describe('MemoryStorage methods', function () { emptyFunc = function () {}; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); kuzzle.bluebird = require('bluebird'); kuzzle.query = sinon.stub(); ms = new MemoryStorage(kuzzle); diff --git a/test/SearchResult/constructor.test.js b/test/SearchResult/constructor.test.js index 44f29d6f7..10cccbc7c 100644 --- a/test/SearchResult/constructor.test.js +++ b/test/SearchResult/constructor.test.js @@ -15,7 +15,7 @@ describe('SearchResult constructor', function () { collection; beforeEach(function () { - kuzzle = new Kuzzle('foo', {defaultIndex: 'bar', connect: 'manual'}); + kuzzle = new Kuzzle('foo', {defaultIndex: 'bar'}); searchOptions = {from:0, size: 1}; searchFilters = {}; collection = kuzzle.collection('foo'); diff --git a/test/SearchResult/methods.test.js b/test/SearchResult/methods.test.js index 4cec1f0fa..2581511e5 100644 --- a/test/SearchResult/methods.test.js +++ b/test/SearchResult/methods.test.js @@ -15,7 +15,7 @@ describe('SearchResult methods', function () { searchFilters; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); kuzzle.query = sinon.stub(); searchOptions = {from:0, size: 1}; searchFilters = {}; diff --git a/test/kuzzle/connect.test.js b/test/kuzzle/connect.test.js index bc96e60ed..35d0fa0fa 100644 --- a/test/kuzzle/connect.test.js +++ b/test/kuzzle/connect.test.js @@ -1,72 +1,63 @@ var should = require('should'), - rewire = require('rewire'), sinon = require('sinon'), - NetworkWrapperMock = require('../mocks/networkWrapper.mock'), - Kuzzle = rewire('../../src/Kuzzle'); + proxyquire = require('proxyquire'), + NetworkWrapperMock = require('../mocks/networkWrapper.mock'); describe('Kuzzle connect', function () { var - clock, - networkWrapperRevert; + Kuzzle, + clock; beforeEach(function () { - networkWrapperRevert = Kuzzle.__set__({ - networkWrapper: function(protocol, host, options) { + Kuzzle = proxyquire('../../src/Kuzzle', { + './networkWrapper': function(protocol, host, options) { return new NetworkWrapperMock(host, options); } }); + clock = sinon.useFakeTimers(); }); afterEach(function() { - networkWrapperRevert(); clock.restore(); }); - - it('should return the current Kuzzle instance', function () { - var - kuzzle = new Kuzzle('somewhere', {connect: 'manual'}), - connectedKuzzle = kuzzle.connect(); - - should(connectedKuzzle).be.exactly(kuzzle); - }); - it('should return immediately if already connected', function () { var promises = []; - ['connecting', 'ready', 'connected'].forEach(function (state) { + ['connecting', 'connected'].forEach(function (state) { promises.push(new Promise(function(resolve) { - var kuzzle = new Kuzzle('somewhere', {connect: 'manual'}, function (err, res) { + var kuzzle = new Kuzzle('somewhere'); + kuzzle.network.state = state; + kuzzle.connect(function (err, res) { should(err).be.null(); should(res).be.exactly(kuzzle); should(res.network.connectCalled).be.false(); should(res.network.state).be.exactly(state); resolve(); }); - kuzzle.network.state = state; - kuzzle.connect(); })); }); clock.tick(); - Promise.all(promises); + return Promise.all(promises); }); - it('should call network wrapper connect() method when the instance is offline', function () { - var kuzzle = new Kuzzle('somewhere', {connect: 'manual'}, function (err, res) { + it('should call network wrapper connect() method when the instance is offline', function (done) { + var kuzzle = new Kuzzle('somewhere'); + kuzzle.network.state = 'offline'; + kuzzle.connect(function (err, res) { should(err).be.null(); should(res).be.exactly(kuzzle); should(res.network.state).be.exactly('connected'); should(res.network.connectCalled).be.true(); + done(); }); - kuzzle.network.state = 'offline'; - kuzzle.connect(); clock.tick(); }); describe('=> Connection Events', function () { it('should registered listeners upon receiving a "error" event', function () { var - kuzzle = new Kuzzle('nowhere', {connect: 'manual'}), + kuzzle = new Kuzzle('nowhere'), eventStub = sinon.stub(); kuzzle.addListener('networkError', eventStub); @@ -78,7 +69,7 @@ describe('Kuzzle connect', function () { it('should registered listeners upon receiving a "connect" event', function () { var - kuzzle = new Kuzzle('somewhere', {connect: 'manual'}), + kuzzle = new Kuzzle('somewhere'), eventStub = sinon.stub(); kuzzle.addListener('connected', eventStub); @@ -90,7 +81,7 @@ describe('Kuzzle connect', function () { it('should registered listeners upon receiving a "reconnect" event', function () { var - kuzzle = new Kuzzle('somewhereagain', {connect: 'manual'}), + kuzzle = new Kuzzle('somewhereagain'), eventStub = sinon.stub(); kuzzle.addListener('reconnected', eventStub); @@ -101,7 +92,7 @@ describe('Kuzzle connect', function () { }); it('should keep a valid JWT at reconnection', function () { - var kuzzle = new Kuzzle('somewhereagain', {connect: 'manual'}); + var kuzzle = new Kuzzle('somewhereagain'); kuzzle.checkToken = sinon.stub(); @@ -119,7 +110,7 @@ describe('Kuzzle connect', function () { it('should empty the JWT at reconnection if it has expired', function () { var - kuzzle = new Kuzzle('somewhereagain', {connect: 'manual'}); + kuzzle = new Kuzzle('somewhereagain'); kuzzle.checkToken = sinon.stub(); @@ -138,13 +129,13 @@ describe('Kuzzle connect', function () { it('should register listeners upon receiving a "disconnect" event', function () { var eventStub = sinon.stub(), - kuzzle = new Kuzzle('somewhere', {connect: 'manual'}, function() { - kuzzle.network.disconnect(); - }); + kuzzle = new Kuzzle('somewhere'); kuzzle.addListener('disconnected', eventStub); - kuzzle.connect(); + kuzzle.connect(function () { + kuzzle.network.disconnect(); + }); clock.tick(); should(eventStub).be.calledOnce(); }); @@ -152,13 +143,13 @@ describe('Kuzzle connect', function () { it('should register listeners upon receiving a "discarded" event', function () { var eventStub = sinon.stub(), - kuzzle = new Kuzzle('somewhere', {connect: 'manual'}, function() { - kuzzle.network.emitEvent('discarded'); - }); + kuzzle = new Kuzzle('somewhere'); kuzzle.addListener('discarded', eventStub); - kuzzle.connect(); + kuzzle.connect(function() { + kuzzle.network.emit('discarded'); + }); clock.tick(); should(eventStub).be.calledOnce(); }); diff --git a/test/kuzzle/constructor.test.js b/test/kuzzle/constructor.test.js index 82a0363a2..b1cc8625d 100644 --- a/test/kuzzle/constructor.test.js +++ b/test/kuzzle/constructor.test.js @@ -1,9 +1,9 @@ var - rewire = require('rewire'), should = require('should'), sinon = require('sinon'), bluebird = require('bluebird'), - Kuzzle = rewire('../../src/Kuzzle'), + proxyquire = require('proxyquire'), + Kuzzle = require('../../src/Kuzzle'), MemoryStorage = require('../../src/MemoryStorage'), NetworkWrapperMock = require('../mocks/networkWrapper.mock'), Security = require('../../src/security/Security'); @@ -19,12 +19,6 @@ describe('Kuzzle constructor', function () { connectStub.restore(); }); - it('should return a new instance even if not called with "new"', function () { - var kuzzle = Kuzzle('somewhere'); - - kuzzle.should.be.instanceof(Kuzzle); - }); - it('should throw an error if no URL is provided', function () { should(function () { new Kuzzle(); @@ -176,7 +170,6 @@ describe('Kuzzle constructor', function () { should(kuzzle.unsubscribe).be.a.Function(); should(kuzzle).have.propertyWithDescriptor('collections', { enumerable: false, writable: true, configurable: false }); - should(kuzzle).have.propertyWithDescriptor('connectCB', { enumerable: false, writable: false, configurable: false }); should(kuzzle).have.propertyWithDescriptor('eventActions', { enumerable: false, writable: false, configurable: false }); should(kuzzle).have.propertyWithDescriptor('eventTimeout', { enumerable: false, writable: false, configurable: false }); should(kuzzle).have.propertyWithDescriptor('protectedEvents', { enumerable: false, writable: false, configurable: false }); @@ -195,7 +188,6 @@ describe('Kuzzle constructor', function () { should(kuzzle.volatile).be.an.Object().and.be.empty(); should(kuzzle.collections).be.an.Object().and.be.empty(); - should(kuzzle.connectCB).be.undefined(); should(kuzzle.eventActions).be.an.Array() .and.containEql('connected') .and.containEql('discarded') @@ -225,65 +217,51 @@ describe('Kuzzle constructor', function () { }); it('should initialize correctly properties using the "options" argument', function () { - Kuzzle.__with__({ - networkWrapper: function(protocol, host, options) { + var MockedKuzzle = proxyquire('../../src/Kuzzle', { + './networkWrapper': function(protocol, host, options) { return new NetworkWrapperMock(host, options); } - })(function() { - var - sdkVersion = require('../../package.json').version, - options = { - autoResubscribe: false, - protocol: 'fakeproto', - volatile: {foo: ['bar', 'baz', 'qux'], bar: 'foo'}, - defaultIndex: 'foobar', - jwt: 'fakejwt', - eventTimeout: 1000 - }, - kuzzle = new Kuzzle('somewhere', options); - - should(kuzzle.autoResubscribe).be.false(); - should(kuzzle.defaultIndex).be.exactly('foobar'); - should(kuzzle.jwt).be.exactly('fakejwt'); - should(kuzzle.protocol).be.exactly('fakeproto'); - should(kuzzle.sdkVersion).be.exactly(sdkVersion); - should(kuzzle.volatile).be.an.Object().and.match(options.volatile); - - should(kuzzle.collections).be.an.Object().and.be.empty(); - should(kuzzle.connectCB).be.undefined(); - should(kuzzle.eventActions).be.an.Array() - .and.containEql('connected') - .and.containEql('discarded') - .and.containEql('disconnected') - .and.containEql('loginAttempt') - .and.containEql('networkError') - .and.containEql('offlineQueuePush') - .and.containEql('offlineQueuePop') - .and.containEql('queryError') - .and.containEql('reconnected') - .and.containEql('tokenExpired'); - should(kuzzle.eventTimeout).be.exactly(1000); - should(kuzzle.protectedEvents).be.an.Object(); - should(kuzzle.protectedEvents.connected).be.eql({timeout: 1000}); - should(kuzzle.protectedEvents.error).be.eql({timeout: 1000}); - should(kuzzle.protectedEvents.disconnected).be.eql({timeout: 1000}); - should(kuzzle.protectedEvents.reconnected).be.eql({timeout: 1000}); - should(kuzzle.protectedEvents.tokenExpired).be.eql({timeout: 1000}); - should(kuzzle.protectedEvents.loginAttempt).be.eql({timeout: 1000}); }); - }); - - it('should handle the connect option properly', function () { - var kuzzle = new Kuzzle('somewhere', {connect: 'manual'}); // eslint-disable-line - - should(connectStub).not.be.called(); - - kuzzle = new Kuzzle('somewhere', {connect: 'auto'}); - should(connectStub).be.calledOnce(); + + var + sdkVersion = require('../../package.json').version, + options = { + autoResubscribe: false, + protocol: 'fakeproto', + volatile: {foo: ['bar', 'baz', 'qux'], bar: 'foo'}, + defaultIndex: 'foobar', + jwt: 'fakejwt', + eventTimeout: 1000 + }, + kuzzle = new MockedKuzzle('somewhere', options); + + should(kuzzle.autoResubscribe).be.false(); + should(kuzzle.defaultIndex).be.exactly('foobar'); + should(kuzzle.jwt).be.exactly('fakejwt'); + should(kuzzle.protocol).be.exactly('fakeproto'); + should(kuzzle.sdkVersion).be.exactly(sdkVersion); + should(kuzzle.volatile).be.an.Object().and.match(options.volatile); - connectStub.reset(); - kuzzle = new Kuzzle('somewhere'); - should(connectStub).be.calledOnce(); + should(kuzzle.collections).be.an.Object().and.be.empty(); + should(kuzzle.eventActions).be.an.Array() + .and.containEql('connected') + .and.containEql('discarded') + .and.containEql('disconnected') + .and.containEql('loginAttempt') + .and.containEql('networkError') + .and.containEql('offlineQueuePush') + .and.containEql('offlineQueuePop') + .and.containEql('queryError') + .and.containEql('reconnected') + .and.containEql('tokenExpired'); + should(kuzzle.eventTimeout).be.exactly(1000); + should(kuzzle.protectedEvents).be.an.Object(); + should(kuzzle.protectedEvents.connected).be.eql({timeout: 1000}); + should(kuzzle.protectedEvents.error).be.eql({timeout: 1000}); + should(kuzzle.protectedEvents.disconnected).be.eql({timeout: 1000}); + should(kuzzle.protectedEvents.reconnected).be.eql({timeout: 1000}); + should(kuzzle.protectedEvents.tokenExpired).be.eql({timeout: 1000}); + should(kuzzle.protectedEvents.loginAttempt).be.eql({timeout: 1000}); }); it('should promisify the right functions', function () { @@ -295,7 +273,7 @@ describe('Kuzzle constructor', function () { should(kuzzle.addListenerPromise).be.undefined(); should(kuzzle.checkTokenPromise).be.a.Function(); should(kuzzle.collectionPromise).be.undefined(); - should(kuzzle.connectPromise).be.undefined(); + should(kuzzle.connectPromise).be.a.Function(); should(kuzzle.createIndexPromise).be.a.Function(); should(kuzzle.createMyCredentialsPromise).be.a.Function(); should(kuzzle.deleteMyCredentialsPromise).be.a.Function(); diff --git a/test/kuzzle/eventEmitter.test.js b/test/kuzzle/eventEmitter.test.js index 9538e6747..315647ecb 100644 --- a/test/kuzzle/eventEmitter.test.js +++ b/test/kuzzle/eventEmitter.test.js @@ -1,7 +1,7 @@ var should = require('should'), sinon = require('sinon'), - KuzzleEventEmitter; + KuzzleEventEmitter = require('../../src/eventEmitter'); describe('Event emitter', function () { var @@ -19,18 +19,6 @@ describe('Event emitter', function () { stubListener3.apply(this, arguments); }; - // Force uncache `KuzzleEventEmitter` module to use it as in a browser mode: - before(function () { - window = 'foo'; // eslint-disable-line - delete(require.cache[require.resolve('../../src/eventEmitter')]); - KuzzleEventEmitter = require('../../src/eventEmitter'); - }); - - after(function () { - delete window; // eslint-disable-line - delete(require.cache[require.resolve('../../src/eventEmitter')]); - }); - beforeEach(function() { kuzzleEventEmitter = new KuzzleEventEmitter(); stubListener1.reset(); @@ -40,14 +28,11 @@ describe('Event emitter', function () { describe('#addListener', function () { it('should properly add new listeners to events', function () { - kuzzleEventEmitter.on('foo', listener1); - kuzzleEventEmitter.on('foo', listener2); - kuzzleEventEmitter.on('bar', listener3); - should(kuzzleEventEmitter._events.foo.length).be.exactly(2); - should(kuzzleEventEmitter._events.foo[0]).be.exactly(listener1); - should(kuzzleEventEmitter._events.foo[1]).be.exactly(listener2); - should(kuzzleEventEmitter._events.bar.length).be.exactly(1); - should(kuzzleEventEmitter._events.bar[0]).be.exactly(listener3); + should(kuzzleEventEmitter.on('foo', listener1)).be.eql(kuzzleEventEmitter); + should(kuzzleEventEmitter.on('foo', listener2)).be.eql(kuzzleEventEmitter); + should(kuzzleEventEmitter.on('bar', listener3)).be.eql(kuzzleEventEmitter); + should(kuzzleEventEmitter.listeners('foo')).eql([listener1, listener2]).and.have.length(2); + should(kuzzleEventEmitter.listeners('bar')).eql([listener3]).and.have.length(1); }); it('should throw an error when providing a non-function listener argument', function () { @@ -56,174 +41,138 @@ describe('Event emitter', function () { }).throw(); }); - it('should emit "newListener" event', function() { - kuzzleEventEmitter.emit = sinon.stub(); - kuzzleEventEmitter.on('foo', listener1); - should(kuzzleEventEmitter.emit).be.calledOnce(); - should(kuzzleEventEmitter.emit).be.calledWith('newListener', 'foo', listener1); + it('should not add a duplicate listener', function () { + should(kuzzleEventEmitter.on('foo', listener1)); + should(kuzzleEventEmitter.on('foo', listener1)); + should(kuzzleEventEmitter.listeners('foo')).eql([listener1]).and.have.length(1); }); }); describe('#prependListener', function () { it('should properly add new listeners to the top of the event list', function () { - kuzzleEventEmitter.on('foo', listener1); - kuzzleEventEmitter.on('foo', listener2); - kuzzleEventEmitter.prependListener('foo', listener3); - should(kuzzleEventEmitter._events.foo.length).be.exactly(3); - should(kuzzleEventEmitter._events.foo[0]).be.exactly(listener3); - should(kuzzleEventEmitter._events.foo[1]).be.exactly(listener1); - should(kuzzleEventEmitter._events.foo[2]).be.exactly(listener2); - }); - - it('should emit "newListener" event', function() { - kuzzleEventEmitter.emit = sinon.stub(); kuzzleEventEmitter.prependListener('foo', listener1); - should(kuzzleEventEmitter.emit).be.calledOnce(); - should(kuzzleEventEmitter.emit).be.calledWith('newListener', 'foo', listener1); + kuzzleEventEmitter.prependListener('foo', listener2); + kuzzleEventEmitter.prependListener('foo', listener3); + should(kuzzleEventEmitter.listeners('foo')).eql([listener3, listener2, listener1]).and.have.length(3); }); }); describe('#once', function () { - it('should call on() method', function () { - kuzzleEventEmitter.on = sinon.stub(); - kuzzleEventEmitter.once('foo', listener1); - should(kuzzleEventEmitter.on).be.calledOnce(); - should(kuzzleEventEmitter.on).be.calledWith('foo', listener1); - }); + it('should register listeners only for 1 time', function () { + kuzzleEventEmitter.on('foo', listener1); + kuzzleEventEmitter.on('foo', listener2); + kuzzleEventEmitter.once('foo', listener3); - it('should properly add new listeners to once events', function () { - kuzzleEventEmitter.once('foo', listener1); - kuzzleEventEmitter.once('foo', listener2); - kuzzleEventEmitter.on('foo', listener3); - kuzzleEventEmitter.once('bar', listener3); + should(kuzzleEventEmitter.listeners('foo')).eql([listener1, listener2, listener3]).and.have.length(3); + + kuzzleEventEmitter.emit('foo'); - should(kuzzleEventEmitter._onceEvents.foo[listener1]).be.true(); - should(kuzzleEventEmitter._onceEvents.foo[listener2]).be.true(); - should(kuzzleEventEmitter._onceEvents.foo[listener3]).be.undefined(); - should(kuzzleEventEmitter._onceEvents.bar[listener3]).be.true(); + should(stubListener1).be.calledOnce(); + should(stubListener2).be.calledOnce(); + should(stubListener3).be.calledOnce(); + + should(kuzzleEventEmitter.listeners('foo')).eql([listener1, listener2]).and.have.length(2); }); }); describe('#prependOnceListener', function () { - it('should call prependListener() method', function () { - kuzzleEventEmitter.prependListener = sinon.stub(); - kuzzleEventEmitter.prependOnceListener('foo', listener1); - should(kuzzleEventEmitter.prependListener).be.calledOnce(); - should(kuzzleEventEmitter.prependListener).be.calledWith('foo', listener1); - }); + it('should prepend listeners only for 1 time', function () { + kuzzleEventEmitter.on('foo', listener1); + kuzzleEventEmitter.on('foo', listener2); + kuzzleEventEmitter.prependOnceListener('foo', listener3); - it('should properly add new listeners to once events', function () { - kuzzleEventEmitter.prependOnceListener('foo', listener1); - kuzzleEventEmitter.prependOnceListener('foo', listener2); - kuzzleEventEmitter.prependListener('foo', listener3); - kuzzleEventEmitter.prependOnceListener('bar', listener3); + should(kuzzleEventEmitter.listeners('foo')).eql([listener3, listener1, listener2]).and.have.length(3); + + kuzzleEventEmitter.emit('foo'); - should(kuzzleEventEmitter._onceEvents.foo[listener1]).be.true(); - should(kuzzleEventEmitter._onceEvents.foo[listener2]).be.true(); - should(kuzzleEventEmitter._onceEvents.foo[listener3]).be.undefined(); - should(kuzzleEventEmitter._onceEvents.bar[listener3]).be.true(); + should(stubListener1).be.calledOnce(); + should(stubListener2).be.calledOnce(); + should(stubListener3).be.calledOnce(); + + should(kuzzleEventEmitter.listeners('foo')).eql([listener1, listener2]).and.have.length(2); }); }); describe('#removeListener', function () { beforeEach(function () { - kuzzleEventEmitter._events = { - foo: [ - listener1, - listener2, - listener3 - ], - bar: [ - listener1, - listener2 - ], - baz: [ - listener3 - ] - }; + kuzzleEventEmitter.addListener('foo', listener1); + kuzzleEventEmitter.addListener('foo', listener2); + kuzzleEventEmitter.addListener('foo', listener3); + + kuzzleEventEmitter.addListener('bar', listener1); + kuzzleEventEmitter.addListener('bar', listener2); + + kuzzleEventEmitter.addListener('baz', listener3); }); it('should remove any one listener from the listener list', function () { kuzzleEventEmitter.removeListener('foo', listener2); - should(kuzzleEventEmitter._events.foo.length).be.exactly(2); - should(kuzzleEventEmitter._events.bar.length).be.exactly(2); - should(kuzzleEventEmitter._events.baz.length).be.exactly(1); + + should(kuzzleEventEmitter.listeners('foo')).eql([listener1, listener3]).and.have.length(2); + should(kuzzleEventEmitter.listeners('bar')).eql([listener1, listener2]).and.have.length(2); + should(kuzzleEventEmitter.listeners('baz')).eql([listener3]).and.have.length(1); }); it('should do nothing when trying to remove a listener from an unknown event', function () { kuzzleEventEmitter.removeListener('foobar', listener2); - should(kuzzleEventEmitter._events.foo.length).be.exactly(3); - should(kuzzleEventEmitter._events.bar.length).be.exactly(2); - should(kuzzleEventEmitter._events.baz.length).be.exactly(1); + + should(kuzzleEventEmitter.listeners('foo')).eql([listener1, listener2, listener3]).and.have.length(3); + should(kuzzleEventEmitter.listeners('bar')).eql([listener1, listener2]).and.have.length(2); + should(kuzzleEventEmitter.listeners('baz')).eql([listener3]).and.have.length(1); }); it('should do nothing if the provided listener does not exist', function () { - kuzzleEventEmitter.removeListener('foobar', listener1); - should(kuzzleEventEmitter._events.foo.length).be.exactly(3); - should(kuzzleEventEmitter._events.bar.length).be.exactly(2); - should(kuzzleEventEmitter._events.baz.length).be.exactly(1); + kuzzleEventEmitter.removeListener('bar', listener3); + should(kuzzleEventEmitter.listeners('foo')).eql([listener1, listener2, listener3]).and.have.length(3); + should(kuzzleEventEmitter.listeners('bar')).eql([listener1, listener2]).and.have.length(2); + should(kuzzleEventEmitter.listeners('baz')).eql([listener3]).and.have.length(1); }); }); describe('#removeAllListeners', function () { beforeEach(function () { - kuzzleEventEmitter._events = { - foo: [ - listener1, - listener2, - listener3 - ], - bar: [ - listener1, - listener2 - ], - baz: [ - listener3 - ] - }; + kuzzleEventEmitter.addListener('foo', listener1); + kuzzleEventEmitter.addListener('foo', listener2); + kuzzleEventEmitter.addListener('foo', listener3); + + kuzzleEventEmitter.addListener('bar', listener1); + kuzzleEventEmitter.addListener('bar', listener2); + + kuzzleEventEmitter.addListener('baz', listener3); }); it('should remove all registered listeners on a given event when asked to', function () { kuzzleEventEmitter.removeAllListeners('bar'); - should(kuzzleEventEmitter._events.foo.length).be.exactly(3); - should(kuzzleEventEmitter._events.bar).be.undefined(); - should(kuzzleEventEmitter._events.baz.length).be.exactly(1); + should(kuzzleEventEmitter.listeners('foo')).eql([listener1, listener2, listener3]).and.have.length(3); + should(kuzzleEventEmitter.listeners('bar')).eql([]).and.have.length(0); + should(kuzzleEventEmitter.listeners('baz')).eql([listener3]).and.have.length(1); }); it('should remove all registered listeners on all events when providing no event argument', function () { kuzzleEventEmitter.removeAllListeners(); - should(kuzzleEventEmitter._events.foo).be.undefined(); - should(kuzzleEventEmitter._events.bar).be.undefined(); - should(kuzzleEventEmitter._events.baz).be.undefined(); + should(kuzzleEventEmitter.listeners('foo')).eql([]).and.have.length(0); + should(kuzzleEventEmitter.listeners('bar')).eql([]).and.have.length(0); + should(kuzzleEventEmitter.listeners('baz')).eql([]).and.have.length(0); }); }); describe('#emit', function () { it('should call all added listeners for a given event', function () { - kuzzleEventEmitter._events = { - foo: [ - listener1, - listener1, - listener2 - ] - }; + kuzzleEventEmitter.addListener('foo', listener1); + kuzzleEventEmitter.addListener('foo', listener2); + kuzzleEventEmitter.addListener('bar', listener2); kuzzleEventEmitter.emit('foo'); - should(stubListener1).be.calledTwice(); + should(stubListener1).be.calledOnce(); should(stubListener2).be.calledOnce(); + should(stubListener3).not.be.called(); }); it('should call "once" listeners only once and othe ones each time the event is fired', function () { - kuzzleEventEmitter._events = { - foo: [ - listener1, - listener2 - ] - }; - kuzzleEventEmitter._onceEvents = {foo: {}}; - kuzzleEventEmitter._onceEvents.foo[listener1] = true; + kuzzleEventEmitter.addOnceListener('foo', listener1); + kuzzleEventEmitter.addListener('foo', listener2); kuzzleEventEmitter.emit('foo'); kuzzleEventEmitter.emit('foo'); @@ -233,11 +182,7 @@ describe('Event emitter', function () { }); it('should allow providing any number of arguments', function () { - kuzzleEventEmitter._events = { - foo: [ - listener1 - ] - }; + kuzzleEventEmitter.addListener('foo', listener1); kuzzleEventEmitter.emit('foo'); should(stubListener1).be.calledOnce(); @@ -246,29 +191,39 @@ describe('Event emitter', function () { stubListener1.reset(); kuzzleEventEmitter.emit('foo', 'bar'); should(stubListener1).be.calledOnce(); - should(stubListener1.firstCall.args).be.an.Array(); - should(stubListener1.firstCall.args).length(1); - should(stubListener1.firstCall.args[0]).be.exactly('bar'); + should(stubListener1.firstCall.args).eql(['bar']).and.have.length(1); stubListener1.reset(); kuzzleEventEmitter.emit('foo', 'bar', ['foo', 'bar']); should(stubListener1).be.calledOnce(); - should(stubListener1.firstCall.args).be.an.Array(); - should(stubListener1.firstCall.args).length(2); - should(stubListener1.firstCall.args[0]).be.exactly('bar'); - should(stubListener1.firstCall.args[1]).be.an.Array(); - should(stubListener1.firstCall.args[1]).match(['foo', 'bar']); + should(stubListener1.firstCall.args).eql(['bar', ['foo', 'bar']]).and.have.length(2); stubListener1.reset(); kuzzleEventEmitter.emit('foo', {foo: 'bar'}, 'bar', ['foo', 'bar']); - should(stubListener1).be.calledOnce(); - should(stubListener1.firstCall.args).be.an.Array(); - should(stubListener1.firstCall.args).length(3); - should(stubListener1.firstCall.args[0]).be.an.Object(); - should(stubListener1.firstCall.args[0].foo).be.exactly('bar'); - should(stubListener1.firstCall.args[1]).be.exactly('bar'); - should(stubListener1.firstCall.args[2]).be.an.Array(); - should(stubListener1.firstCall.args[2]).match(['foo', 'bar']); + should(stubListener1.firstCall.args).eql([{foo: 'bar'}, 'bar', ['foo', 'bar']]).and.have.length(3); + }); + }); + + describe('#eventNames', function () { + it('should return the list of registered event names', function () { + should(kuzzleEventEmitter.on('foo', listener1)).be.eql(kuzzleEventEmitter); + should(kuzzleEventEmitter.once('bar', listener2)).be.eql(kuzzleEventEmitter); + should(kuzzleEventEmitter.on('baz', listener3)).be.eql(kuzzleEventEmitter); + + should(kuzzleEventEmitter.eventNames()).be.eql(['foo', 'bar', 'baz']); + }); + }); + + describe('#listenerCount', function () { + it('should return the number of listeners on a given event', function () { + kuzzleEventEmitter.on('foo', listener1); + kuzzleEventEmitter.once('foo', listener2); + kuzzleEventEmitter.on('bar', listener3); + + should(kuzzleEventEmitter.listenerCount('foo')).be.eql(2); + should(kuzzleEventEmitter.listenerCount('bar')).be.eql(1); + should(kuzzleEventEmitter.listenerCount('baz')).be.eql(0); + should(kuzzleEventEmitter.listenerCount()).be.eql(0); }); }); }); diff --git a/test/kuzzle/listenersManagement.test.js b/test/kuzzle/listenersManagement.test.js index 3be63067c..a38b48c4e 100644 --- a/test/kuzzle/listenersManagement.test.js +++ b/test/kuzzle/listenersManagement.test.js @@ -1,11 +1,11 @@ var should = require('should'), - rewire = require('rewire'), sinon = require('sinon'), - Kuzzle = rewire('../../src/Kuzzle'); + proxyquire = require('proxyquire'); describe('Kuzzle listeners management', function () { var + Kuzzle, addListenerStub = sinon.stub(), emitStub = sinon.stub(), kuzzle; @@ -15,14 +15,15 @@ describe('Kuzzle listeners management', function () { KuzzleEventEmitterMock.prototype.addListener = addListenerStub; KuzzleEventEmitterMock.prototype.emit = emitStub; - Kuzzle.__set__({ - KuzzleEventEmitter: KuzzleEventEmitterMock + + Kuzzle = proxyquire('../../src/Kuzzle', { + './eventEmitter': KuzzleEventEmitterMock }); }); beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual', eventTimeout: 20}); + kuzzle = new Kuzzle('foo', {eventTimeout: 20}); addListenerStub.reset(); emitStub.reset(); }); diff --git a/test/kuzzle/login.test.js b/test/kuzzle/login.test.js index 98279de33..000648633 100644 --- a/test/kuzzle/login.test.js +++ b/test/kuzzle/login.test.js @@ -10,7 +10,7 @@ describe('Kuzzle Login', function () { kuzzle; beforeEach(function() { - kuzzle = new Kuzzle('somewhere', {connect: 'manual', eventTimeout: 0}); + kuzzle = new Kuzzle('somewhere', {eventTimeout: 0}); }); afterEach(function() { diff --git a/test/kuzzle/methods.test.js b/test/kuzzle/methods.test.js index 1942eec90..1eb843c18 100644 --- a/test/kuzzle/methods.test.js +++ b/test/kuzzle/methods.test.js @@ -23,7 +23,7 @@ describe('Kuzzle methods', function () { }; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); result = null; error = null; }); diff --git a/test/kuzzle/network.test.js b/test/kuzzle/network.test.js index 9dbcb8c6d..84c26d69d 100644 --- a/test/kuzzle/network.test.js +++ b/test/kuzzle/network.test.js @@ -1,28 +1,25 @@ var should = require('should'), - rewire = require('rewire'), + proxyquire = require('proxyquire'), sinon = require('sinon'), - NetworkWrapperMock = require('../mocks/networkWrapper.mock'), - Kuzzle = rewire('../../src/Kuzzle'); + NetworkWrapperMock = require('../mocks/networkWrapper.mock'); describe('Kuzzle network methods', function () { - var kuzzle; + var + Kuzzle, + kuzzle; beforeEach(function () { - networkWrapperRevert = Kuzzle.__set__({ - networkWrapper: function(protocol, host, options) { + Kuzzle = proxyquire('../../src/Kuzzle', { + './networkWrapper': function(protocol, host, options) { return new NetworkWrapperMock(host, options); } }); - kuzzle = new Kuzzle('somewhere', {connect: 'manual'}); + kuzzle = new Kuzzle('somewhere'); kuzzle.network.close = sinon.stub(); }); - afterEach(function() { - networkWrapperRevert(); - }); - describe('#flushQueue', function() { it('should return Kuzzle instance', function () { var result = kuzzle.flushQueue(); @@ -92,7 +89,7 @@ describe('Kuzzle network methods', function () { query = {foo: 'bar'}; kuzzle.addListener('queryError', eventStub); - kuzzle.network.emitEvent('queryError', error, query); + kuzzle.network.emit('queryError', error, query); should(eventStub).be.calledOnce(); should(eventStub).be.calledWithMatch({message: 'foo-bar'}, {foo: 'bar'}); @@ -102,7 +99,7 @@ describe('Kuzzle network methods', function () { var eventStub = sinon.stub(); kuzzle.addListener('offlineQueuePush', eventStub); - kuzzle.network.emitEvent('offlineQueuePush', {query: {foo: 'bar'}, cb: 'callback'}); + kuzzle.network.emit('offlineQueuePush', {query: {foo: 'bar'}, cb: 'callback'}); should(eventStub).be.calledOnce(); should(eventStub).be.calledWithMatch({query: {foo: 'bar'}, cb: 'callback'}); @@ -112,7 +109,7 @@ describe('Kuzzle network methods', function () { var eventStub = sinon.stub(); kuzzle.addListener('offlineQueuePop', eventStub); - kuzzle.network.emitEvent('offlineQueuePop', {foo: 'bar'}); + kuzzle.network.emit('offlineQueuePop', {foo: 'bar'}); should(eventStub).be.calledOnce(); should(eventStub).be.calledWithMatch({foo: 'bar'}); @@ -122,14 +119,14 @@ describe('Kuzzle network methods', function () { var eventStub = sinon.stub(); kuzzle.addListener('tokenExpired', eventStub); - kuzzle.network.emitEvent('tokenExpired'); + kuzzle.network.emit('tokenExpired'); should(eventStub).be.calledOnce(); }); it('should empty the jwt when a "tokenExpired" events is triggered', function () { kuzzle.jwt = 'foobar'; - kuzzle.network.emitEvent('tokenExpired'); + kuzzle.network.emit('tokenExpired'); should(kuzzle.jwt).be.undefined(); }); diff --git a/test/kuzzle/query.test.js b/test/kuzzle/query.test.js index d0adb8b8d..feaca9a49 100644 --- a/test/kuzzle/query.test.js +++ b/test/kuzzle/query.test.js @@ -1,14 +1,13 @@ var should = require('should'), sinon = require('sinon'), - rewire = require('rewire'), - NetworkWrapperMock = require('../mocks/networkWrapper.mock'), - Kuzzle = rewire('../../src/Kuzzle'); + proxyquire = require('proxyquire'), + NetworkWrapperMock = require('../mocks/networkWrapper.mock'); describe('Kuzzle query management', function () { describe('#query', function () { var - networkWrapperRevert, + Kuzzle, queryBody = {body: {some: 'query'}}, queryArgs = { controller: 'controller', @@ -19,17 +18,13 @@ describe('Kuzzle query management', function () { kuzzle; beforeEach(function () { - networkWrapperRevert = Kuzzle.__set__({ - networkWrapper: function(protocol, host, options) { + Kuzzle = proxyquire('../../src/Kuzzle', { + './networkWrapper': function(protocol, host, options) { return new NetworkWrapperMock(host, options); } }); - kuzzle = new Kuzzle('foo', {connect: 'manual'}); - }); - - afterEach(function() { - networkWrapperRevert(); + kuzzle = new Kuzzle('foo'); }); it('should generate a valid request object with no "options" argument and no callback', function () { diff --git a/test/kuzzle/subscribe.test.js b/test/kuzzle/subscribe.test.js index 8fdb3e8c4..973ccc7eb 100644 --- a/test/kuzzle/subscribe.test.js +++ b/test/kuzzle/subscribe.test.js @@ -1,36 +1,31 @@ var should = require('should'), sinon = require('sinon'), - rewire = require('rewire'), + proxyquire = require('proxyquire'), NetworkWrapperMock = require('../mocks/networkWrapper.mock'), - Kuzzle = rewire('../../src/Kuzzle'), KuzzleDocument = require('../../src/Document'), KuzzleRoom = require('../../src/Room'); describe('Kuzzle subscription management', function () { var + Kuzzle, cb, - networkWrapperRevert, kuzzle, room; beforeEach(function () { cb = sinon.stub(); - networkWrapperRevert = Kuzzle.__set__({ - networkWrapper: function(protocol, host, options) { + Kuzzle = proxyquire('../../src/Kuzzle', { + './networkWrapper': function(protocol, host, options) { return new NetworkWrapperMock(host, options); } }); - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); room = new KuzzleRoom(kuzzle.collection('foo', 'bar'), {equals: {foo: 'bar'}}, {}); room.notify = sinon.stub(); }); - afterEach(function() { - networkWrapperRevert(); - }); - describe('#subscribe', function () { it('should generate a valid request object', function () { kuzzle.subscribe(room, {}, cb); @@ -196,11 +191,11 @@ describe('Kuzzle subscription management', function () { }); it('should fire a "tokenExpired" event when receiving a TokenExpired notification', function () { - kuzzle.emitEvent = sinon.stub(); + sinon.stub(kuzzle, 'emit'); notificationCB({type: 'TokenExpired'}); - should(kuzzle.emitEvent).be.calledOnce(); - should(kuzzle.emitEvent).be.calledWith('tokenExpired'); + should(kuzzle.emit).be.calledOnce(); + should(kuzzle.emit).be.calledWith('tokenExpired'); }); }); }); diff --git a/test/mocks/networkWrapper.mock.js b/test/mocks/networkWrapper.mock.js index 2b26b3d9f..fb6168233 100644 --- a/test/mocks/networkWrapper.mock.js +++ b/test/mocks/networkWrapper.mock.js @@ -33,7 +33,7 @@ function NetworkWrapperMock (host, options) { self.state = 'connected'; self.emit('connect'); } - }); + }, 0); }; this.disconnect = function() { diff --git a/test/network/offlineQueue.test.js b/test/network/offlineQueue.test.js index 834128a08..90d8aa8f6 100644 --- a/test/network/offlineQueue.test.js +++ b/test/network/offlineQueue.test.js @@ -14,7 +14,7 @@ describe('Offline queue management', function () { beforeEach(function () { var pastTime = 60050; - network = new RTWrapper('somewhere', {connect: 'manual'}); + network = new RTWrapper('somewhere'); // queuing a bunch of 7 requests from 1min ago to right now, 10s apart now = Date.now(); diff --git a/test/network/query.test.js b/test/network/query.test.js index 2f1e51fdd..afe4340b9 100644 --- a/test/network/query.test.js +++ b/test/network/query.test.js @@ -12,9 +12,9 @@ describe('Network query management', function () { network; beforeEach(function () { - network = new RTWrapper('somewhere', {connect: 'manual'}); + network = new RTWrapper('somewhere'); network.send = function(request) { - network.emitEvent(request.requestId, request.response); + network.emit(request.requestId, request.response); }; sendSpy = sinon.spy(network, 'send'); }); @@ -114,7 +114,7 @@ describe('Network query management', function () { }); beforeEach(function () { - network = new RTWrapper('somewhere', {connect: 'manual'}); + network = new RTWrapper('somewhere'); network.state = 'connected'; emitRequestStub.reset(); }); @@ -266,7 +266,7 @@ describe('Network query management', function () { }; beforeEach(function () { - network = new RTWrapper('somewhere', {connect: 'manual'}); + network = new RTWrapper('somewhere'); network.state = 'connected'; network.query = sinon.stub().callsFake(queryStub); error = null; @@ -371,7 +371,7 @@ describe('Network query management', function () { }; beforeEach(function () { - network = new RTWrapper('somewhere', {connect: 'manual'}); + network = new RTWrapper('somewhere'); network.state = 'connected'; network.query = sinon.stub().callsFake(queryStub); error = null; @@ -441,7 +441,7 @@ describe('Network query management', function () { RTWrapper = rewire('../../src/networkWrapper/protocols/abstract/realtime'); RTWrapper.__set__('cleanHistory', cleanStub); - network = new RTWrapper('somewhere', {connect: 'manual'}); + network = new RTWrapper('somewhere'); should(network.cleanHistoryTimer).be.null(); should(cleanStub).not.be.called(); @@ -469,7 +469,7 @@ describe('Network query management', function () { network; RTWrapper = rewire('../../src/networkWrapper/protocols/abstract/realtime'); - network = new RTWrapper('somewhere', {connect: 'manual'}); + network = new RTWrapper('somewhere'); network.clientConnected(); for (i = 100000; i >= 0; i -= 10000) { diff --git a/test/network/socketio.test.js b/test/network/socketio.test.js index f45dfe396..6dc527ce3 100644 --- a/test/network/socketio.test.js +++ b/test/network/socketio.test.js @@ -123,14 +123,14 @@ describe('SocketIO network wrapper', function () { it('should call listeners on connect event', function () { var cb = sinon.stub(); - + should(socketIO.listeners('connect').length).be.eql(0); should(socketIO.listeners('reconnect').length).be.eql(0); socketIO.retrying = false; socketIO.addListener('connect', cb); - should(socketIO.listeners('connect').length).be.eql(1); - should(socketIO.listeners('reconnect').length).be.eql(0); + // should(socketIO.listeners('connect').length).be.eql(1); + // should(socketIO.listeners('reconnect').length).be.eql(0); socketIO.connect(); socketIO.socket.emit('connect'); @@ -138,7 +138,6 @@ describe('SocketIO network wrapper', function () { should(cb).be.calledOnce(); }); - it('should change the state when the client connection is established', function () { socketIO.state = 'connecting'; socketIO.queuing = true; @@ -317,27 +316,39 @@ describe('SocketIO network wrapper', function () { }); it('should be able to listen to an event just once', function () { - var cb = function () {}; + var cb = sinon.stub(); socketIO.once('event', cb); + should(socketIO.listeners('event')).match([cb]).and.have.length(1); should(socketStub.once).be.calledOnce(); - should(socketStub.once).be.calledWith('event', cb); + + socketStub.once.firstCall.args[1](); + should(cb).calledOnce(); + should(socketIO.listeners('event')).have.length(0); }); it('should be able to listen to an event', function () { - var cb = function () {}; + var cb = sinon.stub(); socketIO.on('event', cb); + should(socketIO.listeners('event')).match([cb]).and.have.length(1); should(socketStub.on).be.calledOnce(); - should(socketStub.on).be.calledWith('event', cb); + + socketStub.on.firstCall.args[1](); + should(cb).calledOnce(); + should(socketIO.listeners('event')).match([cb]).and.have.length(1); }); it('should be able to remove an event listener', function () { var cb = function () {}; - socketIO.off('event', cb); + socketIO.on('event', cb); + should(socketIO.listeners('event')).match([cb]).and.have.length(1); + should(socketStub.on).be.calledOnce(); + + socketIO.removeListener('event', cb); should(socketStub.off).be.calledOnce(); - should(socketStub.off).be.calledWith('event', cb); + should(socketIO.listeners('event')).have.length(0); }); it('should be able to send a payload', function () { @@ -351,5 +362,39 @@ describe('SocketIO network wrapper', function () { should(socketStub.close).be.calledOnce(); should(socketIO.socket).be.null(); }); + + it('should remove all listeners from a given event', function () { + socketIO.on('foo', function () {}); + socketIO.on('foo', function () {}); + socketIO.on('foo', function () {}); + socketIO.on('bar', function () {}); + + should(socketIO.listeners('foo')).have.length(3); + should(socketIO.listeners('bar')).have.length(1); + + socketIO.removeAllListeners('foo'); + + should(socketIO.listeners('foo')).have.length(0); + should(socketIO.listeners('bar')).have.length(1); + }); + + it('should remove all listeners from all events', function () { + socketIO.on('foo', function () {}); + socketIO.on('foo', function () {}); + socketIO.on('foo', function () {}); + socketIO.on('bar', function () {}); + socketIO.on('baz', function () {}); + socketIO.on('baz', function () {}); + + should(socketIO.listeners('foo')).have.length(3); + should(socketIO.listeners('bar')).have.length(1); + should(socketIO.listeners('baz')).have.length(2); + + socketIO.removeAllListeners(); + + should(socketIO.listeners('foo')).have.length(0); + should(socketIO.listeners('bar')).have.length(0); + should(socketIO.listeners('baz')).have.length(0); + }); }); }); diff --git a/test/network/websocket.test.js b/test/network/websocket.test.js index 15ad6e037..844daea78 100644 --- a/test/network/websocket.test.js +++ b/test/network/websocket.test.js @@ -347,10 +347,10 @@ describe('WebSocket networking module', function () { should(websocket.listeners('foobar').length).be.equal(2); - websocket.off('foobar', cb1); + websocket.removeListener('foobar', cb1); should(websocket.listeners('foobar').length).be.equal(1); - websocket.off('foobar', cb2); + websocket.removeListener('foobar', cb2); should(websocket.listeners('foobar').length).be.exactly(0); }); @@ -365,10 +365,10 @@ describe('WebSocket networking module', function () { should(websocket.listeners('foobar').length).be.equal(2); - websocket.off('foo', cb1); + websocket.removeListener('foo', cb1); should(websocket.listeners('foobar').length).be.equal(2); - websocket.off('foobar', sinon.stub()); + websocket.removeListener('foobar', sinon.stub()); should(websocket.listeners('foobar').length).be.equal(2); }); diff --git a/test/security/kuzzleProfile/constructor.test.js b/test/security/kuzzleProfile/constructor.test.js index eaacf25d1..1c1431058 100644 --- a/test/security/kuzzleProfile/constructor.test.js +++ b/test/security/kuzzleProfile/constructor.test.js @@ -9,7 +9,7 @@ describe('Profile constructor', function () { kuzzle; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); }); it('should throw an error if no id is provided', function() { diff --git a/test/security/kuzzleProfile/methods.test.js b/test/security/kuzzleProfile/methods.test.js index 691a598fb..5f17f248c 100644 --- a/test/security/kuzzleProfile/methods.test.js +++ b/test/security/kuzzleProfile/methods.test.js @@ -12,7 +12,7 @@ describe('Profile methods', function () { expectedQuery; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); kuzzle.query = sinon.stub(); }); diff --git a/test/security/kuzzleRole/constructor.test.js b/test/security/kuzzleRole/constructor.test.js index 36cb8cf05..50cf273b8 100644 --- a/test/security/kuzzleRole/constructor.test.js +++ b/test/security/kuzzleRole/constructor.test.js @@ -9,7 +9,7 @@ describe('Role constructor', function () { kuzzle; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); }); it('should throw an error if no id is provided', function () { diff --git a/test/security/kuzzleRole/methods.test.js b/test/security/kuzzleRole/methods.test.js index afbc629b4..b01fdf72c 100644 --- a/test/security/kuzzleRole/methods.test.js +++ b/test/security/kuzzleRole/methods.test.js @@ -12,7 +12,7 @@ describe('Role methods', function () { expectedQuery; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); kuzzle.query = sinon.stub(); }); diff --git a/test/security/kuzzleSecurity/constructor.test.js b/test/security/kuzzleSecurity/constructor.test.js index 8967784f4..f2b5b4323 100644 --- a/test/security/kuzzleSecurity/constructor.test.js +++ b/test/security/kuzzleSecurity/constructor.test.js @@ -7,7 +7,7 @@ var describe('Security constructor', function () { it('should initialize properties and return a valid Security object', function () { var - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); should(kuzzle.security).be.instanceof(Security); should(kuzzle.security).have.propertyWithDescriptor('kuzzle', { enumerable: false, writable: false, configurable: false }); @@ -20,7 +20,7 @@ describe('Security constructor', function () { kuzzle; Kuzzle.prototype.bluebird = bluebird; - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); should.exist(kuzzle.security.createRolePromise); should.exist(kuzzle.security.fetchRolePromise); diff --git a/test/security/kuzzleSecurity/credentialsMethods.test.js b/test/security/kuzzleSecurity/credentialsMethods.test.js index ecfb31f7d..f6c6c0931 100644 --- a/test/security/kuzzleSecurity/credentialsMethods.test.js +++ b/test/security/kuzzleSecurity/credentialsMethods.test.js @@ -9,7 +9,7 @@ describe('Credentials methods', function() { describe('#createCredentials', function() { beforeEach(function() { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); }); it('should trigger callback with an error', function (done) { @@ -53,7 +53,7 @@ describe('Credentials methods', function() { describe('#deleteCredentials', function() { beforeEach(function() { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); }); it('should trigger callback with an error', function (done) { @@ -96,7 +96,7 @@ describe('Credentials methods', function() { describe('#getAllCredentialFields', function() { beforeEach(function() { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); }); it('should trigger callback with an error', function (done) { @@ -138,7 +138,7 @@ describe('Credentials methods', function() { describe('#getCredentialFields', function() { beforeEach(function() { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); }); it('should trigger callback with an error', function (done) { @@ -180,7 +180,7 @@ describe('Credentials methods', function() { describe('#getCredentials', function() { beforeEach(function() { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); }); it('should trigger callback with an error', function (done) { @@ -224,7 +224,7 @@ describe('Credentials methods', function() { describe('#hasCredentials', function() { beforeEach(function() { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); }); it('should trigger callback with an error', function (done) { @@ -267,7 +267,7 @@ describe('Credentials methods', function() { describe('#updateCredentials', function() { beforeEach(function() { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); }); it('should trigger callback with an error', function (done) { @@ -311,7 +311,7 @@ describe('Credentials methods', function() { describe('#validateCredentials', function() { beforeEach(function() { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); }); it('should trigger callback with an error', function (done) { diff --git a/test/security/kuzzleSecurity/profilesMethods.test.js b/test/security/kuzzleSecurity/profilesMethods.test.js index 1d9764fc2..71e65b11d 100644 --- a/test/security/kuzzleSecurity/profilesMethods.test.js +++ b/test/security/kuzzleSecurity/profilesMethods.test.js @@ -11,7 +11,7 @@ describe('Security profiles methods', function () { result; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); kuzzle.query = sinon.stub(); }); @@ -315,7 +315,7 @@ describe('Security profiles methods', function () { describe('#scrollProfiles', function () { beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual', defaultIndex: 'bar'}); + kuzzle = new Kuzzle('foo', {defaultIndex: 'bar'}); result = { result: { _scroll_id: 'banana', total: 123, hits: [ {_id: 'foobar', _source: { foo: 'bar'}} ] } }; }); diff --git a/test/security/kuzzleSecurity/rightsMethods.test.js b/test/security/kuzzleSecurity/rightsMethods.test.js index 6137bc952..828052aaf 100644 --- a/test/security/kuzzleSecurity/rightsMethods.test.js +++ b/test/security/kuzzleSecurity/rightsMethods.test.js @@ -61,7 +61,7 @@ describe('Security user rights methods', function () { ]; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); kuzzle.query = sinon.stub(); }); diff --git a/test/security/kuzzleSecurity/rolesMethods.test.js b/test/security/kuzzleSecurity/rolesMethods.test.js index 5ce99426e..79b3f9b72 100644 --- a/test/security/kuzzleSecurity/rolesMethods.test.js +++ b/test/security/kuzzleSecurity/rolesMethods.test.js @@ -11,7 +11,7 @@ describe('Security roles methods', function () { result; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); kuzzle.query = sinon.stub(); }); diff --git a/test/security/kuzzleSecurity/userMethods.test.js b/test/security/kuzzleSecurity/userMethods.test.js index d43e0e221..e03b96a10 100644 --- a/test/security/kuzzleSecurity/userMethods.test.js +++ b/test/security/kuzzleSecurity/userMethods.test.js @@ -11,7 +11,7 @@ describe('Security user methods', function () { result; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); kuzzle.query = sinon.stub(); }); @@ -353,7 +353,7 @@ describe('Security user methods', function () { describe('#scrollUsers', function () { beforeEach(function () { - kuzzle = new Kuzzle('foo', {defaultIndex: 'bar', connect: 'manual'}); + kuzzle = new Kuzzle('foo', {defaultIndex: 'bar'}); result = { result: { _scroll_id: 'banana', total: 123, hits: [ {_id: 'foobar', _source: { foo: 'bar'}} ] } }; }); diff --git a/test/security/kuzzleSecurityDocument/constructor.test.js b/test/security/kuzzleSecurityDocument/constructor.test.js index f4aa22cea..e83ea7256 100644 --- a/test/security/kuzzleSecurityDocument/constructor.test.js +++ b/test/security/kuzzleSecurityDocument/constructor.test.js @@ -8,7 +8,7 @@ describe('KuzzleSecurityDocument constructor', function () { kuzzle; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); }); it('should throw an error if no id is provided', function () { diff --git a/test/security/kuzzleSecurityDocument/methods.test.js b/test/security/kuzzleSecurityDocument/methods.test.js index a7f08dfde..e2ab73ab5 100644 --- a/test/security/kuzzleSecurityDocument/methods.test.js +++ b/test/security/kuzzleSecurityDocument/methods.test.js @@ -6,7 +6,7 @@ var describe('KuzzleSecurityDocument methods', function () { var securityDocument, - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); describe('#toJSON', function () { before(function () { diff --git a/test/security/kuzzleUser/constructor.test.js b/test/security/kuzzleUser/constructor.test.js index e81c56cd2..06e41d4ed 100644 --- a/test/security/kuzzleUser/constructor.test.js +++ b/test/security/kuzzleUser/constructor.test.js @@ -9,7 +9,7 @@ describe('User constructor', function () { kuzzle; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); }); it('should throw an error if no id is provided', function () { diff --git a/test/security/kuzzleUser/methods.test.js b/test/security/kuzzleUser/methods.test.js index 7ca89499c..2f24170ef 100644 --- a/test/security/kuzzleUser/methods.test.js +++ b/test/security/kuzzleUser/methods.test.js @@ -15,7 +15,7 @@ describe('User methods', function () { expectedQuery; beforeEach(function () { - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); kuzzle.query = sinon.stub(); }); @@ -68,7 +68,7 @@ describe('User methods', function () { describe('#replace', function () { beforeEach(function () { sandbox.reset(); - kuzzle = new Kuzzle('foo', {connect: 'manual'}); + kuzzle = new Kuzzle('foo'); result = {result: {_id: 'myUser', _source: {some: 'content', profileIds: ['myProfile']}}}; kuzzleUser = new User(kuzzle.security, result.result._id, result.result._source); }); diff --git a/webpack.config.js b/webpack.config.js index 9278a2f09..5bf595a7d 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -30,7 +30,8 @@ module.exports = { include: [ path.resolve(__dirname, './src/networkWrapper/protocols/'), path.resolve(__dirname, './src/Kuzzle.js'), - path.resolve(__dirname, './src/Room.js') + path.resolve(__dirname, './src/Room.js'), + path.resolve(__dirname, './src/eventEmitter/') ], loader: 'babel-loader', query: {