From ec4c2cff4f79fe77911795d8e59e0b4e19d20ee0 Mon Sep 17 00:00:00 2001 From: scottinet Date: Tue, 6 Sep 2016 16:22:51 +0200 Subject: [PATCH 1/4] normalized return values --- .eslintrc => .eslintrc.json | 2 +- dist/kuzzle.js | 4 +- dist/kuzzle.js.map | 2 +- dist/kuzzle.min.js | 4 - dist/kuzzle.min.map | 1 - src/kuzzle.js | 103 +++------ src/kuzzleDataCollection.js | 99 +++----- src/kuzzleDataMapping.js | 6 +- src/kuzzleDocument.js | 16 +- src/kuzzleRoom.js | 23 +- src/security/kuzzleProfile.js | 10 +- src/security/kuzzleRole.js | 12 +- src/security/kuzzleSecurity.js | 212 +++++------------- src/security/kuzzleSecurityDocument.js | 2 + src/security/kuzzleUser.js | 21 +- test/kuzzle/methods.test.js | 29 +-- test/kuzzleDataCollection/methods.test.js | 18 +- test/kuzzleRoom/methods.test.js | 10 +- test/security/kuzzleProfile/methods.test.js | 10 +- test/security/kuzzleRole/methods.test.js | 8 +- .../kuzzleSecurity/profilesMethods.test.js | 2 +- test/security/kuzzleUser/methods.test.js | 16 +- 22 files changed, 182 insertions(+), 428 deletions(-) rename .eslintrc => .eslintrc.json (95%) delete mode 100644 dist/kuzzle.min.js delete mode 100644 dist/kuzzle.min.map diff --git a/.eslintrc b/.eslintrc.json similarity index 95% rename from .eslintrc rename to .eslintrc.json index dfca9481a..4205fb7bb 100644 --- a/.eslintrc +++ b/.eslintrc.json @@ -39,7 +39,7 @@ "no-undef": 0, "no-undef-init": 1, "no-unreachable": 2, - "no-unused-expressions": 2, + "no-unused-expressions": [2, {"allowShortCircuit": true}], "no-useless-call": 2, "no-with": 2, "quotes": [2, "single"], diff --git a/dist/kuzzle.js b/dist/kuzzle.js index 7e468c5e7..acbceae15 100644 --- a/dist/kuzzle.js +++ b/dist/kuzzle.js @@ -1,3 +1,3 @@ -!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var n in r)("object"==typeof exports?exports:e)[n]=r[n]}}(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){function n(){var e=this,t=Date.now(),r=-1;e.queueTTL>0&&(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.emitEvent("offlineQueuePop",t.query)})}function i(e){var t=Date.now();Object.keys(e).forEach(function(r){e[r]0?(o.call(t,t.offlineQueue[0].query,t.offlineQueue[0].cb),t.emitEvent("offlineQueuePop",t.offlineQueue.shift()),setTimeout(function(){n()},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)})}n()}function s(){var e=this;Object.keys(e.subscriptions).forEach(function(t){Object.keys(e.subscriptions[t]).forEach(function(r){var n=e.subscriptions[t][r];n.renew(n.callback)})})}var l=r(3),c=r(4),a=r(14),f=r(7),d=r(2),h=r(9);e.exports=Kuzzle=function(e,t,r){var n=this;if(!(this instanceof Kuzzle))return new Kuzzle(e,t,r);if(r||"function"!=typeof t||(r=t,t=null),!e||""===e)throw new Error("host argument missing");return Object.defineProperties(this,{collections:{value:{},writable:!0},connectCB:{value:r},eventListeners:{value:{connected:{lastEmitted:null,listeners:[]},error:{lastEmitted:null,listeners:[]},disconnected:{lastEmitted:null,listeners:[]},reconnected:{lastEmitted:null,listeners:[]},jwtTokenExpired:{lastEmitted:null,listeners:[]},loginAttempt:{lastEmitted:null,listeners:[]},offlineQueuePush:{listeners:[]},offlineQueuePop:{listeners:[]}}},eventTimeout:{value:200},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,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,enumerable:!0},host:{value:e,enumerable:!0},wsPort:{value:t&&"number"==typeof t.wsPort?t.wsPort:7513,enumerable:!0},ioPort:{value:t&&"number"==typeof t.ioPort?t.ioPort:7512,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},metadata:{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:null,enumerable:!0,writable:!0}}),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 a(this),enumerable:!0}),Object.defineProperty(this,"emitEvent",{value:function(e){var t=Date.now(),r=Array.prototype.slice.call(arguments,1),n=this.eventListeners[e];return!(n.lastEmitted&&n.lastEmitted>=t-this.eventTimeout)&&(n.listeners.forEach(function(e){process.nextTick(function(){e.fn.apply(void 0,r)})}),void(void 0!==n.lastEmitted&&(n.lastEmitted=t)))}}),Object.defineProperty(this,"memoryStorage",{value:new f(this),enumerable:!0}),t&&t.connect&&"auto"!==t.connect?this.state="ready":this.connect(),i(this.requestHistory),this.bluebird?this.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,r,n){var i=["getAllStatistics","getServerInfo","getStatistics","listCollections","listIndexes","login","logout","now","query","checkToken","whoAmI","updateSelf","getMyRights","refreshIndex","getAutoRefresh","setAutoRefresh"];return n&&i.indexOf(e)!==-1}}):void 0},Kuzzle.prototype.connect=function(){var e=this;return e.network||(e.network=h(e.host,e.wsPort,e.ioPort)),["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",s.call(e),u.call(e),e.emitEvent("connected"),e.connectCB&&e.connectCB(null,e)}),e.network.onConnectError(function(t){var r=new Error('Unable to connect to kuzzle server at "'+e.host+'"');r.internal=t,e.state="error",e.emitEvent("error",r),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&&s.call(e),e.autoReplay&&(n.call(e),u.call(e)),e.emitEvent("reconnected")};e.state="connected",e.jwtToken?e.checkToken(e.jwtToken,function(r,n){!r&&n.valid||(e.jwtToken=void 0,e.emitEvent("jwtTokenExpired")),t()}):t()}),this)},Kuzzle.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 s.call(this),this.emitEvent("loginAttempt",{success:!0}),this},Kuzzle.prototype.getJwtToken=function(){return this.jwtToken},Kuzzle.prototype.login=function(e){var t,r,n=this,i={strategy:e};return arguments[1]&&("object"==typeof arguments[1]?t=arguments[1]:"number"==typeof arguments[1]||"string"==typeof arguments[1]?i.expiresIn=arguments[1]:"function"==typeof arguments[1]&&(r=arguments[1])),arguments[2]&&("number"==typeof arguments[2]||"string"==typeof arguments[2]?i.expiresIn=arguments[2]:"function"==typeof arguments[2]&&(r=arguments[2])),arguments[3]&&"function"==typeof arguments[3]&&(r=arguments[3]),"object"==typeof t&&Object.keys(t).forEach(function(e){i[e]=t[e]}),this.query({controller:"auth",action:"login"},{body:i},{queuable:!1},function(e,t){e?(r&&"function"==typeof r&&r(e),n.emitEvent("loginAttempt",{success:!1,error:e.message})):(t.result.jwt&&n.setJwtToken(t.result.jwt),r&&"function"==typeof r&&r(null,t.result))}),n},Kuzzle.prototype.logout=function(e){var t=this,r={action:"logout",controller:"auth",requestId:l.v4(),body:{}};return this.query({controller:"auth",action:"logout"},r,{queuable:!1},function(r){null===r?(t.jwtToken=void 0,"function"==typeof e&&e(null,t)):"function"==typeof e&&e(r)}),t},Kuzzle.prototype.checkToken=function(e,t){var r=this,n={body:{token:e}};return this.callbackRequired("Kuzzle.checkToken",t),this.query({controller:"auth",action:"checkToken"},n,{queuable:!1},function(e,r){return e?t(e):void t(null,r.result)}),r},Kuzzle.prototype.whoAmI=function(e){var t=this;return t.callbackRequired("Kuzzle.whoAmI",e),t.query({controller:"auth",action:"getCurrentUser"},{},{},function(r,n){return r?e(r):void e(null,new d(t.security,n.result._id,n.result._source))}),t},Kuzzle.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"},{},null,function(e,r){return e?t(e):void t(null,r.result.hits)})},Kuzzle.prototype.updateSelf=function(e,t,r){var n=this,i={},o={controller:"auth",action:"updateSelf"};r||"function"!=typeof t||(r=t,t=null),i.body=e,r?n.query(o,i,t,function(e,t){return e?r(e):void r(null,t.result)}):n.query(o,i,t)},Kuzzle.prototype.addListener=function(e,t){var r,n=Object.keys(this.eventListeners),i=typeof t;if(this.isValid(),n.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+n.toString());if("function"!==i)throw new Error("Invalid listener type: expected a function, got a "+i);return r=l.v4(),this.eventListeners[e].listeners.push({id:r,fn:t}),r},Kuzzle.prototype.getAllStatistics=function(e,t){return t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.getAllStatistics",t),this.query({controller:"admin",action:"getAllStats"},{},e,function(e,r){return e?t(e):void t(null,r.result.hits)}),this},Kuzzle.prototype.getStatistics=function(e,t,r){var n;return 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))),n=function(t,n){return t?r(t):void(e?r(null,n.result.hits):r(null,[n.result]))},this.callbackRequired("Kuzzle.getStatistics",r),e?this.query({controller:"admin",action:"getStats"},{body:{startTime:e}},t,n):this.query({controller:"admin",action:"getLastStats"},{},t,n),this},Kuzzle.prototype.dataCollectionFactory=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)throw new Error('Invalid "index" argument: string expected, got '+typeof t);if("string"!=typeof e)throw new Error('Invalid "collection" argument: string expected, got '+typeof e);return this.collections[t]||(this.collections[t]={}),this.collections[t][e]||(this.collections[t][e]=new c(this,t,e)),this.collections[t][e]},Kuzzle.prototype.flushQueue=function(){return this.offlineQueue=[],this},Kuzzle.prototype.listCollections=function(){var e,t,r,n="all",i=Array.prototype.slice.call(arguments);if(i.forEach(function(n){switch(typeof n){case"string":e=n;break;case"object":t=n;break;case"function":r=n}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.listCollections: index required");e=this.defaultIndex}return this.callbackRequired("Kuzzle.listCollections",r),t&&t.type&&(n=t.type),this.query({index:e,controller:"read",action:"listCollections"},{body:{type:n}},t,function(e,t){return e?r(e):r(null,t.result.collections)}),this},Kuzzle.prototype.listIndexes=function(e,t){return t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.listIndexes",t),this.query({controller:"read",action:"listIndexes"},{},e,function(e,r){return e?t(e):t(null,r.result.indexes)}),this},Kuzzle.prototype.disconnect=function(){var e;this.logout(),this.state="disconnected",this.network.close();for(e in this.collections)this.collections.hasOwnProperty(e)&&delete this.collections[e]},Kuzzle.prototype.getServerInfo=function(e,t){return t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.getServerInfo",t),this.query({controller:"read",action:"serverInfo"},{},e,function(e,r){return e?t(e):void t(null,r.result.serverInfo)}),this},Kuzzle.prototype.refreshIndex=function(){var e,t,r;if(Array.prototype.slice.call(arguments).forEach(function(n){switch(typeof n){case"string":e=n;break;case"object":t=n;break;case"function":r=n}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.refreshIndex: index required");e=this.defaultIndex}return this.query({index:e,controller:"admin",action:"refreshIndex"},{},t,r),this},Kuzzle.prototype.getAutoRefresh=function(){var e,t,r;if(Array.prototype.slice.call(arguments).forEach(function(n){switch(typeof n){case"string":e=n;break;case"object":t=n;break;case"function":r=n}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.getAutoRefresh: index required");e=this.defaultIndex}return this.callbackRequired("Kuzzle.getAutoRefresh",r),this.query({index:e,controller:"admin",action:"getAutoRefresh"},{},t,r),this},Kuzzle.prototype.setAutoRefresh=function(){var e,t,r,n;if(Array.prototype.slice.call(arguments).forEach(function(i){switch(typeof i){case"string":e=i;break;case"boolean":t=i;break;case"object":r=i;break;case"function":n=i}}),!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:"admin",action:"setAutoRefresh"},{body:{autoRefresh:t}},r,n),this},Kuzzle.prototype.now=function(e,t){return t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.now",t),this.query({controller:"read",action:"now"},{},e,function(e,r){return e?t(e):void t(null,r.result.now)}),this},Kuzzle.prototype.query=function(e,t,r,i){var u,s={action:e.action,controller:e.controller,metadata:this.metadata},c=this;if(this.isValid(),i||"function"!=typeof r||(i=r,r=null),r&&(r.metadata&&Object.keys(r.metadata).forEach(function(e){s.metadata[e]=r.metadata[e]}),r.queuable===!1&&"offline"===c.state))return c;if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("Invalid query parameter: "+t);t.metadata&&Object.keys(t.metadata).forEach(function(e){s.metadata[e]=t.metadata[e]});for(u in t)"metadata"!==u&&t.hasOwnProperty(u)&&(s[u]=t[u]);return s=c.addHeaders(s,this.headers),void 0===c.jwtToken||"auth"===s.controller&&"checkToken"===s.action||(s.headers=s.headers||{},s.headers.authorization="Bearer "+c.jwtToken),e.collection&&(s.collection=e.collection),e.index&&(s.index=e.index),s.requestId||(s.requestId=l.v4()),"connected"===c.state||r&&r.queuable===!1?"connected"===c.state?o.call(this,s,i):i&&i(new Error("Unable to execute request: not connected to a Kuzzle server.\nDiscarded request: "+JSON.stringify(s))):(c.queuing||["initializing","connecting"].indexOf(c.state)!==-1)&&(n.call(this,s,i),c.queueFilter&&!c.queueFilter(s)||(c.offlineQueue.push({ts:Date.now(),query:s,cb:i}),c.emitEvent("offlineQueuePush",{query:s,cb:i}))),c},Kuzzle.prototype.removeAllListeners=function(e){var t=Object.keys(this.eventListeners),r=this;if(e){if(t.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+t.toString());this.eventListeners[e].listeners=[]}else t.forEach(function(e){r.eventListeners[e].listeners=[]})},Kuzzle.prototype.removeListener=function(e,t){var r=Object.keys(this.eventListeners),n=this;if(r.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+r.toString());this.eventListeners[e].listeners.forEach(function(r,i){r.id===t&&n.eventListeners[e].listeners.splice(i,1)})},Kuzzle.prototype.replayQueue=function(){return"offline"===this.state||this.autoReplay||(n.call(this),u.call(this)),this},Kuzzle.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},Kuzzle.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},Kuzzle.prototype.startQueuing=function(){return"offline"!==this.state||this.autoQueue||(this.queuing=!0),this},Kuzzle.prototype.stopQueuing=function(){return"offline"!==this.state||this.autoQueue||(this.queuing=!1),this}},function(e,t){function r(e,t,r){if(!t)throw new Error("A security document must have an id");if(Object.defineProperties(this,{kuzzle:{value:e.kuzzle},kuzzleSecurity:{value:e},id:{value:t,enumerable:!0},content:{value:{},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,n){var i=["delete","update"];return n&&i.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},r.prototype["delete"]=function(e,t){var r=this;e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r.kuzzle.query(this.kuzzleSecurity.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 n={},i=this;if("object"!=typeof e)throw new Error('Parameter "content" must be a object');t&&void 0===r&&"function"==typeof t&&(r=t,t=null),n._id=i.id,n.body=e,i.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.updateActionName),n,t,function(e,t){return e?!!r&&r(e):(i.setContent(t.result._source),void(r&&r(null,i)))})},e.exports=r},function(e,t,r){function n(e,t,r){if(i.call(this,e,t,r),Object.defineProperties(this,{deleteActionName:{value:"deleteUser"},updateActionName:{value:"updateUser"}}),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(1);n.prototype=Object.create(i.prototype,{constructor:{value:n}}),n.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},n.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},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.kuzzleSecurity.buildQueryArgs("createOrReplaceUser"),r,e,function(e){return e?!!t&&t(e):void(t&&t(null,n))}),n},n.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e},n.prototype.getProfiles=function(){return this.content.profileIds},e.exports=n},function(e,t){!function(t){"use strict";function r(){var e=t.crypto||t.msCrypto;if(!l&&e&&e.getRandomValues)try{var r=new Uint8Array(16);f=l=function(){return e.getRandomValues(r),r},l()}catch(n){}if(!l){var i=new Array(16);c=l=function(){for(var e,t=0;t<16;t++)0===(3&t)&&(e=4294967296*Math.random()),i[t]=e>>>((3&t)<<3)&255;return i},"undefined"!=typeof console&&console.warn&&console.warn("[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()")}}function n(){if("function"==typeof require)try{var e=require("crypto").randomBytes;a=l=e&&function(){return e(16)},l()}catch(t){}}function i(e,t,r){var n=t&&r||0,i=0;for(t=t||[],e.toLowerCase().replace(/[0-9a-f]{2}/g,function(e){i<16&&(t[n+i++]=y[e])});i<16;)t[n+i++]=0;return t}function o(e,t){var r=t||0,n=p;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++]]}function u(e,t,r){var n=t&&r||0,i=t||[];e=e||{};var u=null!=e.clockseq?e.clockseq:m,s=null!=e.msecs?e.msecs:(new Date).getTime(),l=null!=e.nsecs?e.nsecs:g+1,c=s-w+(l-g)/1e4;if(c<0&&null==e.clockseq&&(u=u+1&16383),(c<0||s>w)&&null==e.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");w=s,g=l,m=u,s+=122192928e5;var a=(1e4*(268435455&s)+l)%4294967296;i[n++]=a>>>24&255,i[n++]=a>>>16&255,i[n++]=a>>>8&255,i[n++]=255&a;var f=s/4294967296*1e4&268435455;i[n++]=f>>>8&255,i[n++]=255&f,i[n++]=f>>>24&15|16,i[n++]=f>>>16&255,i[n++]=u>>>8|128,i[n++]=255&u;for(var d=e.node||v,h=0;h<6;h++)i[n+h]=d[h];return t?t:o(i)}function s(e,t,r){var n=t&&r||0;"string"==typeof e&&(t="binary"===e?new h(16):null,e=null),e=e||{};var i=e.random||(e.rng||l)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t)for(var u=0;u<16;u++)t[n+u]=i[u];return t||o(i)}var l,c,a,f,d;t?r():n();for(var h="function"==typeof Buffer?Buffer:Array,p=[],y={},b=0;b<256;b++)p[b]=(b+256).toString(16).substr(1),y[p[b]]=b;var z=l(),v=[1|z[0],z[1],z[2],z[3],z[4],z[5]],m=16383&(z[6]<<8|z[7]),w=0,g=0,k=s;k.v1=u,k.v4=s,k.parse=i,k.unparse=o,k.BufferClass=h,k._rng=l,k._mathRNG=c,k._nodeRNG=a,k._whatwgRNG=f,"undefined"!=typeof e&&e.exports?e.exports=k:"function"==typeof define&&define.amd?define(function(){return k}):(d=t.uuid,k.noConflict=function(){return t.uuid=d,k},t.uuid=k)}("undefined"!=typeof window?window:null)},function(e,t,r){function n(e,t,r){if(!t||!r)throw new Error("The KuzzleDataCollection object constructor needs an index and a collection arguments");return Object.defineProperties(this,{collection:{value:r,enumerable:!0},index:{value:t,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,n){var i=["publishMessage","setHeaders","subscribe"];return n&&i.indexOf(e)===-1}}):this}var i=r(6),o=r(5),u=r(8);n.prototype.advancedSearch=function(e,t,r){var n,o=this;return r||"function"!=typeof t||(r=t,t=null),o.kuzzle.callbackRequired("KuzzleDataCollection.advancedSearch",r),n=o.kuzzle.addHeaders({body:e},this.headers),o.kuzzle.query(this.buildQueryArgs("read","search"),n,t,function(e,t){var n=[];return e?r(e):(t.result.hits.forEach(function(e){var t=new i(o,e._id,e._source);t.version=e._version,n.push(t)}),void r(null,{total:t.result.total,documents:n}))}),this},n.prototype.count=function(e,t,r){var n;return r||"function"!=typeof t||(r=t,t=null),this.kuzzle.callbackRequired("KuzzleDataCollection.count",r),n=this.kuzzle.addHeaders({body:e},this.headers),this.kuzzle.query(this.buildQueryArgs("read","count"),n,t,function(e,t){return e?r(e):void r(null,t.result.count)}),this},n.prototype.create=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("write","createCollection"),r,e,t),this},n.prototype.createDocument=function(e,t,r,n){var o=this,u={},s="create";return e&&"string"!=typeof e&&(n=r,r=t,t=e,e=null),n||"function"!=typeof r||(n=r,r=null),t instanceof i?u=t.serialize():u.body=t,r&&(s=r.updateIfExist?"createOrReplace":"create"),e&&(u._id=e),u=o.kuzzle.addHeaders(u,o.headers),n?o.kuzzle.query(this.buildQueryArgs("write",s),u,r,function(e,t){var r;return e?n(e):(r=new i(o,t.result._id,t.result._source),r.version=t.result._version,void n(null,r))}):o.kuzzle.query(this.buildQueryArgs("write",s),u,r),this},n.prototype.deleteDocument=function(e,t,r){var n,i={};"string"==typeof e?(i._id=e,n="delete"):(i.body=e,n="deleteByQuery"),r||"function"!=typeof t||(r=t,t=null),i=this.kuzzle.addHeaders(i,this.headers),r?this.kuzzle.query(this.buildQueryArgs("write",n),i,t,function(e,t){return e?r(e):void("delete"===n?r(null,[t.result._id]):r(null,t.result.ids))}):this.kuzzle.query(this.buildQueryArgs("write",n),i,t)},n.prototype.fetchDocument=function(e,t,r){var n={_id:e},o=this;return r||"function"!=typeof t||(r=t,t=null),o.kuzzle.callbackRequired("KuzzleDataCollection.fetch",r),n=o.kuzzle.addHeaders(n,this.headers),o.kuzzle.query(this.buildQueryArgs("read","get"),n,t,function(e,t){var n;return e?r(e):(n=new i(o,t.result._id,t.result._source),n.version=t.result._version,void r(null,n))}),this},n.prototype.fetchAllDocuments=function(e,t){var r={};return t||"function"!=typeof e||(t=e,e=null),e&&(e.from&&(r.from=e.from),e.size&&(r.size=e.size)),this.kuzzle.callbackRequired("KuzzleDataCollection.fetchAll",t),this.advancedSearch(r,e,t),this},n.prototype.getMapping=function(e,t){var r;return t||"function"!=typeof e||(t=e,e=null),this.kuzzle.callbackRequired("KuzzleDataCollection.getMapping",t),r=new o(this),r.refresh(e,t),this},n.prototype.publishMessage=function(e,t,r){var n={};return e instanceof i?n=e.serialize():n.body=e,n=this.kuzzle.addHeaders(n,this.headers),this.kuzzle.query(this.buildQueryArgs("write","publish"),n,t,r),this},n.prototype.replaceDocument=function(e,t,r,n){var o=this,u={_id:e,body:t};return n||"function"!=typeof r||(n=r,r=null),u=o.kuzzle.addHeaders(u,this.headers),n?o.kuzzle.query(this.buildQueryArgs("write","createOrReplace"),u,r,function(e,t){var r;return e?n(e):(r=new i(o,t.result._id,t.result._source),r.version=t.result._version,void n(null,r))}):o.kuzzle.query(this.buildQueryArgs("write","createOrReplace"),u,r),this},n.prototype.subscribe=function(e,t,r){var n;return r||"function"!=typeof t||(r=t,t=null),this.kuzzle.callbackRequired("KuzzleDataCollection.subscribe",r),n=new u(this,t),n.renew(e,r)},n.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("admin","truncateCollection"),r,e,t),this},n.prototype.updateDocument=function(e,t,r,n){var o={_id:e,body:t},u=this;return n||"function"!=typeof r||(n=r,r=null),o=u.kuzzle.addHeaders(o,this.headers),n?u.kuzzle.query(this.buildQueryArgs("write","update"),o,r,function(e,t){var r;return e?n(e):(r=new i(u,t.result._id),void r.refresh(n))}):u.kuzzle.query(this.buildQueryArgs("write","update"),o,r),u},n.prototype.documentFactory=function(e,t){return new i(this,e,t)},n.prototype.roomFactory=function(e){return new u(this,e)},n.prototype.dataMappingFactory=function(e){return new o(this,e)},n.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=n},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,n){var i=["set","setHeaders"];return n&&i.indexOf(e)===-1}}):this}r.prototype.apply=function(e,t){var r=this,n=this.kuzzle.addHeaders({body:{properties:this.mapping}},this.headers);return t||"function"!=typeof e||(t=e,e=null),r.kuzzle.query(this.collection.buildQueryArgs("admin","updateMapping"),n,e,function(n){return n?!!t&&t(n):void r.refresh(e,t)}),this},r.prototype.refresh=function(e,t){var r=this,n=this.kuzzle.addHeaders({},this.headers);return t||"function"!=typeof e||(t=e,e=null),this.kuzzle.query(this.collection.buildQueryArgs("admin","getMapping"),n,e,function(e,n){return e?!!t&&t(e):n.result[r.collection.index]?n.result[r.collection.index].mappings[r.collection.collection]?(r.mapping=n.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,t,r){return Object.defineProperties(this,{collection:{value:e.collection,enumerable:!0},dataCollection:{value:e,enumerable:!0},kuzzle:{value:e.kuzzle,enumerable:!0},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}}),!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,n){var i=["delete","refresh","save"];return n&&i.indexOf(e)!==-1}}):this}r.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e._version=this.version,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("KuzzleDocument.delete: cannot delete a document without a document ID");t?this.kuzzle.query(this.dataCollection.buildQueryArgs("write","delete"),this.serialize(),e,function(e){return e?t(e):void t(null,r.id)}):this.kuzzle.query(this.dataCollection.buildQueryArgs("write","delete"),this.serialize(),e)},r.prototype.refresh=function(e,t){var n=this;if(t||"function"!=typeof e||(t=e,e=null),!n.id)throw new Error("KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided");this.kuzzle.callbackRequired("KuzzleDocument.refresh",t),n.kuzzle.query(n.dataCollection.buildQueryArgs("read","get"),{_id:n.id},e,function(e,i){var o;return e?t(e):(o=new r(n.dataCollection,n.id,i.result._source),o.version=i.result._version,void t(null,o))})},r.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.dataCollection.buildQueryArgs("write","createOrReplace"),r,e,function(e,r){return e?!!t&&t(e):(n.id=r.result._id,n.version=r.result._version,void(t&&t(null,n)))}),n},r.prototype.publish=function(e){var t=this.serialize();return this.kuzzle.query(this.dataCollection.buildQueryArgs("write","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("KuzzleDocument.subscribe",t),!this.id)throw new Error("KuzzleDocument.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){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,n){var i=["setHeaders"];return n&&i.indexOf(e)===-1}}):this}!function(){var e=["id","value"],t=["id","keys"],n={append:e,bgrewriteaof:[],bgsave:[],bitcount:["id","start","end"],bitop:["operation","destkey",t],bitpos:["id","bit",{__opts__:["start","end"]}],blpop:[t,"timeout"],brpoplpush:["source","destination"],dbsize:[],decrby:e,del:[t],discard:[],exec:[],exists:[t],expire:["id","seconds"],expireat:["id","timestamp"], -flushdb:[],getbit:["id","offset"],getrange:["id","start","end"],hdel:["id",["field","fields"]],hexists:["id","field"],hincrby:["id","field","value"],hmset:["id","values"],hset:["id","field","value"],info:["section"],keys:["pattern"],lastsave:[],lindex:["id","idx"],linsert:["id","position","pivot","value"],lpush:["id",["value","values"]],lrange:["id","start","stop"],lrem:["id","count","value"],lset:["id","idx","value"],ltrim:["id","start","stop"],mset:["values"],multi:[],object:["subcommand","args"],pexpire:["id","milliseconds"],pexpireat:["id","timestamp"],pfadd:["id",["element","elements"]],pfmerge:["destkey",["sourcekey","sourcekeys"]],ping:[],psetex:["id","milliseconds","value"],publish:["channel","message"],randomkey:[],rename:["id","newkey"],renamenx:["id","newkey"],restore:["id","ttl","content"],rpoplpush:["source","destination"],sadd:["id",["member","members"]],save:[],set:["id","value",{__opts__:["ex","px","nx","xx"]}],sdiffstore:["destination",t],setbit:["id","offset","value"],setex:["id","seconds","value"],setrange:["id","offset","value"],sinterstore:["destination",t],sismember:["id","member"],smove:["id","destination","member"],sort:["id",{__opts__:["by","offset","count","get","direction","alpha","store"]}],spop:["id","count"],srem:["id",["member","members"]],sunionstore:["destination",t],unwatch:[],wait:["numslaves","timeout"],zadd:["id",{__opts__:["nx","xx","ch","incr","score","member","members"]}],zcount:["id","min","max"],zincrby:["id","value","member"],zinterstore:["destination",t,{__opts__:["weight","weights","aggregate"]}],zlexcount:["id","min","max"],zrange:["id","start","stop",{__opts__:["withscores"]}],zrangebylex:["id","min","max",{__opts__:["offset","count"]}],zrangebyscore:["id","min","max",{__opts__:["withscores","offset","count"]}],zrem:["id","member"],zremrangebylex:["id","min","max"],zremrangebyscore:["id","min","max"],zrevrangebylex:["id","max","min",{__opts__:["offset","count"]}],zrevrangebyscore:["id","max","min",{__opts__:["withscores","offset","count"]}],zrevrank:["id","member"]};n.decr=n.get=n.dump=n.hgetall=n.hkeys=n.hlen=n.hstrlen=n.hvals=n.incr=n.llen=n.lpop=n.persist=n.pttl=n.rpop=n.scard=n.smembers=n.strlen=n.ttl=n.type=n.zcard=["id"],n.getset=n.lpushx=e,n.del=n.exists=n.mget=n.pfcount=n.sdiff=n.sinter=n.sunion=n.watch=[t],n.incrby=n.incrbyfloat=n.decrby,n.brpop=n.blpop,n.hget=n.hexists,n.hmget=n.hdel,n.hsetnx=n.hset,n.msetnx=n.mset,n.rpush=n.lpush,n.hincrbyfloat=n.hincrby,n.srandmember=n.spop,n.zrevrange=n.zrange,n.zscore=n.zrevrank,Object.keys(n).forEach(function(e){r.prototype[e]=function(){var t,r=Array.prototype.slice.call(arguments),i=null,o={controller:"ms",action:e},u={};return"function"==typeof r[r.length-1]&&(t=r.pop()),r.length&&"object"==typeof r[r.length-1]&&1===Object.keys(r[r.length-1]).length&&void 0!==r[r.length-1].queuable&&(i=r.pop()),n[e].forEach(function(e,t){void 0!==r[t]&&(Array.isArray(e)&&(e=Array.isArray(r[t])?e[1]:e[0]),"id"===e?u._id=r[t]:(u.body||(u.body={}),"object"==typeof e&&void 0!==e.__opts__?e.__opts__.forEach(function(e){void 0!==r[t][e]&&(u.body[e]=r[t][e])}):u.body[e]=r[t]))}),this.kuzzle.query(o,u,i,t),this}})}(),e.exports=r},function(e,t,r){function n(e,t){return Object.defineProperties(this,{callback:{value:null,writable:!0},channel:{value:null,writable:!0},id:{value:s.v4()},lastRenewal:{value:null,writable:!0},notifier:{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},metadata:{value:t&&t.metadata?t.metadata:{},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,n){var i=["count"];return n&&i.indexOf(e)!==-1}}):this}function i(e){return e.error?this.callback(e.error):"jwtTokenExpired"===e.action?(this.kuzzle.jwtToken=void 0,this.kuzzle.emitEvent("jwtTokenExpired")):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 u(){return"connected"===this.kuzzle.state&&!this.subscribing}var s=r(3);n.prototype.count=function(e){var t;if(this.kuzzle.callbackRequired("KuzzleRoom.count",e),t=this.kuzzle.addHeaders({body:{roomId:this.roomId}},this.headers),!u.call(this))return this.queue.push({action:"count",args:[e]}),this;if(!this.roomId)throw new Error("KuzzleRoom.count: cannot count subscriptions on an inactive room");return this.kuzzle.query(this.collection.buildQueryArgs("subscribe","count"),t,function(t,r){return t?e(t):void e(null,r.result.count)}),this},n.prototype.renew=function(e,t){var r=Date.now(),n={scope:this.scope,state:this.state,users:this.users},u=this;return!t&&e&&"function"==typeof e&&(t=e,e=null),u.kuzzle.callbackRequired("KuzzleRoom.renew",t),u.lastRenewal&&r-u.lastRenewal<=u.renewalDelay?u:(e&&(u.filters=e),"connected"!==u.kuzzle.state?(u.callback=t,u.kuzzle.subscriptions.pending[u.id]=u,u):u.subscribing?(u.queue.push({action:"renew",args:[e,t]}),u):(u.unsubscribe(),u.roomId=null,u.subscribing=!0,u.callback=t,u.kuzzle.subscriptions.pending[u.id]=u,n.body=u.filters,n=u.kuzzle.addHeaders(n,this.headers),u.kuzzle.query(u.collection.buildQueryArgs("subscribe","on"),n,{metadata:u.metadata},function(e,t){if(delete u.kuzzle.subscriptions.pending[u.id],u.subscribing=!1,e)throw u.queue=[],new Error("Error during Kuzzle subscription: "+e.message);u.lastRenewal=r,u.roomId=t.result.roomId,u.channel=t.result.channel,u.kuzzle.subscriptions[u.roomId]||(u.kuzzle.subscriptions[u.roomId]={}),u.kuzzle.subscriptions[u.roomId][u.id]=u,u.notifier=i.bind(u),u.kuzzle.network.on(u.channel,u.notifier),o.call(u)}),u))},n.prototype.unsubscribe=function(){var e,t=this,r=t.roomId;return u.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("subscribe","off"),{body:{roomId:r}}):e=setInterval(function(){0===Object.keys(t.kuzzle.subscriptions.pending).length&&(t.kuzzle.subscriptions[r]||t.kuzzle.query(t.collection.buildQueryArgs("subscribe","off"),{body:{roomId:r}}),clearInterval(e))},100)):delete t.kuzzle.subscriptions[r][t.id],t.roomId=null),t):(t.queue.push({action:"unsubscribe",args:[]}),t)},n.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=n},function(e,t,r){function n(e,t,n){if("undefined"!=typeof window){if("undefined"!=typeof WebSocket)return new(r(11))(e,t);if(window.io)return new(r(10))(e,n);throw new Error("Aborting: no websocket support detected and no socket.io library loaded either.")}return new(r(!function(){var e=new Error('Cannot find module "./wrappers/wsnode"');throw e.code="MODULE_NOT_FOUND",e}()))(e,t)}e.exports=n},function(e,t){function r(e,t){this.host=e,this.port=t,this.socket=null,this.connect=function(e,t){this.socket=window.io("http://"+this.host+":"+this.port,{reconnection:e,reconnectionDelay:t,forceNew:!0})},this.onConnect=function(e){this.socket.on("connect",e)},this.onConnectError=function(e){this.socket.on("connect_error",e)},this.onDisconnect=function(e){this.socket.on("disconnect",e)},this.onReconnect=function(e){this.socket.on("reconnect",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.socket.close(),this.socket=null}}e.exports=r},function(e,t){function r(e,t){var r=this;this.host=e,this.port=t,this.client=null,this.retrying=!1,this.listeners={error:[],connect:[],disconnect:[],reconnect:[]},this.connect=function(e,t){this.client=new WebSocket("ws://"+this.host+":"+this.port),this.client.onopen=function(){r.retrying?n(r.listeners,"reconnect"):n(r.listeners,"connect")},this.client.onclose=function(){n(r.listeners,"disconnect")},this.client.onerror=function(){e&&(r.retrying=!0,setTimeout(function(){r.connect(e,t)},t)),n(r.listeners,"error")},this.client.onmessage=function(e){var t=JSON.parse(e.data);t.room&&r.listeners[t.room]&&n(r.listeners,t.room,t)}},this.onConnect=function(e){this.listeners.connect.push({fn:e,keep:!0})},this.onConnectError=function(e){this.listeners.error.push({fn:e,keep:!0})},this.onDisconnect=function(e){this.listeners.disconnect.push({fn:e,keep:!0})},this.onReconnect=function(e){this.listeners.reconnect.push({fn:e,keep:!0})},this.once=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,keep:!1})},this.on=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,keep:!0})},this.off=function(e,t){var r;this.listeners[e]&&(r=this.listeners[e].findIndex(function(e){return e.fn===t}),r!==-1&&(1===this.listeners[e].length&&["error","connect","disconnect","reconnect"].indexOf(e)===-1?delete this.listeners[e]:this.listeners[e].splice(r,1)))},this.send=function(e){this.client&&this.client.readyState===this.client.OPEN&&this.client.send(JSON.stringify(e))},this.close=function(){this.listeners={error:[],connect:[],disconnect:[],reconnect:[]},this.retrying=!1,this.client.close(),this.client=null}}function n(e,t,r){var n,i=e[t].length;for(n=0;n1?(e[t].splice(n,1),--n,--i):delete e[t])}e.exports=r},function(e,t,r){function n(e,t,r){if(i.call(this,e,t,r),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(1);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.kuzzleSecurity.buildQueryArgs("createOrReplaceProfile"),r,e,function(e){return e?!!t&&t(e):void(t&&t(null,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},n.prototype.getPolicies=function(){return this.content.policies},e.exports=n},function(e,t,r){function n(e,t,r){if(i.call(this,e,t,r),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(1);n.prototype=Object.create(i.prototype,{constructor:{value:n}}),n.prototype.save=function(e,t){var r=this.serialize(),n=this;e&&void 0===t&&"function"==typeof e&&(t=e,e=null),n.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createOrReplaceRole"),r,e,function(e){return e?!!t&&t(e):void(t&&t(null,n))})},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=["roleFactory","profileFactory","userFactory","isActionAllowed"];return n&&i.indexOf(e)===-1}}):this}var i=r(13),o=r(12),u=r(2);n.prototype.getRole=function(e,t,r){var n,o=this;if(!e)throw new Error("Id parameter is mandatory for getRole function");r||"function"!=typeof t||(r=t,t=null),n={_id:e},o.kuzzle.callbackRequired("KuzzleSecurity.getRole",r),o.kuzzle.query(this.buildQueryArgs("getRole"),n,t,function(e,t){return e?r(e):void r(null,new i(o,t.result._id,t.result._source))})},n.prototype.searchRoles=function(e,t,r){var n=this;r||"function"!=typeof t||(r=t,t=null),n.kuzzle.callbackRequired("KuzzleSecurity.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)}),void r(null,{total:t.result.total,roles:o}))})},n.prototype.createRole=function(e,t,r,n){var o=this,u={},s="createRole";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.createRole: cannot create a role without a role ID");n||"function"!=typeof r||(n=r,r=null),u._id=e,u.body=t,r&&(s=r.replaceIfExist?"createOrReplaceRole":"createRole"),n?o.kuzzle.query(this.buildQueryArgs(s),u,r,function(e,t){var r;return e?n(e):(r=new i(o,t.result._id,t.result._source),void n(null,r))}):o.kuzzle.query(this.buildQueryArgs(s),u)},n.prototype.updateRole=function(e,t,r,n){var o=this,u={},s="updateRole";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.updateRole: cannot update a role without a role ID");n||"function"!=typeof r||(n=r,r=null),u._id=e,u.body=t,n?o.kuzzle.query(this.buildQueryArgs(s),u,r,function(r){return r?n(r):void n(null,new i(o,e,t))}):o.kuzzle.query(this.buildQueryArgs(s),u)},n.prototype.deleteRole=function(e,t,r){var n={_id:e};r||"function"!=typeof t||(r=t,t=null),r?this.kuzzle.query(this.buildQueryArgs("deleteRole"),n,t,function(e,t){return e?r(e):void r(null,t.result._id)}):this.kuzzle.query(this.buildQueryArgs("deleteRole"),n,t)},n.prototype.roleFactory=function(e,t){return new i(this,e,t)},n.prototype.getProfile=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 getProfile function");n={_id:e},i.kuzzle.callbackRequired("KuzzleSecurity.getProfile",r),i.kuzzle.query(this.buildQueryArgs("getProfile"),n,t,function(e,t){return e?r(e):void r(null,new o(i,t.result._id,t.result._source))})},n.prototype.searchProfiles=function(e,t,r){var n=this;r||"function"!=typeof t||(r=t,t=null),n.kuzzle.callbackRequired("KuzzleSecurity.searchProfiles",r),n.kuzzle.query(this.buildQueryArgs("searchProfiles"),{body:e},t,function(e,t){var i;return e?r(e):(i=t.result.hits.map(function(e){return new o(n,e._id,e._source)}),void r(null,{total:t.result.total,profiles:i}))})},n.prototype.createProfile=function(e,t,r,n){var i=this,u={},s="createProfile";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.createProfile: cannot create a profile without a profile ID");n||"function"!=typeof r||(n=r,r=null),u._id=e,u.body=t,r&&(s=r.replaceIfExist?"createOrReplaceProfile":"createProfile"),n?i.kuzzle.query(this.buildQueryArgs(s),u,r,function(e,t){var r;return e?n(e):(r=new o(i,t.result._id,t.result._source),void n(null,r))}):i.kuzzle.query(this.buildQueryArgs(s),u)},n.prototype.updateProfile=function(e,t,r,n){var i=this,u={},s="updateProfile";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.updateProfile: cannot update a profile without a profile ID");n||"function"!=typeof r||(n=r,r=null),u._id=e,u.body=t,n?i.kuzzle.query(this.buildQueryArgs(s),u,r,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)))}):i.kuzzle.query(this.buildQueryArgs(s),u)},n.prototype.deleteProfile=function(e,t,r){var n={_id:e};r||"function"!=typeof t||(r=t,t=null),r?this.kuzzle.query(this.buildQueryArgs("deleteProfile"),n,t,function(e,t){return e?r(e):void r(null,t.result._id)}):this.kuzzle.query(this.buildQueryArgs("deleteProfile"),n,t)},n.prototype.profileFactory=function(e,t){return new o(this,e,t)},n.prototype.getUser=function(e,t,r){var n,i=this;if(!e||"string"!=typeof e)throw new Error("Id parameter is mandatory for getUser function");r||"function"!=typeof t||(r=t,t=null),n={_id:e},i.kuzzle.callbackRequired("KuzzleSecurity.getUser",r),i.kuzzle.query(this.buildQueryArgs("getUser"),n,t,function(e,t){return e?r(e):void r(null,new u(i,t.result._id,t.result._source))})},n.prototype.searchUsers=function(e,t,r){var n=this;r||"function"!=typeof t||(r=t,t=null),n.kuzzle.callbackRequired("KuzzleSecurity.searchUsers",r),n.kuzzle.query(this.buildQueryArgs("searchUsers"),{body:e},t,function(e,t){var i;return e?r(e):(i=t.result.hits.map(function(e){return new u(n,e._id,e._source)}),void r(null,{total:t.result.total,users:i}))})},n.prototype.createUser=function(e,t,r,n){var i=this,o={},s="createUser";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.createUser: cannot create a user without a user ID");n||"function"!=typeof r||(n=r,r=null),o._id=e,o.body=t,r&&(s=r.replaceIfExist?"createOrReplaceUser":"createUser"),n?i.kuzzle.query(this.buildQueryArgs(s),o,null,function(e,t){var r;return e?n(e):(r=new u(i,t.result._id,t.result._source),void n(null,r))}):i.kuzzle.query(this.buildQueryArgs(s),o)},n.prototype.updateUser=function(e,t,r,n){var i=this,o={},s="updateUser";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.updateUser: cannot update an user without an user ID");n||"function"!=typeof r||(n=r,r=null),o._id=e,o.body=t,n?i.kuzzle.query(this.buildQueryArgs(s),o,r,function(e,t){return e?n(e):void n(null,new u(i,t.result._id,t.result._source))}):i.kuzzle.query(this.buildQueryArgs(s),o,r)},n.prototype.deleteUser=function(e,t,r){var n={_id:e};r||"function"!=typeof t||(r=t,t=null),r?this.kuzzle.query(this.buildQueryArgs("deleteUser"),n,t,function(e,t){return e?r(e):void r(null,t.result._id)}):this.kuzzle.query(this.buildQueryArgs("deleteUser"),n,t)},n.prototype.userFactory=function(e,t){return new u(this,e,t)},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,function(e,t){return e?r(e):void r(null,t.result.hits)})},e.exports=n}])}); +!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var r in n)("object"==typeof exports?exports:e)[r]=n[r]}}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return e[r].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){function r(){var e=this,t=Date.now(),n=-1;e.queueTTL>0&&(e.offlineQueue.forEach(function(r,i){r.ts0&&e.offlineQueue.length>e.queueMaxSize&&e.offlineQueue.splice(0,e.offlineQueue.length-e.queueMaxSize).forEach(function(t){e.emitEvent("offlineQueuePop",t.query)})}function i(e){var t=Date.now();Object.keys(e).forEach(function(n){e[n]0?(o.call(t,t.offlineQueue[0].query,t.offlineQueue[0].cb),t.emitEvent("offlineQueuePop",t.offlineQueue.shift()),setTimeout(function(){r()},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!n.hasOwnProperty(e.query.requestId)&&(n[e.query.requestId]=!0)})}r()}function s(){var e=this;Object.keys(e.subscriptions).forEach(function(t){Object.keys(e.subscriptions[t]).forEach(function(n){var r=e.subscriptions[t][n];r.renew(r.callback)})})}var l=n(3),c=n(4),a=n(14),f=n(7),d=n(2),h=n(9);e.exports=Kuzzle=function(e,t,n){var r=this;if(!(this instanceof Kuzzle))return new Kuzzle(e,t,n);if(n||"function"!=typeof t||(n=t,t=null),!e||""===e)throw new Error("host argument missing");return Object.defineProperties(this,{collections:{value:{},writable:!0},connectCB:{value:n},eventListeners:{value:{connected:{lastEmitted:null,listeners:[]},error:{lastEmitted:null,listeners:[]},disconnected:{lastEmitted:null,listeners:[]},reconnected:{lastEmitted:null,listeners:[]},jwtTokenExpired:{lastEmitted:null,listeners:[]},loginAttempt:{lastEmitted:null,listeners:[]},offlineQueuePush:{listeners:[]},offlineQueuePop:{listeners:[]}}},eventTimeout:{value:200},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,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,enumerable:!0},host:{value:e,enumerable:!0},wsPort:{value:t&&"number"==typeof t.wsPort?t.wsPort:7513,enumerable:!0},ioPort:{value:t&&"number"==typeof t.ioPort?t.ioPort:7512,enumerable:!0},sslConnection:{value:!(!t||"boolean"!=typeof t.sslConnection)&&t.sslConnection,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},metadata:{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:null,enumerable:!0,writable:!0}}),t&&(Object.keys(t).forEach(function(e){r.hasOwnProperty(e)&&Object.getOwnPropertyDescriptor(r,e).writable&&(r[e]=t[e])}),"auto"===t.offlineMode&&this.autoReconnect&&(this.autoQueue=this.autoReplay=this.autoResubscribe=!0)),Object.defineProperty(this,"isValid",{value:function(){if("disconnected"===r.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(n){e[n]||(e[n]=t[n])}),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 a(this),enumerable:!0}),Object.defineProperty(this,"emitEvent",{value:function(e){var t=Date.now(),n=Array.prototype.slice.call(arguments,1),r=this.eventListeners[e];return!(r.lastEmitted&&r.lastEmitted>=t-this.eventTimeout)&&(r.listeners.forEach(function(e){process.nextTick(function(){e.fn.apply(void 0,n)})}),void(void 0!==r.lastEmitted&&(r.lastEmitted=t)))}}),Object.defineProperty(this,"memoryStorage",{value:new f(this),enumerable:!0}),t&&t.connect&&"auto"!==t.connect?this.state="ready":this.connect(),i(this.requestHistory),this.bluebird?this.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["getAllStatistics","getServerInfo","getStatistics","listCollections","listIndexes","login","logout","now","query","checkToken","whoAmI","updateSelf","getMyRights","refreshIndex","getAutoRefresh","setAutoRefresh"];return r&&i.indexOf(e)!==-1}}):void 0},Kuzzle.prototype.connect=function(){var e=this;return e.network||(e.network=h(e.host,e.wsPort,e.ioPort,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",s.call(e),u.call(e),e.emitEvent("connected"),e.connectCB&&e.connectCB(null,e)}),e.network.onConnectError(function(t){var n=new Error('Unable to connect to kuzzle server at "'+e.host+'"');n.internal=t,e.state="error",e.emitEvent("error",n),e.connectCB&&e.connectCB(n)}),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&&s.call(e),e.autoReplay&&(r.call(e),u.call(e)),e.emitEvent("reconnected")};e.state="connected",e.jwtToken?e.checkToken(e.jwtToken,function(n,r){!n&&r.valid||(e.jwtToken=void 0,e.emitEvent("jwtTokenExpired")),t()}):t()}),this)},Kuzzle.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 s.call(this),this.emitEvent("loginAttempt",{success:!0}),this},Kuzzle.prototype.getJwtToken=function(){return this.jwtToken},Kuzzle.prototype.login=function(e){var t,n=this,r={strategy:e},i=null;arguments[1]&&("object"==typeof arguments[1]?t=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]),"object"==typeof t&&Object.keys(t).forEach(function(e){r[e]=t[e]}),this.query({controller:"auth",action:"login"},{body:r},{queuable:!1},i&&function(e,t){e?(i(e),n.emitEvent("loginAttempt",{success:!1,error:e.message})):(t.result.jwt&&n.setJwtToken(t.result.jwt),i(null,t.result))})},Kuzzle.prototype.logout=function(e){var t=this,n={action:"logout",controller:"auth",requestId:l.v4(),body:{}};return this.query({controller:"auth",action:"logout"},n,{queuable:!1},"function"!=typeof e?null:function(n){null===n?(t.jwtToken=void 0,e(null,t)):e(n)}),t},Kuzzle.prototype.checkToken=function(e,t){var n={body:{token:e}};this.callbackRequired("Kuzzle.checkToken",t),this.query({controller:"auth",action:"checkToken"},n,{queuable:!1},function(e,n){return e?t(e):void t(null,n.result)})},Kuzzle.prototype.whoAmI=function(e){var t=this;t.callbackRequired("Kuzzle.whoAmI",e),t.query({controller:"auth",action:"getCurrentUser"},{},{},function(n,r){return n?e(n):void e(null,new d(t.security,r.result._id,r.result._source))})},Kuzzle.prototype.getMyRights=function(e,t){var n=this;t||"function"!=typeof e||(t=e,e=null),n.callbackRequired("Kuzzle.getMyRights",t),n.query({controller:"auth",action:"getMyRights"},{},null,function(e,n){return e?t(e):void t(null,n.result.hits)})},Kuzzle.prototype.updateSelf=function(e,t,n){var r=this,i={},o={controller:"auth",action:"updateSelf"};return n||"function"!=typeof t||(n=t,t=null),i.body=e,r.query(o,i,t,n&&function(e,t){n(e,!e&&t.result)}),this},Kuzzle.prototype.addListener=function(e,t){var n,r=Object.keys(this.eventListeners),i=typeof t;if(this.isValid(),r.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+r.toString());if("function"!==i)throw new Error("Invalid listener type: expected a function, got a "+i);return n=l.v4(),this.eventListeners[e].listeners.push({id:n,fn:t}),n},Kuzzle.prototype.getAllStatistics=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.getAllStatistics",t),this.query({controller:"admin",action:"getAllStats"},{},e,function(e,n){return e?t(e):void t(null,n.result.hits)})},Kuzzle.prototype.getStatistics=function(e,t,n){var r,i;n||(1===arguments.length?(n=arguments[0],t=null,e=null):(n=arguments[1],"object"==typeof arguments[0]?(t=arguments[0],e=null):(e=arguments[0],t=null))),r=function(t,r){return t?n(t):void(e?n(null,r.result.hits):n(null,[r.result]))},this.callbackRequired("Kuzzle.getStatistics",n),i=e?{body:{startTime:e}}:{},this.query({controller:"admin",action:"getLastStats"},i,t,r)},Kuzzle.prototype.dataCollectionFactory=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 c(this,t,e)),this.collections[t][e]},Kuzzle.prototype.flushQueue=function(){return this.offlineQueue=[],this},Kuzzle.prototype.listCollections=function(){var e,t,n,r="all",i=Array.prototype.slice.call(arguments);if(i.forEach(function(r){switch(typeof r){case"string":e=r;break;case"object":t=r;break;case"function":n=r}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.listCollections: index required");e=this.defaultIndex}this.callbackRequired("Kuzzle.listCollections",n),t&&t.type&&(r=t.type),this.query({index:e,controller:"read",action:"listCollections"},{body:{type:r}},t,function(e,t){return e?n(e):void n(null,t.result.collections)})},Kuzzle.prototype.listIndexes=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.listIndexes",t),this.query({controller:"read",action:"listIndexes"},{},e,function(e,n){return e?t(e):void t(null,n.result.indexes)})},Kuzzle.prototype.disconnect=function(){var e;this.logout(),this.state="disconnected",this.network.close();for(e in this.collections)this.collections.hasOwnProperty(e)&&delete this.collections[e]},Kuzzle.prototype.getServerInfo=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.getServerInfo",t),this.query({controller:"read",action:"serverInfo"},{},e,function(e,n){return e?t(e):void t(null,n.result.serverInfo)})},Kuzzle.prototype.refreshIndex=function(){var e,t,n;if(Array.prototype.slice.call(arguments).forEach(function(r){switch(typeof r){case"string":e=r;break;case"object":t=r;break;case"function":n=r}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.refreshIndex: index required");e=this.defaultIndex}return this.query({index:e,controller:"admin",action:"refreshIndex"},{},t,n),this},Kuzzle.prototype.getAutoRefresh=function(){var e,t,n;if(Array.prototype.slice.call(arguments).forEach(function(r){switch(typeof r){case"string":e=r;break;case"object":t=r;break;case"function":n=r}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.getAutoRefresh: index required");e=this.defaultIndex}this.callbackRequired("Kuzzle.getAutoRefresh",n),this.query({index:e,controller:"admin",action:"getAutoRefresh"},{},t,n)},Kuzzle.prototype.setAutoRefresh=function(){var e,t,n,r;if(Array.prototype.slice.call(arguments).forEach(function(i){switch(typeof i){case"string":e=i;break;case"boolean":t=i;break;case"object":n=i;break;case"function":r=i}}),!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:"admin",action:"setAutoRefresh"},{body:{autoRefresh:t}},n,r),this},Kuzzle.prototype.now=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.now",t),this.query({controller:"read",action:"now"},{},e,function(e,n){t(e,n&&n.result.now)})},Kuzzle.prototype.query=function(e,t,n,i){var u,s={action:e.action,controller:e.controller,metadata:this.metadata},c=this;if(this.isValid(),i||"function"!=typeof n||(i=n,n=null),n&&(n.metadata&&Object.keys(n.metadata).forEach(function(e){s.metadata[e]=n.metadata[e]}),n.queuable===!1&&"offline"===c.state))return c;if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("Invalid query parameter: "+t);t.metadata&&Object.keys(t.metadata).forEach(function(e){s.metadata[e]=t.metadata[e]});for(u in t)"metadata"!==u&&t.hasOwnProperty(u)&&(s[u]=t[u]);return s=c.addHeaders(s,this.headers),void 0===c.jwtToken||"auth"===s.controller&&"checkToken"===s.action||(s.headers=s.headers||{},s.headers.authorization="Bearer "+c.jwtToken),e.collection&&(s.collection=e.collection),e.index&&(s.index=e.index),s.requestId||(s.requestId=l.v4()),"connected"===c.state||n&&n.queuable===!1?"connected"===c.state?o.call(this,s,i):i&&i(new Error("Unable to execute request: not connected to a Kuzzle server.\nDiscarded request: "+JSON.stringify(s))):(c.queuing||["initializing","connecting"].indexOf(c.state)!==-1)&&(r.call(this,s,i),c.queueFilter&&!c.queueFilter(s)||(c.offlineQueue.push({ts:Date.now(),query:s,cb:i}),c.emitEvent("offlineQueuePush",{query:s,cb:i}))),c},Kuzzle.prototype.removeAllListeners=function(e){var t=Object.keys(this.eventListeners),n=this;if(e){if(t.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+t.toString());this.eventListeners[e].listeners=[]}else t.forEach(function(e){n.eventListeners[e].listeners=[]});return this},Kuzzle.prototype.removeListener=function(e,t){var n=Object.keys(this.eventListeners),r=this;if(n.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+n.toString());return this.eventListeners[e].listeners.forEach(function(n,i){n.id===t&&r.eventListeners[e].listeners.splice(i,1)}),this},Kuzzle.prototype.replayQueue=function(){return"offline"===this.state||this.autoReplay||(r.call(this),u.call(this)),this},Kuzzle.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},Kuzzle.prototype.setHeaders=function(e,t){var n=this;if("object"!=typeof e||Array.isArray(e))throw new Error("Expected a content object, received a "+typeof e);return t?n.headers=e:Object.keys(e).forEach(function(t){n.headers[t]=e[t]}),n},Kuzzle.prototype.startQueuing=function(){return"offline"!==this.state||this.autoQueue||(this.queuing=!0),this},Kuzzle.prototype.stopQueuing=function(){return"offline"!==this.state||this.autoQueue||(this.queuing=!1),this}},function(e,t){function n(e,t,n){if(!t)throw new Error("A security document must have an id");if(Object.defineProperties(this,{kuzzle:{value:e.kuzzle},kuzzleSecurity:{value:e},id:{value:t,enumerable:!0},content:{value:{},writable:!0,enumerable:!0}}),n&&this.setContent(n,!0),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["delete","update"];return r&&i.indexOf(e)!==-1}})}n.prototype.setContent=function(e){return this.content=e,this},n.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e},n.prototype["delete"]=function(e,t){var n=this;e&&void 0===t&&"function"==typeof e&&(t=e,e=null),n.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.deleteActionName),{_id:this.id},e,function(e,n){return e?!!t&&t(e):void(t&&t(null,n.result._id))})},n.prototype.update=function(e,t,n){var r={},i=this;if("object"!=typeof e)throw new Error('Parameter "content" must be a object');return t&&void 0===n&&"function"==typeof t&&(n=t,t=null),r._id=i.id,r.body=e,i.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.updateActionName),r,t,function(e,t){return e?!!n&&n(e):(i.setContent(t.result._source),void(n&&n(null,i)))}),this},e.exports=n},function(e,t,n){function r(e,t,n){if(i.call(this,e,t,n),Object.defineProperties(this,{deleteActionName:{value:"deleteUser"},updateActionName:{value:"updateUser"}}),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["save"];return r&&i.indexOf(e)!==-1}})}var i=n(1);r.prototype=Object.create(i.prototype,{constructor:{value:r}}),r.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},r.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},r.prototype.save=function(e,t){var n=this.serialize(),r=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createOrReplaceUser"),n,e,t&&function(e){t(e,!e&&r)}),r},r.prototype.serialize=function(){return{_id:this.id,body:this.content}},r.prototype.getProfiles=function(){return this.content.profileIds},e.exports=r},function(e,t){!function(t){"use strict";function n(){var e=t.crypto||t.msCrypto;if(!l&&e&&e.getRandomValues)try{var n=new Uint8Array(16);f=l=function(){return e.getRandomValues(n),n},l()}catch(r){}if(!l){var i=new Array(16);c=l=function(){for(var e,t=0;t<16;t++)0===(3&t)&&(e=4294967296*Math.random()),i[t]=e>>>((3&t)<<3)&255;return i},"undefined"!=typeof console&&console.warn&&console.warn("[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()")}}function r(){if("function"==typeof require)try{var e=require("crypto").randomBytes;a=l=e&&function(){return e(16)},l()}catch(t){}}function i(e,t,n){var r=t&&n||0,i=0;for(t=t||[],e.toLowerCase().replace(/[0-9a-f]{2}/g,function(e){i<16&&(t[r+i++]=y[e])});i<16;)t[r+i++]=0;return t}function o(e,t){var n=t||0,r=p;return r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]}function u(e,t,n){var r=t&&n||0,i=t||[];e=e||{};var u=null!=e.clockseq?e.clockseq:m,s=null!=e.msecs?e.msecs:(new Date).getTime(),l=null!=e.nsecs?e.nsecs:k+1,c=s-w+(l-k)/1e4;if(c<0&&null==e.clockseq&&(u=u+1&16383),(c<0||s>w)&&null==e.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");w=s,k=l,m=u,s+=122192928e5;var a=(1e4*(268435455&s)+l)%4294967296;i[r++]=a>>>24&255,i[r++]=a>>>16&255,i[r++]=a>>>8&255,i[r++]=255&a;var f=s/4294967296*1e4&268435455;i[r++]=f>>>8&255,i[r++]=255&f,i[r++]=f>>>24&15|16,i[r++]=f>>>16&255,i[r++]=u>>>8|128,i[r++]=255&u;for(var d=e.node||v,h=0;h<6;h++)i[r+h]=d[h];return t?t:o(i)}function s(e,t,n){var r=t&&n||0;"string"==typeof e&&(t="binary"===e?new h(16):null,e=null),e=e||{};var i=e.random||(e.rng||l)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t)for(var u=0;u<16;u++)t[r+u]=i[u];return t||o(i)}var l,c,a,f,d;t?n():r();for(var h="function"==typeof Buffer?Buffer:Array,p=[],y={},b=0;b<256;b++)p[b]=(b+256).toString(16).substr(1),y[p[b]]=b;var z=l(),v=[1|z[0],z[1],z[2],z[3],z[4],z[5]],m=16383&(z[6]<<8|z[7]),w=0,k=0,g=s;g.v1=u,g.v4=s,g.parse=i,g.unparse=o,g.BufferClass=h,g._rng=l,g._mathRNG=c,g._nodeRNG=a,g._whatwgRNG=f,"undefined"!=typeof e&&e.exports?e.exports=g:"function"==typeof define&&define.amd?define(function(){return g}):(d=t.uuid,g.noConflict=function(){return t.uuid=d,g},t.uuid=g)}("undefined"!=typeof window?window:null)},function(e,t,n){function r(e,t,n){if(!t||!n)throw new Error("The KuzzleDataCollection object constructor needs an index and a collection arguments");return Object.defineProperties(this,{collection:{value:n,enumerable:!0},index:{value:t,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,n,r){var i=["publishMessage","setHeaders","subscribe"];return r&&i.indexOf(e)===-1}}):this}var i=n(6),o=n(5),u=n(8);r.prototype.advancedSearch=function(e,t,n){var r,o=this;n||"function"!=typeof t||(n=t,t=null),o.kuzzle.callbackRequired("KuzzleDataCollection.advancedSearch",n),r=o.kuzzle.addHeaders({body:e},this.headers),o.kuzzle.query(this.buildQueryArgs("read","search"),r,t,function(e,t){var r=[];return e?n(e):(t.result.hits.forEach(function(e){var t=new i(o,e._id,e._source);t.version=e._version,r.push(t)}),void n(null,{total:t.result.total,documents:r}))})},r.prototype.count=function(e,t,n){var r;n||"function"!=typeof t||(n=t,t=null),this.kuzzle.callbackRequired("KuzzleDataCollection.count",n),r=this.kuzzle.addHeaders({body:e},this.headers),this.kuzzle.query(this.buildQueryArgs("read","count"),r,t,function(e,t){n(e,t&&t.result.count)})},r.prototype.create=function(e,t){var n={};return t||"function"!=typeof e||(t=e,e=null),n=this.kuzzle.addHeaders(n,this.headers),this.kuzzle.query(this.buildQueryArgs("write","createCollection"),n,e,t),this},r.prototype.createDocument=function(e,t,n,r){var o=this,u={},s="create";return e&&"string"!=typeof e&&(r=n,n=t,t=e,e=null),r||"function"!=typeof n||(r=n,n=null),t instanceof i?u=t.serialize():u.body=t,n&&(s=n.updateIfExist?"createOrReplace":"create"),e&&(u._id=e),u=o.kuzzle.addHeaders(u,o.headers),o.kuzzle.query(this.buildQueryArgs("write",s),u,n,r&&function(e,t){var n;return e?r(e):(n=new i(o,t.result._id,t.result._source),n.version=t.result._version,void r(null,n))}),this},r.prototype.deleteDocument=function(e,t,n){var r,i={};return"string"==typeof e?(i._id=e,r="delete"):(i.body=e,r="deleteByQuery"),n||"function"!=typeof t||(n=t,t=null),i=this.kuzzle.addHeaders(i,this.headers),this.kuzzle.query(this.buildQueryArgs("write",r),i,t,n&&function(e,t){n(e,!e&&("delete"===r?[t.result._id]:t.result.ids))}),this},r.prototype.fetchDocument=function(e,t,n){var r={_id:e},o=this;n||"function"!=typeof t||(n=t,t=null),o.kuzzle.callbackRequired("KuzzleDataCollection.fetch",n),r=o.kuzzle.addHeaders(r,this.headers),o.kuzzle.query(this.buildQueryArgs("read","get"),r,t,function(e,t){var r;return e?n(e):(r=new i(o,t.result._id,t.result._source),r.version=t.result._version,void n(null,r))})},r.prototype.fetchAllDocuments=function(e,t){var n={};t||"function"!=typeof e||(t=e,e=null),e&&(e.from&&(n.from=e.from),e.size&&(n.size=e.size)),this.kuzzle.callbackRequired("KuzzleDataCollection.fetchAll",t),this.advancedSearch(n,e,t)},r.prototype.getMapping=function(e,t){var n;t||"function"!=typeof e||(t=e,e=null),this.kuzzle.callbackRequired("KuzzleDataCollection.getMapping",t),n=new o(this),n.refresh(e,t)},r.prototype.publishMessage=function(e,t,n){var r={};return e instanceof i?r=e.serialize():r.body=e,r=this.kuzzle.addHeaders(r,this.headers),this.kuzzle.query(this.buildQueryArgs("write","publish"),r,t,n),this},r.prototype.replaceDocument=function(e,t,n,r){var o=this,u={_id:e,body:t};return r||"function"!=typeof n||(r=n,n=null),u=o.kuzzle.addHeaders(u,this.headers),o.kuzzle.query(this.buildQueryArgs("write","createOrReplace"),u,n,r&&function(e,t){var n;return e?r(e):(n=new i(o,t.result._id,t.result._source),n.version=t.result._version,void r(null,n))}),this},r.prototype.subscribe=function(e,t,n){var r;return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.callbackRequired("KuzzleDataCollection.subscribe",n),r=new u(this,t),r.renew(e,n)},r.prototype.truncate=function(e,t){var n={};return t||"function"!=typeof e||(t=e,e=null),n=this.kuzzle.addHeaders(n,this.headers),this.kuzzle.query(this.buildQueryArgs("admin","truncateCollection"),n,e,t),this},r.prototype.updateDocument=function(e,t,n,r){var o={_id:e,body:t},u=this;return r||"function"!=typeof n||(r=n,n=null),o=u.kuzzle.addHeaders(o,this.headers),u.kuzzle.query(this.buildQueryArgs("write","update"),o,n,r&&function(e,t){return e?r(e):void new i(u,t.result._id).refresh(r)}),u},r.prototype.documentFactory=function(e,t){return new i(this,e,t)},r.prototype.roomFactory=function(e){return new u(this,e)},r.prototype.dataMappingFactory=function(e){return new o(this,e)},r.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=r},function(e,t){function n(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,n,r){var i=["set","setHeaders"];return r&&i.indexOf(e)===-1}}):this}n.prototype.apply=function(e,t){var n=this,r=this.kuzzle.addHeaders({body:{properties:this.mapping}},this.headers);return t||"function"!=typeof e||(t=e,e=null),n.kuzzle.query(this.collection.buildQueryArgs("admin","updateMapping"),r,e,function(r){return r?t&&t(r):void n.refresh(e,t)}),this},n.prototype.refresh=function(e,t){var n=this,r=this.kuzzle.addHeaders({},this.headers);return t||"function"!=typeof e||(t=e,e=null),this.kuzzle.query(this.collection.buildQueryArgs("admin","getMapping"),r,e,function(e,r){return e?!!t&&t(e):r.result[n.collection.index]?r.result[n.collection.index].mappings[n.collection.collection]?(n.mapping=r.result[n.collection.index].mappings[n.collection.collection].properties,void 0===n.mapping&&(n.mapping={}),void(t&&t(null,n))):t&&t(new Error("No mapping found for collection "+n.collection.collection)):t&&t(new Error("No mapping found for index "+n.collection.index))}),this},n.prototype.set=function(e,t){return this.mapping[e]=t,this},n.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=n},function(e,t){function n(e,t,n){return Object.defineProperties(this,{collection:{value:e.collection,enumerable:!0},dataCollection:{value:e,enumerable:!0},kuzzle:{value:e.kuzzle,enumerable:!0},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}}),!n&&t&&"object"==typeof t&&(n=t,t=null),n&&(n._version&&(this.version=n._version,delete n._version),this.setContent(n,!0)),t&&Object.defineProperty(this,"id",{value:t,enumerable:!0}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["delete","refresh","save"];return r&&i.indexOf(e)!==-1}}):this}n.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e._version=this.version,e=this.kuzzle.addHeaders(e,this.headers)},n.prototype.toString=function(){return JSON.stringify(this.serialize())},n.prototype["delete"]=function(e,t){var n=this;if(t||"function"!=typeof e||(t=e,e=null),!n.id)throw new Error("KuzzleDocument.delete: cannot delete a document without a document ID");this.kuzzle.query(this.dataCollection.buildQueryArgs("write","delete"),this.serialize(),e,t&&function(e){t(e,!e&&n.id)})},n.prototype.refresh=function(e,t){var r=this;if(t||"function"!=typeof e||(t=e,e=null),!r.id)throw new Error("KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided");this.kuzzle.callbackRequired("KuzzleDocument.refresh",t),r.kuzzle.query(r.dataCollection.buildQueryArgs("read","get"),{_id:r.id},e,function(e,i){var o;return e?t(e):(o=new n(r.dataCollection,r.id,i.result._source),o.version=i.result._version,void t(null,o))})},n.prototype.save=function(e,t){var n=this.serialize(),r=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r.kuzzle.query(this.dataCollection.buildQueryArgs("write","createOrReplace"),n,e,function(e,n){return e?t&&t(e):(r.id=n.result._id,r.version=n.result._version,void(t&&t(null,r)))}),r},n.prototype.publish=function(e){var t=this.serialize();return this.kuzzle.query(this.dataCollection.buildQueryArgs("write","publish"),t,e),this},n.prototype.setContent=function(e,t){var n=this;return t?this.content=e:Object.keys(e).forEach(function(t){n.content[t]=e[t]}),this},n.prototype.subscribe=function(e,t){var n;if(e&&!t&&"function"==typeof e&&(t=e,e=null),this.kuzzle.callbackRequired("KuzzleDocument.subscribe",t),!this.id)throw new Error("KuzzleDocument.subscribe: cannot subscribe to a document if no ID has been provided");return n={ids:{values:[this.id]}},this.dataCollection.subscribe(n,e,t)},n.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=n},function(e,t){function n(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,n,r){var i=["setHeaders"];return r&&i.indexOf(e)===-1}}):this}!function(){var e=["id","value"],t=["id","keys"],r={append:e,bgrewriteaof:[],bgsave:[],bitcount:["id","start","end"],bitop:["operation","destkey",t],bitpos:["id","bit",{__opts__:["start","end"]}],blpop:[t,"timeout"],brpoplpush:["source","destination"],dbsize:[],decrby:e,del:[t],discard:[],exec:[],exists:[t],expire:["id","seconds"],expireat:["id","timestamp"],flushdb:[],getbit:["id","offset"],getrange:["id","start","end"],hdel:["id",["field","fields"]],hexists:["id","field"],hincrby:["id","field","value"],hmset:["id","values"],hset:["id","field","value"],info:["section"],keys:["pattern"],lastsave:[],lindex:["id","idx"],linsert:["id","position","pivot","value"],lpush:["id",["value","values"]],lrange:["id","start","stop"],lrem:["id","count","value"],lset:["id","idx","value"],ltrim:["id","start","stop"],mset:["values"],multi:[],object:["subcommand","args"],pexpire:["id","milliseconds"],pexpireat:["id","timestamp"],pfadd:["id",["element","elements"]],pfmerge:["destkey",["sourcekey","sourcekeys"]],ping:[],psetex:["id","milliseconds","value"], +publish:["channel","message"],randomkey:[],rename:["id","newkey"],renamenx:["id","newkey"],restore:["id","ttl","content"],rpoplpush:["source","destination"],sadd:["id",["member","members"]],save:[],set:["id","value",{__opts__:["ex","px","nx","xx"]}],sdiffstore:["destination",t],setbit:["id","offset","value"],setex:["id","seconds","value"],setrange:["id","offset","value"],sinterstore:["destination",t],sismember:["id","member"],smove:["id","destination","member"],sort:["id",{__opts__:["by","offset","count","get","direction","alpha","store"]}],spop:["id","count"],srem:["id",["member","members"]],sunionstore:["destination",t],unwatch:[],wait:["numslaves","timeout"],zadd:["id",{__opts__:["nx","xx","ch","incr","score","member","members"]}],zcount:["id","min","max"],zincrby:["id","value","member"],zinterstore:["destination",t,{__opts__:["weight","weights","aggregate"]}],zlexcount:["id","min","max"],zrange:["id","start","stop",{__opts__:["withscores"]}],zrangebylex:["id","min","max",{__opts__:["offset","count"]}],zrangebyscore:["id","min","max",{__opts__:["withscores","offset","count"]}],zrem:["id","member"],zremrangebylex:["id","min","max"],zremrangebyscore:["id","min","max"],zrevrangebylex:["id","max","min",{__opts__:["offset","count"]}],zrevrangebyscore:["id","max","min",{__opts__:["withscores","offset","count"]}],zrevrank:["id","member"]};r.decr=r.get=r.dump=r.hgetall=r.hkeys=r.hlen=r.hstrlen=r.hvals=r.incr=r.llen=r.lpop=r.persist=r.pttl=r.rpop=r.scard=r.smembers=r.strlen=r.ttl=r.type=r.zcard=["id"],r.getset=r.lpushx=e,r.del=r.exists=r.mget=r.pfcount=r.sdiff=r.sinter=r.sunion=r.watch=[t],r.incrby=r.incrbyfloat=r.decrby,r.brpop=r.blpop,r.hget=r.hexists,r.hmget=r.hdel,r.hsetnx=r.hset,r.msetnx=r.mset,r.rpush=r.lpush,r.hincrbyfloat=r.hincrby,r.srandmember=r.spop,r.zrevrange=r.zrange,r.zscore=r.zrevrank,Object.keys(r).forEach(function(e){n.prototype[e]=function(){var t,n=Array.prototype.slice.call(arguments),i=null,o={controller:"ms",action:e},u={};return"function"==typeof n[n.length-1]&&(t=n.pop()),n.length&&"object"==typeof n[n.length-1]&&1===Object.keys(n[n.length-1]).length&&void 0!==n[n.length-1].queuable&&(i=n.pop()),r[e].forEach(function(e,t){void 0!==n[t]&&(Array.isArray(e)&&(e=Array.isArray(n[t])?e[1]:e[0]),"id"===e?u._id=n[t]:(u.body||(u.body={}),"object"==typeof e&&void 0!==e.__opts__?e.__opts__.forEach(function(e){void 0!==n[t][e]&&(u.body[e]=n[t][e])}):u.body[e]=n[t]))}),this.kuzzle.query(o,u,i,t),this}})}(),e.exports=n},function(e,t,n){function r(e,t){return Object.defineProperties(this,{callback:{value:null,writable:!0},channel:{value:null,writable:!0},id:{value:s.v4()},lastRenewal:{value:null,writable:!0},notifier:{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},metadata:{value:t&&t.metadata?t.metadata:{},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,n,r){var i=["count"];return r&&i.indexOf(e)!==-1}}):this}function i(e){return e.error?this.callback(e.error):"jwtTokenExpired"===e.action?(this.kuzzle.jwtToken=void 0,this.kuzzle.emitEvent("jwtTokenExpired")):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 u(){return"connected"===this.kuzzle.state&&!this.subscribing}var s=n(3);r.prototype.count=function(e){var t;if(this.kuzzle.callbackRequired("KuzzleRoom.count",e),t=this.kuzzle.addHeaders({body:{roomId:this.roomId}},this.headers),!u.call(this))return void this.queue.push({action:"count",args:[e]});if(!this.roomId)throw new Error("KuzzleRoom.count: cannot count subscriptions on an inactive room");this.kuzzle.query(this.collection.buildQueryArgs("subscribe","count"),t,function(t,n){e(t,n&&n.result.count)})},r.prototype.renew=function(e,t){var n=Date.now(),r={scope:this.scope,state:this.state,users:this.users},u=this;if(!t&&e&&"function"==typeof e&&(t=e,e=null),u.kuzzle.callbackRequired("KuzzleRoom.renew",t),!(u.lastRenewal&&n-u.lastRenewal<=u.renewalDelay)){if(e&&(u.filters=e),"connected"!==u.kuzzle.state)return u.callback=t,void(u.kuzzle.subscriptions.pending[u.id]=u);if(u.subscribing)return void u.queue.push({action:"renew",args:[e,t]});u.unsubscribe(),u.roomId=null,u.subscribing=!0,u.callback=t,u.kuzzle.subscriptions.pending[u.id]=u,r.body=u.filters,r=u.kuzzle.addHeaders(r,this.headers),u.kuzzle.query(u.collection.buildQueryArgs("subscribe","on"),r,{metadata:u.metadata},function(e,t){if(delete u.kuzzle.subscriptions.pending[u.id],u.subscribing=!1,e)throw u.queue=[],new Error("Error during Kuzzle subscription: "+e.message);u.lastRenewal=n,u.roomId=t.result.roomId,u.channel=t.result.channel,u.kuzzle.subscriptions[u.roomId]||(u.kuzzle.subscriptions[u.roomId]={}),u.kuzzle.subscriptions[u.roomId][u.id]=u,u.notifier=i.bind(u),u.kuzzle.network.on(u.channel,u.notifier),o.call(u)})}},r.prototype.unsubscribe=function(){var e,t=this,n=t.roomId;return u.call(this)?(n&&(t.kuzzle.network.off(t.channel,this.notifier),1===Object.keys(t.kuzzle.subscriptions[n]).length?(delete t.kuzzle.subscriptions[n],0===Object.keys(t.kuzzle.subscriptions.pending).length?t.kuzzle.query(t.collection.buildQueryArgs("subscribe","off"),{body:{roomId:n}}):e=setInterval(function(){0===Object.keys(t.kuzzle.subscriptions.pending).length&&(t.kuzzle.subscriptions[n]||t.kuzzle.query(t.collection.buildQueryArgs("subscribe","off"),{body:{roomId:n}}),clearInterval(e))},100)):delete t.kuzzle.subscriptions[n][t.id],t.roomId=null),t):(t.queue.push({action:"unsubscribe",args:[]}),t)},r.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=r},function(e,t,n){function r(e,t,r,i){if("undefined"!=typeof window){if("undefined"!=typeof WebSocket)return new(n(11))(e,t,i);if(window.io)return new(n(10))(e,r,i);throw new Error("Aborting: no websocket support detected and no socket.io library loaded either.")}return new(n(!function(){var e=new Error('Cannot find module "./wrappers/wsnode"');throw e.code="MODULE_NOT_FOUND",e}()))(e,t,i)}e.exports=r},function(e,t){function n(e,t,n){this.host=e,this.port=t,this.ssl=n,this.socket=null,this.connect=function(e,t){this.socket=window.io((this.ssl?"https://":"http://")+this.host+":"+this.port,{reconnection:e,reconnectionDelay:t,forceNew:!0})},this.onConnect=function(e){this.socket.on("connect",e)},this.onConnectError=function(e){this.socket.on("connect_error",e)},this.onDisconnect=function(e){this.socket.on("disconnect",e)},this.onReconnect=function(e){this.socket.on("reconnect",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.socket.close(),this.socket=null}}e.exports=n},function(e,t){function n(e,t,n){var i=this;this.host=e,this.port=t,this.ssl=n,this.client=null,this.retrying=!1,this.listeners={error:[],connect:[],disconnect:[],reconnect:[]},this.connect=function(e,t){this.client=new WebSocket((this.ssl?"wss://":"ws://")+this.host+":"+this.port),this.client.onopen=function(){i.retrying?r(i.listeners,"reconnect"):r(i.listeners,"connect")},this.client.onclose=function(){r(i.listeners,"disconnect")},this.client.onerror=function(){e&&(i.retrying=!0,setTimeout(function(){i.connect(e,t)},t)),r(i.listeners,"error")},this.client.onmessage=function(e){var t=JSON.parse(e.data);t.room&&i.listeners[t.room]&&r(i.listeners,t.room,t)}},this.onConnect=function(e){this.listeners.connect.push({fn:e,keep:!0})},this.onConnectError=function(e){this.listeners.error.push({fn:e,keep:!0})},this.onDisconnect=function(e){this.listeners.disconnect.push({fn:e,keep:!0})},this.onReconnect=function(e){this.listeners.reconnect.push({fn:e,keep:!0})},this.once=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,keep:!1})},this.on=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,keep:!0})},this.off=function(e,t){var n;this.listeners[e]&&(n=this.listeners[e].findIndex(function(e){return e.fn===t}),n!==-1&&(1===this.listeners[e].length&&["error","connect","disconnect","reconnect"].indexOf(e)===-1?delete this.listeners[e]:this.listeners[e].splice(n,1)))},this.send=function(e){this.client&&this.client.readyState===this.client.OPEN&&this.client.send(JSON.stringify(e))},this.close=function(){this.listeners={error:[],connect:[],disconnect:[],reconnect:[]},this.retrying=!1,this.client.close(),this.client=null}}function r(e,t,n){var r,i=e[t].length;for(r=0;r1?(e[t].splice(r,1),--r,--i):delete e[t])}e.exports=n},function(e,t,n){function r(e,t,n){if(i.call(this,e,t,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,n,r){var i=["hydrate","save"];return r&&i.indexOf(e)!==-1}})}var i=n(1);r.prototype=Object.create(i.prototype,{constructor:{value:r}}),r.prototype.save=function(e,t){var n,r=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),n=this.serialize(),r.kuzzle.query(r.kuzzleSecurity.buildQueryArgs("createOrReplaceProfile"),n,e,function(e){t&&t(e,r)}),r},r.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},r.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},r.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e},r.prototype.getPolicies=function(){return this.content.policies},e.exports=r},function(e,t,n){function r(e,t,n){if(i.call(this,e,t,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,n,r){var i=["save"];return r&&i.indexOf(e)!==-1}})}var i=n(1);r.prototype=Object.create(i.prototype,{constructor:{value:r}}),r.prototype.save=function(e,t){var n=this.serialize(),r=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createOrReplaceRole"),n,e,function(e){t&&t(e,r)}),this},e.exports=r},function(e,t,n){function r(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,n,r){var i=["roleFactory","profileFactory","userFactory","isActionAllowed"];return r&&i.indexOf(e)===-1}}):this}var i=n(13),o=n(12),u=n(2);r.prototype.getRole=function(e,t,n){var r,o=this;if(!e)throw new Error("Id parameter is mandatory for getRole function");n||"function"!=typeof t||(n=t,t=null),r={_id:e},o.kuzzle.callbackRequired("KuzzleSecurity.getRole",n),o.kuzzle.query(this.buildQueryArgs("getRole"),r,t,function(e,t){n(e,!e&&new i(o,t.result._id,t.result._source))})},r.prototype.searchRoles=function(e,t,n){var r=this;n||"function"!=typeof t||(n=t,t=null),r.kuzzle.callbackRequired("KuzzleSecurity.searchRoles",n),r.kuzzle.query(this.buildQueryArgs("searchRoles"),{body:e},t,function(e,t){var o;return e?n(e):(o=t.result.hits.map(function(e){return new i(r,e._id,e._source)}),void n(null,{total:t.result.total,roles:o}))})},r.prototype.createRole=function(e,t,n,r){var o=this,u={},s="createRole";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.createRole: cannot create a role without a role ID");r||"function"!=typeof n||(r=n,n=null),u._id=e,u.body=t,n&&(s=n.replaceIfExist?"createOrReplaceRole":"createRole"),o.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(e,t){r(e,!e&&new i(o,t.result._id,t.result._source))})},r.prototype.updateRole=function(e,t,n,r){var o=this,u={_id:e,content:t},s="updateRole";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.updateRole: cannot update a role without a role ID");return r||"function"!=typeof n||(r=n,n=null),o.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(n){r(n,!n&&new i(o,e,t))}),this},r.prototype.deleteRole=function(e,t,n){var r={_id:e};return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteRole"),r,t,n&&function(e,t){n(e,!e&&t.result._id)}),this},r.prototype.roleFactory=function(e,t){return new i(this,e,t)},r.prototype.getProfile=function(e,t,n){var r,i=this;if(n||"function"!=typeof t||(n=t,t=null),!e||"string"!=typeof e)throw new Error("Id parameter is mandatory for getProfile function");r={_id:e},i.kuzzle.callbackRequired("KuzzleSecurity.getProfile",n),i.kuzzle.query(this.buildQueryArgs("getProfile"),r,t,function(e,t){n(e,!e&&new o(i,t.result._id,t.result._source))})},r.prototype.searchProfiles=function(e,t,n){var r=this;n||"function"!=typeof t||(n=t,t=null),r.kuzzle.callbackRequired("KuzzleSecurity.searchProfiles",n),r.kuzzle.query(this.buildQueryArgs("searchProfiles"),{body:e},t,function(e,t){var i;return e?n(e):(i=t.result.hits.map(function(e){return new o(r,e._id,e._source)}),void n(null,{total:t.result.total,profiles:i}))})},r.prototype.createProfile=function(e,t,n,r){var i=this,u={},s="createProfile";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.createProfile: cannot create a profile without a profile ID");r||"function"!=typeof n||(r=n,n=null),u._id=e,u.body=t,n&&(s=n.replaceIfExist?"createOrReplaceProfile":"createProfile"),i.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(e,t){r(e,!e&&new o(i,t.result._id,t.result._source))})},r.prototype.updateProfile=function(e,t,n,r){var i=this,u={},s="updateProfile";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.updateProfile: cannot update a profile without a profile ID");return r||"function"!=typeof n||(r=n,n=null),u._id=e,u.body=t,i.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(e,t){var n={};return e?r(e):(Object.keys(t.result._source).forEach(function(e){n[e]=t.result._source[e]}),void r(null,new o(i,t.result._id,n)))}),this},r.prototype.deleteProfile=function(e,t,n){var r={_id:e};return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteProfile"),r,t,n&&function(e,t){n(e,!e&&t.result._id)}),this},r.prototype.profileFactory=function(e,t){return new o(this,e,t)},r.prototype.getUser=function(e,t,n){var r={_id:e},i=this;if(!e||"string"!=typeof e)throw new Error("Id parameter is mandatory for getUser function");n||"function"!=typeof t||(n=t,t=null),i.kuzzle.callbackRequired("KuzzleSecurity.getUser",n),i.kuzzle.query(this.buildQueryArgs("getUser"),r,t,function(e,t){n(e,!e&&new u(i,t.result._id,t.result._source))})},r.prototype.searchUsers=function(e,t,n){var r=this;n||"function"!=typeof t||(n=t,t=null),r.kuzzle.callbackRequired("KuzzleSecurity.searchUsers",n),r.kuzzle.query(this.buildQueryArgs("searchUsers"),{body:e},t,function(e,t){var i;return e?n(e):(i=t.result.hits.map(function(e){return new u(r,e._id,e._source)}),void n(null,{total:t.result.total,users:i}))})},r.prototype.createUser=function(e,t,n,r){var i=this,o={},s="createUser";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.createUser: cannot create a user without a user ID");r||"function"!=typeof n||(r=n,n=null),o._id=e,o.body=t,n&&(s=n.replaceIfExist?"createOrReplaceUser":"createUser"),i.kuzzle.query(this.buildQueryArgs(s),o,null,r&&function(e,t){r(e,!e&&new u(i,t.result._id,t.result._source))})},r.prototype.updateUser=function(e,t,n,r){var i=this,o={},s="updateUser";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.updateUser: cannot update an user without an user ID");return r||"function"!=typeof n||(r=n,n=null),o._id=e,o.body=t,i.kuzzle.query(this.buildQueryArgs(s),o,n,r&&function(e,t){r(e,!e&&new u(i,t.result._id,t.result._source))}),this},r.prototype.deleteUser=function(e,t,n){var r={_id:e};return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteUser"),r,t,n&&function(e,t){n(e,!e&&t.result._id)}),this},r.prototype.userFactory=function(e,t){return new u(this,e,t)},r.prototype.isActionAllowed=function(e,t,n,r,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(!n||"string"!=typeof n)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===n||"*"===e.action}).filter(function(e){return e.index===r||"*"===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"},r.prototype.getUserRights=function(e,t,n){var r={_id:e},i=this;if(!e||"string"!=typeof e)throw new Error("userId parameter is mandatory for getUserRights function");n||"function"!=typeof t||(n=t,t=null),i.kuzzle.callbackRequired("Kuzzle.getUserRights",n),this.kuzzle.query(this.buildQueryArgs("getUserRights"),r,t,n&&function(e,t){n(e,!e&&t.result.hits)})},e.exports=r}])}); //# sourceMappingURL=kuzzle.js.map \ No newline at end of file diff --git a/dist/kuzzle.js.map b/dist/kuzzle.js.map index 1a132efc7..296cabf84 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 38194c1d337051971b30","webpack:///./src/kuzzle.js","webpack:///./src/security/kuzzleSecurityDocument.js","webpack:///./src/security/kuzzleUser.js","webpack:///../~/node-uuid/uuid.js","webpack:///./src/kuzzleDataCollection.js","webpack:///./src/kuzzleDataMapping.js","webpack:///./src/kuzzleDocument.js","webpack:///./src/kuzzleMemoryStorage.js","webpack:///./src/kuzzleRoom.js","webpack:///./src/networkWrapper/index.js","webpack:///./src/networkWrapper/wrappers/socketio.js","webpack:///./src/networkWrapper/wrappers/wsbrowsers.js","webpack:///./src/security/kuzzleProfile.js","webpack:///./src/security/kuzzleRole.js","webpack:///./src/security/kuzzleSecurity.js"],"names":["root","factory","exports","module","define","amd","a","i","this","modules","__webpack_require__","moduleId","installedModules","id","loaded","call","m","c","p","cleanQueue","self","now","Date","lastDocumentIndex","queueTTL","offlineQueue","forEach","query","index","ts","splice","droppedRequest","emitEvent","queueMaxSize","length","cleanHistory","requestHistory","Object","keys","key","setTimeout","emitRequest","request","cb","undefined","jwtToken","network","once","requestId","response","action","error","message","send","dequeue","additionalQueue","uniqueQueue","dequeuingProcess","shift","Math","max","replayInterval","queuing","offlineQueueLoader","Error","Array","isArray","concat","filter","controller","hasOwnProperty","renewAllSubscriptions","subscriptions","roomId","subscriptionId","subscription","renew","callback","uuid","KuzzleDataCollection","KuzzleSecurity","KuzzleMemoryStorage","KuzzleUser","networkWrapper","Kuzzle","host","options","defineProperties","collections","value","writable","connectCB","eventListeners","connected","lastEmitted","listeners","disconnected","reconnected","jwtTokenExpired","loginAttempt","offlineQueuePush","offlineQueuePop","eventTimeout","state","pending","autoReconnect","enumerable","defaultIndex","reconnectionDelay","wsPort","ioPort","autoQueue","autoReplay","autoResubscribe","headers","metadata","queueFilter","opt","getOwnPropertyDescriptor","offlineMode","defineProperty","header","errorMessagePrefix","event","args","prototype","slice","arguments","eventProperties","listener","process","nextTick","fn","apply","connect","bluebird","promisifyAll","suffix","name","func","target","passes","whitelist","indexOf","onConnect","onConnectError","connectionError","internal","onDisconnect","disconnect","onReconnect","reconnect","checkToken","err","res","valid","setJwtToken","token","success","result","jwt","JSON","stringify","getJwtToken","login","strategy","credentials","expiresIn","body","queuable","logout","v4","callbackRequired","whoAmI","security","_id","_source","getMyRights","hits","updateSelf","content","data","queryArgs","addListener","listenerId","knownEvents","listenerType","isValid","toString","push","getAllStatistics","getStatistics","timestamp","queryCB","startTime","dataCollectionFactory","collection","flushQueue","listCollections","collectionType","arg","type","listIndexes","indexes","close","getServerInfo","serverInfo","refreshIndex","getAutoRefresh","setAutoRefresh","autoRefresh","attr","object","meta","addHeaders","authorization","removeAllListeners","eventName","removeListener","replayQueue","setDefaultIndex","setHeaders","replace","startQueuing","stopQueuing","KuzzleSecurityDocument","kuzzleSecurity","kuzzle","setContent","serialize","buildQueryArgs","deleteActionName","update","updateActionName","create","constructor","setProfiles","profileIds","addProfile","profileId","save","getProfiles","_window","setupBrowser","_crypto","crypto","msCrypto","_rng","getRandomValues","_rnds8","Uint8Array","_whatwgRNG","e","_rnds","_mathRNG","r","random","console","warn","setupNode","require","_rb","randomBytes","_nodeRNG","parse","s","buf","offset","ii","toLowerCase","oct","_hexToByte","unparse","bth","_byteToHex","v1","b","clockseq","_clockseq","msecs","getTime","nsecs","_lastNSecs","dt","_lastMSecs","tl","tmh","node","_nodeId","n","BufferClass","rnds","rng","_previousRoot","Buffer","substr","_seedBytes","noConflict","window","blacklist","KuzzleDocument","KuzzleDataMapping","KuzzleRoom","advancedSearch","filters","documents","doc","newDocument","version","_version","total","count","createDocument","document","updateIfExist","deleteDocument","ids","fetchDocument","documentId","fetchAllDocuments","from","size","getMapping","kuzzleMapping","refresh","publishMessage","replaceDocument","subscribe","room","truncate","updateDocument","documentFactory","roomFactory","dataMappingFactory","mapping","kuzzleDataCollection","properties","mappings","set","field","dataCollection","publish","values","bind","keyVal","idOrKeys","commands","append","bgrewriteaof","bgsave","bitcount","bitop","bitpos","__opts__","blpop","brpoplpush","dbsize","decrby","del","discard","exec","exists","expire","expireat","flushdb","getbit","getrange","hdel","hexists","hincrby","hmset","hset","info","lastsave","lindex","linsert","lpush","lrange","lrem","lset","ltrim","mset","multi","pexpire","pexpireat","pfadd","pfmerge","ping","psetex","randomkey","rename","renamenx","restore","rpoplpush","sadd","sdiffstore","setbit","setex","setrange","sinterstore","sismember","smove","sort","spop","srem","sunionstore","unwatch","wait","zadd","zcount","zincrby","zinterstore","zlexcount","zrange","zrangebylex","zrangebyscore","zrem","zremrangebylex","zremrangebyscore","zrevrangebylex","zrevrangebyscore","zrevrank","decr","get","dump","hgetall","hkeys","hlen","hstrlen","hvals","incr","llen","lpop","persist","pttl","rpop","scard","smembers","strlen","ttl","zcard","getset","lpushx","mget","pfcount","sdiff","sinter","sunion","watch","incrby","incrbyfloat","brpop","hget","hmget","hsetnx","msetnx","rpush","hincrbyfloat","srandmember","zrevrange","zscore","command","pop","v","channel","lastRenewal","notifier","queue","renewalDelay","scope","subscribing","users","subscribeToSelf","notificationCallback","element","isReady","subscribeQuery","unsubscribe","on","interval","off","setInterval","clearInterval","WebSocket","io","code","SocketIO","port","socket","reconnection","forceNew","payload","emit","WSBrowsers","client","retrying","onopen","poke","onclose","onerror","onmessage","keep","findIndex","readyState","OPEN","KuzzleProfile","policies","addPolicy","policy","roleId","setPolicies","map","getPolicies","KuzzleRole","getRole","searchRoles","roles","createRole","replaceIfExist","updateRole","deleteRole","roleFactory","getProfile","searchProfiles","profiles","createProfile","updateProfile","updatedContent","property","deleteProfile","profileFactory","getUser","searchUsers","createUser","updateUser","deleteUser","userFactory","isActionAllowed","rights","filteredRights","right","some","item","getUserRights","userId"],"mappings":"CAAA,SAAAA,EAAAC,GACA,mBAAAC,UAAA,gBAAAC,QACAA,OAAAD,QAAAD,QACA,sBAAAG,gBAAAC,IACAD,UAAAH,OACA,CACA,GAAAK,GAAAL,GACA,QAAAM,KAAAD,IAAA,gBAAAJ,iBAAAF,GAAAO,GAAAD,EAAAC,KAECC,KAAA,WACD,MCAgB,UAAUC,GCN1B,QAAAC,GAAAC,GAGA,GAAAC,EAAAD,GACA,MAAAC,GAAAD,GAAAT,OAGA,IAAAC,GAAAS,EAAAD,IACAT,WACAW,GAAAF,EACAG,QAAA,EAUA,OANAL,GAAAE,GAAAI,KAAAZ,EAAAD,QAAAC,IAAAD,QAAAQ,GAGAP,EAAAW,QAAA,EAGAX,EAAAD,QAvBA,GAAAU,KAqCA,OATAF,GAAAM,EAAAP,EAGAC,EAAAO,EAAAL,EAGAF,EAAAQ,EAAA,GAGAR,EAAA,KDgBM,SAASP,EAAQD,EAASQ,GEolBhC,QAAAS,KACA,GACAC,GAAAZ,KACAa,EAAAC,KAAAD,MACAE,IAEAH,GAAAI,SAAA,IACAJ,EAAAK,aAAAC,QAAA,SAAAC,EAAAC,GACAD,EAAAE,GAAAR,EAAAD,EAAAI,WACAD,EAAAK,KAIAL,QACAH,EAAAK,aACAK,OAAA,EAAAP,EAAA,GACAG,QAAA,SAAAK,GACAX,EAAAY,UAAA,kBAAAD,EAAAJ,UAKAP,EAAAa,aAAA,GAAAb,EAAAK,aAAAS,OAAAd,EAAAa,cACAb,EAAAK,aACAK,OAAA,EAAAV,EAAAK,aAAAS,OAAAd,EAAAa,cACAP,QAAA,SAAAK,GACAX,EAAAY,UAAA,kBAAAD,EAAAJ,SASA,QAAAQ,GAAAC,GACA,GACAf,GAAAC,KAAAD,KAEAgB,QAAAC,KAAAF,GAAAV,QAA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GACA,SAAAc,OAAA,6DAkBA,OAdA2d,GAAAD,EAAAtd,OAAA,SAAAwd,GACA,MAAAA,GAAAvd,gBAAA,MAAAud,EAAAvd,aAEAD,OAAA,SAAAwd,GACA,MAAAA,GAAA1e,YAAA,MAAA0e,EAAA1e,SAEAkB,OAAA,SAAAwd,GACA,MAAAA,GAAAhgB,WAAA,MAAAggB,EAAAhgB,QAEAwC,OAAA,SAAAwd,GACA,MAAAA,GAAAxV,gBAAA,MAAAwV,EAAAxV,aAIAuV,EAAAE,KAAA,SAAAC,GAA2C,kBAAAA,EAAArc,QAC3C,UAGAkc,EAAAE,KAAA,SAAAC,GAA2C,sBAAAA,EAAArc,QAC3C,cAGA,UAWAT,EAAA6C,UAAAka,cAAA,SAAAC,EAAA1c,EAAA3C,GACA,GACA0I,IAAYN,IAAAiX,GACZ5gB,EAAAZ,IAEA,KAAAwhB,GAAA,gBAAAA,GACA,SAAAhe,OAAA,2DAGArB,IAAA,kBAAA2C,KACA3C,EAAA2C,EACAA,EAAA,MAGAlE,EAAA+M,OAAAvD,iBAAA,uBAAAjI,GAEAnC,KAAA2N,OAAAxM,MAAAnB,KAAA8N,eAAA,iBAAAjD,EAAA/F,EAAA,SAAAmE,EAAAC,GACA,MAAAD,GACA9G,EAAA8G,OAGA9G,GAAA,KAAA+G,EAAAK,OAAAmB,SAIA/K,EAAAD,QAAA8E","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 {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(this, function() {\nreturn \n\n\n/** WEBPACK FOOTER **\n ** webpack/universalModuleDefinition\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 {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\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 uuid = __webpack_require__(3),\n\t KuzzleDataCollection = __webpack_require__(4),\n\t KuzzleSecurity = __webpack_require__(14),\n\t KuzzleMemoryStorage = __webpack_require__(7),\n\t KuzzleUser = __webpack_require__(2),\n\t networkWrapper = __webpack_require__(9);\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 * @constructor\n\t */\n\tmodule.exports = Kuzzle = function (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\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 collections: {\n\t value: {},\n\t writable: true\n\t },\n\t connectCB: {\n\t value: cb\n\t },\n\t eventListeners: {\n\t value: {\n\t connected: {lastEmitted: null, listeners: []},\n\t error: {lastEmitted: null, listeners: []},\n\t disconnected: {lastEmitted: null, listeners: []},\n\t reconnected: {lastEmitted: null, listeners: []},\n\t jwtTokenExpired: {lastEmitted: null, listeners: []},\n\t loginAttempt: {lastEmitted: null, listeners: []},\n\t offlineQueuePush: {listeners: []},\n\t offlineQueuePop: {listeners: []}\n\t }\n\t },\n\t eventTimeout: {\n\t value: 200\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 'roomId': {\n\t kuzzleRoomID_1: kuzzleRoomInstance_1,\n\t kuzzleRoomID_2: kuzzleRoomInstance_2,\n\t kuzzleRoomID_...: 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 // read-only properties\n\t autoReconnect: {\n\t value: (options && typeof options.autoReconnect === 'boolean') ? options.autoReconnect : 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 enumerable: true\n\t },\n\t host: {\n\t value: host,\n\t enumerable: true\n\t },\n\t wsPort: {\n\t value: (options && typeof options.wsPort === 'number') ? options.wsPort : 7513,\n\t enumerable: true\n\t },\n\t ioPort: {\n\t value: (options && typeof options.ioPort === 'number') ? options.ioPort : 7512,\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 metadata: {\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: 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 (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 KuzzleSecurity(this),\n\t enumerable: true\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 Object.defineProperty(this, 'emitEvent', {\n\t value: function emitEvent(event) {\n\t var\n\t now = Date.now(),\n\t args = Array.prototype.slice.call(arguments, 1),\n\t eventProperties = this.eventListeners[event];\n\t\n\t if (eventProperties.lastEmitted && eventProperties.lastEmitted >= now - this.eventTimeout) {\n\t return false;\n\t }\n\t\n\t eventProperties.listeners.forEach(function (listener) {\n\t process.nextTick(function () {\n\t listener.fn.apply(undefined, args);\n\t });\n\t });\n\t\n\t // Events without the 'lastEmitted' property can be emitted without minimum time between emissions\n\t if (eventProperties.lastEmitted !== undefined) {\n\t eventProperties.lastEmitted = now;\n\t }\n\t }\n\t });\n\t\n\t Object.defineProperty(this, 'memoryStorage', {\n\t value: new KuzzleMemoryStorage(this),\n\t enumerable: true\n\t });\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 cleanHistory(this.requestHistory);\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', 'listIndexes', 'login', 'logout', 'now', 'query',\n\t '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\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.network = networkWrapper(self.host, self.wsPort, self.ioPort);\n\t }\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.onConnectError(function (error) {\n\t var connectionError = new Error('Unable to connect to kuzzle server at \"' + self.host + '\"');\n\t\n\t connectionError.internal = error;\n\t self.state = 'error';\n\t self.emitEvent('error', connectionError);\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('jwtTokenExpired');\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 * 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 * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.login = function (strategy) {\n\t var\n\t self = this,\n\t request = {\n\t strategy: strategy\n\t },\n\t credentials,\n\t cb;\n\t\n\t // Handle arguments (credentials, expiresIn, cb)\n\t if (arguments[1]) {\n\t if (typeof arguments[1] === 'object') {\n\t credentials = 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 if (typeof credentials === 'object') {\n\t Object.keys(credentials).forEach(function (key) {\n\t request[key] = credentials[key];\n\t });\n\t }\n\t\n\t this.query({controller: 'auth', action: 'login'}, {body: 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 if (cb && typeof cb === 'function') {\n\t cb(null, response.result);\n\t }\n\t }\n\t else {\n\t if (cb && typeof cb === 'function') {\n\t cb(error);\n\t }\n\t\n\t self.emitEvent('loginAttempt', {success: false, error: error.message});\n\t }\n\t });\n\t\n\t return self;\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: uuid.v4(),\n\t body: {}\n\t };\n\t\n\t this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, function(error) {\n\t if (error === null) {\n\t self.jwtToken = undefined;\n\t\n\t if (typeof cb === 'function') {\n\t cb(null, self);\n\t }\n\t }\n\t else if (typeof cb === 'function') {\n\t cb(error);\n\t }\n\t });\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} callback The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t * @return {Kuzzle} The Kuzzle instance to enable chaining.\n\t */\n\tKuzzle.prototype.checkToken = function (token, callback) {\n\t var\n\t self = this,\n\t request = {\n\t body: {\n\t token: token\n\t }\n\t };\n\t\n\t this.callbackRequired('Kuzzle.checkToken', callback);\n\t\n\t this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, function (err, response) {\n\t if (err) {\n\t return callback(err);\n\t }\n\t\n\t callback(null, response.result);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Fetches the current user.\n\t *\n\t * @param {function} callback The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t * @return {Kuzzle} The Kuzzle instance to enable chaining.\n\t */\n\tKuzzle.prototype.whoAmI = function (callback) {\n\t var self = this;\n\t\n\t self.callbackRequired('Kuzzle.whoAmI', callback);\n\t\n\t self.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, function (err, response) {\n\t if (err) {\n\t return callback(err);\n\t }\n\t\n\t callback(null, new KuzzleUser(self.security, response.result._id, response.result._source));\n\t });\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Gets the rights array of the currently logged user.\n\t *\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'}, {}, null, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, 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 */\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 if (cb) {\n\t self.query(queryArgs, data, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result);\n\t });\n\t } else {\n\t self.query(queryArgs, data, options);\n\t }\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 setTimeout(function () {\n\t cleanHistory(requestHistory);\n\t }, 1000);\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 if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n\t self.jwtToken = undefined;\n\t self.emitEvent('jwtTokenExpired', request, cb);\n\t }\n\t\n\t if (cb) {\n\t cb(response.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 KuzzleRoom.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 * 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 * The ID returned by this function is required to remove this listener at a later time.\n\t *\n\t * @param {string} event - name of the global event to subscribe to (see the 'eventListeners' object property)\n\t * @param {function} listener - callback to invoke each time an event is fired\n\t * @returns {string} Unique listener ID\n\t */\n\tKuzzle.prototype.addListener = function(event, listener) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t listenerType = typeof listener,\n\t listenerId;\n\t\n\t this.isValid();\n\t\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\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 listenerId = uuid.v4();\n\t this.eventListeners[event].listeners.push({id: listenerId, fn: listener});\n\t return listenerId;\n\t};\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 * @returns {object} this\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:'admin', action: 'getAllStats'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result.hits);\n\t });\n\t\n\t return this;\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 * @returns {object} this\n\t */\n\tKuzzle.prototype.getStatistics = function (timestamp, options, cb) {\n\t var queryCB;\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 if (timestamp) {\n\t cb(null, res.result.hits);\n\t } else {\n\t cb(null, [res.result]);\n\t }\n\t };\n\t\n\t this.callbackRequired('Kuzzle.getStatistics', cb);\n\t\n\t if (!timestamp) {\n\t this.query({controller: 'admin', action: 'getLastStats'}, {}, options, queryCB);\n\t } else {\n\t this.query({controller: 'admin', action: 'getStats'}, { body: { startTime: timestamp } }, options, queryCB);\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Create a new instance of a KuzzleDataCollection 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 {object} A KuzzleDataCollection instance\n\t */\n\tKuzzle.prototype.dataCollectionFactory = 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') {\n\t throw new Error('Invalid \"index\" argument: string expected, got ' + typeof index);\n\t }\n\t\n\t if (typeof collection !== 'string') {\n\t throw new Error('Invalid \"collection\" argument: string expected, got ' + typeof collection);\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 KuzzleDataCollection(this, index, collection);\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 * @returns {object} this\n\t */\n\tKuzzle.prototype.listCollections = function () {\n\t var\n\t collectionType = 'all',\n\t index,\n\t options,\n\t cb,\n\t args = Array.prototype.slice.call(arguments);\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 if (options && options.type) {\n\t collectionType = options.type;\n\t }\n\t\n\t this.query({index: index, controller: 'read', action: 'listCollections'}, {body: {type: collectionType}}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t return cb(null, res.result.collections);\n\t });\n\t\n\t return this;\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 * @returns {object} this\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: 'read', action: 'listIndexes'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t return cb(null, res.result.indexes);\n\t });\n\t\n\t return this;\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 this.logout();\n\t\n\t this.state = 'disconnected';\n\t this.network.close();\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 * @returns {object} this\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: 'read', action: 'serverInfo'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result.serverInfo);\n\t });\n\t\n\t return this;\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: 'admin', action: 'refreshIndex'}, {}, 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 * @returns {object} this\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: 'admin', action: 'getAutoRefresh'}, {}, options, cb);\n\t\n\t return this;\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: 'admin', 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 * @returns {object} this\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: 'read', action: 'now'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result.now);\n\t });\n\t\n\t return this;\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 * - metadata (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 metadata: this.metadata\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.metadata) {\n\t Object.keys(options.metadata).forEach(function (meta) {\n\t object.metadata[meta] = options.metadata[meta];\n\t });\n\t }\n\t\n\t if (options.queuable === false && self.state === 'offline') {\n\t return self;\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.metadata) {\n\t Object.keys(query.metadata).forEach(function (meta) {\n\t object.metadata[meta] = query.metadata[meta];\n\t });\n\t }\n\t\n\t for (attr in query) {\n\t if (attr !== 'metadata' && 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.headers = object.headers || {};\n\t object.headers.authorization = 'Bearer ' + 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 = uuid.v4();\n\t }\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 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 } else if (self.queuing || ['initializing', 'connecting'].indexOf(self.state) !== -1) {\n\t cleanQueue.call(this, object, cb);\n\t\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 }\n\t }\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Removes all listeners, either from a specific event or from all events\n\t *\n\t * @param {string} event - One of the event described in the Event Handling section of this documentation\n\t */\n\tKuzzle.prototype.removeAllListeners = function (event) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t self = this;\n\t\n\t if (event) {\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n\t }\n\t\n\t this.eventListeners[event].listeners = [];\n\t } else {\n\t knownEvents.forEach(function (eventName) {\n\t self.eventListeners[eventName].listeners = [];\n\t });\n\t }\n\t};\n\t\n\t/**\n\t * Removes a listener from an event.\n\t *\n\t * @param {string} event - One of the event described in the Event Handling section of this documentation\n\t * @param {string} listenerId - The ID returned by addListener\n\t */\n\tKuzzle.prototype.removeListener = function (event, listenerId) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t self = this;\n\t\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n\t }\n\t\n\t this.eventListeners[event].listeners.forEach(function (listener, index) {\n\t if (listener.id === listenerId) {\n\t self.eventListeners[event].listeners.splice(index, 1);\n\t }\n\t });\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\t\n\n\n/***/ },\n/* 1 */\n/***/ function(module, exports) {\n\n\tfunction KuzzleSecurityDocument(kuzzleSecurity, id, content) {\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: kuzzleSecurity.kuzzle\n\t },\n\t kuzzleSecurity: {\n\t value: kuzzleSecurity\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 });\n\t\n\t if (content) {\n\t this.setContent(content, true);\n\t }\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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 {Object} this\n\t */\n\tKuzzleSecurityDocument.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\tKuzzleSecurityDocument.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\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\tKuzzleSecurityDocument.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.kuzzleSecurity.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 */\n\tKuzzleSecurityDocument.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.kuzzleSecurity.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\n\tmodule.exports = KuzzleSecurityDocument;\n\n/***/ },\n/* 2 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleUser(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 });\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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\tKuzzleUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleUser\n\t }\n\t});\n\t\n\t/**\n\t * Set profiles in content\n\t * @param {array} profile - an array of profiles ids string\n\t *\n\t * @returns {KuzzleUser} this\n\t */\n\tKuzzleUser.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 * Add a profile\n\t * @param {string} profile - a profile ids string\n\t *\n\t * @returns {KuzzleUser} this\n\t */\n\tKuzzleUser.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 * Saves this user into Kuzzle.\n\t *\n\t * If this is a new user, this function will create it in Kuzzle.\n\t * Otherwise, this method will replace the latest version of this user in Kuzzle by the current content\n\t * of this object.\n\t *\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @param {object} [options] - Optional parameters\n\t * @returns {*} this\n\t */\n\tKuzzleUser.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.kuzzleSecurity.buildQueryArgs('createOrReplaceUser'), data, options, function (error) {\n\t if (error) {\n\t return cb ? cb(error) : false;\n\t }\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 * Serialize this object into a JSON object\n\t *\n\t * @return {object} JSON object representing this User\n\t */\n\tKuzzleUser.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\n\t return data;\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\tKuzzleUser.prototype.getProfiles = function () {\n\t return this.content.profileIds;\n\t};\n\t\n\tmodule.exports = KuzzleUser;\n\n\n/***/ },\n/* 3 */\n/***/ function(module, exports) {\n\n\t// uuid.js\n\t//\n\t// Copyright (c) 2010-2012 Robert Kieffer\n\t// MIT License - http://opensource.org/licenses/mit-license.php\n\t\n\t/*global window, require, define */\n\t(function(_window) {\n\t 'use strict';\n\t\n\t // Unique ID creation requires a high quality random # generator. We feature\n\t // detect to determine the best RNG source, normalizing to a function that\n\t // returns 128-bits of randomness, since that's what's usually required\n\t var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot;\n\t\n\t function setupBrowser() {\n\t // Allow for MSIE11 msCrypto\n\t var _crypto = _window.crypto || _window.msCrypto;\n\t\n\t if (!_rng && _crypto && _crypto.getRandomValues) {\n\t // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto\n\t //\n\t // Moderately fast, high quality\n\t try {\n\t var _rnds8 = new Uint8Array(16);\n\t _whatwgRNG = _rng = function whatwgRNG() {\n\t _crypto.getRandomValues(_rnds8);\n\t return _rnds8;\n\t };\n\t _rng();\n\t } catch(e) {}\n\t }\n\t\n\t if (!_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 _mathRNG = _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 if ('undefined' !== typeof console && console.warn) {\n\t console.warn(\"[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()\");\n\t }\n\t }\n\t }\n\t\n\t function setupNode() {\n\t // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html\n\t //\n\t // Moderately fast, high quality\n\t if ('function' === typeof require) {\n\t try {\n\t var _rb = require('crypto').randomBytes;\n\t _nodeRNG = _rng = _rb && function() {return _rb(16);};\n\t _rng();\n\t } catch(e) {}\n\t }\n\t }\n\t\n\t if (_window) {\n\t setupBrowser();\n\t } else {\n\t setupNode();\n\t }\n\t\n\t // Buffer class to use\n\t var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;\n\t\n\t // Maps for number <-> hex string conversion\n\t var _byteToHex = [];\n\t var _hexToByte = {};\n\t for (var i = 0; i < 256; i++) {\n\t _byteToHex[i] = (i + 0x100).toString(16).substr(1);\n\t _hexToByte[_byteToHex[i]] = i;\n\t }\n\t\n\t // **`parse()` - Parse a UUID into it's component bytes**\n\t function parse(s, buf, offset) {\n\t var i = (buf && offset) || 0, ii = 0;\n\t\n\t buf = buf || [];\n\t s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {\n\t if (ii < 16) { // Don't overflow!\n\t buf[i + ii++] = _hexToByte[oct];\n\t }\n\t });\n\t\n\t // Zero out remaining bytes if string was short\n\t while (ii < 16) {\n\t buf[i + ii++] = 0;\n\t }\n\t\n\t return buf;\n\t }\n\t\n\t // **`unparse()` - Convert UUID byte array (ala parse()) into a string**\n\t function unparse(buf, offset) {\n\t var i = offset || 0, 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\t // **`v1()` - Generate time-based UUID**\n\t //\n\t // Inspired by https://github.com/LiosK/UUID.js\n\t // and http://docs.python.org/library/uuid.html\n\t\n\t // random #'s we need to init node and clockseq\n\t var _seedBytes = _rng();\n\t\n\t // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n\t var _nodeId = [\n\t _seedBytes[0] | 0x01,\n\t _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]\n\t ];\n\t\n\t // Per 4.2.2, randomize (14 bit) clockseq\n\t var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;\n\t\n\t // Previous uuid creation time\n\t var _lastMSecs = 0, _lastNSecs = 0;\n\t\n\t // See https://github.com/broofa/node-uuid for API details\n\t function v1(options, buf, offset) {\n\t var i = buf && offset || 0;\n\t var b = buf || [];\n\t\n\t options = options || {};\n\t\n\t var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;\n\t\n\t // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n\t // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n\t // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n\t // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\t var msecs = (options.msecs != null) ? options.msecs : new Date().getTime();\n\t\n\t // Per 4.2.1.2, use count of uuid's generated during the current clock\n\t // cycle to simulate higher resolution clock\n\t var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;\n\t\n\t // Time since last uuid creation (in msecs)\n\t var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\t\n\t // Per 4.2.1.2, Bump clockseq on clock regression\n\t if (dt < 0 && options.clockseq == null) {\n\t clockseq = clockseq + 1 & 0x3fff;\n\t }\n\t\n\t // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n\t // time interval\n\t if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {\n\t nsecs = 0;\n\t }\n\t\n\t // Per 4.2.1.2 Throw error if too many uuids are requested\n\t if (nsecs >= 10000) {\n\t throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n\t }\n\t\n\t _lastMSecs = msecs;\n\t _lastNSecs = nsecs;\n\t _clockseq = clockseq;\n\t\n\t // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\t msecs += 12219292800000;\n\t\n\t // `time_low`\n\t var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n\t b[i++] = tl >>> 24 & 0xff;\n\t b[i++] = tl >>> 16 & 0xff;\n\t b[i++] = tl >>> 8 & 0xff;\n\t b[i++] = tl & 0xff;\n\t\n\t // `time_mid`\n\t var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n\t b[i++] = tmh >>> 8 & 0xff;\n\t b[i++] = tmh & 0xff;\n\t\n\t // `time_high_and_version`\n\t b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\t b[i++] = tmh >>> 16 & 0xff;\n\t\n\t // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\t b[i++] = clockseq >>> 8 | 0x80;\n\t\n\t // `clock_seq_low`\n\t b[i++] = clockseq & 0xff;\n\t\n\t // `node`\n\t var node = options.node || _nodeId;\n\t for (var n = 0; n < 6; n++) {\n\t b[i + n] = node[n];\n\t }\n\t\n\t return buf ? buf : unparse(b);\n\t }\n\t\n\t // **`v4()` - Generate random UUID**\n\t\n\t // See https://github.com/broofa/node-uuid for API details\n\t function v4(options, buf, offset) {\n\t // Deprecated - 'format' argument, as supported in v1.2\n\t var i = buf && offset || 0;\n\t\n\t if (typeof(options) === 'string') {\n\t buf = (options === 'binary') ? new BufferClass(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 || unparse(rnds);\n\t }\n\t\n\t // Export public API\n\t var uuid = v4;\n\t uuid.v1 = v1;\n\t uuid.v4 = v4;\n\t uuid.parse = parse;\n\t uuid.unparse = unparse;\n\t uuid.BufferClass = BufferClass;\n\t uuid._rng = _rng;\n\t uuid._mathRNG = _mathRNG;\n\t uuid._nodeRNG = _nodeRNG;\n\t uuid._whatwgRNG = _whatwgRNG;\n\t\n\t if (('undefined' !== typeof module) && module.exports) {\n\t // Publish as node.js module\n\t module.exports = uuid;\n\t } else if (typeof define === 'function' && define.amd) {\n\t // Publish as AMD module\n\t define(function() {return uuid;});\n\t\n\t\n\t } else {\n\t // Publish as global (in browsers)\n\t _previousRoot = _window.uuid;\n\t\n\t // **`noConflict()` - (browser only) to reset global 'uuid' var**\n\t uuid.noConflict = function() {\n\t _window.uuid = _previousRoot;\n\t return uuid;\n\t };\n\t\n\t _window.uuid = uuid;\n\t }\n\t})('undefined' !== typeof window ? window : null);\n\n\n/***/ },\n/* 4 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleDocument = __webpack_require__(6),\n\t KuzzleDataMapping = __webpack_require__(5),\n\t KuzzleRoom = __webpack_require__(8);\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 * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @param {string} index - Index containing the data collection\n\t * @param {string} collection - name of the data collection to handle\n\t * @constructor\n\t */\n\tfunction KuzzleDataCollection(kuzzle, index, collection) {\n\t if (!index || !collection) {\n\t throw new Error('The KuzzleDataCollection object constructor needs an index and a collection arguments');\n\t }\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 * 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 * @returns {Object} this\n\t */\n\tKuzzleDataCollection.prototype.advancedSearch = 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 = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleDataCollection.advancedSearch', cb);\n\t\n\t query = self.kuzzle.addHeaders({body: filters}, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('read', '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 KuzzleDocument(self, doc._id, doc._source);\n\t\n\t newDocument.version = doc._version;\n\t\n\t documents.push(newDocument);\n\t });\n\t\n\t cb(null, { total: result.result.total, documents: documents });\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 * @returns {Object} this\n\t */\n\tKuzzleDataCollection.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('KuzzleDataCollection.count', cb);\n\t\n\t query = this.kuzzle.addHeaders({body: filters}, this.headers);\n\t\n\t this.kuzzle.query(this.buildQueryArgs('read', 'count'), query, options, function (error, result) {\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t cb(null, result.result.count);\n\t });\n\t\n\t return this;\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\tKuzzleDataCollection.prototype.create = 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('write', 'createCollection'), data, options, cb);\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 * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t * - updateIfExist (boolean, default: false):\n\t * If the same document already exists: throw an error if sets to false.\n\t * Update the existing document otherwise\n\t *\n\t * @param {string} [id] - (optional) document identifier\n\t * @param {object} document - either an instance of a KuzzleDocument 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\tKuzzleDataCollection.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 KuzzleDocument) {\n\t data = document.serialize();\n\t } else {\n\t data.body = document;\n\t }\n\t\n\t if (options) {\n\t action = options.updateIfExist ? 'createOrReplace' : 'create';\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 if (cb) {\n\t self.kuzzle.query(this.buildQueryArgs('write', action), data, options, 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 KuzzleDocument(self, res.result._id, res.result._source);\n\t doc.version = res.result._version;\n\t cb(null, doc);\n\t });\n\t } else {\n\t self.kuzzle.query(this.buildQueryArgs('write', action), data, options);\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 * - metadata (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 {Object} this\n\t */\n\tKuzzleDataCollection.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 = 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 if (cb) {\n\t this.kuzzle.query(this.buildQueryArgs('write', action), data, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t if (action === 'delete') {\n\t cb(null, [res.result._id]);\n\t } else {\n\t cb(null, res.result.ids);\n\t }\n\t });\n\t } else {\n\t this.kuzzle.query(this.buildQueryArgs('write', action), data, options);\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 * @returns {Object} this\n\t */\n\tKuzzleDataCollection.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('KuzzleDataCollection.fetch', cb);\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('read', '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 KuzzleDocument(self, res.result._id, res.result._source);\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 * Retrieves all documents stored in this data collection\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t * @returns {Object} this\n\t */\n\tKuzzleDataCollection.prototype.fetchAllDocuments = function (options, cb) {\n\t var filters = {};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t // copying pagination options to the search filter\n\t if (options) {\n\t if (options.from) {\n\t filters.from = options.from;\n\t }\n\t\n\t if (options.size) {\n\t filters.size = options.size;\n\t }\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDataCollection.fetchAll', cb);\n\t\n\t this.advancedSearch(filters, options, cb);\n\t\n\t return this;\n\t};\n\t\n\t\n\t/**\n\t * Instantiates a KuzzleDataMapping 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 KuzzleDataMapping object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.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('KuzzleDataCollection.getMapping', cb);\n\t\n\t kuzzleMapping = new KuzzleDataMapping(this);\n\t kuzzleMapping.refresh(options, cb);\n\t\n\t return this;\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 * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} document - either a KuzzleDocument 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\tKuzzleDataCollection.prototype.publishMessage = function (document, options, cb) {\n\t var data = {};\n\t\n\t if (document instanceof KuzzleDocument) {\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('write', '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 * - metadata (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 KuzzleDocument object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.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 if (cb) {\n\t self.kuzzle.query(this.buildQueryArgs('write', 'createOrReplace'), 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 KuzzleDocument(self, res.result._id, res.result._source);\n\t document.version = res.result._version;\n\t cb(null, document);\n\t });\n\t } else {\n\t self.kuzzle.query(this.buildQueryArgs('write', 'createOrReplace'), data, options);\n\t }\n\t\n\t return this;\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 {*} KuzzleRoom object\n\t */\n\tKuzzleDataCollection.prototype.subscribe = function (filters, options, cb) {\n\t var room;\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('KuzzleDataCollection.subscribe', cb);\n\t\n\t room = new KuzzleRoom(this, options);\n\t\n\t return room.renew(filters, cb);\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\tKuzzleDataCollection.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('admin', 'truncateCollection'), 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 * - metadata (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 KuzzleDocument object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n\t var\n\t 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 data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t if (cb) {\n\t self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options, function (err, res) {\n\t var doc;\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t doc = new KuzzleDocument(self, res.result._id);\n\t doc.refresh(cb);\n\t });\n\t } else {\n\t self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options);\n\t }\n\t\n\t return self;\n\t};\n\t\n\t\n\t/**\n\t * Instantiate a new KuzzleDocument 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\tKuzzleDataCollection.prototype.documentFactory = function (id, content) {\n\t return new KuzzleDocument(this, id, content);\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleRoom 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\tKuzzleDataCollection.prototype.roomFactory = function (options) {\n\t return new KuzzleRoom(this, options);\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleDataMapping 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 KuzzleDataMapping object with\n\t * @constructor\n\t */\n\tKuzzleDataCollection.prototype.dataMappingFactory = function (mapping) {\n\t return new KuzzleDataMapping(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\tKuzzleDataCollection.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 = KuzzleDataCollection;\n\n\n/***/ },\n/* 5 */\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 KuzzleDataMapping object allow to get the current mapping of a data collection and to modify it if needed.\n\t *\n\t * @param {object} kuzzleDataCollection - Instance of the inherited KuzzleDataCollection object\n\t * @param {object} mapping - mappings\n\t * @constructor\n\t */\n\tfunction KuzzleDataMapping(kuzzleDataCollection, mapping) {\n\t Object.defineProperties(this, {\n\t //read-only properties\n\t collection: {\n\t value: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzleDataCollection.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\tKuzzleDataMapping.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('admin', 'updateMapping'), data, options, function (err) {\n\t if (err) {\n\t return cb ? cb(err) : false;\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\tKuzzleDataMapping.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('admin', '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)) : false;\n\t }\n\t } else {\n\t return cb ? cb(new Error('No mapping found for index ' + self.collection.index)) : false;\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 {KuzzleDataMapping}\n\t */\n\tKuzzleDataMapping.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\tKuzzleDataMapping.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 = KuzzleDataMapping;\n\n\n/***/ },\n/* 6 */\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 * KuzzleDocument 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 {object} kuzzleDataCollection - an instanciated KuzzleDataCollection 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 * @constructor\n\t */\n\tfunction KuzzleDocument(kuzzleDataCollection, documentId, content) {\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t collection: {\n\t value: kuzzleDataCollection.collection,\n\t enumerable: true\n\t },\n\t dataCollection: {\n\t value: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.kuzzle,\n\t enumerable: true\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(kuzzleDataCollection.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 });\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\tKuzzleDocument.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._version = this.version;\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\tKuzzleDocument.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 * - metadata (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\tKuzzleDocument.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('KuzzleDocument.delete: cannot delete a document without a document ID');\n\t }\n\t\n\t if (cb) {\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'delete'), this.serialize(), options, function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, self.id);\n\t });\n\t } else {\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'delete'), this.serialize(), options);\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\tKuzzleDocument.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('KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided');\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDocument.refresh', cb);\n\t\n\t self.kuzzle.query(self.dataCollection.buildQueryArgs('read', '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 KuzzleDocument(self.dataCollection, self.id, res.result._source);\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 * - metadata (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\tKuzzleDocument.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('write', 'createOrReplace'), data, options, function (error, res) {\n\t if (error) {\n\t return cb ? cb(error) : false;\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 * - metadata (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\tKuzzleDocument.prototype.publish = function (options) {\n\t var data = this.serialize();\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('write', '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\tKuzzleDocument.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\tKuzzleDocument.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('KuzzleDocument.subscribe', cb);\n\t\n\t if (!this.id) {\n\t throw new Error('KuzzleDocument.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\tKuzzleDocument.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 = KuzzleDocument;\n\n\n/***/ },\n/* 7 */\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 * 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), excepting:\n\t * * all cluster based functions\n\t * * all script based functions\n\t * * all cursors functions\n\t *\n\t * For instance:\n\t * kuzzle.memoryStorage\n\t * .set('myKey', 'myValue')\n\t * .get('myKey', function (err, response) {\n\t * console.log(response.result);\n\t *\n\t * // { _id: 'foo', body: { value: 'myValue' }}\n\t * });\n\t *\n\t *\n\t * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @constructor\n\t */\n\tfunction KuzzleMemoryStorage(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\n\t/**\n\t * constructs the memoryStorage functions.\n\t */\n\t(function() {\n\t\n\t var\n\t keyVal = ['id', 'value'],\n\t idOrKeys = ['id', 'keys'],\n\t commands = {\n\t append: keyVal,\n\t bgrewriteaof: [],\n\t bgsave: [],\n\t bitcount: ['id', 'start', 'end'],\n\t bitop: ['operation', 'destkey', idOrKeys],\n\t bitpos: ['id', 'bit', { __opts__: ['start', 'end']}],\n\t blpop: [idOrKeys, 'timeout'],\n\t brpoplpush: ['source', 'destination'],\n\t dbsize: [],\n\t decrby: keyVal,\n\t del: [idOrKeys],\n\t discard: [],\n\t exec: [],\n\t exists: [idOrKeys],\n\t expire: ['id', 'seconds'],\n\t expireat: ['id', 'timestamp'],\n\t flushdb: [],\n\t // @todo: implement geolocation methods once available in Redis stable release\n\t getbit: ['id', 'offset'],\n\t getrange: ['id', 'start', 'end'],\n\t hdel: ['id', ['field', 'fields']],\n\t hexists: ['id', 'field'],\n\t hincrby: ['id', 'field', 'value'],\n\t hmset: ['id', 'values'],\n\t hset: ['id', 'field', 'value'],\n\t info: ['section'],\n\t keys: [ 'pattern' ],\n\t lastsave: [],\n\t lindex: ['id', 'idx'],\n\t linsert: ['id', 'position', 'pivot', 'value'],\n\t lpush: ['id', ['value', 'values']],\n\t lrange: ['id', 'start', 'stop'],\n\t lrem: ['id', 'count', 'value'],\n\t lset: ['id', 'idx', 'value'],\n\t ltrim: ['id', 'start', 'stop'],\n\t mset: ['values'],\n\t multi: [],\n\t object: ['subcommand', 'args'],\n\t pexpire: ['id', 'milliseconds'],\n\t pexpireat: ['id', 'timestamp'],\n\t pfadd: ['id', ['element', 'elements']],\n\t pfmerge: ['destkey', ['sourcekey', 'sourcekeys']],\n\t ping: [],\n\t psetex: ['id', 'milliseconds', 'value'],\n\t publish: ['channel', 'message'],\n\t randomkey: [],\n\t rename: ['id', 'newkey'],\n\t renamenx: ['id', 'newkey'],\n\t restore: ['id', 'ttl', 'content'],\n\t rpoplpush: ['source', 'destination'],\n\t sadd: ['id', ['member', 'members']],\n\t save: [],\n\t set: ['id', 'value', {__opts__:['ex', 'px', 'nx', 'xx']}],\n\t sdiffstore: ['destination', idOrKeys],\n\t setbit: ['id', 'offset', 'value'],\n\t setex: ['id', 'seconds', 'value'],\n\t setrange: ['id', 'offset', 'value'],\n\t sinterstore: ['destination', idOrKeys],\n\t sismember: ['id', 'member'],\n\t smove: ['id', 'destination', 'member'],\n\t sort: ['id', {__opts__:['by', 'offset', 'count', 'get', 'direction', 'alpha', 'store']}],\n\t spop: ['id', 'count'],\n\t srem: ['id', ['member', 'members']],\n\t sunionstore: ['destination', idOrKeys],\n\t unwatch: [],\n\t wait: ['numslaves', 'timeout'],\n\t zadd: ['id', {__opts__: ['nx', 'xx', 'ch', 'incr', 'score', 'member', 'members']}],\n\t zcount: ['id', 'min', 'max'],\n\t zincrby: ['id', 'value', 'member'],\n\t zinterstore: ['destination', idOrKeys, {__opts__: ['weight', 'weights', 'aggregate']}],\n\t zlexcount: ['id', 'min', 'max'],\n\t zrange: ['id', 'start', 'stop', {__opts__: ['withscores']}],\n\t zrangebylex: ['id', 'min', 'max', {__opts__: ['offset', 'count']}],\n\t zrangebyscore: ['id', 'min', 'max', {__opts__: ['withscores', 'offset', 'count']}],\n\t zrem: ['id', 'member'],\n\t zremrangebylex: ['id', 'min', 'max'],\n\t zremrangebyscore: ['id', 'min', 'max'],\n\t zrevrangebylex: ['id', 'max', 'min', {__opts__: ['offset', 'count']}],\n\t zrevrangebyscore: ['id', 'max', 'min', {__opts__: ['withscores', 'offset', 'count']}],\n\t zrevrank: ['id', 'member']\n\t };\n\t\n\t // unique argument key\n\t commands.decr = commands.get = commands.dump = commands.hgetall = commands.hkeys = commands.hlen = commands.hstrlen = commands.hvals = commands.incr = commands.llen = commands.lpop = commands.persist = commands.pttl = commands.rpop = commands.scard = commands.smembers = commands.strlen = commands.ttl = commands.type = commands.zcard = ['id'];\n\t\n\t // key value\n\t commands.getset = commands.lpushx = keyVal;\n\t\n\t // key key...\n\t commands.del = commands.exists = commands.mget = commands.pfcount = commands.sdiff = commands.sinter = commands.sunion = commands.watch = [idOrKeys];\n\t\n\t commands.incrby = commands.incrbyfloat = commands.decrby;\n\t commands.brpop = commands.blpop;\n\t commands.hget = commands.hexists;\n\t commands.hmget = commands.hdel;\n\t commands.hsetnx = commands.hset;\n\t commands.msetnx = commands.mset;\n\t commands.rpush = commands.lpush;\n\t commands.hincrbyfloat = commands.hincrby;\n\t commands.srandmember = commands.spop;\n\t commands.zrevrange = commands.zrange;\n\t commands.zscore = commands.zrevrank;\n\t\n\t Object.keys(commands).forEach(function (command) {\n\t KuzzleMemoryStorage.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 (typeof args[args.length - 1] === 'function') {\n\t cb = args.pop();\n\t }\n\t\n\t if (args.length && typeof args[args.length - 1] === 'object' && Object.keys(args[args.length - 1]).length === 1 && args[args.length - 1].queuable !== undefined) {\n\t options = args.pop();\n\t }\n\t\n\t commands[command].forEach(function (v, i) {\n\t if (args[i] === undefined) {\n\t return;\n\t }\n\t\n\t if (Array.isArray(v)) {\n\t v = Array.isArray(args[i]) ? v[1] : v[0];\n\t }\n\t\n\t if (v === 'id') {\n\t data._id = args[i];\n\t }\n\t else {\n\t if (!data.body) {\n\t data.body = {};\n\t }\n\t\n\t if (typeof v === 'object' && v.__opts__ !== undefined) {\n\t v.__opts__.forEach(function (arg) {\n\t if (args[i][arg] !== undefined) {\n\t data.body[arg] = args[i][arg];\n\t }\n\t });\n\t }\n\t else {\n\t data.body[v] = args[i];\n\t }\n\t }\n\t });\n\t\n\t this.kuzzle.query(query, data, options, cb);\n\t\n\t return this;\n\t\n\t };\n\t });\n\t\n\t})();\n\t\n\tmodule.exports = KuzzleMemoryStorage;\n\n\n/***/ },\n/* 8 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t uuid = __webpack_require__(3);\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} kuzzleDataCollection - an instantiated and valid kuzzle object\n\t * @param {object} [options] - subscription optional configuration\n\t * @constructor\n\t */\n\tfunction KuzzleRoom(kuzzleDataCollection, 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: uuid.v4()\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 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: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.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(kuzzleDataCollection.headers)),\n\t enumerable: true,\n\t writable: true\n\t },\n\t metadata: {\n\t value: (options && options.metadata) ? options.metadata : {},\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\tKuzzleRoom.prototype.count = function (cb) {\n\t var data;\n\t\n\t this.kuzzle.callbackRequired('KuzzleRoom.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 this;\n\t }\n\t\n\t if (!this.roomId) {\n\t throw new Error('KuzzleRoom.count: cannot count subscriptions on an inactive room');\n\t }\n\t\n\t this.kuzzle.query(this.collection.buildQueryArgs('subscribe', 'count'), data, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result.count);\n\t });\n\t\n\t return this;\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} cb - called for each new notification\n\t */\n\tKuzzleRoom.prototype.renew = function (filters, cb) {\n\t var\n\t now = Date.now(),\n\t subscribeQuery = {\n\t scope: this.scope,\n\t state: this.state,\n\t users: this.users\n\t },\n\t self = this;\n\t\n\t if (!cb && filters && typeof filters === 'function') {\n\t cb = filters;\n\t filters = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleRoom.renew', cb);\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 self;\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 = cb;\n\t self.kuzzle.subscriptions.pending[self.id] = self;\n\t return self;\n\t }\n\t\n\t if (self.subscribing) {\n\t self.queue.push({action: 'renew', args: [filters, cb]});\n\t return self;\n\t }\n\t\n\t self.unsubscribe();\n\t self.roomId = null;\n\t self.subscribing = true;\n\t self.callback = 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, this.headers);\n\t\n\t self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'on'), subscribeQuery, {metadata: self.metadata}, 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 throw 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 });\n\t\n\t return self;\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\tKuzzleRoom.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('subscribe', 'off'), {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('subscribe', 'off'), {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\tKuzzleRoom.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.error) {\n\t return this.callback(data.error);\n\t }\n\t\n\t if (data.action === 'jwtTokenExpired') {\n\t this.kuzzle.jwtToken = undefined;\n\t return this.kuzzle.emitEvent('jwtTokenExpired');\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 if (this.kuzzle.state !== 'connected' || this.subscribing) {\n\t return false;\n\t }\n\t return true;\n\t}\n\t\n\tmodule.exports = KuzzleRoom;\n\n\n/***/ },\n/* 9 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/**\n\t *\n\t * @param host\n\t * @param wsPort\n\t * @param ioPort\n\t * @returns {Object} tnstantiated WebSocket/Socket.IO object\n\t */\n\t\n\tfunction network(host, wsPort, ioPort) {\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__(11))(host, wsPort);\n\t }\n\t // otherwise fallback to socket.io, if available\n\t else if (window.io) {\n\t return new (__webpack_require__(10))(host, ioPort);\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__(!(function webpackMissingModule() { var e = new Error(\"Cannot find module \\\"./wrappers/wsnode\\\"\"); e.code = 'MODULE_NOT_FOUND'; throw e; }())))(host, wsPort);\n\t}\n\t\n\tmodule.exports = network;\n\n\n/***/ },\n/* 10 */\n/***/ function(module, exports) {\n\n\tfunction SocketIO(host, port) {\n\t this.host = host;\n\t this.port = port;\n\t this.socket = null;\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 this.socket = window.io('http://' + this.host + ':' + this.port, {\n\t reconnection: autoReconnect,\n\t reconnectionDelay: reconnectionDelay,\n\t forceNew: true\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.socket.on('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.socket.on('connect_error', 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.socket.on('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.socket.on('reconnect', callback);\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.socket.close();\n\t this.socket = null;\n\t };\n\t}\n\t\n\tmodule.exports = SocketIO;\n\n\n/***/ },\n/* 11 */\n/***/ function(module, exports) {\n\n\tfunction WSBrowsers(host, port) {\n\t var self = this;\n\t this.host = host;\n\t this.port = port;\n\t this.client = null;\n\t this.retrying = false;\n\t\n\t /*\n\t Listeners are stored using the following format:\n\t roomId: {\n\t fn: callback_function,\n\t once: boolean\n\t }\n\t */\n\t this.listeners = {\n\t error: [],\n\t connect: [],\n\t disconnect: [],\n\t reconnect: []\n\t };\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 this.client = new WebSocket('ws://' + this.host + ':' + this.port);\n\t\n\t this.client.onopen = function () {\n\t if (self.retrying) {\n\t poke(self.listeners, 'reconnect');\n\t }\n\t else {\n\t poke(self.listeners, 'connect');\n\t }\n\t };\n\t\n\t this.client.onclose = function () {\n\t poke(self.listeners, 'disconnect');\n\t };\n\t\n\t this.client.onerror = function () {\n\t if (autoReconnect) {\n\t self.retrying = true;\n\t setTimeout(function () {\n\t self.connect(autoReconnect, reconnectionDelay);\n\t }, reconnectionDelay);\n\t }\n\t\n\t poke(self.listeners, 'error');\n\t };\n\t\n\t this.client.onmessage = function (payload) {\n\t var data = JSON.parse(payload.data);\n\t\n\t if (data.room && self.listeners[data.room]) {\n\t poke(self.listeners, data.room, 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.listeners.connect.push({\n\t fn: callback,\n\t keep: true\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 this.listeners.error.push({\n\t fn: callback,\n\t keep: true\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 this.listeners.disconnect.push({\n\t fn: callback,\n\t keep: true\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 this.listeners.reconnect.push({\n\t fn: callback,\n\t keep: true\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 if (!this.listeners[roomId]) {\n\t this.listeners[roomId] = [];\n\t }\n\t\n\t this.listeners[roomId].push({\n\t fn: callback,\n\t keep: false\n\t });\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 if (!this.listeners[roomId]) {\n\t this.listeners[roomId] = [];\n\t }\n\t\n\t this.listeners[roomId].push({\n\t fn: callback,\n\t keep: true\n\t });\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 var index;\n\t\n\t if (this.listeners[roomId]) {\n\t index = this.listeners[roomId].findIndex(function (listener) {\n\t return listener.fn === callback;\n\t });\n\t\n\t if (index !== -1) {\n\t if (this.listeners[roomId].length === 1 && ['error', 'connect', 'disconnect', 'reconnect'].indexOf(roomId) === -1) {\n\t delete this.listeners[roomId];\n\t }\n\t else {\n\t this.listeners[roomId].splice(index, 1);\n\t }\n\t }\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 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.listeners = {\n\t error: [],\n\t connect: [],\n\t disconnect: [],\n\t reconnect: []\n\t };\n\t\n\t this.retrying = false;\n\t this.client.close();\n\t this.client = null;\n\t };\n\t}\n\t\n\t/**\n\t * Executes all registered listeners in the provided\n\t * \"listeners\" structure.\n\t *\n\t * Listeners are of the following format:\n\t * [\n\t * { fn: callback, once: boolean },\n\t * ...\n\t * ]\n\t *\n\t * @private\n\t * @param {Object} listeners\n\t * @param {string} roomId\n\t * @param {Object} [payload]\n\t */\n\tfunction poke (listeners, roomId, payload) {\n\t var\n\t i,\n\t length = listeners[roomId].length;\n\t\n\t for (i = 0; i < length; ++i) {\n\t listeners[roomId][i].fn(payload);\n\t\n\t if (!listeners[roomId][i].keep) {\n\t if (listeners[roomId].length > 1) {\n\t listeners[roomId].splice(i, 1);\n\t --i;\n\t --length;\n\t }\n\t else {\n\t delete listeners[roomId];\n\t }\n\t }\n\t }\n\t}\n\t\n\tmodule.exports = WSBrowsers;\n\n\n/***/ },\n/* 12 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleProfile(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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\tKuzzleProfile.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleProfile\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 {Object} this\n\t */\n\tKuzzleProfile.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.kuzzleSecurity.buildQueryArgs('createOrReplaceProfile'), data, options, function (error) {\n\t if (error) {\n\t return cb ? cb(error) : false;\n\t }\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/**\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 {KuzzleProfile} this\n\t */\n\tKuzzleProfile.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 {KuzzleProfile} this\n\t */\n\tKuzzleProfile.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\tKuzzleProfile.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\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\tKuzzleProfile.prototype.getPolicies = function () {\n\t return this.content.policies;\n\t};\n\t\n\tmodule.exports = KuzzleProfile;\n\n\n/***/ },\n/* 13 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleRole(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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\tKuzzleRole.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleRole\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 */\n\tKuzzleRole.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.kuzzleSecurity.buildQueryArgs('createOrReplaceRole'), data, options, function (error) {\n\t if (error) {\n\t return cb ? cb(error) : false;\n\t }\n\t\n\t if (cb) {\n\t cb(null, self);\n\t }\n\t });\n\t};\n\t\n\tmodule.exports = KuzzleRole;\n\n/***/ },\n/* 14 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleRole = __webpack_require__(13),\n\t KuzzleProfile = __webpack_require__(12),\n\t KuzzleUser = __webpack_require__(2);\n\t\n\t/**\n\t * Kuzzle security constructor\n\t *\n\t * @param kuzzle\n\t * @returns {KuzzleSecurity}\n\t * @constructor\n\t */\n\tfunction KuzzleSecurity(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 = ['roleFactory', 'profileFactory', 'userFactory', '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} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getRole = 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 getRole 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('KuzzleSecurity.getRole', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, new KuzzleRole(self, response.result._id, response.result._source));\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} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t *\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.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 KuzzleRole(self, doc._id, doc._source);\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.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 if (cb) {\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, 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 KuzzleRole(self, res.result._id, res.result._source);\n\t cb(null, doc);\n\t });\n\t } else {\n\t self.kuzzle.query(this.buildQueryArgs(action), data);\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.updateRole = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'updateRole';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.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 data._id = id;\n\t data.body = content;\n\t\n\t if (cb) {\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, function (err) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, new KuzzleRole(self, id, content));\n\t });\n\t } else {\n\t self.kuzzle.query(this.buildQueryArgs(action), data);\n\t }\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleSecurity.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 if (cb) {\n\t this.kuzzle.query(this.buildQueryArgs('deleteRole'), data, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result._id);\n\t });\n\t } else {\n\t this.kuzzle.query(this.buildQueryArgs('deleteRole'), data, options);\n\t }\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleRole 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 * @constructor\n\t */\n\tKuzzleSecurity.prototype.roleFactory = function(id, content) {\n\t return new KuzzleRole(this, id, content);\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} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getProfile = 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 getProfile function');\n\t }\n\t\n\t\n\t data = {_id: id};\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.getProfile', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n\t if (error) {\n\t return cb(error);\n\t }\n\t\n\t cb(null, new KuzzleProfile(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.searchProfiles', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n\t var documents;\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 KuzzleProfile(self, doc._id, doc._source);\n\t });\n\t\n\t cb(null, { total: response.result.total, profiles: documents });\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 {object} content - attribute `roles` in `content` must only contains an array of role id\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.createProfile = function (id, content, 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('KuzzleSecurity.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 data.body = content;\n\t\n\t if (options) {\n\t action = options.replaceIfExist ? 'createOrReplaceProfile' : 'createProfile';\n\t }\n\t\n\t if (cb) {\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, 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 KuzzleProfile(self, res.result._id, res.result._source);\n\t cb(null, doc);\n\t });\n\t } else {\n\t self.kuzzle.query(this.buildQueryArgs(action), data);\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 {object} content - a plain javascript object representing the profile's modification\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.updateProfile = function (id, content, 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('KuzzleSecurity.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 data.body = content;\n\t\n\t if (cb) {\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, 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 KuzzleProfile(self, res.result._id, updatedContent));\n\t });\n\t } else {\n\t self.kuzzle.query(this.buildQueryArgs(action), data);\n\t }\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleSecurity.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 if (cb) {\n\t this.kuzzle.query(this.buildQueryArgs('deleteProfile'), data, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result._id);\n\t });\n\t } else {\n\t this.kuzzle.query(this.buildQueryArgs('deleteProfile'), data, options);\n\t }\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleProfile 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 * @constructor\n\t */\n\tKuzzleSecurity.prototype.profileFactory = function(id, content) {\n\t return new KuzzleProfile(this, id, content);\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} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getUser = function (id, options, cb) {\n\t var\n\t data,\n\t self = this;\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('Id parameter is mandatory for getUser 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('KuzzleSecurity.getUser', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, new KuzzleUser(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.searchUsers', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n\t var documents;\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 KuzzleUser(self, doc._id, doc._source);\n\t });\n\t\n\t cb(null, { total: response.result.total, users: documents });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new user 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 user already exists: throw an error if sets to false.\n\t * Replace the existing user otherwise\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.createUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'createUser';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.createUser: cannot create 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 data._id = id;\n\t data.body = content;\n\t\n\t if (options) {\n\t action = options.replaceIfExist ? 'createOrReplaceUser' : 'createUser';\n\t }\n\t\n\t if (cb) {\n\t self.kuzzle.query(this.buildQueryArgs(action), data, null, 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 KuzzleUser(self, res.result._id, res.result._source);\n\t cb(null, doc);\n\t });\n\t } else {\n\t self.kuzzle.query(this.buildQueryArgs(action), data);\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.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 if (cb) {\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, new KuzzleUser(self, res.result._id, res.result._source));\n\t });\n\t } else {\n\t self.kuzzle.query(this.buildQueryArgs(action), data, options);\n\t }\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleSecurity.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 if (cb) {\n\t this.kuzzle.query(this.buildQueryArgs('deleteUser'), data, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result._id);\n\t });\n\t } else {\n\t this.kuzzle.query(this.buildQueryArgs('deleteUser'), data, options);\n\t }\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleUser 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 * @constructor\n\t */\n\tKuzzleSecurity.prototype.userFactory = function(id, content) {\n\t return new KuzzleUser(this, id, content);\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\tKuzzleSecurity.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.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} [options] - (optional) arguments\n\t * @param {function} cb The callback containing the normalized array of rights.\n\t */\n\tKuzzleSecurity.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, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, res.result.hits);\n\t });\n\t};\n\t\n\tmodule.exports = KuzzleSecurity;\n\n\n/***/ }\n/******/ ])\n});\n;\n\n\n/** WEBPACK FOOTER **\n ** kuzzle.js\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/** WEBPACK FOOTER **\n ** webpack/bootstrap 38194c1d337051971b30\n **/","var\n uuid = require('node-uuid'),\n KuzzleDataCollection = require('./kuzzleDataCollection'),\n KuzzleSecurity = require('./security/kuzzleSecurity'),\n KuzzleMemoryStorage = require('./kuzzleMemoryStorage'),\n KuzzleUser = require('./security/kuzzleUser'),\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 * @constructor\n */\nmodule.exports = Kuzzle = function (host, options, cb) {\n var self = this;\n\n if (!(this instanceof Kuzzle)) {\n return new Kuzzle(host, options, cb);\n }\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 collections: {\n value: {},\n writable: true\n },\n connectCB: {\n value: cb\n },\n eventListeners: {\n value: {\n connected: {lastEmitted: null, listeners: []},\n error: {lastEmitted: null, listeners: []},\n disconnected: {lastEmitted: null, listeners: []},\n reconnected: {lastEmitted: null, listeners: []},\n jwtTokenExpired: {lastEmitted: null, listeners: []},\n loginAttempt: {lastEmitted: null, listeners: []},\n offlineQueuePush: {listeners: []},\n offlineQueuePop: {listeners: []}\n }\n },\n eventTimeout: {\n value: 200\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 'roomId': {\n kuzzleRoomID_1: kuzzleRoomInstance_1,\n kuzzleRoomID_2: kuzzleRoomInstance_2,\n kuzzleRoomID_...: 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 // read-only properties\n autoReconnect: {\n value: (options && typeof options.autoReconnect === 'boolean') ? options.autoReconnect : 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 enumerable: true\n },\n host: {\n value: host,\n enumerable: true\n },\n wsPort: {\n value: (options && typeof options.wsPort === 'number') ? options.wsPort : 7513,\n enumerable: true\n },\n ioPort: {\n value: (options && typeof options.ioPort === 'number') ? options.ioPort : 7512,\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 metadata: {\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: null,\n enumerable: true,\n writable: true\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 KuzzleSecurity(this),\n enumerable: true\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 Object.defineProperty(this, 'emitEvent', {\n value: function emitEvent(event) {\n var\n now = Date.now(),\n args = Array.prototype.slice.call(arguments, 1),\n eventProperties = this.eventListeners[event];\n\n if (eventProperties.lastEmitted && eventProperties.lastEmitted >= now - this.eventTimeout) {\n return false;\n }\n\n eventProperties.listeners.forEach(function (listener) {\n process.nextTick(function () {\n listener.fn.apply(undefined, args);\n });\n });\n\n // Events without the 'lastEmitted' property can be emitted without minimum time between emissions\n if (eventProperties.lastEmitted !== undefined) {\n eventProperties.lastEmitted = now;\n }\n }\n });\n\n Object.defineProperty(this, 'memoryStorage', {\n value: new KuzzleMemoryStorage(this),\n enumerable: true\n });\n\n\n if (!options || !options.connect || options.connect === 'auto') {\n this.connect();\n } else {\n this.state = 'ready';\n }\n\n cleanHistory(this.requestHistory);\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', 'listIndexes', 'login', 'logout', 'now', 'query',\n 'checkToken', 'whoAmI', 'updateSelf', 'getMyRights',\n 'refreshIndex', 'getAutoRefresh', 'setAutoRefresh'\n ];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n};\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.network = networkWrapper(self.host, self.wsPort, self.ioPort);\n }\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.onConnectError(function (error) {\n var connectionError = new Error('Unable to connect to kuzzle server at \"' + self.host + '\"');\n\n connectionError.internal = error;\n self.state = 'error';\n self.emitEvent('error', connectionError);\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('jwtTokenExpired');\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 * 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 * @returns {Kuzzle}\n */\nKuzzle.prototype.login = function (strategy) {\n var\n self = this,\n request = {\n strategy: strategy\n },\n credentials,\n cb;\n\n // Handle arguments (credentials, expiresIn, cb)\n if (arguments[1]) {\n if (typeof arguments[1] === 'object') {\n credentials = 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 if (typeof credentials === 'object') {\n Object.keys(credentials).forEach(function (key) {\n request[key] = credentials[key];\n });\n }\n\n this.query({controller: 'auth', action: 'login'}, {body: request}, {queuable: false}, function(error, response) {\n if (!error) {\n if (response.result.jwt) {\n self.setJwtToken(response.result.jwt);\n }\n\n if (cb && typeof cb === 'function') {\n cb(null, response.result);\n }\n }\n else {\n if (cb && typeof cb === 'function') {\n cb(error);\n }\n\n self.emitEvent('loginAttempt', {success: false, error: error.message});\n }\n });\n\n return self;\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: uuid.v4(),\n body: {}\n };\n\n this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, function(error) {\n if (error === null) {\n self.jwtToken = undefined;\n\n if (typeof cb === 'function') {\n cb(null, self);\n }\n }\n else if (typeof cb === 'function') {\n cb(error);\n }\n });\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} callback The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n * @return {Kuzzle} The Kuzzle instance to enable chaining.\n */\nKuzzle.prototype.checkToken = function (token, callback) {\n var\n self = this,\n request = {\n body: {\n token: token\n }\n };\n\n this.callbackRequired('Kuzzle.checkToken', callback);\n\n this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, function (err, response) {\n if (err) {\n return callback(err);\n }\n\n callback(null, response.result);\n });\n\n return self;\n};\n\n/**\n * Fetches the current user.\n *\n * @param {function} callback The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n * @return {Kuzzle} The Kuzzle instance to enable chaining.\n */\nKuzzle.prototype.whoAmI = function (callback) {\n var self = this;\n\n self.callbackRequired('Kuzzle.whoAmI', callback);\n\n self.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, function (err, response) {\n if (err) {\n return callback(err);\n }\n\n callback(null, new KuzzleUser(self.security, response.result._id, response.result._source));\n });\n\n return self;\n};\n\n/**\n * Gets the rights array of the currently logged user.\n *\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'}, {}, null, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, 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 */\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 if (cb) {\n self.query(queryArgs, data, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result);\n });\n } else {\n self.query(queryArgs, data, options);\n }\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 setTimeout(function () {\n cleanHistory(requestHistory);\n }, 1000);\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 if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n self.jwtToken = undefined;\n self.emitEvent('jwtTokenExpired', request, cb);\n }\n\n if (cb) {\n cb(response.error, response);\n }\n });\n }\n\n this.network.send(request);\n\n // Track requests made to allow KuzzleRoom.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 * 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 * The ID returned by this function is required to remove this listener at a later time.\n *\n * @param {string} event - name of the global event to subscribe to (see the 'eventListeners' object property)\n * @param {function} listener - callback to invoke each time an event is fired\n * @returns {string} Unique listener ID\n */\nKuzzle.prototype.addListener = function(event, listener) {\n var\n knownEvents = Object.keys(this.eventListeners),\n listenerType = typeof listener,\n listenerId;\n\n this.isValid();\n\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n if (listenerType !== 'function') {\n throw new Error('Invalid listener type: expected a function, got a ' + listenerType);\n }\n\n listenerId = uuid.v4();\n this.eventListeners[event].listeners.push({id: listenerId, fn: listener});\n return listenerId;\n};\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 * @returns {object} this\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:'admin', action: 'getAllStats'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result.hits);\n });\n\n return this;\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 * @returns {object} this\n */\nKuzzle.prototype.getStatistics = function (timestamp, options, cb) {\n var queryCB;\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 if (timestamp) {\n cb(null, res.result.hits);\n } else {\n cb(null, [res.result]);\n }\n };\n\n this.callbackRequired('Kuzzle.getStatistics', cb);\n\n if (!timestamp) {\n this.query({controller: 'admin', action: 'getLastStats'}, {}, options, queryCB);\n } else {\n this.query({controller: 'admin', action: 'getStats'}, { body: { startTime: timestamp } }, options, queryCB);\n }\n\n return this;\n};\n\n/**\n * Create a new instance of a KuzzleDataCollection 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 {object} A KuzzleDataCollection instance\n */\nKuzzle.prototype.dataCollectionFactory = 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') {\n throw new Error('Invalid \"index\" argument: string expected, got ' + typeof index);\n }\n\n if (typeof collection !== 'string') {\n throw new Error('Invalid \"collection\" argument: string expected, got ' + typeof collection);\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 KuzzleDataCollection(this, index, collection);\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 * @returns {object} this\n */\nKuzzle.prototype.listCollections = function () {\n var\n collectionType = 'all',\n index,\n options,\n cb,\n args = Array.prototype.slice.call(arguments);\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 if (options && options.type) {\n collectionType = options.type;\n }\n\n this.query({index: index, controller: 'read', action: 'listCollections'}, {body: {type: collectionType}}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n return cb(null, res.result.collections);\n });\n\n return this;\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 * @returns {object} this\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: 'read', action: 'listIndexes'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n return cb(null, res.result.indexes);\n });\n\n return this;\n};\n\n/**\n * Disconnects from Kuzzle and invalidate this instance.\n */\nKuzzle.prototype.disconnect = function () {\n var collection;\n\n this.logout();\n\n this.state = 'disconnected';\n this.network.close();\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 * @returns {object} this\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: 'read', action: 'serverInfo'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result.serverInfo);\n });\n\n return this;\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: 'admin', action: 'refreshIndex'}, {}, 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 * @returns {object} this\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: 'admin', action: 'getAutoRefresh'}, {}, options, cb);\n\n return this;\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: 'admin', 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 * @returns {object} this\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: 'read', action: 'now'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result.now);\n });\n\n return this;\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 * - metadata (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 metadata: this.metadata\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.metadata) {\n Object.keys(options.metadata).forEach(function (meta) {\n object.metadata[meta] = options.metadata[meta];\n });\n }\n\n if (options.queuable === false && self.state === 'offline') {\n return self;\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.metadata) {\n Object.keys(query.metadata).forEach(function (meta) {\n object.metadata[meta] = query.metadata[meta];\n });\n }\n\n for (attr in query) {\n if (attr !== 'metadata' && 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.headers = object.headers || {};\n object.headers.authorization = 'Bearer ' + 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 = uuid.v4();\n }\n\n if (self.state === 'connected' || (options && options.queuable === false)) {\n if (self.state === 'connected') {\n emitRequest.call(this, object, cb);\n } else if (cb) {\n cb(new Error('Unable to execute request: not connected to a Kuzzle server.\\nDiscarded request: ' + JSON.stringify(object)));\n }\n } else if (self.queuing || ['initializing', 'connecting'].indexOf(self.state) !== -1) {\n cleanQueue.call(this, object, cb);\n\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 }\n }\n\n return self;\n};\n\n/**\n * Removes all listeners, either from a specific event or from all events\n *\n * @param {string} event - One of the event described in the Event Handling section of this documentation\n */\nKuzzle.prototype.removeAllListeners = function (event) {\n var\n knownEvents = Object.keys(this.eventListeners),\n self = this;\n\n if (event) {\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n this.eventListeners[event].listeners = [];\n } else {\n knownEvents.forEach(function (eventName) {\n self.eventListeners[eventName].listeners = [];\n });\n }\n};\n\n/**\n * Removes a listener from an event.\n *\n * @param {string} event - One of the event described in the Event Handling section of this documentation\n * @param {string} listenerId - The ID returned by addListener\n */\nKuzzle.prototype.removeListener = function (event, listenerId) {\n var\n knownEvents = Object.keys(this.eventListeners),\n self = this;\n\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n this.eventListeners[event].listeners.forEach(function (listener, index) {\n if (listener.id === listenerId) {\n self.eventListeners[event].listeners.splice(index, 1);\n }\n });\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\n\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzle.js\n ** module id = 0\n ** module chunks = 0\n **/","function KuzzleSecurityDocument(kuzzleSecurity, id, content) {\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: kuzzleSecurity.kuzzle\n },\n kuzzleSecurity: {\n value: kuzzleSecurity\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 });\n\n if (content) {\n this.setContent(content, true);\n }\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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 {Object} this\n */\nKuzzleSecurityDocument.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 */\nKuzzleSecurityDocument.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\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 */\nKuzzleSecurityDocument.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.kuzzleSecurity.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 */\nKuzzleSecurityDocument.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.kuzzleSecurity.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\nmodule.exports = KuzzleSecurityDocument;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleSecurityDocument.js\n ** module id = 1\n ** module chunks = 0\n **/","var\n KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleUser(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteUser'\n },\n updateActionName: {\n value: 'updateUser'\n }\n });\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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\nKuzzleUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleUser\n }\n});\n\n/**\n * Set profiles in content\n * @param {array} profile - an array of profiles ids string\n *\n * @returns {KuzzleUser} this\n */\nKuzzleUser.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 * Add a profile\n * @param {string} profile - a profile ids string\n *\n * @returns {KuzzleUser} this\n */\nKuzzleUser.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 * Saves this user into Kuzzle.\n *\n * If this is a new user, this function will create it in Kuzzle.\n * Otherwise, this method will replace the latest version of this user in Kuzzle by the current content\n * of this object.\n *\n * @param {responseCallback} [cb] - Handles the query response\n * @param {object} [options] - Optional parameters\n * @returns {*} this\n */\nKuzzleUser.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.kuzzleSecurity.buildQueryArgs('createOrReplaceUser'), data, options, function (error) {\n if (error) {\n return cb ? cb(error) : false;\n }\n\n if (cb) {\n cb(null, self);\n }\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 */\nKuzzleUser.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\n return data;\n};\n\n/**\n * Return the associated profiles IDs\n *\n * @return {array} the associated profiles IDs\n */\nKuzzleUser.prototype.getProfiles = function () {\n return this.content.profileIds;\n};\n\nmodule.exports = KuzzleUser;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleUser.js\n ** module id = 2\n ** module chunks = 0\n **/","// uuid.js\n//\n// Copyright (c) 2010-2012 Robert Kieffer\n// MIT License - http://opensource.org/licenses/mit-license.php\n\n/*global window, require, define */\n(function(_window) {\n 'use strict';\n\n // Unique ID creation requires a high quality random # generator. We feature\n // detect to determine the best RNG source, normalizing to a function that\n // returns 128-bits of randomness, since that's what's usually required\n var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot;\n\n function setupBrowser() {\n // Allow for MSIE11 msCrypto\n var _crypto = _window.crypto || _window.msCrypto;\n\n if (!_rng && _crypto && _crypto.getRandomValues) {\n // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto\n //\n // Moderately fast, high quality\n try {\n var _rnds8 = new Uint8Array(16);\n _whatwgRNG = _rng = function whatwgRNG() {\n _crypto.getRandomValues(_rnds8);\n return _rnds8;\n };\n _rng();\n } catch(e) {}\n }\n\n if (!_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 _mathRNG = _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 if ('undefined' !== typeof console && console.warn) {\n console.warn(\"[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()\");\n }\n }\n }\n\n function setupNode() {\n // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html\n //\n // Moderately fast, high quality\n if ('function' === typeof require) {\n try {\n var _rb = require('crypto').randomBytes;\n _nodeRNG = _rng = _rb && function() {return _rb(16);};\n _rng();\n } catch(e) {}\n }\n }\n\n if (_window) {\n setupBrowser();\n } else {\n setupNode();\n }\n\n // Buffer class to use\n var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;\n\n // Maps for number <-> hex string conversion\n var _byteToHex = [];\n var _hexToByte = {};\n for (var i = 0; i < 256; i++) {\n _byteToHex[i] = (i + 0x100).toString(16).substr(1);\n _hexToByte[_byteToHex[i]] = i;\n }\n\n // **`parse()` - Parse a UUID into it's component bytes**\n function parse(s, buf, offset) {\n var i = (buf && offset) || 0, ii = 0;\n\n buf = buf || [];\n s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {\n if (ii < 16) { // Don't overflow!\n buf[i + ii++] = _hexToByte[oct];\n }\n });\n\n // Zero out remaining bytes if string was short\n while (ii < 16) {\n buf[i + ii++] = 0;\n }\n\n return buf;\n }\n\n // **`unparse()` - Convert UUID byte array (ala parse()) into a string**\n function unparse(buf, offset) {\n var i = offset || 0, 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\n // **`v1()` - Generate time-based UUID**\n //\n // Inspired by https://github.com/LiosK/UUID.js\n // and http://docs.python.org/library/uuid.html\n\n // random #'s we need to init node and clockseq\n var _seedBytes = _rng();\n\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n var _nodeId = [\n _seedBytes[0] | 0x01,\n _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]\n ];\n\n // Per 4.2.2, randomize (14 bit) clockseq\n var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;\n\n // Previous uuid creation time\n var _lastMSecs = 0, _lastNSecs = 0;\n\n // See https://github.com/broofa/node-uuid for API details\n function v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || [];\n\n options = options || {};\n\n var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;\n\n // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n var msecs = (options.msecs != null) ? options.msecs : new Date().getTime();\n\n // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;\n\n // Time since last uuid creation (in msecs)\n var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\n // Per 4.2.1.2, Bump clockseq on clock regression\n if (dt < 0 && options.clockseq == null) {\n clockseq = clockseq + 1 & 0x3fff;\n }\n\n // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {\n nsecs = 0;\n }\n\n // Per 4.2.1.2 Throw error if too many uuids are requested\n if (nsecs >= 10000) {\n throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq;\n\n // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n msecs += 12219292800000;\n\n // `time_low`\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff;\n\n // `time_mid`\n var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff;\n\n // `time_high_and_version`\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n b[i++] = tmh >>> 16 & 0xff;\n\n // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n b[i++] = clockseq >>> 8 | 0x80;\n\n // `clock_seq_low`\n b[i++] = clockseq & 0xff;\n\n // `node`\n var node = options.node || _nodeId;\n for (var n = 0; n < 6; n++) {\n b[i + n] = node[n];\n }\n\n return buf ? buf : unparse(b);\n }\n\n // **`v4()` - Generate random UUID**\n\n // See https://github.com/broofa/node-uuid for API details\n function v4(options, buf, offset) {\n // Deprecated - 'format' argument, as supported in v1.2\n var i = buf && offset || 0;\n\n if (typeof(options) === 'string') {\n buf = (options === 'binary') ? new BufferClass(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 || unparse(rnds);\n }\n\n // Export public API\n var uuid = v4;\n uuid.v1 = v1;\n uuid.v4 = v4;\n uuid.parse = parse;\n uuid.unparse = unparse;\n uuid.BufferClass = BufferClass;\n uuid._rng = _rng;\n uuid._mathRNG = _mathRNG;\n uuid._nodeRNG = _nodeRNG;\n uuid._whatwgRNG = _whatwgRNG;\n\n if (('undefined' !== typeof module) && module.exports) {\n // Publish as node.js module\n module.exports = uuid;\n } else if (typeof define === 'function' && define.amd) {\n // Publish as AMD module\n define(function() {return uuid;});\n\n\n } else {\n // Publish as global (in browsers)\n _previousRoot = _window.uuid;\n\n // **`noConflict()` - (browser only) to reset global 'uuid' var**\n uuid.noConflict = function() {\n _window.uuid = _previousRoot;\n return uuid;\n };\n\n _window.uuid = uuid;\n }\n})('undefined' !== typeof window ? window : null);\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ../~/node-uuid/uuid.js\n ** module id = 3\n ** module chunks = 0\n **/","var\n KuzzleDocument = require('./kuzzleDocument'),\n KuzzleDataMapping = require('./kuzzleDataMapping'),\n KuzzleRoom = require('./kuzzleRoom');\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 * @param {object} kuzzle - Kuzzle instance to inherit from\n * @param {string} index - Index containing the data collection\n * @param {string} collection - name of the data collection to handle\n * @constructor\n */\nfunction KuzzleDataCollection(kuzzle, index, collection) {\n if (!index || !collection) {\n throw new Error('The KuzzleDataCollection object constructor needs an index and a collection arguments');\n }\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 * 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 * @returns {Object} this\n */\nKuzzleDataCollection.prototype.advancedSearch = function (filters, options, cb) {\n var\n query,\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleDataCollection.advancedSearch', cb);\n\n query = self.kuzzle.addHeaders({body: filters}, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('read', '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 KuzzleDocument(self, doc._id, doc._source);\n\n newDocument.version = doc._version;\n\n documents.push(newDocument);\n });\n\n cb(null, { total: result.result.total, documents: documents });\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 * @returns {Object} this\n */\nKuzzleDataCollection.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('KuzzleDataCollection.count', cb);\n\n query = this.kuzzle.addHeaders({body: filters}, this.headers);\n\n this.kuzzle.query(this.buildQueryArgs('read', 'count'), query, options, function (error, result) {\n if (error) {\n return cb(error);\n }\n\n cb(null, result.result.count);\n });\n\n return this;\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 */\nKuzzleDataCollection.prototype.create = 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('write', 'createCollection'), data, options, cb);\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 * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n * - updateIfExist (boolean, default: false):\n * If the same document already exists: throw an error if sets to false.\n * Update the existing document otherwise\n *\n * @param {string} [id] - (optional) document identifier\n * @param {object} document - either an instance of a KuzzleDocument object, or a document\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Object} this\n */\nKuzzleDataCollection.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 KuzzleDocument) {\n data = document.serialize();\n } else {\n data.body = document;\n }\n\n if (options) {\n action = options.updateIfExist ? 'createOrReplace' : 'create';\n }\n\n if (id) {\n data._id = id;\n }\n\n data = self.kuzzle.addHeaders(data, self.headers);\n\n if (cb) {\n self.kuzzle.query(this.buildQueryArgs('write', action), data, options, function (err, res) {\n var doc;\n\n if (err) {\n return cb(err);\n }\n\n doc = new KuzzleDocument(self, res.result._id, res.result._source);\n doc.version = res.result._version;\n cb(null, doc);\n });\n } else {\n self.kuzzle.query(this.buildQueryArgs('write', action), data, options);\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 * - metadata (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 {Object} this\n */\nKuzzleDataCollection.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 = 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 if (cb) {\n this.kuzzle.query(this.buildQueryArgs('write', action), data, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n if (action === 'delete') {\n cb(null, [res.result._id]);\n } else {\n cb(null, res.result.ids);\n }\n });\n } else {\n this.kuzzle.query(this.buildQueryArgs('write', action), data, options);\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 * @returns {Object} this\n */\nKuzzleDataCollection.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('KuzzleDataCollection.fetch', cb);\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('read', 'get'), data, options, function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new KuzzleDocument(self, res.result._id, res.result._source);\n document.version = res.result._version;\n cb(null, document);\n });\n\n return this;\n};\n\n/**\n * Retrieves all documents stored in this data collection\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n * @returns {Object} this\n */\nKuzzleDataCollection.prototype.fetchAllDocuments = function (options, cb) {\n var filters = {};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n // copying pagination options to the search filter\n if (options) {\n if (options.from) {\n filters.from = options.from;\n }\n\n if (options.size) {\n filters.size = options.size;\n }\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.fetchAll', cb);\n\n this.advancedSearch(filters, options, cb);\n\n return this;\n};\n\n\n/**\n * Instantiates a KuzzleDataMapping object containing the current mapping of this collection.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated KuzzleDataMapping object\n * @return {object} this\n */\nKuzzleDataCollection.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('KuzzleDataCollection.getMapping', cb);\n\n kuzzleMapping = new KuzzleDataMapping(this);\n kuzzleMapping.refresh(options, cb);\n\n return this;\n};\n\n/**\n * Publish a realtime message\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} document - either a KuzzleDocument instance or a JSON object\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Returns a raw Kuzzle response\n * @returns {*} this\n */\nKuzzleDataCollection.prototype.publishMessage = function (document, options, cb) {\n var data = {};\n\n if (document instanceof KuzzleDocument) {\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('write', '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 * - metadata (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 KuzzleDocument object\n * @return {object} this\n */\nKuzzleDataCollection.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 if (cb) {\n self.kuzzle.query(this.buildQueryArgs('write', 'createOrReplace'), data, options, function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new KuzzleDocument(self, res.result._id, res.result._source);\n document.version = res.result._version;\n cb(null, document);\n });\n } else {\n self.kuzzle.query(this.buildQueryArgs('write', 'createOrReplace'), data, options);\n }\n\n return this;\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 {*} KuzzleRoom object\n */\nKuzzleDataCollection.prototype.subscribe = function (filters, options, cb) {\n var room;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.subscribe', cb);\n\n room = new KuzzleRoom(this, options);\n\n return room.renew(filters, cb);\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 */\nKuzzleDataCollection.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('admin', 'truncateCollection'), 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 * - metadata (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 KuzzleDocument object\n * @return {object} this\n */\nKuzzleDataCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n var\n 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 data = self.kuzzle.addHeaders(data, this.headers);\n\n if (cb) {\n self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options, function (err, res) {\n var doc;\n if (err) {\n return cb(err);\n }\n\n doc = new KuzzleDocument(self, res.result._id);\n doc.refresh(cb);\n });\n } else {\n self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options);\n }\n\n return self;\n};\n\n\n/**\n * Instantiate a new KuzzleDocument 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 */\nKuzzleDataCollection.prototype.documentFactory = function (id, content) {\n return new KuzzleDocument(this, id, content);\n};\n\n/**\n * Instantiate a new KuzzleRoom 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 */\nKuzzleDataCollection.prototype.roomFactory = function (options) {\n return new KuzzleRoom(this, options);\n};\n\n/**\n * Instantiate a new KuzzleDataMapping 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 KuzzleDataMapping object with\n * @constructor\n */\nKuzzleDataCollection.prototype.dataMappingFactory = function (mapping) {\n return new KuzzleDataMapping(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 */\nKuzzleDataCollection.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\nmodule.exports = KuzzleDataCollection;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDataCollection.js\n ** module id = 4\n ** module chunks = 0\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 * 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 KuzzleDataMapping object allow to get the current mapping of a data collection and to modify it if needed.\n *\n * @param {object} kuzzleDataCollection - Instance of the inherited KuzzleDataCollection object\n * @param {object} mapping - mappings\n * @constructor\n */\nfunction KuzzleDataMapping(kuzzleDataCollection, mapping) {\n Object.defineProperties(this, {\n //read-only properties\n collection: {\n value: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.kuzzle,\n enumerable: true\n },\n // writable properties\n headers: {\n value: JSON.parse(JSON.stringify(kuzzleDataCollection.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 */\nKuzzleDataMapping.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('admin', 'updateMapping'), data, options, function (err) {\n if (err) {\n return cb ? cb(err) : false;\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 */\nKuzzleDataMapping.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('admin', '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)) : false;\n }\n } else {\n return cb ? cb(new Error('No mapping found for index ' + self.collection.index)) : false;\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 {KuzzleDataMapping}\n */\nKuzzleDataMapping.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 */\nKuzzleDataMapping.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\nmodule.exports = KuzzleDataMapping;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDataMapping.js\n ** module id = 5\n ** module chunks = 0\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 handles documents either as realtime messages or as stored documents.\n * KuzzleDocument 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 {object} kuzzleDataCollection - an instanciated KuzzleDataCollection object\n * @param {string} [documentId] - ID of an existing document\n * @param {object} [content] - Initializes this document with the provided content\n * @constructor\n */\nfunction KuzzleDocument(kuzzleDataCollection, documentId, content) {\n Object.defineProperties(this, {\n // read-only properties\n collection: {\n value: kuzzleDataCollection.collection,\n enumerable: true\n },\n dataCollection: {\n value: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.kuzzle,\n enumerable: true\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(kuzzleDataCollection.headers)),\n enumerable: true,\n writable: true\n },\n version: {\n value: undefined,\n enumerable: true,\n writable: true\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 */\nKuzzleDocument.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._version = this.version;\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 */\nKuzzleDocument.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 * - metadata (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 */\nKuzzleDocument.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('KuzzleDocument.delete: cannot delete a document without a document ID');\n }\n\n if (cb) {\n this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'delete'), this.serialize(), options, function (err) {\n if (err) {\n return cb(err);\n }\n\n cb(null, self.id);\n });\n } else {\n this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'delete'), this.serialize(), options);\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 */\nKuzzleDocument.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('KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided');\n }\n\n this.kuzzle.callbackRequired('KuzzleDocument.refresh', cb);\n\n self.kuzzle.query(self.dataCollection.buildQueryArgs('read', 'get'), {_id: self.id}, options, function (error, res) {\n var newDocument;\n\n if (error) {\n return cb(error);\n }\n\n newDocument = new KuzzleDocument(self.dataCollection, self.id, res.result._source);\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 * - metadata (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 */\nKuzzleDocument.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('write', 'createOrReplace'), data, options, function (error, res) {\n if (error) {\n return cb ? cb(error) : false;\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 * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @returns {*} this\n */\nKuzzleDocument.prototype.publish = function (options) {\n var data = this.serialize();\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('write', '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 */\nKuzzleDocument.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 */\nKuzzleDocument.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('KuzzleDocument.subscribe', cb);\n\n if (!this.id) {\n throw new Error('KuzzleDocument.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 */\nKuzzleDocument.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\n\nmodule.exports = KuzzleDocument;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDocument.js\n ** module id = 6\n ** module chunks = 0\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), excepting:\n * * all cluster based functions\n * * all script based functions\n * * all cursors functions\n *\n * For instance:\n * kuzzle.memoryStorage\n * .set('myKey', 'myValue')\n * .get('myKey', function (err, response) {\n * console.log(response.result);\n *\n * // { _id: 'foo', body: { value: 'myValue' }}\n * });\n *\n *\n * @param {object} kuzzle - Kuzzle instance to inherit from\n * @constructor\n */\nfunction KuzzleMemoryStorage(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\n/**\n * constructs the memoryStorage functions.\n */\n(function() {\n\n var\n keyVal = ['id', 'value'],\n idOrKeys = ['id', 'keys'],\n commands = {\n append: keyVal,\n bgrewriteaof: [],\n bgsave: [],\n bitcount: ['id', 'start', 'end'],\n bitop: ['operation', 'destkey', idOrKeys],\n bitpos: ['id', 'bit', { __opts__: ['start', 'end']}],\n blpop: [idOrKeys, 'timeout'],\n brpoplpush: ['source', 'destination'],\n dbsize: [],\n decrby: keyVal,\n del: [idOrKeys],\n discard: [],\n exec: [],\n exists: [idOrKeys],\n expire: ['id', 'seconds'],\n expireat: ['id', 'timestamp'],\n flushdb: [],\n // @todo: implement geolocation methods once available in Redis stable release\n getbit: ['id', 'offset'],\n getrange: ['id', 'start', 'end'],\n hdel: ['id', ['field', 'fields']],\n hexists: ['id', 'field'],\n hincrby: ['id', 'field', 'value'],\n hmset: ['id', 'values'],\n hset: ['id', 'field', 'value'],\n info: ['section'],\n keys: [ 'pattern' ],\n lastsave: [],\n lindex: ['id', 'idx'],\n linsert: ['id', 'position', 'pivot', 'value'],\n lpush: ['id', ['value', 'values']],\n lrange: ['id', 'start', 'stop'],\n lrem: ['id', 'count', 'value'],\n lset: ['id', 'idx', 'value'],\n ltrim: ['id', 'start', 'stop'],\n mset: ['values'],\n multi: [],\n object: ['subcommand', 'args'],\n pexpire: ['id', 'milliseconds'],\n pexpireat: ['id', 'timestamp'],\n pfadd: ['id', ['element', 'elements']],\n pfmerge: ['destkey', ['sourcekey', 'sourcekeys']],\n ping: [],\n psetex: ['id', 'milliseconds', 'value'],\n publish: ['channel', 'message'],\n randomkey: [],\n rename: ['id', 'newkey'],\n renamenx: ['id', 'newkey'],\n restore: ['id', 'ttl', 'content'],\n rpoplpush: ['source', 'destination'],\n sadd: ['id', ['member', 'members']],\n save: [],\n set: ['id', 'value', {__opts__:['ex', 'px', 'nx', 'xx']}],\n sdiffstore: ['destination', idOrKeys],\n setbit: ['id', 'offset', 'value'],\n setex: ['id', 'seconds', 'value'],\n setrange: ['id', 'offset', 'value'],\n sinterstore: ['destination', idOrKeys],\n sismember: ['id', 'member'],\n smove: ['id', 'destination', 'member'],\n sort: ['id', {__opts__:['by', 'offset', 'count', 'get', 'direction', 'alpha', 'store']}],\n spop: ['id', 'count'],\n srem: ['id', ['member', 'members']],\n sunionstore: ['destination', idOrKeys],\n unwatch: [],\n wait: ['numslaves', 'timeout'],\n zadd: ['id', {__opts__: ['nx', 'xx', 'ch', 'incr', 'score', 'member', 'members']}],\n zcount: ['id', 'min', 'max'],\n zincrby: ['id', 'value', 'member'],\n zinterstore: ['destination', idOrKeys, {__opts__: ['weight', 'weights', 'aggregate']}],\n zlexcount: ['id', 'min', 'max'],\n zrange: ['id', 'start', 'stop', {__opts__: ['withscores']}],\n zrangebylex: ['id', 'min', 'max', {__opts__: ['offset', 'count']}],\n zrangebyscore: ['id', 'min', 'max', {__opts__: ['withscores', 'offset', 'count']}],\n zrem: ['id', 'member'],\n zremrangebylex: ['id', 'min', 'max'],\n zremrangebyscore: ['id', 'min', 'max'],\n zrevrangebylex: ['id', 'max', 'min', {__opts__: ['offset', 'count']}],\n zrevrangebyscore: ['id', 'max', 'min', {__opts__: ['withscores', 'offset', 'count']}],\n zrevrank: ['id', 'member']\n };\n\n // unique argument key\n commands.decr = commands.get = commands.dump = commands.hgetall = commands.hkeys = commands.hlen = commands.hstrlen = commands.hvals = commands.incr = commands.llen = commands.lpop = commands.persist = commands.pttl = commands.rpop = commands.scard = commands.smembers = commands.strlen = commands.ttl = commands.type = commands.zcard = ['id'];\n\n // key value\n commands.getset = commands.lpushx = keyVal;\n\n // key key...\n commands.del = commands.exists = commands.mget = commands.pfcount = commands.sdiff = commands.sinter = commands.sunion = commands.watch = [idOrKeys];\n\n commands.incrby = commands.incrbyfloat = commands.decrby;\n commands.brpop = commands.blpop;\n commands.hget = commands.hexists;\n commands.hmget = commands.hdel;\n commands.hsetnx = commands.hset;\n commands.msetnx = commands.mset;\n commands.rpush = commands.lpush;\n commands.hincrbyfloat = commands.hincrby;\n commands.srandmember = commands.spop;\n commands.zrevrange = commands.zrange;\n commands.zscore = commands.zrevrank;\n\n Object.keys(commands).forEach(function (command) {\n KuzzleMemoryStorage.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 (typeof args[args.length - 1] === 'function') {\n cb = args.pop();\n }\n\n if (args.length && typeof args[args.length - 1] === 'object' && Object.keys(args[args.length - 1]).length === 1 && args[args.length - 1].queuable !== undefined) {\n options = args.pop();\n }\n\n commands[command].forEach(function (v, i) {\n if (args[i] === undefined) {\n return;\n }\n\n if (Array.isArray(v)) {\n v = Array.isArray(args[i]) ? v[1] : v[0];\n }\n\n if (v === 'id') {\n data._id = args[i];\n }\n else {\n if (!data.body) {\n data.body = {};\n }\n\n if (typeof v === 'object' && v.__opts__ !== undefined) {\n v.__opts__.forEach(function (arg) {\n if (args[i][arg] !== undefined) {\n data.body[arg] = args[i][arg];\n }\n });\n }\n else {\n data.body[v] = args[i];\n }\n }\n });\n\n this.kuzzle.query(query, data, options, cb);\n\n return this;\n\n };\n });\n\n})();\n\nmodule.exports = KuzzleMemoryStorage;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleMemoryStorage.js\n ** module id = 7\n ** module chunks = 0\n **/","var\n uuid = require('node-uuid');\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} kuzzleDataCollection - an instantiated and valid kuzzle object\n * @param {object} [options] - subscription optional configuration\n * @constructor\n */\nfunction KuzzleRoom(kuzzleDataCollection, 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: uuid.v4()\n },\n lastRenewal: {\n value: null,\n writable: true\n },\n notifier: {\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: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.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(kuzzleDataCollection.headers)),\n enumerable: true,\n writable: true\n },\n metadata: {\n value: (options && options.metadata) ? options.metadata : {},\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 */\nKuzzleRoom.prototype.count = function (cb) {\n var data;\n\n this.kuzzle.callbackRequired('KuzzleRoom.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 this;\n }\n\n if (!this.roomId) {\n throw new Error('KuzzleRoom.count: cannot count subscriptions on an inactive room');\n }\n\n this.kuzzle.query(this.collection.buildQueryArgs('subscribe', 'count'), data, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result.count);\n });\n\n return this;\n};\n\n/**\n * Renew the subscription using new filters\n *\n * @param {object} [filters] - Filters in Kuzzle DSL format\n * @param {responseCallback} cb - called for each new notification\n */\nKuzzleRoom.prototype.renew = function (filters, cb) {\n var\n now = Date.now(),\n subscribeQuery = {\n scope: this.scope,\n state: this.state,\n users: this.users\n },\n self = this;\n\n if (!cb && filters && typeof filters === 'function') {\n cb = filters;\n filters = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleRoom.renew', cb);\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 self;\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 = cb;\n self.kuzzle.subscriptions.pending[self.id] = self;\n return self;\n }\n\n if (self.subscribing) {\n self.queue.push({action: 'renew', args: [filters, cb]});\n return self;\n }\n\n self.unsubscribe();\n self.roomId = null;\n self.subscribing = true;\n self.callback = cb;\n self.kuzzle.subscriptions.pending[self.id] = self;\n\n subscribeQuery.body = self.filters;\n subscribeQuery = self.kuzzle.addHeaders(subscribeQuery, this.headers);\n\n self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'on'), subscribeQuery, {metadata: self.metadata}, function (error, response) {\n delete self.kuzzle.subscriptions.pending[self.id];\n self.subscribing = false;\n\n if (error) {\n self.queue = [];\n throw 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 });\n\n return self;\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 */\nKuzzleRoom.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('subscribe', 'off'), {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('subscribe', 'off'), {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 */\nKuzzleRoom.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.error) {\n return this.callback(data.error);\n }\n\n if (data.action === 'jwtTokenExpired') {\n this.kuzzle.jwtToken = undefined;\n return this.kuzzle.emitEvent('jwtTokenExpired');\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 if (this.kuzzle.state !== 'connected' || this.subscribing) {\n return false;\n }\n return true;\n}\n\nmodule.exports = KuzzleRoom;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleRoom.js\n ** module id = 8\n ** module chunks = 0\n **/","/**\n *\n * @param host\n * @param wsPort\n * @param ioPort\n * @returns {Object} tnstantiated WebSocket/Socket.IO object\n */\n\nfunction network(host, wsPort, ioPort) {\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/wsbrowsers'))(host, wsPort);\n }\n // otherwise fallback to socket.io, if available\n else if (window.io) {\n return new (require('./wrappers/socketio'))(host, ioPort);\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/wsnode'))(host, wsPort);\n}\n\nmodule.exports = network;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/index.js\n ** module id = 9\n ** module chunks = 0\n **/","function SocketIO(host, port) {\n this.host = host;\n this.port = port;\n this.socket = null;\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 this.socket = window.io('http://' + this.host + ':' + this.port, {\n reconnection: autoReconnect,\n reconnectionDelay: reconnectionDelay,\n forceNew: true\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.socket.on('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.socket.on('connect_error', 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.socket.on('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.socket.on('reconnect', callback);\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.socket.close();\n this.socket = null;\n };\n}\n\nmodule.exports = SocketIO;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/wrappers/socketio.js\n ** module id = 10\n ** module chunks = 0\n **/","function WSBrowsers(host, port) {\n var self = this;\n this.host = host;\n this.port = port;\n this.client = null;\n this.retrying = false;\n\n /*\n Listeners are stored using the following format:\n roomId: {\n fn: callback_function,\n once: boolean\n }\n */\n this.listeners = {\n error: [],\n connect: [],\n disconnect: [],\n reconnect: []\n };\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 this.client = new WebSocket('ws://' + this.host + ':' + this.port);\n\n this.client.onopen = function () {\n if (self.retrying) {\n poke(self.listeners, 'reconnect');\n }\n else {\n poke(self.listeners, 'connect');\n }\n };\n\n this.client.onclose = function () {\n poke(self.listeners, 'disconnect');\n };\n\n this.client.onerror = function () {\n if (autoReconnect) {\n self.retrying = true;\n setTimeout(function () {\n self.connect(autoReconnect, reconnectionDelay);\n }, reconnectionDelay);\n }\n\n poke(self.listeners, 'error');\n };\n\n this.client.onmessage = function (payload) {\n var data = JSON.parse(payload.data);\n\n if (data.room && self.listeners[data.room]) {\n poke(self.listeners, data.room, 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.listeners.connect.push({\n fn: callback,\n keep: true\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 this.listeners.error.push({\n fn: callback,\n keep: true\n });\n };\n\n /**\n * Fires the provided callback whenever a disconnection occurred\n * @param {function} callback\n */\n this.onDisconnect = function (callback) {\n this.listeners.disconnect.push({\n fn: callback,\n keep: true\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 this.listeners.reconnect.push({\n fn: callback,\n keep: true\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 if (!this.listeners[roomId]) {\n this.listeners[roomId] = [];\n }\n\n this.listeners[roomId].push({\n fn: callback,\n keep: false\n });\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 if (!this.listeners[roomId]) {\n this.listeners[roomId] = [];\n }\n\n this.listeners[roomId].push({\n fn: callback,\n keep: true\n });\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 var index;\n\n if (this.listeners[roomId]) {\n index = this.listeners[roomId].findIndex(function (listener) {\n return listener.fn === callback;\n });\n\n if (index !== -1) {\n if (this.listeners[roomId].length === 1 && ['error', 'connect', 'disconnect', 'reconnect'].indexOf(roomId) === -1) {\n delete this.listeners[roomId];\n }\n else {\n this.listeners[roomId].splice(index, 1);\n }\n }\n }\n };\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.listeners = {\n error: [],\n connect: [],\n disconnect: [],\n reconnect: []\n };\n\n this.retrying = false;\n this.client.close();\n this.client = null;\n };\n}\n\n/**\n * Executes all registered listeners in the provided\n * \"listeners\" structure.\n *\n * Listeners are of the following format:\n * [\n * { fn: callback, once: boolean },\n * ...\n * ]\n *\n * @private\n * @param {Object} listeners\n * @param {string} roomId\n * @param {Object} [payload]\n */\nfunction poke (listeners, roomId, payload) {\n var\n i,\n length = listeners[roomId].length;\n\n for (i = 0; i < length; ++i) {\n listeners[roomId][i].fn(payload);\n\n if (!listeners[roomId][i].keep) {\n if (listeners[roomId].length > 1) {\n listeners[roomId].splice(i, 1);\n --i;\n --length;\n }\n else {\n delete listeners[roomId];\n }\n }\n }\n}\n\nmodule.exports = WSBrowsers;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/wrappers/wsbrowsers.js\n ** module id = 11\n ** module chunks = 0\n **/","var\n KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleProfile(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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\nKuzzleProfile.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleProfile\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 {Object} this\n */\nKuzzleProfile.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.kuzzleSecurity.buildQueryArgs('createOrReplaceProfile'), data, options, function (error) {\n if (error) {\n return cb ? cb(error) : false;\n }\n\n if (cb) {\n cb(null, self);\n }\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 {KuzzleProfile} this\n */\nKuzzleProfile.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 {KuzzleProfile} this\n */\nKuzzleProfile.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 */\nKuzzleProfile.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\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 */\nKuzzleProfile.prototype.getPolicies = function () {\n return this.content.policies;\n};\n\nmodule.exports = KuzzleProfile;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleProfile.js\n ** module id = 12\n ** module chunks = 0\n **/","var KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleRole(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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\nKuzzleRole.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleRole\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 */\nKuzzleRole.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.kuzzleSecurity.buildQueryArgs('createOrReplaceRole'), data, options, function (error) {\n if (error) {\n return cb ? cb(error) : false;\n }\n\n if (cb) {\n cb(null, self);\n }\n });\n};\n\nmodule.exports = KuzzleRole;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleRole.js\n ** module id = 13\n ** module chunks = 0\n **/","var\n KuzzleRole = require('./kuzzleRole'),\n KuzzleProfile = require('./kuzzleProfile'),\n KuzzleUser = require('./kuzzleUser');\n\n/**\n * Kuzzle security constructor\n *\n * @param kuzzle\n * @returns {KuzzleSecurity}\n * @constructor\n */\nfunction KuzzleSecurity(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 = ['roleFactory', 'profileFactory', 'userFactory', '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} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getRole = function (id, options, cb) {\n var\n data,\n self = this;\n\n if (!id) {\n throw new Error('Id parameter is mandatory for getRole 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('KuzzleSecurity.getRole', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n if (err) {\n return cb(err);\n }\n\n cb(null, new KuzzleRole(self, response.result._id, response.result._source));\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} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n *\n */\nKuzzleSecurity.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('KuzzleSecurity.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 KuzzleRole(self, doc._id, doc._source);\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.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('KuzzleSecurity.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 if (cb) {\n self.kuzzle.query(this.buildQueryArgs(action), data, options, function (err, res) {\n var doc;\n\n if (err) {\n return cb(err);\n }\n\n doc = new KuzzleRole(self, res.result._id, res.result._source);\n cb(null, doc);\n });\n } else {\n self.kuzzle.query(this.buildQueryArgs(action), data);\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.updateRole = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'updateRole';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.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 data._id = id;\n data.body = content;\n\n if (cb) {\n self.kuzzle.query(this.buildQueryArgs(action), data, options, function (err) {\n if (err) {\n return cb(err);\n }\n\n cb(null, new KuzzleRole(self, id, content));\n });\n } else {\n self.kuzzle.query(this.buildQueryArgs(action), data);\n }\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleSecurity.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 if (cb) {\n this.kuzzle.query(this.buildQueryArgs('deleteRole'), data, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result._id);\n });\n } else {\n this.kuzzle.query(this.buildQueryArgs('deleteRole'), data, options);\n }\n};\n\n/**\n * Instantiate a new KuzzleRole 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 * @constructor\n */\nKuzzleSecurity.prototype.roleFactory = function(id, content) {\n return new KuzzleRole(this, id, content);\n};\n\n\n/**\n * Get a specific profile from kuzzle\n *\n *\n * @param {string} id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getProfile = 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 getProfile function');\n }\n\n\n data = {_id: id};\n\n self.kuzzle.callbackRequired('KuzzleSecurity.getProfile', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n if (error) {\n return cb(error);\n }\n\n cb(null, new KuzzleProfile(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.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('KuzzleSecurity.searchProfiles', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new KuzzleProfile(self, doc._id, doc._source);\n });\n\n cb(null, { total: response.result.total, profiles: documents });\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 {object} content - attribute `roles` in `content` must only contains an array of role id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.createProfile = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'createProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.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 data.body = content;\n\n if (options) {\n action = options.replaceIfExist ? 'createOrReplaceProfile' : 'createProfile';\n }\n\n if (cb) {\n self.kuzzle.query(this.buildQueryArgs(action), data, options, function (err, res) {\n var doc;\n\n if (err) {\n return cb(err);\n }\n\n doc = new KuzzleProfile(self, res.result._id, res.result._source);\n cb(null, doc);\n });\n } else {\n self.kuzzle.query(this.buildQueryArgs(action), data);\n }\n};\n\n\n/**\n * Update a profile in Kuzzle.\n *\n * @param {string} id - profile identifier\n * @param {object} content - a plain javascript object representing the profile's modification\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.updateProfile = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'updateProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.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 data.body = content;\n\n if (cb) {\n self.kuzzle.query(this.buildQueryArgs(action), data, options, 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 KuzzleProfile(self, res.result._id, updatedContent));\n });\n } else {\n self.kuzzle.query(this.buildQueryArgs(action), data);\n }\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleSecurity.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 if (cb) {\n this.kuzzle.query(this.buildQueryArgs('deleteProfile'), data, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result._id);\n });\n } else {\n this.kuzzle.query(this.buildQueryArgs('deleteProfile'), data, options);\n }\n};\n\n/**\n * Instantiate a new KuzzleProfile 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 * @constructor\n */\nKuzzleSecurity.prototype.profileFactory = function(id, content) {\n return new KuzzleProfile(this, id, content);\n};\n\n/**\n * Get a specific user from kuzzle using its unique ID\n *\n * @param {string} id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getUser = function (id, options, cb) {\n var\n data,\n self = this;\n\n if (!id || typeof id !== 'string') {\n throw new Error('Id parameter is mandatory for getUser 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('KuzzleSecurity.getUser', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n if (err) {\n return cb(err);\n }\n\n cb(null, new KuzzleUser(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.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('KuzzleSecurity.searchUsers', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new KuzzleUser(self, doc._id, doc._source);\n });\n\n cb(null, { total: response.result.total, users: documents });\n });\n};\n\n/**\n * Create a new user in Kuzzle.\n *\n * Takes an optional argument object with the following property:\n * - replaceIfExist (boolean, default: false):\n * If the same user already exists: throw an error if sets to false.\n * Replace the existing user otherwise\n *\n * @param {string} id - user identifier\n * @param {object} content - attribute `profile` in `content` must only contains the profile id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.createUser = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'createUser';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.createUser: cannot create a user without a 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 if (options) {\n action = options.replaceIfExist ? 'createOrReplaceUser' : 'createUser';\n }\n\n if (cb) {\n self.kuzzle.query(this.buildQueryArgs(action), data, null, function (err, res) {\n var doc;\n\n if (err) {\n return cb(err);\n }\n\n doc = new KuzzleUser(self, res.result._id, res.result._source);\n cb(null, doc);\n });\n } else {\n self.kuzzle.query(this.buildQueryArgs(action), data);\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.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('KuzzleSecurity.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 if (cb) {\n self.kuzzle.query(this.buildQueryArgs(action), data, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, new KuzzleUser(self, res.result._id, res.result._source));\n });\n } else {\n self.kuzzle.query(this.buildQueryArgs(action), data, options);\n }\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleSecurity.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 if (cb) {\n this.kuzzle.query(this.buildQueryArgs('deleteUser'), data, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result._id);\n });\n } else {\n this.kuzzle.query(this.buildQueryArgs('deleteUser'), data, options);\n }\n};\n\n/**\n * Instantiate a new KuzzleUser 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 * @constructor\n */\nKuzzleSecurity.prototype.userFactory = function(id, content) {\n return new KuzzleUser(this, id, content);\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 */\nKuzzleSecurity.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.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} [options] - (optional) arguments\n * @param {function} cb The callback containing the normalized array of rights.\n */\nKuzzleSecurity.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, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, res.result.hits);\n });\n};\n\nmodule.exports = KuzzleSecurity;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleSecurity.js\n ** module id = 14\n ** module chunks = 0\n **/"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///kuzzle.js","webpack:///webpack/bootstrap 6e56962709edb509472f","webpack:///./src/kuzzle.js","webpack:///./src/security/kuzzleSecurityDocument.js","webpack:///./src/security/kuzzleUser.js","webpack:///./~/node-uuid/uuid.js","webpack:///./src/kuzzleDataCollection.js","webpack:///./src/kuzzleDataMapping.js","webpack:///./src/kuzzleDocument.js","webpack:///./src/kuzzleMemoryStorage.js","webpack:///./src/kuzzleRoom.js","webpack:///./src/networkWrapper/index.js","webpack:///./src/networkWrapper/wrappers/socketio.js","webpack:///./src/networkWrapper/wrappers/wsbrowsers.js","webpack:///./src/security/kuzzleProfile.js","webpack:///./src/security/kuzzleRole.js","webpack:///./src/security/kuzzleSecurity.js"],"names":["root","factory","exports","module","define","amd","a","i","this","modules","__webpack_require__","moduleId","installedModules","id","loaded","call","m","c","p","cleanQueue","self","now","Date","lastDocumentIndex","queueTTL","offlineQueue","forEach","query","index","ts","splice","droppedRequest","emitEvent","queueMaxSize","length","cleanHistory","requestHistory","Object","keys","key","setTimeout","emitRequest","request","cb","undefined","jwtToken","network","once","requestId","response","action","error","message","send","dequeue","additionalQueue","uniqueQueue","dequeuingProcess","shift","Math","max","replayInterval","queuing","offlineQueueLoader","Error","Array","isArray","concat","filter","controller","hasOwnProperty","renewAllSubscriptions","subscriptions","roomId","subscriptionId","subscription","renew","callback","uuid","KuzzleDataCollection","KuzzleSecurity","KuzzleMemoryStorage","KuzzleUser","networkWrapper","Kuzzle","host","options","defineProperties","collections","value","writable","connectCB","eventListeners","connected","lastEmitted","listeners","disconnected","reconnected","jwtTokenExpired","loginAttempt","offlineQueuePush","offlineQueuePop","eventTimeout","state","pending","autoReconnect","enumerable","defaultIndex","reconnectionDelay","wsPort","ioPort","sslConnection","autoQueue","autoReplay","autoResubscribe","headers","metadata","queueFilter","opt","getOwnPropertyDescriptor","offlineMode","defineProperty","header","errorMessagePrefix","event","args","prototype","slice","arguments","eventProperties","listener","process","nextTick","fn","apply","connect","bluebird","promisifyAll","suffix","name","func","target","passes","whitelist","indexOf","onConnect","onConnectError","connectionError","internal","onDisconnect","disconnect","onReconnect","reconnect","checkToken","err","res","valid","setJwtToken","token","success","result","jwt","JSON","stringify","getJwtToken","login","strategy","credentials","expiresIn","body","queuable","logout","v4","callbackRequired","whoAmI","security","_id","_source","getMyRights","hits","updateSelf","content","data","queryArgs","addListener","listenerId","knownEvents","listenerType","isValid","toString","push","getAllStatistics","getStatistics","timestamp","queryCB","startTime","dataCollectionFactory","collection","flushQueue","listCollections","collectionType","arg","type","listIndexes","indexes","close","getServerInfo","serverInfo","refreshIndex","getAutoRefresh","setAutoRefresh","autoRefresh","attr","object","meta","addHeaders","authorization","removeAllListeners","eventName","removeListener","replayQueue","setDefaultIndex","setHeaders","replace","startQueuing","stopQueuing","KuzzleSecurityDocument","kuzzleSecurity","kuzzle","setContent","serialize","buildQueryArgs","deleteActionName","update","updateActionName","create","constructor","setProfiles","profileIds","addProfile","profileId","save","getProfiles","_window","setupBrowser","_crypto","crypto","msCrypto","_rng","getRandomValues","_rnds8","Uint8Array","_whatwgRNG","e","_rnds","_mathRNG","r","random","console","warn","setupNode","require","_rb","randomBytes","_nodeRNG","parse","s","buf","offset","ii","toLowerCase","oct","_hexToByte","unparse","bth","_byteToHex","v1","b","clockseq","_clockseq","msecs","getTime","nsecs","_lastNSecs","dt","_lastMSecs","tl","tmh","node","_nodeId","n","BufferClass","rnds","rng","_previousRoot","Buffer","substr","_seedBytes","noConflict","window","blacklist","KuzzleDocument","KuzzleDataMapping","KuzzleRoom","advancedSearch","filters","documents","doc","newDocument","version","_version","total","count","createDocument","document","updateIfExist","deleteDocument","ids","fetchDocument","documentId","fetchAllDocuments","from","size","getMapping","kuzzleMapping","refresh","publishMessage","replaceDocument","subscribe","room","truncate","updateDocument","documentFactory","roomFactory","dataMappingFactory","mapping","kuzzleDataCollection","properties","mappings","set","field","dataCollection","publish","values","bind","keyVal","idOrKeys","commands","append","bgrewriteaof","bgsave","bitcount","bitop","bitpos","__opts__","blpop","brpoplpush","dbsize","decrby","del","discard","exec","exists","expire","expireat","flushdb","getbit","getrange","hdel","hexists","hincrby","hmset","hset","info","lastsave","lindex","linsert","lpush","lrange","lrem","lset","ltrim","mset","multi","pexpire","pexpireat","pfadd","pfmerge","ping","psetex","randomkey","rename","renamenx","restore","rpoplpush","sadd","sdiffstore","setbit","setex","setrange","sinterstore","sismember","smove","sort","spop","srem","sunionstore","unwatch","wait","zadd","zcount","zincrby","zinterstore","zlexcount","zrange","zrangebylex","zrangebyscore","zrem","zremrangebylex","zremrangebyscore","zrevrangebylex","zrevrangebyscore","zrevrank","decr","get","dump","hgetall","hkeys","hlen","hstrlen","hvals","incr","llen","lpop","persist","pttl","rpop","scard","smembers","strlen","ttl","zcard","getset","lpushx","mget","pfcount","sdiff","sinter","sunion","watch","incrby","incrbyfloat","brpop","hget","hmget","hsetnx","msetnx","rpush","hincrbyfloat","srandmember","zrevrange","zscore","command","pop","v","channel","lastRenewal","notifier","queue","renewalDelay","scope","subscribing","users","subscribeToSelf","notificationCallback","element","isReady","subscribeQuery","unsubscribe","on","interval","off","setInterval","clearInterval","WebSocket","io","code","SocketIO","port","ssl","socket","reconnection","forceNew","payload","emit","WSBrowsers","client","retrying","onopen","poke","onclose","onerror","onmessage","keep","findIndex","readyState","OPEN","KuzzleProfile","policies","addPolicy","policy","roleId","setPolicies","map","getPolicies","KuzzleRole","getRole","searchRoles","roles","createRole","replaceIfExist","updateRole","deleteRole","roleFactory","getProfile","searchProfiles","profiles","createProfile","updateProfile","updatedContent","property","deleteProfile","profileFactory","getUser","searchUsers","createUser","updateUser","deleteUser","userFactory","isActionAllowed","rights","filteredRights","right","some","item","getUserRights","userId"],"mappings":"CAAA,SAAAA,EAAAC,GACA,mBAAAC,UAAA,gBAAAC,QACAA,OAAAD,QAAAD,QACA,sBAAAG,gBAAAC,IACAD,UAAAH,OACA,CACA,GAAAK,GAAAL,GACA,QAAAM,KAAAD,IAAA,gBAAAJ,iBAAAF,GAAAO,GAAAD,EAAAC,KAECC,KAAA,WACD,MCAgB,UAAUC,GCN1B,QAAAC,GAAAC,GAGA,GAAAC,EAAAD,GACA,MAAAC,GAAAD,GAAAT,OAGA,IAAAC,GAAAS,EAAAD,IACAT,WACAW,GAAAF,EACAG,QAAA,EAUA,OANAL,GAAAE,GAAAI,KAAAZ,EAAAD,QAAAC,IAAAD,QAAAQ,GAGAP,EAAAW,QAAA,EAGAX,EAAAD,QAvBA,GAAAU,KAqCA,OATAF,GAAAM,EAAAP,EAGAC,EAAAO,EAAAL,EAGAF,EAAAQ,EAAA,GAGAR,EAAA,KDgBM,SAASP,EAAQD,EAASQ,GEokBhC,QAAAS,KACA,GACAC,GAAAZ,KACAa,EAAAC,KAAAD,MACAE,IAEAH,GAAAI,SAAA,IACAJ,EAAAK,aAAAC,QAAA,SAAAC,EAAAC,GACAD,EAAAE,GAAAR,EAAAD,EAAAI,WACAD,EAAAK,KAIAL,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A,GAAAzd,gBAAA,MAAAyd,EAAAzd,aAEAD,OAAA,SAAA0d,GACA,MAAAA,GAAA5e,YAAA,MAAA4e,EAAA5e,SAEAkB,OAAA,SAAA0d,GACA,MAAAA,GAAAlgB,WAAA,MAAAkgB,EAAAlgB,QAEAwC,OAAA,SAAA0d,GACA,MAAAA,GAAAzV,gBAAA,MAAAyV,EAAAzV,aAIAwV,EAAAE,KAAA,SAAAC,GAA2C,kBAAAA,EAAAvc,QAC3C,UAGAoc,EAAAE,KAAA,SAAAC,GAA2C,sBAAAA,EAAAvc,QAC3C,cAGA,UAWAT,EAAA8C,UAAAma,cAAA,SAAAC,EAAA5c,EAAA3C,GACA,GACA2I,IAAYN,IAAAkX,GACZ9gB,EAAAZ,IAEA,KAAA0hB,GAAA,gBAAAA,GACA,SAAAle,OAAA,2DAGArB,IAAA,kBAAA2C,KACA3C,EAAA2C,EACAA,EAAA,MAGAlE,EAAAgN,OAAAvD,iBAAA,uBAAAlI,GAEAnC,KAAA4N,OAAAzM,MAAAnB,KAAA+N,eAAA,iBAAAjD,EAAAhG,EAAA3C,GAAA,SAAA+G,EAAAC,GACAhH,EAAA+G,MAAAC,EAAAK,OAAAmB,SAIAhL,EAAAD,QAAA8E","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 {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(this, function() {\nreturn \n\n\n/** WEBPACK FOOTER **\n ** webpack/universalModuleDefinition\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 {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\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 uuid = __webpack_require__(3),\n\t KuzzleDataCollection = __webpack_require__(4),\n\t KuzzleSecurity = __webpack_require__(14),\n\t KuzzleMemoryStorage = __webpack_require__(7),\n\t KuzzleUser = __webpack_require__(2),\n\t networkWrapper = __webpack_require__(9);\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 * @constructor\n\t */\n\tmodule.exports = Kuzzle = function (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\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 collections: {\n\t value: {},\n\t writable: true\n\t },\n\t connectCB: {\n\t value: cb\n\t },\n\t eventListeners: {\n\t value: {\n\t connected: {lastEmitted: null, listeners: []},\n\t error: {lastEmitted: null, listeners: []},\n\t disconnected: {lastEmitted: null, listeners: []},\n\t reconnected: {lastEmitted: null, listeners: []},\n\t jwtTokenExpired: {lastEmitted: null, listeners: []},\n\t loginAttempt: {lastEmitted: null, listeners: []},\n\t offlineQueuePush: {listeners: []},\n\t offlineQueuePop: {listeners: []}\n\t }\n\t },\n\t eventTimeout: {\n\t value: 200\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 'roomId': {\n\t kuzzleRoomID_1: kuzzleRoomInstance_1,\n\t kuzzleRoomID_2: kuzzleRoomInstance_2,\n\t kuzzleRoomID_...: 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 // read-only properties\n\t autoReconnect: {\n\t value: (options && typeof options.autoReconnect === 'boolean') ? options.autoReconnect : 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 enumerable: true\n\t },\n\t host: {\n\t value: host,\n\t enumerable: true\n\t },\n\t wsPort: {\n\t value: (options && typeof options.wsPort === 'number') ? options.wsPort : 7513,\n\t enumerable: true\n\t },\n\t ioPort: {\n\t value: (options && typeof options.ioPort === 'number') ? options.ioPort : 7512,\n\t enumerable: true\n\t },\n\t sslConnection: {\n\t value: (options && typeof options.sslConnection === 'boolean') ? options.sslConnection : false,\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 metadata: {\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: 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 (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 KuzzleSecurity(this),\n\t enumerable: true\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 Object.defineProperty(this, 'emitEvent', {\n\t value: function emitEvent(event) {\n\t var\n\t now = Date.now(),\n\t args = Array.prototype.slice.call(arguments, 1),\n\t eventProperties = this.eventListeners[event];\n\t\n\t if (eventProperties.lastEmitted && eventProperties.lastEmitted >= now - this.eventTimeout) {\n\t return false;\n\t }\n\t\n\t eventProperties.listeners.forEach(function (listener) {\n\t process.nextTick(function () {\n\t listener.fn.apply(undefined, args);\n\t });\n\t });\n\t\n\t // Events without the 'lastEmitted' property can be emitted without minimum time between emissions\n\t if (eventProperties.lastEmitted !== undefined) {\n\t eventProperties.lastEmitted = now;\n\t }\n\t }\n\t });\n\t\n\t Object.defineProperty(this, 'memoryStorage', {\n\t value: new KuzzleMemoryStorage(this),\n\t enumerable: true\n\t });\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 cleanHistory(this.requestHistory);\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', 'listIndexes', 'login', 'logout', 'now', 'query',\n\t '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\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.network = networkWrapper(self.host, self.wsPort, self.ioPort, self.sslConnection);\n\t }\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.onConnectError(function (error) {\n\t var connectionError = new Error('Unable to connect to kuzzle server at \"' + self.host + '\"');\n\t\n\t connectionError.internal = error;\n\t self.state = 'error';\n\t self.emitEvent('error', connectionError);\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('jwtTokenExpired');\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 * 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 * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.login = function (strategy) {\n\t var\n\t self = this,\n\t request = {\n\t strategy: strategy\n\t },\n\t credentials,\n\t cb = null;\n\t\n\t // Handle arguments (credentials, expiresIn, cb)\n\t if (arguments[1]) {\n\t if (typeof arguments[1] === 'object') {\n\t credentials = 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 if (typeof credentials === 'object') {\n\t Object.keys(credentials).forEach(function (key) {\n\t request[key] = credentials[key];\n\t });\n\t }\n\t\n\t this.query({controller: 'auth', action: 'login'}, {body: request}, {queuable: false}, cb && 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(null, response.result);\n\t }\n\t else {\n\t cb(error);\n\t self.emitEvent('loginAttempt', {success: false, error: error.message});\n\t }\n\t });\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: uuid.v4(),\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 if (error === null) {\n\t self.jwtToken = undefined;\n\t cb(null, self);\n\t }\n\t else {\n\t cb(error);\n\t }\n\t });\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} callback The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t * @return {Kuzzle} The Kuzzle instance to enable chaining.\n\t */\n\tKuzzle.prototype.checkToken = function (token, callback) {\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', callback);\n\t\n\t this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, function (err, response) {\n\t if (err) {\n\t return callback(err);\n\t }\n\t\n\t callback(null, response.result);\n\t });\n\t};\n\t\n\t/**\n\t * Fetches the current user.\n\t *\n\t * @param {function} callback The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t * @return {Kuzzle} The Kuzzle instance to enable chaining.\n\t */\n\tKuzzle.prototype.whoAmI = function (callback) {\n\t var self = this;\n\t\n\t self.callbackRequired('Kuzzle.whoAmI', callback);\n\t\n\t self.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, function (err, response) {\n\t if (err) {\n\t return callback(err);\n\t }\n\t\n\t callback(null, new KuzzleUser(self.security, response.result._id, response.result._source));\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'}, {}, null, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, 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 */\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 && 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 setTimeout(function () {\n\t cleanHistory(requestHistory);\n\t }, 1000);\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 if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n\t self.jwtToken = undefined;\n\t self.emitEvent('jwtTokenExpired', request, cb);\n\t }\n\t\n\t cb && cb(response.error, response);\n\t });\n\t }\n\t\n\t this.network.send(request);\n\t\n\t // Track requests made to allow KuzzleRoom.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 * 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 * The ID returned by this function is required to remove this listener at a later time.\n\t *\n\t * @param {string} event - name of the global event to subscribe to (see the 'eventListeners' object property)\n\t * @param {function} listener - callback to invoke each time an event is fired\n\t * @returns {string} Unique listener ID\n\t */\n\tKuzzle.prototype.addListener = function(event, listener) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t listenerType = typeof listener,\n\t listenerId;\n\t\n\t this.isValid();\n\t\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\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 listenerId = uuid.v4();\n\t this.eventListeners[event].listeners.push({id: listenerId, fn: listener});\n\t return listenerId;\n\t};\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 * @returns {object} this\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:'admin', action: 'getAllStats'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, 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 * @returns {object} this\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 if (timestamp) {\n\t cb(null, res.result.hits);\n\t } else {\n\t cb(null, [res.result]);\n\t }\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: 'admin', action: 'getLastStats'}, body, options, queryCB);\n\t};\n\t\n\t/**\n\t * Create a new instance of a KuzzleDataCollection 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 {object} A KuzzleDataCollection instance\n\t */\n\tKuzzle.prototype.dataCollectionFactory = 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 KuzzleDataCollection(this, index, collection);\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 * @returns {object} this\n\t */\n\tKuzzle.prototype.listCollections = function () {\n\t var\n\t collectionType = 'all',\n\t index,\n\t options,\n\t cb,\n\t args = Array.prototype.slice.call(arguments);\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 if (options && options.type) {\n\t collectionType = options.type;\n\t }\n\t\n\t this.query({index: index, controller: 'read', action: 'listCollections'}, {body: {type: collectionType}}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, 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 * @returns {object} this\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: 'read', action: 'listIndexes'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, 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 this.logout();\n\t\n\t this.state = 'disconnected';\n\t this.network.close();\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 * @returns {object} this\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: 'read', action: 'serverInfo'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, 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: 'admin', action: 'refreshIndex'}, {}, 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 * @returns {object} this\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: 'admin', 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: 'admin', 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 * @returns {object} this\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: 'read', action: 'now'}, {}, options, function (err, res) {\n\t cb(err, res && 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 * - metadata (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 metadata: this.metadata\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.metadata) {\n\t Object.keys(options.metadata).forEach(function (meta) {\n\t object.metadata[meta] = options.metadata[meta];\n\t });\n\t }\n\t\n\t if (options.queuable === false && self.state === 'offline') {\n\t return self;\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.metadata) {\n\t Object.keys(query.metadata).forEach(function (meta) {\n\t object.metadata[meta] = query.metadata[meta];\n\t });\n\t }\n\t\n\t for (attr in query) {\n\t if (attr !== 'metadata' && 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.headers = object.headers || {};\n\t object.headers.authorization = 'Bearer ' + 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 = uuid.v4();\n\t }\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 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 } else if (self.queuing || ['initializing', 'connecting'].indexOf(self.state) !== -1) {\n\t cleanQueue.call(this, object, cb);\n\t\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 }\n\t }\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Removes all listeners, either from a specific event or from all events\n\t *\n\t * @param {string} event - One of the event described in the Event Handling section of this documentation\n\t */\n\tKuzzle.prototype.removeAllListeners = function (event) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t self = this;\n\t\n\t if (event) {\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n\t }\n\t\n\t this.eventListeners[event].listeners = [];\n\t } else {\n\t knownEvents.forEach(function (eventName) {\n\t self.eventListeners[eventName].listeners = [];\n\t });\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Removes a listener from an event.\n\t *\n\t * @param {string} event - One of the event described in the Event Handling section of this documentation\n\t * @param {string} listenerId - The ID returned by addListener\n\t */\n\tKuzzle.prototype.removeListener = function (event, listenerId) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t self = this;\n\t\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n\t }\n\t\n\t this.eventListeners[event].listeners.forEach(function (listener, index) {\n\t if (listener.id === listenerId) {\n\t self.eventListeners[event].listeners.splice(index, 1);\n\t }\n\t });\n\t\n\t return this;\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\n\n/***/ },\n/* 1 */\n/***/ function(module, exports) {\n\n\tfunction KuzzleSecurityDocument(kuzzleSecurity, id, content) {\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: kuzzleSecurity.kuzzle\n\t },\n\t kuzzleSecurity: {\n\t value: kuzzleSecurity\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 });\n\t\n\t if (content) {\n\t this.setContent(content, true);\n\t }\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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 {Object} this\n\t */\n\tKuzzleSecurityDocument.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\tKuzzleSecurityDocument.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\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\tKuzzleSecurityDocument.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.kuzzleSecurity.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 */\n\tKuzzleSecurityDocument.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.kuzzleSecurity.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 = KuzzleSecurityDocument;\n\n/***/ },\n/* 2 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleUser(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 });\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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\tKuzzleUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleUser\n\t }\n\t});\n\t\n\t/**\n\t * Set profiles in content\n\t * @param {array} profile - an array of profiles ids string\n\t *\n\t * @returns {KuzzleUser} this\n\t */\n\tKuzzleUser.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 * Add a profile\n\t * @param {string} profile - a profile ids string\n\t *\n\t * @returns {KuzzleUser} this\n\t */\n\tKuzzleUser.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 * Saves this user into Kuzzle.\n\t *\n\t * If this is a new user, this function will create it in Kuzzle.\n\t * Otherwise, this method will replace the latest version of this user in Kuzzle by the current content\n\t * of this object.\n\t *\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @param {object} [options] - Optional parameters\n\t * @returns {*} this\n\t */\n\tKuzzleUser.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.kuzzleSecurity.buildQueryArgs('createOrReplaceUser'), data, options, cb && function (error) {\n\t cb(error, !error && 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\tKuzzleUser.prototype.serialize = function () {\n\t return {_id: this.id, body: this.content};\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\tKuzzleUser.prototype.getProfiles = function () {\n\t return this.content.profileIds;\n\t};\n\t\n\tmodule.exports = KuzzleUser;\n\n\n/***/ },\n/* 3 */\n/***/ function(module, exports) {\n\n\t// uuid.js\n\t//\n\t// Copyright (c) 2010-2012 Robert Kieffer\n\t// MIT License - http://opensource.org/licenses/mit-license.php\n\t\n\t/*global window, require, define */\n\t(function(_window) {\n\t 'use strict';\n\t\n\t // Unique ID creation requires a high quality random # generator. We feature\n\t // detect to determine the best RNG source, normalizing to a function that\n\t // returns 128-bits of randomness, since that's what's usually required\n\t var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot;\n\t\n\t function setupBrowser() {\n\t // Allow for MSIE11 msCrypto\n\t var _crypto = _window.crypto || _window.msCrypto;\n\t\n\t if (!_rng && _crypto && _crypto.getRandomValues) {\n\t // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto\n\t //\n\t // Moderately fast, high quality\n\t try {\n\t var _rnds8 = new Uint8Array(16);\n\t _whatwgRNG = _rng = function whatwgRNG() {\n\t _crypto.getRandomValues(_rnds8);\n\t return _rnds8;\n\t };\n\t _rng();\n\t } catch(e) {}\n\t }\n\t\n\t if (!_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 _mathRNG = _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 if ('undefined' !== typeof console && console.warn) {\n\t console.warn(\"[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()\");\n\t }\n\t }\n\t }\n\t\n\t function setupNode() {\n\t // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html\n\t //\n\t // Moderately fast, high quality\n\t if ('function' === typeof require) {\n\t try {\n\t var _rb = require('crypto').randomBytes;\n\t _nodeRNG = _rng = _rb && function() {return _rb(16);};\n\t _rng();\n\t } catch(e) {}\n\t }\n\t }\n\t\n\t if (_window) {\n\t setupBrowser();\n\t } else {\n\t setupNode();\n\t }\n\t\n\t // Buffer class to use\n\t var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;\n\t\n\t // Maps for number <-> hex string conversion\n\t var _byteToHex = [];\n\t var _hexToByte = {};\n\t for (var i = 0; i < 256; i++) {\n\t _byteToHex[i] = (i + 0x100).toString(16).substr(1);\n\t _hexToByte[_byteToHex[i]] = i;\n\t }\n\t\n\t // **`parse()` - Parse a UUID into it's component bytes**\n\t function parse(s, buf, offset) {\n\t var i = (buf && offset) || 0, ii = 0;\n\t\n\t buf = buf || [];\n\t s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {\n\t if (ii < 16) { // Don't overflow!\n\t buf[i + ii++] = _hexToByte[oct];\n\t }\n\t });\n\t\n\t // Zero out remaining bytes if string was short\n\t while (ii < 16) {\n\t buf[i + ii++] = 0;\n\t }\n\t\n\t return buf;\n\t }\n\t\n\t // **`unparse()` - Convert UUID byte array (ala parse()) into a string**\n\t function unparse(buf, offset) {\n\t var i = offset || 0, 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\t // **`v1()` - Generate time-based UUID**\n\t //\n\t // Inspired by https://github.com/LiosK/UUID.js\n\t // and http://docs.python.org/library/uuid.html\n\t\n\t // random #'s we need to init node and clockseq\n\t var _seedBytes = _rng();\n\t\n\t // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n\t var _nodeId = [\n\t _seedBytes[0] | 0x01,\n\t _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]\n\t ];\n\t\n\t // Per 4.2.2, randomize (14 bit) clockseq\n\t var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;\n\t\n\t // Previous uuid creation time\n\t var _lastMSecs = 0, _lastNSecs = 0;\n\t\n\t // See https://github.com/broofa/node-uuid for API details\n\t function v1(options, buf, offset) {\n\t var i = buf && offset || 0;\n\t var b = buf || [];\n\t\n\t options = options || {};\n\t\n\t var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;\n\t\n\t // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n\t // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n\t // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n\t // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\t var msecs = (options.msecs != null) ? options.msecs : new Date().getTime();\n\t\n\t // Per 4.2.1.2, use count of uuid's generated during the current clock\n\t // cycle to simulate higher resolution clock\n\t var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;\n\t\n\t // Time since last uuid creation (in msecs)\n\t var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\t\n\t // Per 4.2.1.2, Bump clockseq on clock regression\n\t if (dt < 0 && options.clockseq == null) {\n\t clockseq = clockseq + 1 & 0x3fff;\n\t }\n\t\n\t // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n\t // time interval\n\t if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {\n\t nsecs = 0;\n\t }\n\t\n\t // Per 4.2.1.2 Throw error if too many uuids are requested\n\t if (nsecs >= 10000) {\n\t throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n\t }\n\t\n\t _lastMSecs = msecs;\n\t _lastNSecs = nsecs;\n\t _clockseq = clockseq;\n\t\n\t // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\t msecs += 12219292800000;\n\t\n\t // `time_low`\n\t var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n\t b[i++] = tl >>> 24 & 0xff;\n\t b[i++] = tl >>> 16 & 0xff;\n\t b[i++] = tl >>> 8 & 0xff;\n\t b[i++] = tl & 0xff;\n\t\n\t // `time_mid`\n\t var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n\t b[i++] = tmh >>> 8 & 0xff;\n\t b[i++] = tmh & 0xff;\n\t\n\t // `time_high_and_version`\n\t b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\t b[i++] = tmh >>> 16 & 0xff;\n\t\n\t // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\t b[i++] = clockseq >>> 8 | 0x80;\n\t\n\t // `clock_seq_low`\n\t b[i++] = clockseq & 0xff;\n\t\n\t // `node`\n\t var node = options.node || _nodeId;\n\t for (var n = 0; n < 6; n++) {\n\t b[i + n] = node[n];\n\t }\n\t\n\t return buf ? buf : unparse(b);\n\t }\n\t\n\t // **`v4()` - Generate random UUID**\n\t\n\t // See https://github.com/broofa/node-uuid for API details\n\t function v4(options, buf, offset) {\n\t // Deprecated - 'format' argument, as supported in v1.2\n\t var i = buf && offset || 0;\n\t\n\t if (typeof(options) === 'string') {\n\t buf = (options === 'binary') ? new BufferClass(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 || unparse(rnds);\n\t }\n\t\n\t // Export public API\n\t var uuid = v4;\n\t uuid.v1 = v1;\n\t uuid.v4 = v4;\n\t uuid.parse = parse;\n\t uuid.unparse = unparse;\n\t uuid.BufferClass = BufferClass;\n\t uuid._rng = _rng;\n\t uuid._mathRNG = _mathRNG;\n\t uuid._nodeRNG = _nodeRNG;\n\t uuid._whatwgRNG = _whatwgRNG;\n\t\n\t if (('undefined' !== typeof module) && module.exports) {\n\t // Publish as node.js module\n\t module.exports = uuid;\n\t } else if (typeof define === 'function' && define.amd) {\n\t // Publish as AMD module\n\t define(function() {return uuid;});\n\t\n\t\n\t } else {\n\t // Publish as global (in browsers)\n\t _previousRoot = _window.uuid;\n\t\n\t // **`noConflict()` - (browser only) to reset global 'uuid' var**\n\t uuid.noConflict = function() {\n\t _window.uuid = _previousRoot;\n\t return uuid;\n\t };\n\t\n\t _window.uuid = uuid;\n\t }\n\t})('undefined' !== typeof window ? window : null);\n\n\n/***/ },\n/* 4 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleDocument = __webpack_require__(6),\n\t KuzzleDataMapping = __webpack_require__(5),\n\t KuzzleRoom = __webpack_require__(8);\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 * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @param {string} index - Index containing the data collection\n\t * @param {string} collection - name of the data collection to handle\n\t * @constructor\n\t */\n\tfunction KuzzleDataCollection(kuzzle, index, collection) {\n\t if (!index || !collection) {\n\t throw new Error('The KuzzleDataCollection object constructor needs an index and a collection arguments');\n\t }\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 * 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 * @returns {Object} this\n\t */\n\tKuzzleDataCollection.prototype.advancedSearch = 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 = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleDataCollection.advancedSearch', cb);\n\t\n\t query = self.kuzzle.addHeaders({body: filters}, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('read', '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 KuzzleDocument(self, doc._id, doc._source);\n\t\n\t newDocument.version = doc._version;\n\t\n\t documents.push(newDocument);\n\t });\n\t\n\t cb(null, { total: result.result.total, documents: documents });\n\t });\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 * @returns {Object} this\n\t */\n\tKuzzleDataCollection.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('KuzzleDataCollection.count', cb);\n\t\n\t query = this.kuzzle.addHeaders({body: filters}, this.headers);\n\t\n\t this.kuzzle.query(this.buildQueryArgs('read', 'count'), query, options, function (error, result) {\n\t cb(error, result && result.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\tKuzzleDataCollection.prototype.create = 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('write', 'createCollection'), data, options, cb);\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 * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t * - updateIfExist (boolean, default: false):\n\t * If the same document already exists: throw an error if sets to false.\n\t * Update the existing document otherwise\n\t *\n\t * @param {string} [id] - (optional) document identifier\n\t * @param {object} document - either an instance of a KuzzleDocument 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\tKuzzleDataCollection.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 KuzzleDocument) {\n\t data = document.serialize();\n\t } else {\n\t data.body = document;\n\t }\n\t\n\t if (options) {\n\t action = options.updateIfExist ? 'createOrReplace' : 'create';\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('write', 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 KuzzleDocument(self, res.result._id, res.result._source);\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 * - metadata (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 {Object} this\n\t */\n\tKuzzleDataCollection.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 = 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('write', action), data, options, cb && function (err, res) {\n\t cb(err, !err && (action === 'delete' ? [res.result._id] : res.result.ids));\n\t });\n\t\n\t return this;\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 * @returns {Object} this\n\t */\n\tKuzzleDataCollection.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('KuzzleDataCollection.fetch', cb);\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('read', '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 KuzzleDocument(self, res.result._id, res.result._source);\n\t document.version = res.result._version;\n\t cb(null, document);\n\t });\n\t};\n\t\n\t/**\n\t * Retrieves all documents stored in this data collection\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t * @returns {Object} this\n\t */\n\tKuzzleDataCollection.prototype.fetchAllDocuments = function (options, cb) {\n\t var filters = {};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t // copying pagination options to the search filter\n\t if (options) {\n\t if (options.from) {\n\t filters.from = options.from;\n\t }\n\t\n\t if (options.size) {\n\t filters.size = options.size;\n\t }\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDataCollection.fetchAll', cb);\n\t\n\t this.advancedSearch(filters, options, cb);\n\t};\n\t\n\t\n\t/**\n\t * Instantiates a KuzzleDataMapping 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 KuzzleDataMapping object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.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('KuzzleDataCollection.getMapping', cb);\n\t\n\t kuzzleMapping = new KuzzleDataMapping(this);\n\t kuzzleMapping.refresh(options, cb);\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 * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} document - either a KuzzleDocument 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\tKuzzleDataCollection.prototype.publishMessage = function (document, options, cb) {\n\t var data = {};\n\t\n\t if (document instanceof KuzzleDocument) {\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('write', '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 * - metadata (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 KuzzleDocument object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.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('write', '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 KuzzleDocument(self, res.result._id, res.result._source);\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 * 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 {*} KuzzleRoom object\n\t */\n\tKuzzleDataCollection.prototype.subscribe = function (filters, options, cb) {\n\t var room;\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('KuzzleDataCollection.subscribe', cb);\n\t\n\t room = new KuzzleRoom(this, options);\n\t\n\t return room.renew(filters, cb);\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\tKuzzleDataCollection.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('admin', 'truncateCollection'), 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 * - metadata (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 KuzzleDocument object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n\t var\n\t 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 data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options, cb && function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t (new KuzzleDocument(self, res.result._id)).refresh(cb);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t\n\t/**\n\t * Instantiate a new KuzzleDocument 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\tKuzzleDataCollection.prototype.documentFactory = function (id, content) {\n\t return new KuzzleDocument(this, id, content);\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleRoom 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\tKuzzleDataCollection.prototype.roomFactory = function (options) {\n\t return new KuzzleRoom(this, options);\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleDataMapping 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 KuzzleDataMapping object with\n\t * @constructor\n\t */\n\tKuzzleDataCollection.prototype.dataMappingFactory = function (mapping) {\n\t return new KuzzleDataMapping(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\tKuzzleDataCollection.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 = KuzzleDataCollection;\n\n\n/***/ },\n/* 5 */\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 KuzzleDataMapping object allow to get the current mapping of a data collection and to modify it if needed.\n\t *\n\t * @param {object} kuzzleDataCollection - Instance of the inherited KuzzleDataCollection object\n\t * @param {object} mapping - mappings\n\t * @constructor\n\t */\n\tfunction KuzzleDataMapping(kuzzleDataCollection, mapping) {\n\t Object.defineProperties(this, {\n\t //read-only properties\n\t collection: {\n\t value: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzleDataCollection.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\tKuzzleDataMapping.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('admin', '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\tKuzzleDataMapping.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('admin', '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 {KuzzleDataMapping}\n\t */\n\tKuzzleDataMapping.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\tKuzzleDataMapping.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 = KuzzleDataMapping;\n\n\n/***/ },\n/* 6 */\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 * KuzzleDocument 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 {object} kuzzleDataCollection - an instanciated KuzzleDataCollection 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 * @constructor\n\t */\n\tfunction KuzzleDocument(kuzzleDataCollection, documentId, content) {\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t collection: {\n\t value: kuzzleDataCollection.collection,\n\t enumerable: true\n\t },\n\t dataCollection: {\n\t value: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.kuzzle,\n\t enumerable: true\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(kuzzleDataCollection.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 });\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\tKuzzleDocument.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._version = this.version;\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\tKuzzleDocument.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 * - metadata (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\tKuzzleDocument.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('KuzzleDocument.delete: cannot delete a document without a document ID');\n\t }\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'delete'), this.serialize(), options, cb && function (err) {\n\t cb(err, !err && self.id);\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\tKuzzleDocument.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('KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided');\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDocument.refresh', cb);\n\t\n\t self.kuzzle.query(self.dataCollection.buildQueryArgs('read', '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 KuzzleDocument(self.dataCollection, self.id, res.result._source);\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 * - metadata (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\tKuzzleDocument.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('write', '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 * - metadata (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\tKuzzleDocument.prototype.publish = function (options) {\n\t var data = this.serialize();\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('write', '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\tKuzzleDocument.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\tKuzzleDocument.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('KuzzleDocument.subscribe', cb);\n\t\n\t if (!this.id) {\n\t throw new Error('KuzzleDocument.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\tKuzzleDocument.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 = KuzzleDocument;\n\n\n/***/ },\n/* 7 */\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 * 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), excepting:\n\t * * all cluster based functions\n\t * * all script based functions\n\t * * all cursors functions\n\t *\n\t * For instance:\n\t * kuzzle.memoryStorage\n\t * .set('myKey', 'myValue')\n\t * .get('myKey', function (err, response) {\n\t * console.log(response.result);\n\t *\n\t * // { _id: 'foo', body: { value: 'myValue' }}\n\t * });\n\t *\n\t *\n\t * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @constructor\n\t */\n\tfunction KuzzleMemoryStorage(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\n\t/**\n\t * constructs the memoryStorage functions.\n\t */\n\t(function() {\n\t\n\t var\n\t keyVal = ['id', 'value'],\n\t idOrKeys = ['id', 'keys'],\n\t commands = {\n\t append: keyVal,\n\t bgrewriteaof: [],\n\t bgsave: [],\n\t bitcount: ['id', 'start', 'end'],\n\t bitop: ['operation', 'destkey', idOrKeys],\n\t bitpos: ['id', 'bit', { __opts__: ['start', 'end']}],\n\t blpop: [idOrKeys, 'timeout'],\n\t brpoplpush: ['source', 'destination'],\n\t dbsize: [],\n\t decrby: keyVal,\n\t del: [idOrKeys],\n\t discard: [],\n\t exec: [],\n\t exists: [idOrKeys],\n\t expire: ['id', 'seconds'],\n\t expireat: ['id', 'timestamp'],\n\t flushdb: [],\n\t // @todo: implement geolocation methods once available in Redis stable release\n\t getbit: ['id', 'offset'],\n\t getrange: ['id', 'start', 'end'],\n\t hdel: ['id', ['field', 'fields']],\n\t hexists: ['id', 'field'],\n\t hincrby: ['id', 'field', 'value'],\n\t hmset: ['id', 'values'],\n\t hset: ['id', 'field', 'value'],\n\t info: ['section'],\n\t keys: [ 'pattern' ],\n\t lastsave: [],\n\t lindex: ['id', 'idx'],\n\t linsert: ['id', 'position', 'pivot', 'value'],\n\t lpush: ['id', ['value', 'values']],\n\t lrange: ['id', 'start', 'stop'],\n\t lrem: ['id', 'count', 'value'],\n\t lset: ['id', 'idx', 'value'],\n\t ltrim: ['id', 'start', 'stop'],\n\t mset: ['values'],\n\t multi: [],\n\t object: ['subcommand', 'args'],\n\t pexpire: ['id', 'milliseconds'],\n\t pexpireat: ['id', 'timestamp'],\n\t pfadd: ['id', ['element', 'elements']],\n\t pfmerge: ['destkey', ['sourcekey', 'sourcekeys']],\n\t ping: [],\n\t psetex: ['id', 'milliseconds', 'value'],\n\t publish: ['channel', 'message'],\n\t randomkey: [],\n\t rename: ['id', 'newkey'],\n\t renamenx: ['id', 'newkey'],\n\t restore: ['id', 'ttl', 'content'],\n\t rpoplpush: ['source', 'destination'],\n\t sadd: ['id', ['member', 'members']],\n\t save: [],\n\t set: ['id', 'value', {__opts__:['ex', 'px', 'nx', 'xx']}],\n\t sdiffstore: ['destination', idOrKeys],\n\t setbit: ['id', 'offset', 'value'],\n\t setex: ['id', 'seconds', 'value'],\n\t setrange: ['id', 'offset', 'value'],\n\t sinterstore: ['destination', idOrKeys],\n\t sismember: ['id', 'member'],\n\t smove: ['id', 'destination', 'member'],\n\t sort: ['id', {__opts__:['by', 'offset', 'count', 'get', 'direction', 'alpha', 'store']}],\n\t spop: ['id', 'count'],\n\t srem: ['id', ['member', 'members']],\n\t sunionstore: ['destination', idOrKeys],\n\t unwatch: [],\n\t wait: ['numslaves', 'timeout'],\n\t zadd: ['id', {__opts__: ['nx', 'xx', 'ch', 'incr', 'score', 'member', 'members']}],\n\t zcount: ['id', 'min', 'max'],\n\t zincrby: ['id', 'value', 'member'],\n\t zinterstore: ['destination', idOrKeys, {__opts__: ['weight', 'weights', 'aggregate']}],\n\t zlexcount: ['id', 'min', 'max'],\n\t zrange: ['id', 'start', 'stop', {__opts__: ['withscores']}],\n\t zrangebylex: ['id', 'min', 'max', {__opts__: ['offset', 'count']}],\n\t zrangebyscore: ['id', 'min', 'max', {__opts__: ['withscores', 'offset', 'count']}],\n\t zrem: ['id', 'member'],\n\t zremrangebylex: ['id', 'min', 'max'],\n\t zremrangebyscore: ['id', 'min', 'max'],\n\t zrevrangebylex: ['id', 'max', 'min', {__opts__: ['offset', 'count']}],\n\t zrevrangebyscore: ['id', 'max', 'min', {__opts__: ['withscores', 'offset', 'count']}],\n\t zrevrank: ['id', 'member']\n\t };\n\t\n\t // unique argument key\n\t commands.decr = commands.get = commands.dump = commands.hgetall = commands.hkeys = commands.hlen = commands.hstrlen = commands.hvals = commands.incr = commands.llen = commands.lpop = commands.persist = commands.pttl = commands.rpop = commands.scard = commands.smembers = commands.strlen = commands.ttl = commands.type = commands.zcard = ['id'];\n\t\n\t // key value\n\t commands.getset = commands.lpushx = keyVal;\n\t\n\t // key key...\n\t commands.del = commands.exists = commands.mget = commands.pfcount = commands.sdiff = commands.sinter = commands.sunion = commands.watch = [idOrKeys];\n\t\n\t commands.incrby = commands.incrbyfloat = commands.decrby;\n\t commands.brpop = commands.blpop;\n\t commands.hget = commands.hexists;\n\t commands.hmget = commands.hdel;\n\t commands.hsetnx = commands.hset;\n\t commands.msetnx = commands.mset;\n\t commands.rpush = commands.lpush;\n\t commands.hincrbyfloat = commands.hincrby;\n\t commands.srandmember = commands.spop;\n\t commands.zrevrange = commands.zrange;\n\t commands.zscore = commands.zrevrank;\n\t\n\t Object.keys(commands).forEach(function (command) {\n\t KuzzleMemoryStorage.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 (typeof args[args.length - 1] === 'function') {\n\t cb = args.pop();\n\t }\n\t\n\t if (args.length && typeof args[args.length - 1] === 'object' && Object.keys(args[args.length - 1]).length === 1 && args[args.length - 1].queuable !== undefined) {\n\t options = args.pop();\n\t }\n\t\n\t commands[command].forEach(function (v, i) {\n\t if (args[i] === undefined) {\n\t return;\n\t }\n\t\n\t if (Array.isArray(v)) {\n\t v = Array.isArray(args[i]) ? v[1] : v[0];\n\t }\n\t\n\t if (v === 'id') {\n\t data._id = args[i];\n\t }\n\t else {\n\t if (!data.body) {\n\t data.body = {};\n\t }\n\t\n\t if (typeof v === 'object' && v.__opts__ !== undefined) {\n\t v.__opts__.forEach(function (arg) {\n\t if (args[i][arg] !== undefined) {\n\t data.body[arg] = args[i][arg];\n\t }\n\t });\n\t }\n\t else {\n\t data.body[v] = args[i];\n\t }\n\t }\n\t });\n\t\n\t this.kuzzle.query(query, data, options, cb);\n\t\n\t return this;\n\t\n\t };\n\t });\n\t\n\t})();\n\t\n\tmodule.exports = KuzzleMemoryStorage;\n\n\n/***/ },\n/* 8 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t uuid = __webpack_require__(3);\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} kuzzleDataCollection - an instantiated and valid kuzzle object\n\t * @param {object} [options] - subscription optional configuration\n\t * @constructor\n\t */\n\tfunction KuzzleRoom(kuzzleDataCollection, 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: uuid.v4()\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 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: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.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(kuzzleDataCollection.headers)),\n\t enumerable: true,\n\t writable: true\n\t },\n\t metadata: {\n\t value: (options && options.metadata) ? options.metadata : {},\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\tKuzzleRoom.prototype.count = function (cb) {\n\t var data;\n\t\n\t this.kuzzle.callbackRequired('KuzzleRoom.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('KuzzleRoom.count: cannot count subscriptions on an inactive room');\n\t }\n\t\n\t this.kuzzle.query(this.collection.buildQueryArgs('subscribe', '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} cb - called for each new notification\n\t */\n\tKuzzleRoom.prototype.renew = function (filters, cb) {\n\t var\n\t now = Date.now(),\n\t subscribeQuery = {\n\t scope: this.scope,\n\t state: this.state,\n\t users: this.users\n\t },\n\t self = this;\n\t\n\t if (!cb && filters && typeof filters === 'function') {\n\t cb = filters;\n\t filters = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleRoom.renew', cb);\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;\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 = 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, 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 = 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, this.headers);\n\t\n\t self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'on'), subscribeQuery, {metadata: self.metadata}, 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 throw 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 });\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\tKuzzleRoom.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('subscribe', 'off'), {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('subscribe', 'off'), {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\tKuzzleRoom.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.error) {\n\t return this.callback(data.error);\n\t }\n\t\n\t if (data.action === 'jwtTokenExpired') {\n\t this.kuzzle.jwtToken = undefined;\n\t return this.kuzzle.emitEvent('jwtTokenExpired');\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 = KuzzleRoom;\n\n\n/***/ },\n/* 9 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/**\n\t *\n\t * @param host\n\t * @param wsPort\n\t * @param ioPort\n\t * @returns {Object} tnstantiated WebSocket/Socket.IO object\n\t */\n\t\n\tfunction network(host, wsPort, ioPort, 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__(11))(host, wsPort, sslConnection);\n\t }\n\t // otherwise fallback to socket.io, if available\n\t else if (window.io) {\n\t return new (__webpack_require__(10))(host, ioPort, 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__(!(function webpackMissingModule() { var e = new Error(\"Cannot find module \\\"./wrappers/wsnode\\\"\"); e.code = 'MODULE_NOT_FOUND'; throw e; }())))(host, wsPort, sslConnection);\n\t}\n\t\n\tmodule.exports = network;\n\n\n/***/ },\n/* 10 */\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\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 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\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.socket.on('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.socket.on('connect_error', 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.socket.on('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.socket.on('reconnect', callback);\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.socket.close();\n\t this.socket = null;\n\t };\n\t}\n\t\n\tmodule.exports = SocketIO;\n\n\n/***/ },\n/* 11 */\n/***/ function(module, exports) {\n\n\tfunction WSBrowsers(host, port, ssl) {\n\t var self = this;\n\t this.host = host;\n\t this.port = port;\n\t this.ssl = ssl;\n\t this.client = null;\n\t this.retrying = false;\n\t\n\t /*\n\t Listeners are stored using the following format:\n\t roomId: {\n\t fn: callback_function,\n\t once: boolean\n\t }\n\t */\n\t this.listeners = {\n\t error: [],\n\t connect: [],\n\t disconnect: [],\n\t reconnect: []\n\t };\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 this.client = new WebSocket((this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port);\n\t\n\t this.client.onopen = function () {\n\t if (self.retrying) {\n\t poke(self.listeners, 'reconnect');\n\t }\n\t else {\n\t poke(self.listeners, 'connect');\n\t }\n\t };\n\t\n\t this.client.onclose = function () {\n\t poke(self.listeners, 'disconnect');\n\t };\n\t\n\t this.client.onerror = function () {\n\t if (autoReconnect) {\n\t self.retrying = true;\n\t setTimeout(function () {\n\t self.connect(autoReconnect, reconnectionDelay);\n\t }, reconnectionDelay);\n\t }\n\t\n\t poke(self.listeners, 'error');\n\t };\n\t\n\t this.client.onmessage = function (payload) {\n\t var data = JSON.parse(payload.data);\n\t\n\t if (data.room && self.listeners[data.room]) {\n\t poke(self.listeners, data.room, 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.listeners.connect.push({\n\t fn: callback,\n\t keep: true\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 this.listeners.error.push({\n\t fn: callback,\n\t keep: true\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 this.listeners.disconnect.push({\n\t fn: callback,\n\t keep: true\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 this.listeners.reconnect.push({\n\t fn: callback,\n\t keep: true\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 if (!this.listeners[roomId]) {\n\t this.listeners[roomId] = [];\n\t }\n\t\n\t this.listeners[roomId].push({\n\t fn: callback,\n\t keep: false\n\t });\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 if (!this.listeners[roomId]) {\n\t this.listeners[roomId] = [];\n\t }\n\t\n\t this.listeners[roomId].push({\n\t fn: callback,\n\t keep: true\n\t });\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 var index;\n\t\n\t if (this.listeners[roomId]) {\n\t index = this.listeners[roomId].findIndex(function (listener) {\n\t return listener.fn === callback;\n\t });\n\t\n\t if (index !== -1) {\n\t if (this.listeners[roomId].length === 1 && ['error', 'connect', 'disconnect', 'reconnect'].indexOf(roomId) === -1) {\n\t delete this.listeners[roomId];\n\t }\n\t else {\n\t this.listeners[roomId].splice(index, 1);\n\t }\n\t }\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 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.listeners = {\n\t error: [],\n\t connect: [],\n\t disconnect: [],\n\t reconnect: []\n\t };\n\t\n\t this.retrying = false;\n\t this.client.close();\n\t this.client = null;\n\t };\n\t}\n\t\n\t/**\n\t * Executes all registered listeners in the provided\n\t * \"listeners\" structure.\n\t *\n\t * Listeners are of the following format:\n\t * [\n\t * { fn: callback, once: boolean },\n\t * ...\n\t * ]\n\t *\n\t * @private\n\t * @param {Object} listeners\n\t * @param {string} roomId\n\t * @param {Object} [payload]\n\t */\n\tfunction poke (listeners, roomId, payload) {\n\t var\n\t i,\n\t length = listeners[roomId].length;\n\t\n\t for (i = 0; i < length; ++i) {\n\t listeners[roomId][i].fn(payload);\n\t\n\t if (!listeners[roomId][i].keep) {\n\t if (listeners[roomId].length > 1) {\n\t listeners[roomId].splice(i, 1);\n\t --i;\n\t --length;\n\t }\n\t else {\n\t delete listeners[roomId];\n\t }\n\t }\n\t }\n\t}\n\t\n\tmodule.exports = WSBrowsers;\n\n\n/***/ },\n/* 12 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleProfile(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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\tKuzzleProfile.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleProfile\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 {Object} this\n\t */\n\tKuzzleProfile.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.kuzzleSecurity.buildQueryArgs('createOrReplaceProfile'), data, options, function (error) {\n\t cb && cb(error, 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 {KuzzleProfile} this\n\t */\n\tKuzzleProfile.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 {KuzzleProfile} this\n\t */\n\tKuzzleProfile.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\tKuzzleProfile.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\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\tKuzzleProfile.prototype.getPolicies = function () {\n\t return this.content.policies;\n\t};\n\t\n\tmodule.exports = KuzzleProfile;\n\n\n/***/ },\n/* 13 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleRole(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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\tKuzzleRole.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleRole\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 */\n\tKuzzleRole.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.kuzzleSecurity.buildQueryArgs('createOrReplaceRole'), data, options, function (error) {\n\t cb && cb(error, self);\n\t });\n\t\n\t return this;\n\t};\n\t\n\tmodule.exports = KuzzleRole;\n\n/***/ },\n/* 14 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleRole = __webpack_require__(13),\n\t KuzzleProfile = __webpack_require__(12),\n\t KuzzleUser = __webpack_require__(2);\n\t\n\t/**\n\t * Kuzzle security constructor\n\t *\n\t * @param kuzzle\n\t * @returns {KuzzleSecurity}\n\t * @constructor\n\t */\n\tfunction KuzzleSecurity(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 = ['roleFactory', 'profileFactory', 'userFactory', '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} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getRole = 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 getRole 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('KuzzleSecurity.getRole', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n\t cb(err, !err && new KuzzleRole(self, response.result._id, response.result._source));\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} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t *\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.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 KuzzleRole(self, doc._id, doc._source);\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.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 && new KuzzleRole(self, res.result._id, res.result._source));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.updateRole = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {_id: id, content: content},\n\t action = 'updateRole';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.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) {\n\t cb(err, !err && new KuzzleRole(self, id, content));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleSecurity.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 && res.result._id);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleRole 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 * @constructor\n\t */\n\tKuzzleSecurity.prototype.roleFactory = function(id, content) {\n\t return new KuzzleRole(this, id, content);\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} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getProfile = 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 getProfile function');\n\t }\n\t\n\t\n\t data = {_id: id};\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.getProfile', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n\t cb(error, !error && new KuzzleProfile(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.searchProfiles', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n\t var documents;\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 KuzzleProfile(self, doc._id, doc._source);\n\t });\n\t\n\t cb(null, { total: response.result.total, profiles: documents });\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 {object} content - attribute `roles` in `content` must only contains an array of role id\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.createProfile = function (id, content, 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('KuzzleSecurity.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 data.body = content;\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 && new KuzzleProfile(self, res.result._id, res.result._source));\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 {object} content - a plain javascript object representing the profile's modification\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.updateProfile = function (id, content, 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('KuzzleSecurity.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 data.body = content;\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 KuzzleProfile(self, res.result._id, updatedContent));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleSecurity.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 && res.result._id);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleProfile 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 * @constructor\n\t */\n\tKuzzleSecurity.prototype.profileFactory = function(id, content) {\n\t return new KuzzleProfile(this, id, content);\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} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getUser = 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 getUser 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('KuzzleSecurity.getUser', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n\t cb(err, !err && new KuzzleUser(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.searchUsers', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n\t var documents;\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 KuzzleUser(self, doc._id, doc._source);\n\t });\n\t\n\t cb(null, { total: response.result.total, users: documents });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new user 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 user already exists: throw an error if sets to false.\n\t * Replace the existing user otherwise\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.createUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {},\n\t action = 'createUser';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.createUser: cannot create 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 data._id = id;\n\t data.body = content;\n\t\n\t if (options) {\n\t action = options.replaceIfExist ? 'createOrReplaceUser' : 'createUser';\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, null, cb && function (err, res) {\n\t cb(err, !err && new KuzzleUser(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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.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 && new KuzzleUser(self, res.result._id, res.result._source));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleSecurity.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 && res.result._id);\n\t });\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleUser 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 * @constructor\n\t */\n\tKuzzleSecurity.prototype.userFactory = function(id, content) {\n\t return new KuzzleUser(this, id, content);\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\tKuzzleSecurity.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} [options] - (optional) arguments\n\t * @param {function} cb The callback containing the normalized array of rights.\n\t */\n\tKuzzleSecurity.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 && res.result.hits);\n\t });\n\t};\n\t\n\tmodule.exports = KuzzleSecurity;\n\n\n/***/ }\n/******/ ])\n});\n;\n\n\n/** WEBPACK FOOTER **\n ** kuzzle.js\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/** WEBPACK FOOTER **\n ** webpack/bootstrap 6e56962709edb509472f\n **/","var\n uuid = require('node-uuid'),\n KuzzleDataCollection = require('./kuzzleDataCollection'),\n KuzzleSecurity = require('./security/kuzzleSecurity'),\n KuzzleMemoryStorage = require('./kuzzleMemoryStorage'),\n KuzzleUser = require('./security/kuzzleUser'),\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 * @constructor\n */\nmodule.exports = Kuzzle = function (host, options, cb) {\n var self = this;\n\n if (!(this instanceof Kuzzle)) {\n return new Kuzzle(host, options, cb);\n }\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 collections: {\n value: {},\n writable: true\n },\n connectCB: {\n value: cb\n },\n eventListeners: {\n value: {\n connected: {lastEmitted: null, listeners: []},\n error: {lastEmitted: null, listeners: []},\n disconnected: {lastEmitted: null, listeners: []},\n reconnected: {lastEmitted: null, listeners: []},\n jwtTokenExpired: {lastEmitted: null, listeners: []},\n loginAttempt: {lastEmitted: null, listeners: []},\n offlineQueuePush: {listeners: []},\n offlineQueuePop: {listeners: []}\n }\n },\n eventTimeout: {\n value: 200\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 'roomId': {\n kuzzleRoomID_1: kuzzleRoomInstance_1,\n kuzzleRoomID_2: kuzzleRoomInstance_2,\n kuzzleRoomID_...: 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 // read-only properties\n autoReconnect: {\n value: (options && typeof options.autoReconnect === 'boolean') ? options.autoReconnect : 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 enumerable: true\n },\n host: {\n value: host,\n enumerable: true\n },\n wsPort: {\n value: (options && typeof options.wsPort === 'number') ? options.wsPort : 7513,\n enumerable: true\n },\n ioPort: {\n value: (options && typeof options.ioPort === 'number') ? options.ioPort : 7512,\n enumerable: true\n },\n sslConnection: {\n value: (options && typeof options.sslConnection === 'boolean') ? options.sslConnection : false,\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 metadata: {\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: null,\n enumerable: true,\n writable: true\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 KuzzleSecurity(this),\n enumerable: true\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 Object.defineProperty(this, 'emitEvent', {\n value: function emitEvent(event) {\n var\n now = Date.now(),\n args = Array.prototype.slice.call(arguments, 1),\n eventProperties = this.eventListeners[event];\n\n if (eventProperties.lastEmitted && eventProperties.lastEmitted >= now - this.eventTimeout) {\n return false;\n }\n\n eventProperties.listeners.forEach(function (listener) {\n process.nextTick(function () {\n listener.fn.apply(undefined, args);\n });\n });\n\n // Events without the 'lastEmitted' property can be emitted without minimum time between emissions\n if (eventProperties.lastEmitted !== undefined) {\n eventProperties.lastEmitted = now;\n }\n }\n });\n\n Object.defineProperty(this, 'memoryStorage', {\n value: new KuzzleMemoryStorage(this),\n enumerable: true\n });\n\n\n if (!options || !options.connect || options.connect === 'auto') {\n this.connect();\n } else {\n this.state = 'ready';\n }\n\n cleanHistory(this.requestHistory);\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', 'listIndexes', 'login', 'logout', 'now', 'query',\n 'checkToken', 'whoAmI', 'updateSelf', 'getMyRights',\n 'refreshIndex', 'getAutoRefresh', 'setAutoRefresh'\n ];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n};\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.network = networkWrapper(self.host, self.wsPort, self.ioPort, self.sslConnection);\n }\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.onConnectError(function (error) {\n var connectionError = new Error('Unable to connect to kuzzle server at \"' + self.host + '\"');\n\n connectionError.internal = error;\n self.state = 'error';\n self.emitEvent('error', connectionError);\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('jwtTokenExpired');\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 * 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 * @returns {Kuzzle}\n */\nKuzzle.prototype.login = function (strategy) {\n var\n self = this,\n request = {\n strategy: strategy\n },\n credentials,\n cb = null;\n\n // Handle arguments (credentials, expiresIn, cb)\n if (arguments[1]) {\n if (typeof arguments[1] === 'object') {\n credentials = 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 if (typeof credentials === 'object') {\n Object.keys(credentials).forEach(function (key) {\n request[key] = credentials[key];\n });\n }\n\n this.query({controller: 'auth', action: 'login'}, {body: request}, {queuable: false}, cb && function(error, response) {\n if (!error) {\n if (response.result.jwt) {\n self.setJwtToken(response.result.jwt);\n }\n\n cb(null, response.result);\n }\n else {\n cb(error);\n self.emitEvent('loginAttempt', {success: false, error: error.message});\n }\n });\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: uuid.v4(),\n body: {}\n };\n\n this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, typeof cb !== 'function' ? null : function(error) {\n if (error === null) {\n self.jwtToken = undefined;\n cb(null, self);\n }\n else {\n cb(error);\n }\n });\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} callback The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n * @return {Kuzzle} The Kuzzle instance to enable chaining.\n */\nKuzzle.prototype.checkToken = function (token, callback) {\n var\n request = {\n body: {\n token: token\n }\n };\n\n this.callbackRequired('Kuzzle.checkToken', callback);\n\n this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, function (err, response) {\n if (err) {\n return callback(err);\n }\n\n callback(null, response.result);\n });\n};\n\n/**\n * Fetches the current user.\n *\n * @param {function} callback The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n * @return {Kuzzle} The Kuzzle instance to enable chaining.\n */\nKuzzle.prototype.whoAmI = function (callback) {\n var self = this;\n\n self.callbackRequired('Kuzzle.whoAmI', callback);\n\n self.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, function (err, response) {\n if (err) {\n return callback(err);\n }\n\n callback(null, new KuzzleUser(self.security, response.result._id, response.result._source));\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'}, {}, null, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, 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 */\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 && 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 setTimeout(function () {\n cleanHistory(requestHistory);\n }, 1000);\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 if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n self.jwtToken = undefined;\n self.emitEvent('jwtTokenExpired', request, cb);\n }\n\n cb && cb(response.error, response);\n });\n }\n\n this.network.send(request);\n\n // Track requests made to allow KuzzleRoom.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 * 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 * The ID returned by this function is required to remove this listener at a later time.\n *\n * @param {string} event - name of the global event to subscribe to (see the 'eventListeners' object property)\n * @param {function} listener - callback to invoke each time an event is fired\n * @returns {string} Unique listener ID\n */\nKuzzle.prototype.addListener = function(event, listener) {\n var\n knownEvents = Object.keys(this.eventListeners),\n listenerType = typeof listener,\n listenerId;\n\n this.isValid();\n\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n if (listenerType !== 'function') {\n throw new Error('Invalid listener type: expected a function, got a ' + listenerType);\n }\n\n listenerId = uuid.v4();\n this.eventListeners[event].listeners.push({id: listenerId, fn: listener});\n return listenerId;\n};\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 * @returns {object} this\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:'admin', action: 'getAllStats'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, 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 * @returns {object} this\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 if (timestamp) {\n cb(null, res.result.hits);\n } else {\n cb(null, [res.result]);\n }\n };\n\n this.callbackRequired('Kuzzle.getStatistics', cb);\n\n body = timestamp ? {body: {startTime: timestamp}} : {};\n this.query({controller: 'admin', action: 'getLastStats'}, body, options, queryCB);\n};\n\n/**\n * Create a new instance of a KuzzleDataCollection 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 {object} A KuzzleDataCollection instance\n */\nKuzzle.prototype.dataCollectionFactory = 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 KuzzleDataCollection(this, index, collection);\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 * @returns {object} this\n */\nKuzzle.prototype.listCollections = function () {\n var\n collectionType = 'all',\n index,\n options,\n cb,\n args = Array.prototype.slice.call(arguments);\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 if (options && options.type) {\n collectionType = options.type;\n }\n\n this.query({index: index, controller: 'read', action: 'listCollections'}, {body: {type: collectionType}}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, 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 * @returns {object} this\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: 'read', action: 'listIndexes'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, 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 this.logout();\n\n this.state = 'disconnected';\n this.network.close();\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 * @returns {object} this\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: 'read', action: 'serverInfo'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, 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: 'admin', action: 'refreshIndex'}, {}, 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 * @returns {object} this\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: 'admin', 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: 'admin', 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 * @returns {object} this\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: 'read', action: 'now'}, {}, options, function (err, res) {\n cb(err, res && 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 * - metadata (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 metadata: this.metadata\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.metadata) {\n Object.keys(options.metadata).forEach(function (meta) {\n object.metadata[meta] = options.metadata[meta];\n });\n }\n\n if (options.queuable === false && self.state === 'offline') {\n return self;\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.metadata) {\n Object.keys(query.metadata).forEach(function (meta) {\n object.metadata[meta] = query.metadata[meta];\n });\n }\n\n for (attr in query) {\n if (attr !== 'metadata' && 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.headers = object.headers || {};\n object.headers.authorization = 'Bearer ' + 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 = uuid.v4();\n }\n\n if (self.state === 'connected' || (options && options.queuable === false)) {\n if (self.state === 'connected') {\n emitRequest.call(this, object, cb);\n } else if (cb) {\n cb(new Error('Unable to execute request: not connected to a Kuzzle server.\\nDiscarded request: ' + JSON.stringify(object)));\n }\n } else if (self.queuing || ['initializing', 'connecting'].indexOf(self.state) !== -1) {\n cleanQueue.call(this, object, cb);\n\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 }\n }\n\n return self;\n};\n\n/**\n * Removes all listeners, either from a specific event or from all events\n *\n * @param {string} event - One of the event described in the Event Handling section of this documentation\n */\nKuzzle.prototype.removeAllListeners = function (event) {\n var\n knownEvents = Object.keys(this.eventListeners),\n self = this;\n\n if (event) {\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n this.eventListeners[event].listeners = [];\n } else {\n knownEvents.forEach(function (eventName) {\n self.eventListeners[eventName].listeners = [];\n });\n }\n\n return this;\n};\n\n/**\n * Removes a listener from an event.\n *\n * @param {string} event - One of the event described in the Event Handling section of this documentation\n * @param {string} listenerId - The ID returned by addListener\n */\nKuzzle.prototype.removeListener = function (event, listenerId) {\n var\n knownEvents = Object.keys(this.eventListeners),\n self = this;\n\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n this.eventListeners[event].listeners.forEach(function (listener, index) {\n if (listener.id === listenerId) {\n self.eventListeners[event].listeners.splice(index, 1);\n }\n });\n\n return this;\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\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzle.js\n ** module id = 0\n ** module chunks = 0\n **/","function KuzzleSecurityDocument(kuzzleSecurity, id, content) {\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: kuzzleSecurity.kuzzle\n },\n kuzzleSecurity: {\n value: kuzzleSecurity\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 });\n\n if (content) {\n this.setContent(content, true);\n }\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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 {Object} this\n */\nKuzzleSecurityDocument.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 */\nKuzzleSecurityDocument.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\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 */\nKuzzleSecurityDocument.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.kuzzleSecurity.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 */\nKuzzleSecurityDocument.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.kuzzleSecurity.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 = KuzzleSecurityDocument;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleSecurityDocument.js\n ** module id = 1\n ** module chunks = 0\n **/","var\n KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleUser(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteUser'\n },\n updateActionName: {\n value: 'updateUser'\n }\n });\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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\nKuzzleUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleUser\n }\n});\n\n/**\n * Set profiles in content\n * @param {array} profile - an array of profiles ids string\n *\n * @returns {KuzzleUser} this\n */\nKuzzleUser.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 * Add a profile\n * @param {string} profile - a profile ids string\n *\n * @returns {KuzzleUser} this\n */\nKuzzleUser.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 * Saves this user into Kuzzle.\n *\n * If this is a new user, this function will create it in Kuzzle.\n * Otherwise, this method will replace the latest version of this user in Kuzzle by the current content\n * of this object.\n *\n * @param {responseCallback} [cb] - Handles the query response\n * @param {object} [options] - Optional parameters\n * @returns {*} this\n */\nKuzzleUser.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.kuzzleSecurity.buildQueryArgs('createOrReplaceUser'), data, options, cb && function (error) {\n cb(error, !error && 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 */\nKuzzleUser.prototype.serialize = function () {\n return {_id: this.id, body: this.content};\n};\n\n/**\n * Return the associated profiles IDs\n *\n * @return {array} the associated profiles IDs\n */\nKuzzleUser.prototype.getProfiles = function () {\n return this.content.profileIds;\n};\n\nmodule.exports = KuzzleUser;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleUser.js\n ** module id = 2\n ** module chunks = 0\n **/","// uuid.js\n//\n// Copyright (c) 2010-2012 Robert Kieffer\n// MIT License - http://opensource.org/licenses/mit-license.php\n\n/*global window, require, define */\n(function(_window) {\n 'use strict';\n\n // Unique ID creation requires a high quality random # generator. We feature\n // detect to determine the best RNG source, normalizing to a function that\n // returns 128-bits of randomness, since that's what's usually required\n var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot;\n\n function setupBrowser() {\n // Allow for MSIE11 msCrypto\n var _crypto = _window.crypto || _window.msCrypto;\n\n if (!_rng && _crypto && _crypto.getRandomValues) {\n // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto\n //\n // Moderately fast, high quality\n try {\n var _rnds8 = new Uint8Array(16);\n _whatwgRNG = _rng = function whatwgRNG() {\n _crypto.getRandomValues(_rnds8);\n return _rnds8;\n };\n _rng();\n } catch(e) {}\n }\n\n if (!_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 _mathRNG = _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 if ('undefined' !== typeof console && console.warn) {\n console.warn(\"[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()\");\n }\n }\n }\n\n function setupNode() {\n // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html\n //\n // Moderately fast, high quality\n if ('function' === typeof require) {\n try {\n var _rb = require('crypto').randomBytes;\n _nodeRNG = _rng = _rb && function() {return _rb(16);};\n _rng();\n } catch(e) {}\n }\n }\n\n if (_window) {\n setupBrowser();\n } else {\n setupNode();\n }\n\n // Buffer class to use\n var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;\n\n // Maps for number <-> hex string conversion\n var _byteToHex = [];\n var _hexToByte = {};\n for (var i = 0; i < 256; i++) {\n _byteToHex[i] = (i + 0x100).toString(16).substr(1);\n _hexToByte[_byteToHex[i]] = i;\n }\n\n // **`parse()` - Parse a UUID into it's component bytes**\n function parse(s, buf, offset) {\n var i = (buf && offset) || 0, ii = 0;\n\n buf = buf || [];\n s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {\n if (ii < 16) { // Don't overflow!\n buf[i + ii++] = _hexToByte[oct];\n }\n });\n\n // Zero out remaining bytes if string was short\n while (ii < 16) {\n buf[i + ii++] = 0;\n }\n\n return buf;\n }\n\n // **`unparse()` - Convert UUID byte array (ala parse()) into a string**\n function unparse(buf, offset) {\n var i = offset || 0, 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\n // **`v1()` - Generate time-based UUID**\n //\n // Inspired by https://github.com/LiosK/UUID.js\n // and http://docs.python.org/library/uuid.html\n\n // random #'s we need to init node and clockseq\n var _seedBytes = _rng();\n\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n var _nodeId = [\n _seedBytes[0] | 0x01,\n _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]\n ];\n\n // Per 4.2.2, randomize (14 bit) clockseq\n var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;\n\n // Previous uuid creation time\n var _lastMSecs = 0, _lastNSecs = 0;\n\n // See https://github.com/broofa/node-uuid for API details\n function v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || [];\n\n options = options || {};\n\n var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;\n\n // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n var msecs = (options.msecs != null) ? options.msecs : new Date().getTime();\n\n // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;\n\n // Time since last uuid creation (in msecs)\n var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\n // Per 4.2.1.2, Bump clockseq on clock regression\n if (dt < 0 && options.clockseq == null) {\n clockseq = clockseq + 1 & 0x3fff;\n }\n\n // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {\n nsecs = 0;\n }\n\n // Per 4.2.1.2 Throw error if too many uuids are requested\n if (nsecs >= 10000) {\n throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq;\n\n // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n msecs += 12219292800000;\n\n // `time_low`\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff;\n\n // `time_mid`\n var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff;\n\n // `time_high_and_version`\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n b[i++] = tmh >>> 16 & 0xff;\n\n // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n b[i++] = clockseq >>> 8 | 0x80;\n\n // `clock_seq_low`\n b[i++] = clockseq & 0xff;\n\n // `node`\n var node = options.node || _nodeId;\n for (var n = 0; n < 6; n++) {\n b[i + n] = node[n];\n }\n\n return buf ? buf : unparse(b);\n }\n\n // **`v4()` - Generate random UUID**\n\n // See https://github.com/broofa/node-uuid for API details\n function v4(options, buf, offset) {\n // Deprecated - 'format' argument, as supported in v1.2\n var i = buf && offset || 0;\n\n if (typeof(options) === 'string') {\n buf = (options === 'binary') ? new BufferClass(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 || unparse(rnds);\n }\n\n // Export public API\n var uuid = v4;\n uuid.v1 = v1;\n uuid.v4 = v4;\n uuid.parse = parse;\n uuid.unparse = unparse;\n uuid.BufferClass = BufferClass;\n uuid._rng = _rng;\n uuid._mathRNG = _mathRNG;\n uuid._nodeRNG = _nodeRNG;\n uuid._whatwgRNG = _whatwgRNG;\n\n if (('undefined' !== typeof module) && module.exports) {\n // Publish as node.js module\n module.exports = uuid;\n } else if (typeof define === 'function' && define.amd) {\n // Publish as AMD module\n define(function() {return uuid;});\n\n\n } else {\n // Publish as global (in browsers)\n _previousRoot = _window.uuid;\n\n // **`noConflict()` - (browser only) to reset global 'uuid' var**\n uuid.noConflict = function() {\n _window.uuid = _previousRoot;\n return uuid;\n };\n\n _window.uuid = uuid;\n }\n})('undefined' !== typeof window ? window : null);\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/node-uuid/uuid.js\n ** module id = 3\n ** module chunks = 0\n **/","var\n KuzzleDocument = require('./kuzzleDocument'),\n KuzzleDataMapping = require('./kuzzleDataMapping'),\n KuzzleRoom = require('./kuzzleRoom');\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 * @param {object} kuzzle - Kuzzle instance to inherit from\n * @param {string} index - Index containing the data collection\n * @param {string} collection - name of the data collection to handle\n * @constructor\n */\nfunction KuzzleDataCollection(kuzzle, index, collection) {\n if (!index || !collection) {\n throw new Error('The KuzzleDataCollection object constructor needs an index and a collection arguments');\n }\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 * 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 * @returns {Object} this\n */\nKuzzleDataCollection.prototype.advancedSearch = function (filters, options, cb) {\n var\n query,\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleDataCollection.advancedSearch', cb);\n\n query = self.kuzzle.addHeaders({body: filters}, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('read', '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 KuzzleDocument(self, doc._id, doc._source);\n\n newDocument.version = doc._version;\n\n documents.push(newDocument);\n });\n\n cb(null, { total: result.result.total, documents: documents });\n });\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 * @returns {Object} this\n */\nKuzzleDataCollection.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('KuzzleDataCollection.count', cb);\n\n query = this.kuzzle.addHeaders({body: filters}, this.headers);\n\n this.kuzzle.query(this.buildQueryArgs('read', 'count'), query, options, function (error, result) {\n cb(error, result && result.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 */\nKuzzleDataCollection.prototype.create = 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('write', 'createCollection'), data, options, cb);\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 * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n * - updateIfExist (boolean, default: false):\n * If the same document already exists: throw an error if sets to false.\n * Update the existing document otherwise\n *\n * @param {string} [id] - (optional) document identifier\n * @param {object} document - either an instance of a KuzzleDocument object, or a document\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Object} this\n */\nKuzzleDataCollection.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 KuzzleDocument) {\n data = document.serialize();\n } else {\n data.body = document;\n }\n\n if (options) {\n action = options.updateIfExist ? 'createOrReplace' : 'create';\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('write', action), data, options, cb && function (err, res) {\n var doc;\n\n if (err) {\n return cb(err);\n }\n\n doc = new KuzzleDocument(self, res.result._id, res.result._source);\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 * - metadata (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 {Object} this\n */\nKuzzleDataCollection.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 = 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('write', action), data, options, cb && function (err, res) {\n cb(err, !err && (action === 'delete' ? [res.result._id] : res.result.ids));\n });\n\n return this;\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 * @returns {Object} this\n */\nKuzzleDataCollection.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('KuzzleDataCollection.fetch', cb);\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('read', 'get'), data, options, function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new KuzzleDocument(self, res.result._id, res.result._source);\n document.version = res.result._version;\n cb(null, document);\n });\n};\n\n/**\n * Retrieves all documents stored in this data collection\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n * @returns {Object} this\n */\nKuzzleDataCollection.prototype.fetchAllDocuments = function (options, cb) {\n var filters = {};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n // copying pagination options to the search filter\n if (options) {\n if (options.from) {\n filters.from = options.from;\n }\n\n if (options.size) {\n filters.size = options.size;\n }\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.fetchAll', cb);\n\n this.advancedSearch(filters, options, cb);\n};\n\n\n/**\n * Instantiates a KuzzleDataMapping object containing the current mapping of this collection.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated KuzzleDataMapping object\n * @return {object} this\n */\nKuzzleDataCollection.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('KuzzleDataCollection.getMapping', cb);\n\n kuzzleMapping = new KuzzleDataMapping(this);\n kuzzleMapping.refresh(options, cb);\n};\n\n/**\n * Publish a realtime message\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} document - either a KuzzleDocument instance or a JSON object\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Returns a raw Kuzzle response\n * @returns {*} this\n */\nKuzzleDataCollection.prototype.publishMessage = function (document, options, cb) {\n var data = {};\n\n if (document instanceof KuzzleDocument) {\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('write', '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 * - metadata (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 KuzzleDocument object\n * @return {object} this\n */\nKuzzleDataCollection.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('write', 'createOrReplace'), data, options, cb && function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new KuzzleDocument(self, res.result._id, res.result._source);\n document.version = res.result._version;\n cb(null, document);\n });\n\n return this;\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 {*} KuzzleRoom object\n */\nKuzzleDataCollection.prototype.subscribe = function (filters, options, cb) {\n var room;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.subscribe', cb);\n\n room = new KuzzleRoom(this, options);\n\n return room.renew(filters, cb);\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 */\nKuzzleDataCollection.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('admin', 'truncateCollection'), 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 * - metadata (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 KuzzleDocument object\n * @return {object} this\n */\nKuzzleDataCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n var\n 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 data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options, cb && function (err, res) {\n if (err) {\n return cb(err);\n }\n\n (new KuzzleDocument(self, res.result._id)).refresh(cb);\n });\n\n return self;\n};\n\n\n/**\n * Instantiate a new KuzzleDocument 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 */\nKuzzleDataCollection.prototype.documentFactory = function (id, content) {\n return new KuzzleDocument(this, id, content);\n};\n\n/**\n * Instantiate a new KuzzleRoom 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 */\nKuzzleDataCollection.prototype.roomFactory = function (options) {\n return new KuzzleRoom(this, options);\n};\n\n/**\n * Instantiate a new KuzzleDataMapping 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 KuzzleDataMapping object with\n * @constructor\n */\nKuzzleDataCollection.prototype.dataMappingFactory = function (mapping) {\n return new KuzzleDataMapping(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 */\nKuzzleDataCollection.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\nmodule.exports = KuzzleDataCollection;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDataCollection.js\n ** module id = 4\n ** module chunks = 0\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 * 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 KuzzleDataMapping object allow to get the current mapping of a data collection and to modify it if needed.\n *\n * @param {object} kuzzleDataCollection - Instance of the inherited KuzzleDataCollection object\n * @param {object} mapping - mappings\n * @constructor\n */\nfunction KuzzleDataMapping(kuzzleDataCollection, mapping) {\n Object.defineProperties(this, {\n //read-only properties\n collection: {\n value: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.kuzzle,\n enumerable: true\n },\n // writable properties\n headers: {\n value: JSON.parse(JSON.stringify(kuzzleDataCollection.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 */\nKuzzleDataMapping.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('admin', '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 */\nKuzzleDataMapping.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('admin', '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 {KuzzleDataMapping}\n */\nKuzzleDataMapping.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 */\nKuzzleDataMapping.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\nmodule.exports = KuzzleDataMapping;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDataMapping.js\n ** module id = 5\n ** module chunks = 0\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 handles documents either as realtime messages or as stored documents.\n * KuzzleDocument 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 {object} kuzzleDataCollection - an instanciated KuzzleDataCollection object\n * @param {string} [documentId] - ID of an existing document\n * @param {object} [content] - Initializes this document with the provided content\n * @constructor\n */\nfunction KuzzleDocument(kuzzleDataCollection, documentId, content) {\n Object.defineProperties(this, {\n // read-only properties\n collection: {\n value: kuzzleDataCollection.collection,\n enumerable: true\n },\n dataCollection: {\n value: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.kuzzle,\n enumerable: true\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(kuzzleDataCollection.headers)),\n enumerable: true,\n writable: true\n },\n version: {\n value: undefined,\n enumerable: true,\n writable: true\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 */\nKuzzleDocument.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._version = this.version;\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 */\nKuzzleDocument.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 * - metadata (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 */\nKuzzleDocument.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('KuzzleDocument.delete: cannot delete a document without a document ID');\n }\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'delete'), this.serialize(), options, cb && function (err) {\n cb(err, !err && self.id);\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 */\nKuzzleDocument.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('KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided');\n }\n\n this.kuzzle.callbackRequired('KuzzleDocument.refresh', cb);\n\n self.kuzzle.query(self.dataCollection.buildQueryArgs('read', 'get'), {_id: self.id}, options, function (error, res) {\n var newDocument;\n\n if (error) {\n return cb(error);\n }\n\n newDocument = new KuzzleDocument(self.dataCollection, self.id, res.result._source);\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 * - metadata (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 */\nKuzzleDocument.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('write', '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 * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @returns {*} this\n */\nKuzzleDocument.prototype.publish = function (options) {\n var data = this.serialize();\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('write', '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 */\nKuzzleDocument.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 */\nKuzzleDocument.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('KuzzleDocument.subscribe', cb);\n\n if (!this.id) {\n throw new Error('KuzzleDocument.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 */\nKuzzleDocument.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\n\nmodule.exports = KuzzleDocument;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDocument.js\n ** module id = 6\n ** module chunks = 0\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), excepting:\n * * all cluster based functions\n * * all script based functions\n * * all cursors functions\n *\n * For instance:\n * kuzzle.memoryStorage\n * .set('myKey', 'myValue')\n * .get('myKey', function (err, response) {\n * console.log(response.result);\n *\n * // { _id: 'foo', body: { value: 'myValue' }}\n * });\n *\n *\n * @param {object} kuzzle - Kuzzle instance to inherit from\n * @constructor\n */\nfunction KuzzleMemoryStorage(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\n/**\n * constructs the memoryStorage functions.\n */\n(function() {\n\n var\n keyVal = ['id', 'value'],\n idOrKeys = ['id', 'keys'],\n commands = {\n append: keyVal,\n bgrewriteaof: [],\n bgsave: [],\n bitcount: ['id', 'start', 'end'],\n bitop: ['operation', 'destkey', idOrKeys],\n bitpos: ['id', 'bit', { __opts__: ['start', 'end']}],\n blpop: [idOrKeys, 'timeout'],\n brpoplpush: ['source', 'destination'],\n dbsize: [],\n decrby: keyVal,\n del: [idOrKeys],\n discard: [],\n exec: [],\n exists: [idOrKeys],\n expire: ['id', 'seconds'],\n expireat: ['id', 'timestamp'],\n flushdb: [],\n // @todo: implement geolocation methods once available in Redis stable release\n getbit: ['id', 'offset'],\n getrange: ['id', 'start', 'end'],\n hdel: ['id', ['field', 'fields']],\n hexists: ['id', 'field'],\n hincrby: ['id', 'field', 'value'],\n hmset: ['id', 'values'],\n hset: ['id', 'field', 'value'],\n info: ['section'],\n keys: [ 'pattern' ],\n lastsave: [],\n lindex: ['id', 'idx'],\n linsert: ['id', 'position', 'pivot', 'value'],\n lpush: ['id', ['value', 'values']],\n lrange: ['id', 'start', 'stop'],\n lrem: ['id', 'count', 'value'],\n lset: ['id', 'idx', 'value'],\n ltrim: ['id', 'start', 'stop'],\n mset: ['values'],\n multi: [],\n object: ['subcommand', 'args'],\n pexpire: ['id', 'milliseconds'],\n pexpireat: ['id', 'timestamp'],\n pfadd: ['id', ['element', 'elements']],\n pfmerge: ['destkey', ['sourcekey', 'sourcekeys']],\n ping: [],\n psetex: ['id', 'milliseconds', 'value'],\n publish: ['channel', 'message'],\n randomkey: [],\n rename: ['id', 'newkey'],\n renamenx: ['id', 'newkey'],\n restore: ['id', 'ttl', 'content'],\n rpoplpush: ['source', 'destination'],\n sadd: ['id', ['member', 'members']],\n save: [],\n set: ['id', 'value', {__opts__:['ex', 'px', 'nx', 'xx']}],\n sdiffstore: ['destination', idOrKeys],\n setbit: ['id', 'offset', 'value'],\n setex: ['id', 'seconds', 'value'],\n setrange: ['id', 'offset', 'value'],\n sinterstore: ['destination', idOrKeys],\n sismember: ['id', 'member'],\n smove: ['id', 'destination', 'member'],\n sort: ['id', {__opts__:['by', 'offset', 'count', 'get', 'direction', 'alpha', 'store']}],\n spop: ['id', 'count'],\n srem: ['id', ['member', 'members']],\n sunionstore: ['destination', idOrKeys],\n unwatch: [],\n wait: ['numslaves', 'timeout'],\n zadd: ['id', {__opts__: ['nx', 'xx', 'ch', 'incr', 'score', 'member', 'members']}],\n zcount: ['id', 'min', 'max'],\n zincrby: ['id', 'value', 'member'],\n zinterstore: ['destination', idOrKeys, {__opts__: ['weight', 'weights', 'aggregate']}],\n zlexcount: ['id', 'min', 'max'],\n zrange: ['id', 'start', 'stop', {__opts__: ['withscores']}],\n zrangebylex: ['id', 'min', 'max', {__opts__: ['offset', 'count']}],\n zrangebyscore: ['id', 'min', 'max', {__opts__: ['withscores', 'offset', 'count']}],\n zrem: ['id', 'member'],\n zremrangebylex: ['id', 'min', 'max'],\n zremrangebyscore: ['id', 'min', 'max'],\n zrevrangebylex: ['id', 'max', 'min', {__opts__: ['offset', 'count']}],\n zrevrangebyscore: ['id', 'max', 'min', {__opts__: ['withscores', 'offset', 'count']}],\n zrevrank: ['id', 'member']\n };\n\n // unique argument key\n commands.decr = commands.get = commands.dump = commands.hgetall = commands.hkeys = commands.hlen = commands.hstrlen = commands.hvals = commands.incr = commands.llen = commands.lpop = commands.persist = commands.pttl = commands.rpop = commands.scard = commands.smembers = commands.strlen = commands.ttl = commands.type = commands.zcard = ['id'];\n\n // key value\n commands.getset = commands.lpushx = keyVal;\n\n // key key...\n commands.del = commands.exists = commands.mget = commands.pfcount = commands.sdiff = commands.sinter = commands.sunion = commands.watch = [idOrKeys];\n\n commands.incrby = commands.incrbyfloat = commands.decrby;\n commands.brpop = commands.blpop;\n commands.hget = commands.hexists;\n commands.hmget = commands.hdel;\n commands.hsetnx = commands.hset;\n commands.msetnx = commands.mset;\n commands.rpush = commands.lpush;\n commands.hincrbyfloat = commands.hincrby;\n commands.srandmember = commands.spop;\n commands.zrevrange = commands.zrange;\n commands.zscore = commands.zrevrank;\n\n Object.keys(commands).forEach(function (command) {\n KuzzleMemoryStorage.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 (typeof args[args.length - 1] === 'function') {\n cb = args.pop();\n }\n\n if (args.length && typeof args[args.length - 1] === 'object' && Object.keys(args[args.length - 1]).length === 1 && args[args.length - 1].queuable !== undefined) {\n options = args.pop();\n }\n\n commands[command].forEach(function (v, i) {\n if (args[i] === undefined) {\n return;\n }\n\n if (Array.isArray(v)) {\n v = Array.isArray(args[i]) ? v[1] : v[0];\n }\n\n if (v === 'id') {\n data._id = args[i];\n }\n else {\n if (!data.body) {\n data.body = {};\n }\n\n if (typeof v === 'object' && v.__opts__ !== undefined) {\n v.__opts__.forEach(function (arg) {\n if (args[i][arg] !== undefined) {\n data.body[arg] = args[i][arg];\n }\n });\n }\n else {\n data.body[v] = args[i];\n }\n }\n });\n\n this.kuzzle.query(query, data, options, cb);\n\n return this;\n\n };\n });\n\n})();\n\nmodule.exports = KuzzleMemoryStorage;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleMemoryStorage.js\n ** module id = 7\n ** module chunks = 0\n **/","var\n uuid = require('node-uuid');\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} kuzzleDataCollection - an instantiated and valid kuzzle object\n * @param {object} [options] - subscription optional configuration\n * @constructor\n */\nfunction KuzzleRoom(kuzzleDataCollection, 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: uuid.v4()\n },\n lastRenewal: {\n value: null,\n writable: true\n },\n notifier: {\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: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.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(kuzzleDataCollection.headers)),\n enumerable: true,\n writable: true\n },\n metadata: {\n value: (options && options.metadata) ? options.metadata : {},\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 */\nKuzzleRoom.prototype.count = function (cb) {\n var data;\n\n this.kuzzle.callbackRequired('KuzzleRoom.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('KuzzleRoom.count: cannot count subscriptions on an inactive room');\n }\n\n this.kuzzle.query(this.collection.buildQueryArgs('subscribe', '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} cb - called for each new notification\n */\nKuzzleRoom.prototype.renew = function (filters, cb) {\n var\n now = Date.now(),\n subscribeQuery = {\n scope: this.scope,\n state: this.state,\n users: this.users\n },\n self = this;\n\n if (!cb && filters && typeof filters === 'function') {\n cb = filters;\n filters = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleRoom.renew', cb);\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;\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 = 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, cb]});\n return;\n }\n\n self.unsubscribe();\n self.roomId = null;\n self.subscribing = true;\n self.callback = cb;\n self.kuzzle.subscriptions.pending[self.id] = self;\n\n subscribeQuery.body = self.filters;\n subscribeQuery = self.kuzzle.addHeaders(subscribeQuery, this.headers);\n\n self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'on'), subscribeQuery, {metadata: self.metadata}, function (error, response) {\n delete self.kuzzle.subscriptions.pending[self.id];\n self.subscribing = false;\n\n if (error) {\n self.queue = [];\n throw 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 });\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 */\nKuzzleRoom.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('subscribe', 'off'), {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('subscribe', 'off'), {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 */\nKuzzleRoom.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.error) {\n return this.callback(data.error);\n }\n\n if (data.action === 'jwtTokenExpired') {\n this.kuzzle.jwtToken = undefined;\n return this.kuzzle.emitEvent('jwtTokenExpired');\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 = KuzzleRoom;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleRoom.js\n ** module id = 8\n ** module chunks = 0\n **/","/**\n *\n * @param host\n * @param wsPort\n * @param ioPort\n * @returns {Object} tnstantiated WebSocket/Socket.IO object\n */\n\nfunction network(host, wsPort, ioPort, 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/wsbrowsers'))(host, wsPort, sslConnection);\n }\n // otherwise fallback to socket.io, if available\n else if (window.io) {\n return new (require('./wrappers/socketio'))(host, ioPort, 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/wsnode'))(host, wsPort, sslConnection);\n}\n\nmodule.exports = network;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/index.js\n ** module id = 9\n ** module chunks = 0\n **/","function SocketIO(host, port, ssl) {\n this.host = host;\n this.port = port;\n this.ssl = ssl;\n this.socket = null;\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 this.socket = window.io((this.ssl ? 'https://' : 'http://') + this.host + ':' + this.port, {\n reconnection: autoReconnect,\n reconnectionDelay: reconnectionDelay,\n forceNew: true\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.socket.on('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.socket.on('connect_error', 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.socket.on('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.socket.on('reconnect', callback);\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.socket.close();\n this.socket = null;\n };\n}\n\nmodule.exports = SocketIO;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/wrappers/socketio.js\n ** module id = 10\n ** module chunks = 0\n **/","function WSBrowsers(host, port, ssl) {\n var self = this;\n this.host = host;\n this.port = port;\n this.ssl = ssl;\n this.client = null;\n this.retrying = false;\n\n /*\n Listeners are stored using the following format:\n roomId: {\n fn: callback_function,\n once: boolean\n }\n */\n this.listeners = {\n error: [],\n connect: [],\n disconnect: [],\n reconnect: []\n };\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 this.client = new WebSocket((this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port);\n\n this.client.onopen = function () {\n if (self.retrying) {\n poke(self.listeners, 'reconnect');\n }\n else {\n poke(self.listeners, 'connect');\n }\n };\n\n this.client.onclose = function () {\n poke(self.listeners, 'disconnect');\n };\n\n this.client.onerror = function () {\n if (autoReconnect) {\n self.retrying = true;\n setTimeout(function () {\n self.connect(autoReconnect, reconnectionDelay);\n }, reconnectionDelay);\n }\n\n poke(self.listeners, 'error');\n };\n\n this.client.onmessage = function (payload) {\n var data = JSON.parse(payload.data);\n\n if (data.room && self.listeners[data.room]) {\n poke(self.listeners, data.room, 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.listeners.connect.push({\n fn: callback,\n keep: true\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 this.listeners.error.push({\n fn: callback,\n keep: true\n });\n };\n\n /**\n * Fires the provided callback whenever a disconnection occurred\n * @param {function} callback\n */\n this.onDisconnect = function (callback) {\n this.listeners.disconnect.push({\n fn: callback,\n keep: true\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 this.listeners.reconnect.push({\n fn: callback,\n keep: true\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 if (!this.listeners[roomId]) {\n this.listeners[roomId] = [];\n }\n\n this.listeners[roomId].push({\n fn: callback,\n keep: false\n });\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 if (!this.listeners[roomId]) {\n this.listeners[roomId] = [];\n }\n\n this.listeners[roomId].push({\n fn: callback,\n keep: true\n });\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 var index;\n\n if (this.listeners[roomId]) {\n index = this.listeners[roomId].findIndex(function (listener) {\n return listener.fn === callback;\n });\n\n if (index !== -1) {\n if (this.listeners[roomId].length === 1 && ['error', 'connect', 'disconnect', 'reconnect'].indexOf(roomId) === -1) {\n delete this.listeners[roomId];\n }\n else {\n this.listeners[roomId].splice(index, 1);\n }\n }\n }\n };\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.listeners = {\n error: [],\n connect: [],\n disconnect: [],\n reconnect: []\n };\n\n this.retrying = false;\n this.client.close();\n this.client = null;\n };\n}\n\n/**\n * Executes all registered listeners in the provided\n * \"listeners\" structure.\n *\n * Listeners are of the following format:\n * [\n * { fn: callback, once: boolean },\n * ...\n * ]\n *\n * @private\n * @param {Object} listeners\n * @param {string} roomId\n * @param {Object} [payload]\n */\nfunction poke (listeners, roomId, payload) {\n var\n i,\n length = listeners[roomId].length;\n\n for (i = 0; i < length; ++i) {\n listeners[roomId][i].fn(payload);\n\n if (!listeners[roomId][i].keep) {\n if (listeners[roomId].length > 1) {\n listeners[roomId].splice(i, 1);\n --i;\n --length;\n }\n else {\n delete listeners[roomId];\n }\n }\n }\n}\n\nmodule.exports = WSBrowsers;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/wrappers/wsbrowsers.js\n ** module id = 11\n ** module chunks = 0\n **/","var\n KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleProfile(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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\nKuzzleProfile.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleProfile\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 {Object} this\n */\nKuzzleProfile.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.kuzzleSecurity.buildQueryArgs('createOrReplaceProfile'), data, options, function (error) {\n cb && cb(error, 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 {KuzzleProfile} this\n */\nKuzzleProfile.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 {KuzzleProfile} this\n */\nKuzzleProfile.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 */\nKuzzleProfile.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\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 */\nKuzzleProfile.prototype.getPolicies = function () {\n return this.content.policies;\n};\n\nmodule.exports = KuzzleProfile;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleProfile.js\n ** module id = 12\n ** module chunks = 0\n **/","var KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleRole(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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\nKuzzleRole.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleRole\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 */\nKuzzleRole.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.kuzzleSecurity.buildQueryArgs('createOrReplaceRole'), data, options, function (error) {\n cb && cb(error, self);\n });\n\n return this;\n};\n\nmodule.exports = KuzzleRole;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleRole.js\n ** module id = 13\n ** module chunks = 0\n **/","var\n KuzzleRole = require('./kuzzleRole'),\n KuzzleProfile = require('./kuzzleProfile'),\n KuzzleUser = require('./kuzzleUser');\n\n/**\n * Kuzzle security constructor\n *\n * @param kuzzle\n * @returns {KuzzleSecurity}\n * @constructor\n */\nfunction KuzzleSecurity(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 = ['roleFactory', 'profileFactory', 'userFactory', '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} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getRole = function (id, options, cb) {\n var\n data,\n self = this;\n\n if (!id) {\n throw new Error('Id parameter is mandatory for getRole 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('KuzzleSecurity.getRole', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n cb(err, !err && new KuzzleRole(self, response.result._id, response.result._source));\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} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n *\n */\nKuzzleSecurity.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('KuzzleSecurity.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 KuzzleRole(self, doc._id, doc._source);\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.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('KuzzleSecurity.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 && new KuzzleRole(self, res.result._id, res.result._source));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.updateRole = function (id, content, options, cb) {\n var\n self = this,\n data = {_id: id, content: content},\n action = 'updateRole';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.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) {\n cb(err, !err && new KuzzleRole(self, id, content));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleSecurity.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 && res.result._id);\n });\n\n return this;\n};\n\n/**\n * Instantiate a new KuzzleRole 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 * @constructor\n */\nKuzzleSecurity.prototype.roleFactory = function(id, content) {\n return new KuzzleRole(this, id, content);\n};\n\n\n/**\n * Get a specific profile from kuzzle\n *\n *\n * @param {string} id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getProfile = 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 getProfile function');\n }\n\n\n data = {_id: id};\n\n self.kuzzle.callbackRequired('KuzzleSecurity.getProfile', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n cb(error, !error && new KuzzleProfile(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.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('KuzzleSecurity.searchProfiles', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new KuzzleProfile(self, doc._id, doc._source);\n });\n\n cb(null, { total: response.result.total, profiles: documents });\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 {object} content - attribute `roles` in `content` must only contains an array of role id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.createProfile = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'createProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.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 data.body = content;\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 && new KuzzleProfile(self, res.result._id, res.result._source));\n });\n};\n\n\n/**\n * Update a profile in Kuzzle.\n *\n * @param {string} id - profile identifier\n * @param {object} content - a plain javascript object representing the profile's modification\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.updateProfile = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'updateProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.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 data.body = content;\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 KuzzleProfile(self, res.result._id, updatedContent));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleSecurity.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 && res.result._id);\n });\n\n return this;\n};\n\n/**\n * Instantiate a new KuzzleProfile 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 * @constructor\n */\nKuzzleSecurity.prototype.profileFactory = function(id, content) {\n return new KuzzleProfile(this, id, content);\n};\n\n/**\n * Get a specific user from kuzzle using its unique ID\n *\n * @param {string} id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getUser = 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 getUser function');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleSecurity.getUser', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n cb(err, !err && new KuzzleUser(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.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('KuzzleSecurity.searchUsers', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new KuzzleUser(self, doc._id, doc._source);\n });\n\n cb(null, { total: response.result.total, users: documents });\n });\n};\n\n/**\n * Create a new user in Kuzzle.\n *\n * Takes an optional argument object with the following property:\n * - replaceIfExist (boolean, default: false):\n * If the same user already exists: throw an error if sets to false.\n * Replace the existing user otherwise\n *\n * @param {string} id - user identifier\n * @param {object} content - attribute `profile` in `content` must only contains the profile id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.createUser = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'createUser';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.createUser: cannot create a user without a 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 if (options) {\n action = options.replaceIfExist ? 'createOrReplaceUser' : 'createUser';\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, null, cb && function (err, res) {\n cb(err, !err && new KuzzleUser(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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.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('KuzzleSecurity.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 && new KuzzleUser(self, res.result._id, res.result._source));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleSecurity.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 && res.result._id);\n });\n\n return this;\n};\n\n/**\n * Instantiate a new KuzzleUser 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 * @constructor\n */\nKuzzleSecurity.prototype.userFactory = function(id, content) {\n return new KuzzleUser(this, id, content);\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 */\nKuzzleSecurity.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} [options] - (optional) arguments\n * @param {function} cb The callback containing the normalized array of rights.\n */\nKuzzleSecurity.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 && res.result.hits);\n });\n};\n\nmodule.exports = KuzzleSecurity;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleSecurity.js\n ** module id = 14\n ** module chunks = 0\n **/"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/kuzzle.min.js b/dist/kuzzle.min.js deleted file mode 100644 index b803b27ce..000000000 --- a/dist/kuzzle.min.js +++ /dev/null @@ -1,4 +0,0 @@ -// Official Javascript SDK for Kuzzle v2.0.0 - License: Apache-2.0 -!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g1)for(var c=1;c>>((3&b)<<3)&255;return c},"undefined"!=typeof console&&console.warn&&console.warn("[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()")}}function f(){if("function"==typeof a)try{var b=a("crypto").randomBytes;m=k=b&&function(){return b(16)},k()}catch(a){}}function g(a,b,c){var d=b&&c||0,e=0;for(b=b||[],a.toLowerCase().replace(/[0-9a-f]{2}/g,function(a){e<16&&(b[d+e++]=r[a])});e<16;)b[d+e++]=0;return b}function h(a,b){var c=b||0,d=q;return d[a[c++]]+d[a[c++]]+d[a[c++]]+d[a[c++]]+"-"+d[a[c++]]+d[a[c++]]+"-"+d[a[c++]]+d[a[c++]]+"-"+d[a[c++]]+d[a[c++]]+"-"+d[a[c++]]+d[a[c++]]+d[a[c++]]+d[a[c++]]+d[a[c++]]+d[a[c++]]}function i(a,b,c){var d=b&&c||0,e=b||[];a=a||{};var f=null!=a.clockseq?a.clockseq:v,g=null!=a.msecs?a.msecs:(new Date).getTime(),i=null!=a.nsecs?a.nsecs:x+1,j=g-w+(i-x)/1e4;if(j<0&&null==a.clockseq&&(f=f+1&16383),(j<0||g>w)&&null==a.nsecs&&(i=0),i>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");w=g,x=i,v=f,g+=122192928e5;var k=(1e4*(268435455&g)+i)%4294967296;e[d++]=k>>>24&255,e[d++]=k>>>16&255,e[d++]=k>>>8&255,e[d++]=255&k;var l=g/4294967296*1e4&268435455;e[d++]=l>>>8&255,e[d++]=255&l,e[d++]=l>>>24&15|16,e[d++]=l>>>16&255,e[d++]=f>>>8|128,e[d++]=255&f;for(var m=a.node||u,n=0;n<6;n++)e[d+n]=m[n];return b?b:h(e)}function j(a,b,c){var d=b&&c||0;"string"==typeof a&&(b="binary"===a?new p(16):null,a=null),a=a||{};var e=a.random||(a.rng||k)();if(e[6]=15&e[6]|64,e[8]=63&e[8]|128,b)for(var f=0;f<16;f++)b[d+f]=e[f];return b||h(e)}var k,l,m,n,o;d?e():f();for(var p="function"==typeof c?c:Array,q=[],r={},s=0;s<256;s++)q[s]=(s+256).toString(16).substr(1),r[q[s]]=s;var t=k(),u=[1|t[0],t[1],t[2],t[3],t[4],t[5]],v=16383&(t[6]<<8|t[7]),w=0,x=0,y=j;y.v1=i,y.v4=j,y.parse=g,y.unparse=h,y.BufferClass=p,y._rng=k,y._mathRNG=l,y._nodeRNG=m,y._whatwgRNG=n,"undefined"!=typeof b&&b.exports?b.exports=y:"function"==typeof define&&define.amd?define(function(){return y}):(o=d.uuid,y.noConflict=function(){return d.uuid=o,y},d.uuid=y)}("undefined"!=typeof window?window:null)}).call(this,a("buffer").Buffer)},{}],3:[function(a,b,c){(function(c){function d(){var a=this,b=Date.now(),c=-1;a.queueTTL>0&&(a.offlineQueue.forEach(function(d,e){d.ts0&&a.offlineQueue.length>a.queueMaxSize&&a.offlineQueue.splice(0,a.offlineQueue.length-a.queueMaxSize).forEach(function(b){a.emitEvent("offlineQueuePop",b.query)})}function e(a){var b=Date.now();Object.keys(a).forEach(function(c){a[c]0?(f.call(b,b.offlineQueue[0].query,b.offlineQueue[0].cb),b.emitEvent("offlineQueuePop",b.offlineQueue.shift()),setTimeout(function(){d()},Math.max(0,b.replayInterval))):b.queuing=!1};if(b.offlineQueueLoader){if("function"!=typeof b.offlineQueueLoader)throw new Error("Invalid value for offlineQueueLoader property. Expected: function. Got: "+typeof b.offlineQueueLoader);if(a=b.offlineQueueLoader(),!Array.isArray(a))throw new Error("Invalid value returned by the offlineQueueLoader function. Expected: array. Got: "+typeof a);b.offlineQueue=a.concat(b.offlineQueue).filter(function(a){if(!a.query||void 0===a.query.requestId||!a.query.action||!a.query.controller)throw new Error("Invalid offline queue request. One or more missing properties: requestId, action, controller.");return!c.hasOwnProperty(a.query.requestId)&&(c[a.query.requestId]=!0)})}d()}function h(){var a=this;Object.keys(a.subscriptions).forEach(function(b){Object.keys(a.subscriptions[b]).forEach(function(c){var d=a.subscriptions[b][c];d.renew(d.callback)})})}var i=a("node-uuid"),j=a("./kuzzleDataCollection"),k=a("./security/kuzzleSecurity"),l=a("./kuzzleMemoryStorage"),m=a("./security/kuzzleUser"),n=a("./networkWrapper");b.exports=Kuzzle=function(a,b,d){var f=this;if(!(this instanceof Kuzzle))return new Kuzzle(a,b,d);if(d||"function"!=typeof b||(d=b,b=null),!a||""===a)throw new Error("host argument missing");return Object.defineProperties(this,{collections:{value:{},writable:!0},connectCB:{value:d},eventListeners:{value:{connected:{lastEmitted:null,listeners:[]},error:{lastEmitted:null,listeners:[]},disconnected:{lastEmitted:null,listeners:[]},reconnected:{lastEmitted:null,listeners:[]},jwtTokenExpired:{lastEmitted:null,listeners:[]},loginAttempt:{lastEmitted:null,listeners:[]},offlineQueuePush:{listeners:[]},offlineQueuePop:{listeners:[]}}},eventTimeout:{value:200},queuing:{value:!1,writable:!0},requestHistory:{value:{},writable:!0},state:{value:"initializing",writable:!0},subscriptions:{value:{pending:{}},writable:!0},autoReconnect:{value:!b||"boolean"!=typeof b.autoReconnect||b.autoReconnect,enumerable:!0},defaultIndex:{value:b&&"string"==typeof b.defaultIndex?b.defaultIndex:void 0,writable:!0,enumerable:!0},reconnectionDelay:{value:b&&"number"==typeof b.reconnectionDelay?b.reconnectionDelay:1e3,enumerable:!0},host:{value:a,enumerable:!0},wsPort:{value:b&&"number"==typeof b.wsPort?b.wsPort:7513,enumerable:!0},ioPort:{value:b&&"number"==typeof b.ioPort?b.ioPort:7512,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},metadata:{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:null,enumerable:!0,writable:!0}}),b&&(Object.keys(b).forEach(function(a){f.hasOwnProperty(a)&&Object.getOwnPropertyDescriptor(f,a).writable&&(f[a]=b[a])}),"auto"===b.offlineMode&&this.autoReconnect&&(this.autoQueue=this.autoReplay=this.autoResubscribe=!0)),Object.defineProperty(this,"isValid",{value:function(){if("disconnected"===f.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(a,b){return Object.keys(b).forEach(function(c){a[c]||(a[c]=b[c])}),a}}),Object.defineProperty(this,"callbackRequired",{value:function(a,b){if(!b||"function"!=typeof b)throw new Error(a+": a callback argument is required for read queries")}}),Object.defineProperty(this,"security",{value:new k(this),enumerable:!0}),Object.defineProperty(this,"emitEvent",{value:function(a){var b=Date.now(),d=Array.prototype.slice.call(arguments,1),e=this.eventListeners[a];return!(e.lastEmitted&&e.lastEmitted>=b-this.eventTimeout)&&(e.listeners.forEach(function(a){c.nextTick(function(){a.fn.apply(void 0,d)})}),void(void 0!==e.lastEmitted&&(e.lastEmitted=b)))}}),Object.defineProperty(this,"memoryStorage",{value:new l(this),enumerable:!0}),b&&b.connect&&"auto"!==b.connect?this.state="ready":this.connect(),e(this.requestHistory),this.bluebird?this.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(a,b,c,d){var e=["getAllStatistics","getServerInfo","getStatistics","listCollections","listIndexes","login","logout","now","query","checkToken","whoAmI"];return d&&e.indexOf(a)!==-1}}):void 0},Kuzzle.prototype.connect=function(){var a=this;return a.network||(a.network=n(a.host,a.wsPort,a.ioPort)),["initializing","ready","disconnected","error","offline"].indexOf(this.state)===-1?(a.connectCB&&a.connectCB(null,a),a):(a.state="connecting",a.network.connect(a.autoReconnect,a.reconnectionDelay),a.network.onConnect(function(){a.state="connected",h.call(a),g.call(a),a.emitEvent("connected"),a.connectCB&&a.connectCB(null,a)}),a.network.onConnectError(function(b){var c=new Error('Unable to connect to kuzzle server at "'+a.host+'"');c.internal=b,a.state="error",a.emitEvent("error",c),a.connectCB&&a.connectCB(c)}),a.network.onDisconnect(function(){a.state="offline",a.autoReconnect||a.disconnect(),a.autoQueue&&(a.queuing=!0),a.emitEvent("disconnected")}),a.network.onReconnect(function(){var b=function(){a.autoResubscribe&&h.call(a),a.autoReplay&&(d.call(a),g.call(a)),a.emitEvent("reconnected")};a.state="connected",a.jwtToken?a.checkToken(a.jwtToken,function(c,d){!c&&d.valid||(a.jwtToken=void 0,a.emitEvent("jwtTokenExpired")),b()}):b()}),this)},Kuzzle.prototype.setJwtToken=function(a){if("string"==typeof a)this.jwtToken=a;else{if("object"!=typeof a)return this.emitEvent("loginAttempt",{success:!1,error:"Invalid token argument: "+a}),this;if(!a.result||!a.result.jwt||"string"!=typeof a.result.jwt)return this.emitEvent("loginAttempt",{success:!1,error:"Cannot find a valid JWT token in the following object: "+JSON.stringify(a)}),this;this.jwtToken=a.result.jwt}return h.call(this),this.emitEvent("loginAttempt",{success:!0}),this},Kuzzle.prototype.getJwtToken=function(){return this.jwtToken},Kuzzle.prototype.login=function(a){var b,c,d=this,e={strategy:a};return arguments[1]&&("object"==typeof arguments[1]?b=arguments[1]:"number"==typeof arguments[1]||"string"==typeof arguments[1]?e.expiresIn=arguments[1]:"function"==typeof arguments[1]&&(c=arguments[1])),arguments[2]&&("number"==typeof arguments[2]||"string"==typeof arguments[2]?e.expiresIn=arguments[2]:"function"==typeof arguments[2]&&(c=arguments[2])),arguments[3]&&"function"==typeof arguments[3]&&(c=arguments[3]),"object"==typeof b&&Object.keys(b).forEach(function(a){e[a]=b[a]}),this.query({controller:"auth",action:"login"},{body:e},{queuable:!1},function(a,b){a?(c&&"function"==typeof c&&c(a),d.emitEvent("loginAttempt",{success:!1,error:a.message})):(b.result.jwt&&d.setJwtToken(b.result.jwt),c&&"function"==typeof c&&c(null,b.result))}),d},Kuzzle.prototype.logout=function(a){var b=this,c={action:"logout",controller:"auth",requestId:i.v4(),body:{}};return this.query({controller:"auth",action:"logout"},c,{queuable:!1},function(c){null===c?(b.jwtToken=void 0,"function"==typeof a&&a(null,b)):"function"==typeof a&&a(c)}),b},Kuzzle.prototype.checkToken=function(a,b){var c=this,d={body:{token:a}};return this.callbackRequired("Kuzzle.checkToken",b),this.query({controller:"auth",action:"checkToken"},d,{queuable:!1},function(a,c){return a?b(a):void b(null,c.result)}),c},Kuzzle.prototype.whoAmI=function(a){var b=this;return b.callbackRequired("Kuzzle.whoAmI",a),b.query({controller:"auth",action:"getCurrentUser"},{},{},function(c,d){return c?a(c):void a(null,new m(b.security,d.result._id,d.result._source))}),b},Kuzzle.prototype.getMyRights=function(a,b){var c=this;b||"function"!=typeof a||(b=a,a=null),c.callbackRequired("Kuzzle.getMyRights",b),c.query({controller:"auth",action:"getMyRights"},{},null,function(a,c){return a?b(a):void b(null,c.result.hits)})},Kuzzle.prototype.updateSelf=function(a,b,c){var d=this,e={},f={controller:"auth",action:"updateSelf"};c||"function"!=typeof b||(c=b,b=null),e.body=a,c?d.query(f,e,b,function(a,b){return a?c(a):void c(null,b.result)}):d.query(f,e,b)},Kuzzle.prototype.addListener=function(a,b){var c,d=Object.keys(this.eventListeners),e=typeof b;if(this.isValid(),d.indexOf(a)===-1)throw new Error("["+a+"] is not a known event. Known events: "+d.toString());if("function"!==e)throw new Error("Invalid listener type: expected a function, got a "+e);return c=i.v4(),this.eventListeners[a].listeners.push({id:c,fn:b}),c},Kuzzle.prototype.getAllStatistics=function(a,b){return b||"function"!=typeof a||(b=a,a=null),this.callbackRequired("Kuzzle.getAllStatistics",b),this.query({controller:"admin",action:"getAllStats"},{},a,function(a,c){return a?b(a):void b(null,c.result.hits)}),this},Kuzzle.prototype.getStatistics=function(a,b,c){var d;return c||(1===arguments.length?(c=arguments[0],b=null,a=null):(c=arguments[1],"object"==typeof arguments[0]?(b=arguments[0],a=null):(a=arguments[0],b=null))),d=function(b,d){return b?c(b):void(a?c(null,d.result.hits):c(null,[d.result]))},this.callbackRequired("Kuzzle.getStatistics",c),a?this.query({controller:"admin",action:"getStats"},{body:{startTime:a}},b,d):this.query({controller:"admin",action:"getLastStats"},{},b,d),this},Kuzzle.prototype.dataCollectionFactory=function(a,b){if(this.isValid(),!b){if(!this.defaultIndex)throw new Error("Unable to create a new data collection object: no index specified");b=this.defaultIndex}if("string"!=typeof b)throw new Error('Invalid "index" argument: string expected, got '+typeof b);if("string"!=typeof a)throw new Error('Invalid "collection" argument: string expected, got '+typeof a);return this.collections[b]||(this.collections[b]={}),this.collections[b][a]||(this.collections[b][a]=new j(this,b,a)),this.collections[b][a]},Kuzzle.prototype.flushQueue=function(){return this.offlineQueue=[],this},Kuzzle.prototype.listCollections=function(){var a,b,c,d="all",e=Array.prototype.slice.call(arguments);if(e.forEach(function(d){switch(typeof d){case"string":a=d;break;case"object":b=d;break;case"function":c=d}}),!a){if(!this.defaultIndex)throw new Error("Kuzzle.listCollections: index required");a=this.defaultIndex}return this.callbackRequired("Kuzzle.listCollections",c),b&&b.type&&(d=b.type),this.query({index:a,controller:"read",action:"listCollections"},{body:{type:d}},b,function(a,b){return a?c(a):c(null,b.result.collections)}),this},Kuzzle.prototype.listIndexes=function(a,b){return b||"function"!=typeof a||(b=a,a=null),this.callbackRequired("Kuzzle.listIndexes",b),this.query({controller:"read",action:"listIndexes"},{},a,function(a,c){return a?b(a):b(null,c.result.indexes)}),this},Kuzzle.prototype.disconnect=function(){var a;this.logout(),this.state="disconnected",this.network.close();for(a in this.collections)this.collections.hasOwnProperty(a)&&delete this.collections[a]},Kuzzle.prototype.getServerInfo=function(a,b){return b||"function"!=typeof a||(b=a,a=null),this.callbackRequired("Kuzzle.getServerInfo",b),this.query({controller:"read",action:"serverInfo"},{},a,function(a,c){return a?b(a):void b(null,c.result.serverInfo)}),this},Kuzzle.prototype.refreshIndex=function(){var a,b,c;if(Array.prototype.slice.call(arguments).forEach(function(d){switch(typeof d){case"string":a=d;break;case"object":b=d;break;case"function":c=d}}),!a){if(!this.defaultIndex)throw new Error("Kuzzle.refreshIndex: index required");a=this.defaultIndex}return this.query({index:a,controller:"admin",action:"refreshIndex"},{},b,c),this},Kuzzle.prototype.getAutoRefresh=function(){var a,b,c;if(Array.prototype.slice.call(arguments).forEach(function(d){switch(typeof d){case"string":a=d;break;case"object":b=d;break;case"function":c=d}}),!a){if(!this.defaultIndex)throw new Error("Kuzzle.getAutoRefresh: index required");a=this.defaultIndex}return this.callbackRequired("Kuzzle.getAutoRefresh",c),this.query({index:a,controller:"admin",action:"getAutoRefresh"},{},b,c),this},Kuzzle.prototype.setAutoRefresh=function(){var a,b,c,d;if(Array.prototype.slice.call(arguments).forEach(function(e){switch(typeof e){case"string":a=e;break;case"boolean":b=e;break;case"object":c=e;break;case"function":d=e}}),!a){if(!this.defaultIndex)throw new Error("Kuzzle.setAutoRefresh: index required");a=this.defaultIndex}if(void 0===b)throw new Error("Kuzzle.setAutoRefresh: autoRefresh value is required");return this.query({index:a,controller:"admin",action:"setAutoRefresh"},{body:{autoRefresh:b}},c,d),this},Kuzzle.prototype.now=function(a,b){return b||"function"!=typeof a||(b=a,a=null),this.callbackRequired("Kuzzle.now",b),this.query({controller:"read",action:"now"},{},a,function(a,c){return a?b(a):void b(null,c.result.now)}),this},Kuzzle.prototype.query=function(a,b,c,e){var g,h={action:a.action,controller:a.controller,metadata:this.metadata},j=this;if(this.isValid(),e||"function"!=typeof c||(e=c,c=null),c&&(c.metadata&&Object.keys(c.metadata).forEach(function(a){h.metadata[a]=c.metadata[a]}),c.queuable===!1&&"offline"===j.state))return j;if(!b||"object"!=typeof b||Array.isArray(b))throw new Error("Invalid query parameter: "+b);b.metadata&&Object.keys(b.metadata).forEach(function(a){h.metadata[a]=b.metadata[a]});for(g in b)"metadata"!==g&&b.hasOwnProperty(g)&&(h[g]=b[g]);return h=j.addHeaders(h,this.headers),void 0===j.jwtToken||"auth"===h.controller&&"checkToken"===h.action||(h.headers=h.headers||{},h.headers.authorization="Bearer "+j.jwtToken),a.collection&&(h.collection=a.collection),a.index&&(h.index=a.index),h.requestId||(h.requestId=i.v4()),"connected"===j.state||c&&c.queuable===!1?"connected"===j.state?f.call(this,h,e):e&&e(new Error("Unable to execute request: not connected to a Kuzzle server.\nDiscarded request: "+JSON.stringify(h))):(j.queuing||["initializing","connecting"].indexOf(j.state)!==-1)&&(d.call(this,h,e),j.queueFilter&&!j.queueFilter(h)||(j.offlineQueue.push({ts:Date.now(),query:h,cb:e}),j.emitEvent("offlineQueuePush",{query:h,cb:e}))),j},Kuzzle.prototype.removeAllListeners=function(a){var b=Object.keys(this.eventListeners),c=this;if(a){if(b.indexOf(a)===-1)throw new Error("["+a+"] is not a known event. Known events: "+b.toString());this.eventListeners[a].listeners=[]}else b.forEach(function(a){c.eventListeners[a].listeners=[]})},Kuzzle.prototype.removeListener=function(a,b){var c=Object.keys(this.eventListeners),d=this;if(c.indexOf(a)===-1)throw new Error("["+a+"] is not a known event. Known events: "+c.toString());this.eventListeners[a].listeners.forEach(function(c,e){c.id===b&&d.eventListeners[a].listeners.splice(e,1)})},Kuzzle.prototype.replayQueue=function(){return"offline"===this.state||this.autoReplay||(d.call(this),g.call(this)),this},Kuzzle.prototype.setDefaultIndex=function(a){if("string"!=typeof a)throw new Error("Invalid default index: ["+a+"] (an index name is expected)");if(0===a.length)throw new Error("Cannot set an empty index as the default index");return this.defaultIndex=a,this},Kuzzle.prototype.setHeaders=function(a,b){var c=this;if("object"!=typeof a||Array.isArray(a))throw new Error("Expected a content object, received a "+typeof a);return b?c.headers=a:Object.keys(a).forEach(function(b){c.headers[b]=a[b]}),c},Kuzzle.prototype.startQueuing=function(){return"offline"!==this.state||this.autoQueue||(this.queuing=!0),this},Kuzzle.prototype.stopQueuing=function(){return"offline"!==this.state||this.autoQueue||(this.queuing=!1),this}}).call(this,a("_process"))},{"./kuzzleDataCollection":4,"./kuzzleMemoryStorage":7,"./networkWrapper":9,"./security/kuzzleSecurity":14,"./security/kuzzleUser":16,_process:1,"node-uuid":2}],4:[function(a,b,c){function d(a,b,c){if(!b||!c)throw new Error("The KuzzleDataCollection object constructor needs an index and a collection arguments");return Object.defineProperties(this,{collection:{value:c,enumerable:!0},index:{value:b,enumerable:!0},kuzzle:{value:a,enumerable:!0},headers:{value:JSON.parse(JSON.stringify(a.headers)),enumerable:!0,writable:!0}}),Object.defineProperty(this,"buildQueryArgs",{value:function(a,b){return{controller:a,action:b,collection:this.collection,index:this.index}}}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(a,b,c,d){var e=["publishMessage","setHeaders","subscribe"];return d&&e.indexOf(a)===-1}}):this}var e=a("./kuzzleDocument"),f=a("./kuzzleDataMapping"),g=a("./kuzzleRoom");d.prototype.advancedSearch=function(a,b,c){var d,f=this;return c||"function"!=typeof b||(c=b,b=null),f.kuzzle.callbackRequired("KuzzleDataCollection.advancedSearch",c),d=f.kuzzle.addHeaders({body:a},this.headers),f.kuzzle.query(this.buildQueryArgs("read","search"),d,b,function(a,b){var d=[];return a?c(a):(b.result.hits.forEach(function(a){var b=new e(f,a._id,a._source);b.version=a._version,d.push(b)}),void c(null,{total:b.result.total,documents:d}))}),this},d.prototype.count=function(a,b,c){var d;return c||"function"!=typeof b||(c=b,b=null),this.kuzzle.callbackRequired("KuzzleDataCollection.count",c),d=this.kuzzle.addHeaders({body:a},this.headers),this.kuzzle.query(this.buildQueryArgs("read","count"),d,b,function(a,b){return a?c(a):void c(null,b.result.count)}),this},d.prototype.create=function(a,b){var c={};return b||"function"!=typeof a||(b=a,a=null),c=this.kuzzle.addHeaders(c,this.headers),this.kuzzle.query(this.buildQueryArgs("write","createCollection"),c,a,b),this},d.prototype.createDocument=function(a,b,c,d){var f=this,g={},h="create";return a&&"string"!=typeof a&&(d=c,c=b,b=a,a=null),d||"function"!=typeof c||(d=c,c=null),b instanceof e?g=b.serialize():g.body=b,c&&(h=c.updateIfExist?"createOrReplace":"create"),a&&(g._id=a),g=f.kuzzle.addHeaders(g,f.headers),d?f.kuzzle.query(this.buildQueryArgs("write",h),g,c,function(a,b){var c;return a?d(a):(c=new e(f,b.result._id,b.result._source),c.version=b.result._version,void d(null,c))}):f.kuzzle.query(this.buildQueryArgs("write",h),g,c),this},d.prototype.deleteDocument=function(a,b,c){var d,e={};"string"==typeof a?(e._id=a,d="delete"):(e.body=a,d="deleteByQuery"),c||"function"!=typeof b||(c=b,b=null),e=this.kuzzle.addHeaders(e,this.headers),c?this.kuzzle.query(this.buildQueryArgs("write",d),e,b,function(a,b){return a?c(a):void("delete"===d?c(null,[b.result._id]):c(null,b.result.ids))}):this.kuzzle.query(this.buildQueryArgs("write",d),e,b)},d.prototype.fetchDocument=function(a,b,c){var d={_id:a},f=this;return c||"function"!=typeof b||(c=b,b=null),f.kuzzle.callbackRequired("KuzzleDataCollection.fetch",c),d=f.kuzzle.addHeaders(d,this.headers),f.kuzzle.query(this.buildQueryArgs("read","get"),d,b,function(a,b){var d;return a?c(a):(d=new e(f,b.result._id,b.result._source),d.version=b.result._version,void c(null,d))}),this},d.prototype.fetchAllDocuments=function(a,b){var c={};return b||"function"!=typeof a||(b=a,a=null),a&&(a.from&&(c.from=a.from),a.size&&(c.size=a.size)),this.kuzzle.callbackRequired("KuzzleDataCollection.fetchAll",b),this.advancedSearch(c,a,b),this},d.prototype.getMapping=function(a,b){var c;return b||"function"!=typeof a||(b=a,a=null),this.kuzzle.callbackRequired("KuzzleDataCollection.getMapping",b),c=new f(this),c.refresh(a,b),this},d.prototype.publishMessage=function(a,b,c){var d={};return a instanceof e?d=a.serialize():d.body=a,d=this.kuzzle.addHeaders(d,this.headers),this.kuzzle.query(this.buildQueryArgs("write","publish"),d,b,c),this},d.prototype.replaceDocument=function(a,b,c,d){var f=this,g={_id:a,body:b};return d||"function"!=typeof c||(d=c,c=null),g=f.kuzzle.addHeaders(g,this.headers),d?f.kuzzle.query(this.buildQueryArgs("write","createOrReplace"),g,c,function(a,b){var c;return a?d(a):(c=new e(f,b.result._id,b.result._source),c.version=b.result._version,void d(null,c))}):f.kuzzle.query(this.buildQueryArgs("write","createOrReplace"),g,c),this},d.prototype.subscribe=function(a,b,c){var d;return c||"function"!=typeof b||(c=b,b=null),this.kuzzle.callbackRequired("KuzzleDataCollection.subscribe",c),d=new g(this,b),d.renew(a,c)},d.prototype.truncate=function(a,b){var c={};return b||"function"!=typeof a||(b=a,a=null),c=this.kuzzle.addHeaders(c,this.headers),this.kuzzle.query(this.buildQueryArgs("admin","truncateCollection"),c,a,b),this},d.prototype.updateDocument=function(a,b,c,d){var f={_id:a,body:b},g=this;return d||"function"!=typeof c||(d=c,c=null),f=g.kuzzle.addHeaders(f,this.headers),d?g.kuzzle.query(this.buildQueryArgs("write","update"),f,c,function(a,b){var c;return a?d(a):(c=new e(g,b.result._id),void c.refresh(d))}):g.kuzzle.query(this.buildQueryArgs("write","update"),f,c),g},d.prototype.documentFactory=function(a,b){return new e(this,a,b)},d.prototype.roomFactory=function(a){return new g(this,a)},d.prototype.dataMappingFactory=function(a){return new f(this,a)},d.prototype.setHeaders=function(a,b){return this.kuzzle.setHeaders.call(this,a,b),this},b.exports=d},{"./kuzzleDataMapping":5,"./kuzzleDocument":6,"./kuzzleRoom":8}],5:[function(a,b,c){function d(a,b){return Object.defineProperties(this,{collection:{value:a,enumerable:!0},kuzzle:{value:a.kuzzle,enumerable:!0},headers:{value:JSON.parse(JSON.stringify(a.headers)),enumerable:!0,writable:!0},mapping:{value:b||{},enumerable:!0,writable:!0}}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(a,b,c,d){var e=["set","setHeaders"];return d&&e.indexOf(a)===-1}}):this}d.prototype.apply=function(a,b){var c=this,d=this.kuzzle.addHeaders({body:{properties:this.mapping}},this.headers);return b||"function"!=typeof a||(b=a,a=null),c.kuzzle.query(this.collection.buildQueryArgs("admin","updateMapping"),d,a,function(d){return d?!!b&&b(d):void c.refresh(a,b)}),this},d.prototype.refresh=function(a,b){var c=this,d=this.kuzzle.addHeaders({},this.headers);return b||"function"!=typeof a||(b=a,a=null),this.kuzzle.query(this.collection.buildQueryArgs("admin","getMapping"),d,a,function(a,d){return a?!!b&&b(a):d.result[c.collection.index]?d.result[c.collection.index].mappings[c.collection.collection]?(c.mapping=d.result[c.collection.index].mappings[c.collection.collection].properties,void 0===c.mapping&&(c.mapping={}),void(b&&b(null,c))):!!b&&b(new Error("No mapping found for collection "+c.collection.collection)):!!b&&b(new Error("No mapping found for index "+c.collection.index))}),this},d.prototype.set=function(a,b){return this.mapping[a]=b,this},d.prototype.setHeaders=function(a,b){return this.kuzzle.setHeaders.call(this,a,b),this},b.exports=d},{}],6:[function(a,b,c){function d(a,b,c){return Object.defineProperties(this,{collection:{value:a.collection,enumerable:!0},dataCollection:{value:a,enumerable:!0},kuzzle:{value:a.kuzzle,enumerable:!0},id:{value:void 0,enumerable:!0,writable:!0},content:{value:{},writable:!0,enumerable:!0},headers:{value:JSON.parse(JSON.stringify(a.headers)),enumerable:!0,writable:!0},version:{value:void 0,enumerable:!0,writable:!0}}),!c&&b&&"object"==typeof b&&(c=b,b=null),c&&(c._version&&(this.version=c._version,delete c._version),this.setContent(c,!0)),b&&Object.defineProperty(this,"id",{value:b,enumerable:!0}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(a,b,c,d){var e=["delete","refresh","save"];return d&&e.indexOf(a)!==-1}}):this}d.prototype.serialize=function(){var a={};return this.id&&(a._id=this.id),a.body=this.content,a._version=this.version,a=this.kuzzle.addHeaders(a,this.headers)},d.prototype.toString=function(){return JSON.stringify(this.serialize())},d.prototype.delete=function(a,b){var c=this;if(b||"function"!=typeof a||(b=a,a=null),!c.id)throw new Error("KuzzleDocument.delete: cannot delete a document without a document ID");b?this.kuzzle.query(this.dataCollection.buildQueryArgs("write","delete"),this.serialize(),a,function(a){return a?b(a):void b(null,c.id)}):this.kuzzle.query(this.dataCollection.buildQueryArgs("write","delete"),this.serialize(),a)},d.prototype.refresh=function(a,b){var c=this;if(b||"function"!=typeof a||(b=a,a=null),!c.id)throw new Error("KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided");this.kuzzle.callbackRequired("KuzzleDocument.refresh",b),c.kuzzle.query(c.dataCollection.buildQueryArgs("read","get"),{_id:c.id},a,function(a,e){var f;return a?b(a):(f=new d(c.dataCollection,c.id,e.result._source),f.version=e.result._version,void b(null,f))})},d.prototype.save=function(a,b){var c=this.serialize(),d=this;return a&&void 0===b&&"function"==typeof a&&(b=a,a=null),d.kuzzle.query(this.dataCollection.buildQueryArgs("write","createOrReplace"),c,a,function(a,c){return a?!!b&&b(a):(d.id=c.result._id,d.version=c.result._version,void(b&&b(null,d)))}),d},d.prototype.publish=function(a){var b=this.serialize();return this.kuzzle.query(this.dataCollection.buildQueryArgs("write","publish"),b,a),this},d.prototype.setContent=function(a,b){var c=this;return b?this.content=a:Object.keys(a).forEach(function(b){c.content[b]=a[b]}),this},d.prototype.subscribe=function(a,b){var c;if(a&&!b&&"function"==typeof a&&(b=a,a=null),this.kuzzle.callbackRequired("KuzzleDocument.subscribe",b),!this.id)throw new Error("KuzzleDocument.subscribe: cannot subscribe to a document if no ID has been provided");return c={ids:{values:[this.id]}},this.dataCollection.subscribe(c,a,b)},d.prototype.setHeaders=function(a,b){return this.kuzzle.setHeaders.call(this,a,b),this},b.exports=d},{}],7:[function(a,b,c){function d(a){return Object.defineProperties(this,{kuzzle:{value:a,enumerable:!0},headers:{value:JSON.parse(JSON.stringify(a.headers)),enumerable:!0,writable:!0}}),this.setHeaders=a.setHeaders.bind(this),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(a,b,c,d){var e=["setHeaders"];return d&&e.indexOf(a)===-1}}):this}!function(){var a=["id","value"],b=["id","keys"],c={append:a,bgrewriteaof:[],bgsave:[],bitcount:["id","start","end"],bitop:["operation","destkey",b],bitpos:["id","bit",{__opts__:["start","end"]}],blpop:[b,"timeout"],brpoplpush:["source","destination"],dbsize:[],decrby:a,del:[b],discard:[],exec:[],exists:[b],expire:["id","seconds"],expireat:["id","timestamp"],flushdb:[],getbit:["id","offset"],getrange:["id","start","end"],hdel:["id",["field","fields"]],hexists:["id","field"],hincrby:["id","field","value"],hmset:["id","values"],hset:["id","field","value"],info:["section"],keys:["pattern"],lastsave:[],lindex:["id","idx"],linsert:["id","position","pivot","value"],lpush:["id",["value","values"]],lrange:["id","start","stop"],lrem:["id","count","value"],lset:["id","idx","value"],ltrim:["id","start","stop"],mset:["values"],multi:[],object:["subcommand","args"],pexpire:["id","milliseconds"],pexpireat:["id","timestamp"],pfadd:["id",["element","elements"]],pfmerge:["destkey",["sourcekey","sourcekeys"]],ping:[],psetex:["id","milliseconds","value"],publish:["channel","message"],randomkey:[],rename:["id","newkey"],renamenx:["id","newkey"],restore:["id","ttl","content"],rpoplpush:["source","destination"], -sadd:["id",["member","members"]],save:[],set:["id","value",{__opts__:["ex","px","nx","xx"]}],sdiffstore:["destination",b],setbit:["id","offset","value"],setex:["id","seconds","value"],setrange:["id","offset","value"],sinterstore:["destination",b],sismember:["id","member"],smove:["id","destination","member"],sort:["id",{__opts__:["by","offset","count","get","direction","alpha","store"]}],spop:["id","count"],srem:["id",["member","members"]],sunionstore:["destination",b],unwatch:[],wait:["numslaves","timeout"],zadd:["id",{__opts__:["nx","xx","ch","incr","score","member","members"]}],zcount:["id","min","max"],zincrby:["id","value","member"],zinterstore:["destination",b,{__opts__:["weight","weights","aggregate"]}],zlexcount:["id","min","max"],zrange:["id","start","stop",{__opts__:["withscores"]}],zrangebylex:["id","min","max",{__opts__:["offset","count"]}],zrangebyscore:["id","min","max",{__opts__:["withscores","offset","count"]}],zrem:["id","member"],zremrangebylex:["id","min","max"],zremrangebyscore:["id","min","max"],zrevrangebylex:["id","max","min",{__opts__:["offset","count"]}],zrevrangebyscore:["id","max","min",{__opts__:["withscores","offset","count"]}],zrevrank:["id","member"]};c.decr=c.get=c.dump=c.hgetall=c.hkeys=c.hlen=c.hstrlen=c.hvals=c.incr=c.llen=c.lpop=c.persist=c.pttl=c.rpop=c.scard=c.smembers=c.strlen=c.ttl=c.type=c.zcard=["id"],c.getset=c.lpushx=a,c.del=c.exists=c.mget=c.pfcount=c.sdiff=c.sinter=c.sunion=c.watch=[b],c.incrby=c.incrbyfloat=c.decrby,c.brpop=c.blpop,c.hget=c.hexists,c.hmget=c.hdel,c.hsetnx=c.hset,c.msetnx=c.mset,c.rpush=c.lpush,c.hincrbyfloat=c.hincrby,c.srandmember=c.spop,c.zrevrange=c.zrange,c.zscore=c.zrevrank,Object.keys(c).forEach(function(a){d.prototype[a]=function(){var b,d=Array.prototype.slice.call(arguments),e=null,f={controller:"ms",action:a},g={};return"function"==typeof d[d.length-1]&&(b=d.pop()),d.length&&"object"==typeof d[d.length-1]&&1===Object.keys(d[d.length-1]).length&&void 0!==d[d.length-1].queuable&&(e=d.pop()),c[a].forEach(function(a,b){void 0!==d[b]&&(Array.isArray(a)&&(a=Array.isArray(d[b])?a[1]:a[0]),"id"===a?g._id=d[b]:(g.body||(g.body={}),"object"==typeof a&&void 0!==a.__opts__?a.__opts__.forEach(function(a){void 0!==d[b][a]&&(g.body[a]=d[b][a])}):g.body[a]=d[b]))}),this.kuzzle.query(f,g,e,b),this}})}(),b.exports=d},{}],8:[function(a,b,c){function d(a,b){return Object.defineProperties(this,{callback:{value:null,writable:!0},channel:{value:null,writable:!0},id:{value:h.v4()},lastRenewal:{value:null,writable:!0},notifier:{value:null,writable:!0},queue:{value:[],writable:!0},renewalDelay:{value:500},scope:{value:b&&b.scope?b.scope:"all"},state:{value:b&&b.state?b.state:"done"},subscribing:{value:!1,writable:!0},users:{value:b&&b.users?b.users:"none"},collection:{value:a,enumerable:!0},kuzzle:{value:a.kuzzle,enumerable:!0},filters:{value:null,enumerable:!0,writable:!0},headers:{value:JSON.parse(JSON.stringify(a.headers)),enumerable:!0,writable:!0},metadata:{value:b&&b.metadata?b.metadata:{},enumerable:!0,writable:!0},roomId:{value:null,enumerable:!0,writable:!0},subscribeToSelf:{value:!b||"boolean"!=typeof b.subscribeToSelf||b.subscribeToSelf,enumerable:!0,writable:!0}}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(a,b,c,d){var e=["count"];return d&&e.indexOf(a)!==-1}}):this}function e(a){return a.error?this.callback(a.error):"jwtTokenExpired"===a.action?(this.kuzzle.jwtToken=void 0,this.kuzzle.emitEvent("jwtTokenExpired")):void(this.kuzzle.requestHistory[a.requestId]?(this.subscribeToSelf&&this.callback(null,a),delete this.kuzzle.requestHistory[a.requestId]):this.callback(null,a))}function f(){for(var a;this.queue.length>0;)a=this.queue.shift(),this[a.action].apply(this,a.args)}function g(){return"connected"===this.kuzzle.state&&!this.subscribing}var h=a("node-uuid");d.prototype.count=function(a){var b;if(this.kuzzle.callbackRequired("KuzzleRoom.count",a),b=this.kuzzle.addHeaders({body:{roomId:this.roomId}},this.headers),!g.call(this))return this.queue.push({action:"count",args:[a]}),this;if(!this.roomId)throw new Error("KuzzleRoom.count: cannot count subscriptions on an inactive room");return this.kuzzle.query(this.collection.buildQueryArgs("subscribe","count"),b,function(b,c){return b?a(b):void a(null,c.result.count)}),this},d.prototype.renew=function(a,b){var c=Date.now(),d={scope:this.scope,state:this.state,users:this.users},g=this;return!b&&a&&"function"==typeof a&&(b=a,a=null),g.kuzzle.callbackRequired("KuzzleRoom.renew",b),g.lastRenewal&&c-g.lastRenewal<=g.renewalDelay?g:(a&&(g.filters=a),"connected"!==g.kuzzle.state?(g.callback=b,g.kuzzle.subscriptions.pending[g.id]=g,g):g.subscribing?(g.queue.push({action:"renew",args:[a,b]}),g):(g.unsubscribe(),g.roomId=null,g.subscribing=!0,g.callback=b,g.kuzzle.subscriptions.pending[g.id]=g,d.body=g.filters,d=g.kuzzle.addHeaders(d,this.headers),g.kuzzle.query(g.collection.buildQueryArgs("subscribe","on"),d,{metadata:g.metadata},function(a,b){if(delete g.kuzzle.subscriptions.pending[g.id],g.subscribing=!1,a)throw g.queue=[],new Error("Error during Kuzzle subscription: "+a.message);g.lastRenewal=c,g.roomId=b.result.roomId,g.channel=b.result.channel,g.kuzzle.subscriptions[g.roomId]||(g.kuzzle.subscriptions[g.roomId]={}),g.kuzzle.subscriptions[g.roomId][g.id]=g,g.notifier=e.bind(g),g.kuzzle.network.on(g.channel,g.notifier),f.call(g)}),g))},d.prototype.unsubscribe=function(){var a,b=this,c=b.roomId;return g.call(this)?(c&&(b.kuzzle.network.off(b.channel,this.notifier),1===Object.keys(b.kuzzle.subscriptions[c]).length?(delete b.kuzzle.subscriptions[c],0===Object.keys(b.kuzzle.subscriptions.pending).length?b.kuzzle.query(b.collection.buildQueryArgs("subscribe","off"),{body:{roomId:c}}):a=setInterval(function(){0===Object.keys(b.kuzzle.subscriptions.pending).length&&(b.kuzzle.subscriptions[c]||b.kuzzle.query(b.collection.buildQueryArgs("subscribe","off"),{body:{roomId:c}}),clearInterval(a))},100)):delete b.kuzzle.subscriptions[c][b.id],b.roomId=null),b):(b.queue.push({action:"unsubscribe",args:[]}),b)},d.prototype.setHeaders=function(a,b){return this.kuzzle.setHeaders.call(this,a,b),this},b.exports=d},{"node-uuid":2}],9:[function(a,b,c){function d(b,c,d){if("undefined"!=typeof window){if("undefined"!=typeof WebSocket)return new(a("./wrappers/wsbrowsers"))(b,c);if(window.io)return new(a("./wrappers/socketio"))(b,d);throw new Error("Aborting: no websocket support detected and no socket.io library loaded either.")}return new(a("./wrappers/wsnode"))(b,c)}b.exports=d},{"./wrappers/socketio":10,"./wrappers/wsbrowsers":11,"./wrappers/wsnode":void 0}],10:[function(a,b,c){function d(a,b){this.host=a,this.port=b,this.socket=null,this.connect=function(a,b){this.socket=window.io("http://"+this.host+":"+this.port,{reconnection:a,reconnectionDelay:b,forceNew:!0})},this.onConnect=function(a){this.socket.on("connect",a)},this.onConnectError=function(a){this.socket.on("connect_error",a)},this.onDisconnect=function(a){this.socket.on("disconnect",a)},this.onReconnect=function(a){this.socket.on("reconnect",a)},this.once=function(a,b){this.socket.once(a,b)},this.on=function(a,b){this.socket.on(a,b)},this.off=function(a,b){this.socket.off(a,b)},this.send=function(a){this.socket.emit("kuzzle",a)},this.close=function(){this.socket.close(),this.socket=null}}b.exports=d},{}],11:[function(a,b,c){function d(a,b){var c=this;this.host=a,this.port=b,this.client=null,this.retrying=!1,this.listeners={error:[],connect:[],disconnect:[],reconnect:[]},this.connect=function(a,b){this.client=new WebSocket("ws://"+this.host+":"+this.port),this.client.onopen=function(){c.retrying?e(c.listeners,"reconnect"):e(c.listeners,"connect")},this.client.onclose=function(){e(c.listeners,"disconnect")},this.client.onerror=function(){a&&(c.retrying=!0,setTimeout(function(){c.connect(a,b)},b)),e(c.listeners,"error")},this.client.onmessage=function(a){var b=JSON.parse(a.data);b.room&&c.listeners[b.room]&&e(c.listeners,b.room,b)}},this.onConnect=function(a){this.listeners.connect.push({fn:a,keep:!0})},this.onConnectError=function(a){this.listeners.error.push({fn:a,keep:!0})},this.onDisconnect=function(a){this.listeners.disconnect.push({fn:a,keep:!0})},this.onReconnect=function(a){this.listeners.reconnect.push({fn:a,keep:!0})},this.once=function(a,b){this.listeners[a]||(this.listeners[a]=[]),this.listeners[a].push({fn:b,keep:!1})},this.on=function(a,b){this.listeners[a]||(this.listeners[a]=[]),this.listeners[a].push({fn:b,keep:!0})},this.off=function(a,b){var c;this.listeners[a]&&(c=this.listeners[a].findIndex(function(a){return a.fn===b}),c!==-1&&(1===this.listeners[a].length&&["error","connect","disconnect","reconnect"].indexOf(a)===-1?delete this.listeners[a]:this.listeners[a].splice(c,1)))},this.send=function(a){this.client&&this.client.readyState===this.client.OPEN&&this.client.send(JSON.stringify(a))},this.close=function(){this.listeners={error:[],connect:[],disconnect:[],reconnect:[]},this.retrying=!1,this.client.close(),this.client=null}}function e(a,b,c){var d,e=a[b].length;for(d=0;d1?(a[b].splice(d,1),--d,--e):delete a[b])}b.exports=d},{}],12:[function(a,b,c){function d(a,b,c){if(e.call(this,a,b,c),Object.defineProperties(this,{deleteActionName:{value:"deleteProfile"},updateActionName:{value:"updateProfile"}}),a.kuzzle.bluebird)return a.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(a,b,c,d){var e=["hydrate","save"];return d&&e.indexOf(a)!==-1}})}var e=a("./kuzzleSecurityDocument");d.prototype=Object.create(e.prototype,{constructor:{value:d}}),d.prototype.save=function(a,b){var c,d=this;if(!this.content.policies)throw new Error('Argument "policies" is mandatory in a profile. This argument contains an array of objects.');return a&&void 0===b&&"function"==typeof a&&(b=a,a=null),c=this.serialize(),d.kuzzle.query(d.kuzzleSecurity.buildQueryArgs("createOrReplaceProfile"),c,a,function(a){return a?!!b&&b(a):void(b&&b(null,d))}),d},d.prototype.addPolicy=function(a){if("object"!=typeof a||"string"!=typeof a.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(a),this},d.prototype.setPolicies=function(a){if(!Array.isArray(a))throw new Error('Parameter "policies" must be an array of objects containing at least a "roleId" member which must be a string');return a.map(function(a){if("object"!=typeof a||"string"!=typeof a.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=a,this},d.prototype.serialize=function(){var a={};return this.id&&(a._id=this.id),a.body=this.content,a},d.prototype.getPolicies=function(){return this.content.policies},b.exports=d},{"./kuzzleSecurityDocument":15}],13:[function(a,b,c){function d(a,b,c){if(e.call(this,a,b,c),Object.defineProperties(this,{deleteActionName:{value:"deleteRole"},updateActionName:{value:"updateRole"}}),a.kuzzle.bluebird)return a.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(a,b,c,d){var e=["save"];return d&&e.indexOf(a)!==-1}})}var e=a("./kuzzleSecurityDocument");d.prototype=Object.create(e.prototype,{constructor:{value:d}}),d.prototype.save=function(a,b){var c=this.serialize(),d=this;a&&void 0===b&&"function"==typeof a&&(b=a,a=null),d.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createOrReplaceRole"),c,a,function(a){return a?!!b&&b(a):void(b&&b(null,d))})},b.exports=d},{"./kuzzleSecurityDocument":15}],14:[function(a,b,c){function d(a){return Object.defineProperty(this,"kuzzle",{value:a}),Object.defineProperty(this,"buildQueryArgs",{value:function(a){return{controller:"security",action:a}}}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(a,b,c,d){var e=["roleFactory","profileFactory","userFactory","isActionAllowed"];return d&&e.indexOf(a)===-1}}):this}var e=a("./kuzzleRole"),f=a("./kuzzleProfile"),g=a("./kuzzleUser");d.prototype.getRole=function(a,b,c){var d,f=this;if(!a)throw new Error("Id parameter is mandatory for getRole function");c||"function"!=typeof b||(c=b,b=null),d={_id:a},f.kuzzle.callbackRequired("KuzzleSecurity.getRole",c),f.kuzzle.query(this.buildQueryArgs("getRole"),d,b,function(a,b){return a?c(a):void c(null,new e(f,b.result._id,b.result._source))})},d.prototype.searchRoles=function(a,b,c){var d=this;c||"function"!=typeof b||(c=b,b=null),d.kuzzle.callbackRequired("KuzzleSecurity.searchRoles",c),d.kuzzle.query(this.buildQueryArgs("searchRoles"),{body:a},b,function(a,b){var f;return a?c(a):(f=b.result.hits.map(function(a){return new e(d,a._id,a._source)}),void c(null,{total:b.result.total,roles:f}))})},d.prototype.createRole=function(a,b,c,d){var f=this,g={},h="createRole";if(!a||"string"!=typeof a)throw new Error("KuzzleSecurity.createRole: cannot create a role without a role ID");d||"function"!=typeof c||(d=c,c=null),g._id=a,g.body=b,c&&(h=c.replaceIfExist?"createOrReplaceRole":"createRole"),d?f.kuzzle.query(this.buildQueryArgs(h),g,c,function(a,b){var c;return a?d(a):(c=new e(f,b.result._id,b.result._source),void d(null,c))}):f.kuzzle.query(this.buildQueryArgs(h),g)},d.prototype.updateRole=function(a,b,c,d){var f=this,g={},h="updateRole";if(!a||"string"!=typeof a)throw new Error("KuzzleSecurity.updateRole: cannot update a role without a role ID");d||"function"!=typeof c||(d=c,c=null),g._id=a,g.body=b,d?f.kuzzle.query(this.buildQueryArgs(h),g,c,function(c){return c?d(c):void d(null,new e(f,a,b))}):f.kuzzle.query(this.buildQueryArgs(h),g)},d.prototype.deleteRole=function(a,b,c){var d={_id:a};c||"function"!=typeof b||(c=b,b=null),c?this.kuzzle.query(this.buildQueryArgs("deleteRole"),d,b,function(a,b){return a?c(a):void c(null,b.result._id)}):this.kuzzle.query(this.buildQueryArgs("deleteRole"),d,b)},d.prototype.roleFactory=function(a,b){return new e(this,a,b)},d.prototype.getProfile=function(a,b,c){var d,e=this;if(c||"function"!=typeof b||(c=b,b=null),!a||"string"!=typeof a)throw new Error("Id parameter is mandatory for getProfile function");d={_id:a},e.kuzzle.callbackRequired("KuzzleSecurity.getProfile",c),e.kuzzle.query(this.buildQueryArgs("getProfile"),d,b,function(a,b){return a?c(a):void c(null,new f(e,b.result._id,b.result._source))})},d.prototype.searchProfiles=function(a,b,c){var d=this;c||"function"!=typeof b||(c=b,b=null),d.kuzzle.callbackRequired("KuzzleSecurity.searchProfiles",c),d.kuzzle.query(this.buildQueryArgs("searchProfiles"),{body:a},b,function(a,b){var e;return a?c(a):(e=b.result.hits.map(function(a){return new f(d,a._id,a._source)}),void c(null,{total:b.result.total,profiles:e}))})},d.prototype.createProfile=function(a,b,c,d){var e=this,g={},h="createProfile";if(!a||"string"!=typeof a)throw new Error("KuzzleSecurity.createProfile: cannot create a profile without a profile ID");d||"function"!=typeof c||(d=c,c=null),g._id=a,g.body=b,c&&(h=c.replaceIfExist?"createOrReplaceProfile":"createProfile"),d?e.kuzzle.query(this.buildQueryArgs(h),g,c,function(a,b){var c;return a?d(a):(c=new f(e,b.result._id,b.result._source),void d(null,c))}):e.kuzzle.query(this.buildQueryArgs(h),g)},d.prototype.updateProfile=function(a,b,c,d){var e=this,g={},h="updateProfile";if(!a||"string"!=typeof a)throw new Error("KuzzleSecurity.updateProfile: cannot update a profile without a profile ID");d||"function"!=typeof c||(d=c,c=null),g._id=a,g.body=b,d?e.kuzzle.query(this.buildQueryArgs(h),g,c,function(a,b){var c={};return a?d(a):(Object.keys(b.result._source).forEach(function(a){c[a]=b.result._source[a]}),void d(null,new f(e,b.result._id,c)))}):e.kuzzle.query(this.buildQueryArgs(h),g)},d.prototype.deleteProfile=function(a,b,c){var d={_id:a};c||"function"!=typeof b||(c=b,b=null),c?this.kuzzle.query(this.buildQueryArgs("deleteProfile"),d,b,function(a,b){return a?c(a):void c(null,b.result._id)}):this.kuzzle.query(this.buildQueryArgs("deleteProfile"),d,b)},d.prototype.profileFactory=function(a,b){return new f(this,a,b)},d.prototype.getUser=function(a,b,c){var d,e=this;if(!a||"string"!=typeof a)throw new Error("Id parameter is mandatory for getUser function");c||"function"!=typeof b||(c=b,b=null),d={_id:a},e.kuzzle.callbackRequired("KuzzleSecurity.getUser",c),e.kuzzle.query(this.buildQueryArgs("getUser"),d,b,function(a,b){return a?c(a):void c(null,new g(e,b.result._id,b.result._source))})},d.prototype.searchUsers=function(a,b,c){var d=this;c||"function"!=typeof b||(c=b,b=null),d.kuzzle.callbackRequired("KuzzleSecurity.searchUsers",c),d.kuzzle.query(this.buildQueryArgs("searchUsers"),{body:a},b,function(a,b){var e;return a?c(a):(e=b.result.hits.map(function(a){return new g(d,a._id,a._source)}),void c(null,{total:b.result.total,users:e}))})},d.prototype.createUser=function(a,b,c,d){var e=this,f={},h="createUser";if(!a||"string"!=typeof a)throw new Error("KuzzleSecurity.createUser: cannot create a user without a user ID");d||"function"!=typeof c||(d=c,c=null),f._id=a,f.body=b,c&&(h=c.replaceIfExist?"createOrReplaceUser":"createUser"),d?e.kuzzle.query(this.buildQueryArgs(h),f,null,function(a,b){var c;return a?d(a):(c=new g(e,b.result._id,b.result._source),void d(null,c))}):e.kuzzle.query(this.buildQueryArgs(h),f)},d.prototype.updateUser=function(a,b,c,d){var e=this,f={},h="updateUser";if(!a||"string"!=typeof a)throw new Error("KuzzleSecurity.updateUser: cannot update an user without an user ID");d||"function"!=typeof c||(d=c,c=null),f._id=a,f.body=b,d?e.kuzzle.query(this.buildQueryArgs(h),f,c,function(a,b){return a?d(a):void d(null,new g(e,b.result._id,b.result._source))}):e.kuzzle.query(this.buildQueryArgs(h),f,c)},d.prototype.deleteUser=function(a,b,c){var d={_id:a};c||"function"!=typeof b||(c=b,b=null),c?this.kuzzle.query(this.buildQueryArgs("deleteUser"),d,b,function(a,b){return a?c(a):void c(null,b.result._id)}):this.kuzzle.query(this.buildQueryArgs("deleteUser"),d,b)},d.prototype.userFactory=function(a,b){return new g(this,a,b)},d.prototype.isActionAllowed=function(a,b,c,d,e){var f;if(!a||"object"!=typeof a)throw new Error("rights parameter is mandatory for isActionAllowed function");if(!b||"string"!=typeof b)throw new Error("controller parameter is mandatory for isActionAllowed function");if(!c||"string"!=typeof c)throw new Error("action parameter is mandatory for isActionAllowed function");return f=a.filter(function(a){return a.controller===b||"*"===a.controller}).filter(function(a){return a.action===c||"*"===a.action}).filter(function(a){return a.index===d||"*"===a.index}).filter(function(a){return a.collection===e||"*"===a.collection}),f.some(function(a){return"allowed"===a.value})?"allowed":f.some(function(a){return"conditional"===a.value})?"conditional":"denied"},d.prototype.getUserRights=function(a,b,c){var d={_id:a},e=this;if(!a||"string"!=typeof a)throw new Error("userId parameter is mandatory for getUserRights function");c||"function"!=typeof b||(c=b,b=null),e.kuzzle.callbackRequired("Kuzzle.getUserRights",c),this.kuzzle.query(this.buildQueryArgs("getUserRights"),d,b,function(a,b){return a?c(a):void c(null,b.result.hits)})},b.exports=d},{"./kuzzleProfile":12,"./kuzzleRole":13,"./kuzzleUser":16}],15:[function(a,b,c){function d(a,b,c){if(!b)throw new Error("A security document must have an id");if(Object.defineProperties(this,{kuzzle:{value:a.kuzzle},kuzzleSecurity:{value:a},id:{value:b,enumerable:!0},content:{value:{},writable:!0,enumerable:!0}}),c&&this.setContent(c,!0),a.kuzzle.bluebird)return a.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(a,b,c,d){var e=["delete","update"];return d&&e.indexOf(a)!==-1}})}d.prototype.setContent=function(a){return this.content=a,this},d.prototype.serialize=function(){var a={};return this.id&&(a._id=this.id),a.body=this.content,a},d.prototype.delete=function(a,b){var c=this;a&&void 0===b&&"function"==typeof a&&(b=a,a=null),c.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.deleteActionName),{_id:this.id},a,function(a,c){return a?!!b&&b(a):void(b&&b(null,c.result._id))})},d.prototype.update=function(a,b,c){var d={},e=this;if("object"!=typeof a)throw new Error('Parameter "content" must be a object');b&&void 0===c&&"function"==typeof b&&(c=b,b=null),d._id=e.id,d.body=a,e.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.updateActionName),d,b,function(a,b){return a?!!c&&c(a):(e.setContent(b.result._source),void(c&&c(null,e)))})},b.exports=d},{}],16:[function(a,b,c){function d(a,b,c){if(e.call(this,a,b,c),Object.defineProperties(this,{deleteActionName:{value:"deleteUser"},updateActionName:{value:"updateUser"}}),a.kuzzle.bluebird)return a.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(a,b,c,d){var e=["save"];return d&&e.indexOf(a)!==-1}})}var e=a("./kuzzleSecurityDocument");d.prototype=Object.create(e.prototype,{constructor:{value:d}}),d.prototype.setProfiles=function(a){if(!Array.isArray(a)||"string"!=typeof a[0])throw new Error('Parameter "profilesIds" must be an array of strings');return this.content.profilesIds=a,this},d.prototype.addProfile=function(a){if("string"!=typeof a)throw new Error('Parameter "profileId" must be a string');return this.content.profilesIds||(this.content.profilesIds=[]),this.content.profilesIds.indexOf(a)===-1&&this.content.profilesIds.push(a),this},d.prototype.save=function(a,b){var c=this.serialize(),d=this;return a&&void 0===b&&"function"==typeof a&&(b=a,a=null),d.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createOrReplaceUser"),c,a,function(a){return a?!!b&&b(a):void(b&&b(null,d))}),d},d.prototype.serialize=function(){var a={};return this.id&&(a._id=this.id),a.body=this.content,a},d.prototype.getProfiles=function(){return this.content.profilesIds},b.exports=d},{"./kuzzleSecurityDocument":15}]},{},[3]); -//# sourceMappingURL=kuzzle.min.map \ No newline at end of file diff --git a/dist/kuzzle.min.map b/dist/kuzzle.min.map deleted file mode 100644 index dde4c6022..000000000 --- a/dist/kuzzle.min.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["kuzzle.js"],"names":["e","t","n","r","s","o","u","a","require","i","f","Error","code","l","exports","call","length","1","module","runTimeout","fun","cachedSetTimeout","setTimeout","runClearTimeout","marker","cachedClearTimeout","clearTimeout","cleanUpNextTick","draining","currentQueue","queue","concat","queueIndex","drainQueue","timeout","len","run","Item","array","this","noop","process","nextTick","args","Array","arguments","push","prototype","apply","title","browser","env","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","binding","name","cwd","chdir","dir","umask","2","Buffer","_window","setupBrowser","_crypto","crypto","msCrypto","_rng","getRandomValues","_rnds8","Uint8Array","_whatwgRNG","_rnds","_mathRNG","Math","random","console","warn","setupNode","_rb","randomBytes","_nodeRNG","parse","buf","offset","ii","toLowerCase","replace","oct","_hexToByte","unparse","bth","_byteToHex","v1","options","b","clockseq","_clockseq","msecs","Date","getTime","nsecs","_lastNSecs","dt","_lastMSecs","tl","tmh","node","_nodeId","v4","BufferClass","rnds","rng","_previousRoot","toString","substr","_seedBytes","uuid","define","amd","noConflict","window","3","cleanQueue","self","now","lastDocumentIndex","queueTTL","offlineQueue","forEach","query","index","ts","splice","droppedRequest","emitEvent","queueMaxSize","cleanHistory","requestHistory","Object","keys","key","emitRequest","request","cb","undefined","jwtToken","network","requestId","response","action","error","message","send","dequeue","additionalQueue","uniqueQueue","dequeuingProcess","shift","max","replayInterval","queuing","offlineQueueLoader","isArray","filter","controller","hasOwnProperty","renewAllSubscriptions","subscriptions","roomId","subscriptionId","subscription","renew","callback","KuzzleDataCollection","KuzzleSecurity","KuzzleMemoryStorage","KuzzleUser","networkWrapper","Kuzzle","host","defineProperties","collections","value","writable","connectCB","eventListeners","connected","lastEmitted","listeners","disconnected","reconnected","jwtTokenExpired","loginAttempt","offlineQueuePush","offlineQueuePop","eventTimeout","state","pending","autoReconnect","enumerable","defaultIndex","reconnectionDelay","wsPort","ioPort","autoQueue","autoReplay","autoResubscribe","headers","metadata","queueFilter","opt","getOwnPropertyDescriptor","offlineMode","defineProperty","header","errorMessagePrefix","event","slice","eventProperties","listener","fn","connect","bluebird","promisifyAll","suffix","func","target","passes","whitelist","indexOf","onConnect","onConnectError","connectionError","internal","onDisconnect","disconnect","onReconnect","reconnect","checkToken","err","res","valid","setJwtToken","token","success","result","jwt","JSON","stringify","getJwtToken","login","strategy","credentials","expiresIn","body","queuable","logout","callbackRequired","whoAmI","security","_id","_source","getMyRights","hits","updateSelf","content","data","queryArgs","listenerId","knownEvents","listenerType","isValid","id","getAllStatistics","getStatistics","timestamp","queryCB","startTime","dataCollectionFactory","collection","flushQueue","listCollections","collectionType","arg","type","listIndexes","indexes","close","getServerInfo","serverInfo","refreshIndex","getAutoRefresh","setAutoRefresh","autoRefresh","attr","object","meta","addHeaders","authorization","eventName","replayQueue","setDefaultIndex","setHeaders","startQueuing","stopQueuing","./kuzzleDataCollection","./kuzzleMemoryStorage","./networkWrapper","./security/kuzzleSecurity","./security/kuzzleUser","_process","node-uuid","4","kuzzle","blacklist","KuzzleDocument","KuzzleDataMapping","KuzzleRoom","advancedSearch","filters","buildQueryArgs","documents","doc","newDocument","_version","total","count","create","createDocument","document","serialize","updateIfExist","deleteDocument","ids","fetchDocument","documentId","fetchAllDocuments","from","size","getMapping","kuzzleMapping","refresh","publishMessage","replaceDocument","subscribe","room","truncate","updateDocument","documentFactory","roomFactory","dataMappingFactory","mapping","./kuzzleDataMapping","./kuzzleDocument","./kuzzleRoom","5","kuzzleDataCollection","properties","mappings","set","field","6","dataCollection","setContent","delete","save","publish","values","7","bind","keyVal","idOrKeys","commands","append","bgrewriteaof","bgsave","bitcount","bitop","bitpos","__opts__","blpop","brpoplpush","dbsize","decrby","del","discard","exec","exists","expire","expireat","flushdb","getbit","getrange","hdel","hexists","hincrby","hmset","hset","info","lastsave","lindex","linsert","lpush","lrange","lrem","lset","ltrim","mset","multi","pexpire","pexpireat","pfadd","pfmerge","ping","psetex","randomkey","rename","renamenx","restore","rpoplpush","sadd","sdiffstore","setbit","setex","setrange","sinterstore","sismember","smove","sort","spop","srem","sunionstore","unwatch","wait","zadd","zcount","zincrby","zinterstore","zlexcount","zrange","zrangebylex","zrangebyscore","zrem","zremrangebylex","zremrangebyscore","zrevrangebylex","zrevrangebyscore","zrevrank","decr","get","dump","hgetall","hkeys","hlen","hstrlen","hvals","incr","llen","lpop","persist","pttl","rpop","scard","smembers","strlen","ttl","zcard","getset","lpushx","mget","pfcount","sdiff","sinter","sunion","watch","incrby","incrbyfloat","brpop","hget","hmget","hsetnx","msetnx","rpush","hincrbyfloat","srandmember","zrevrange","zscore","command","pop","v","8","channel","lastRenewal","notifier","renewalDelay","scope","subscribing","users","subscribeToSelf","notificationCallback","element","isReady","subscribeQuery","unsubscribe","interval","setInterval","clearInterval","9","WebSocket","io","./wrappers/socketio","./wrappers/wsbrowsers","./wrappers/wsnode","10","SocketIO","port","socket","reconnection","forceNew","payload","11","WSBrowsers","client","retrying","onopen","poke","onclose","onerror","onmessage","keep","findIndex","readyState","OPEN","12","KuzzleProfile","kuzzleSecurity","KuzzleSecurityDocument","deleteActionName","updateActionName","constructor","policies","addPolicy","policy","roleId","setPolicies","map","getPolicies","./kuzzleSecurityDocument","13","KuzzleRole","14","getRole","searchRoles","roles","createRole","replaceIfExist","updateRole","deleteRole","roleFactory","getProfile","searchProfiles","profiles","createProfile","updateProfile","updatedContent","property","deleteProfile","profileFactory","getUser","searchUsers","createUser","updateUser","deleteUser","userFactory","isActionAllowed","rights","filteredRights","right","some","item","getUserRights","userId","./kuzzleProfile","./kuzzleRole","./kuzzleUser","15","update","16","setProfiles","profilesIds","addProfile","profileId","getProfiles"],"mappings":";CAAA,QAAUA,GAAEC,EAAEC,EAAEC,GAAG,QAASC,GAAEC,EAAEC,GAAG,IAAIJ,EAAEG,GAAG,CAAC,IAAIJ,EAAEI,GAAG,CAAC,GAAIE,GAAkB,kBAATC,UAAqBA,OAAQ,KAAIF,GAAGC,EAAE,MAAOA,GAAEF,GAAE,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2O,QAAQoU,aAGtBpkB,EAAOJ,QAAU2K,IAEdmX,2BAA2B,UAAU","file":"kuzzle.min.js"} \ No newline at end of file diff --git a/src/kuzzle.js b/src/kuzzle.js index 933872dca..3c9699e77 100644 --- a/src/kuzzle.js +++ b/src/kuzzle.js @@ -456,7 +456,7 @@ Kuzzle.prototype.login = function (strategy) { strategy: strategy }, credentials, - cb; + cb = null; // Handle arguments (credentials, expiresIn, cb) if (arguments[1]) { @@ -491,20 +491,13 @@ Kuzzle.prototype.login = function (strategy) { self.setJwtToken(response.result.jwt); } - if (cb && typeof cb === 'function') { - cb(null, response.result); - } + cb && cb(null, response.result); } else { - if (cb && typeof cb === 'function') { - cb(error); - } - + cb && cb(error); self.emitEvent('loginAttempt', {success: false, error: error.message}); } }); - - return self; }; /** @@ -523,15 +516,12 @@ Kuzzle.prototype.logout = function (cb) { body: {} }; - this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, function(error) { + this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, typeof cb !== 'function' ? null : function(error) { if (error === null) { self.jwtToken = undefined; - - if (typeof cb === 'function') { - cb(null, self); - } + cb(null, self); } - else if (typeof cb === 'function') { + else { cb(error); } }); @@ -549,7 +539,6 @@ Kuzzle.prototype.logout = function (cb) { */ Kuzzle.prototype.checkToken = function (token, callback) { var - self = this, request = { body: { token: token @@ -565,8 +554,6 @@ Kuzzle.prototype.checkToken = function (token, callback) { callback(null, response.result); }); - - return self; }; /** @@ -588,13 +575,12 @@ Kuzzle.prototype.whoAmI = function (callback) { callback(null, new KuzzleUser(self.security, response.result._id, response.result._source)); }); - - return self; }; /** * 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) { @@ -636,17 +622,11 @@ Kuzzle.prototype.updateSelf = function (content, options, cb) { data.body = content; - if (cb) { - self.query(queryArgs, data, options, function (err, res) { - if (err) { - return cb(err); - } + self.query(queryArgs, data, options, cb && function (err, res) { + cb(err, err ? undefined : res.result); + }); - cb(null, res.result); - }); - } else { - self.query(queryArgs, data, options); - } + return this; }; /** @@ -719,9 +699,7 @@ function emitRequest (request, cb) { self.emitEvent('jwtTokenExpired', request, cb); } - if (cb) { - cb(response.error, response); - } + cb && cb(response.error, response); }); } @@ -847,8 +825,6 @@ Kuzzle.prototype.getAllStatistics = function (options, cb) { cb(null, res.result.hits); }); - - return this; }; /** @@ -861,7 +837,9 @@ Kuzzle.prototype.getAllStatistics = function (options, cb) { * @returns {object} this */ Kuzzle.prototype.getStatistics = function (timestamp, options, cb) { - var queryCB; + var + queryCB, + body; if (!cb) { if (arguments.length === 1) { @@ -885,22 +863,13 @@ Kuzzle.prototype.getStatistics = function (timestamp, options, cb) { return cb(err); } - if (timestamp) { - cb(null, res.result.hits); - } else { - cb(null, [res.result]); - } + cb(null, timestamp ? res.result.hits : [res.result]); }; this.callbackRequired('Kuzzle.getStatistics', cb); - if (!timestamp) { - this.query({controller: 'admin', action: 'getLastStats'}, {}, options, queryCB); - } else { - this.query({controller: 'admin', action: 'getStats'}, { body: { startTime: timestamp } }, options, queryCB); - } - - return this; + body = timestamp ? {body: {startTime: timestamp}} : {}; + this.query({controller: 'admin', action: timestamp ? 'getStats' : 'getLastStats'}, body, options, queryCB); }; /** @@ -922,12 +891,8 @@ Kuzzle.prototype.dataCollectionFactory = function(collection, index) { index = this.defaultIndex; } - if (typeof index !== 'string') { - throw new Error('Invalid "index" argument: string expected, got ' + typeof index); - } - - if (typeof collection !== 'string') { - throw new Error('Invalid "collection" argument: string expected, got ' + typeof collection); + if (typeof index !== 'string' || typeof collection !== 'string') { + throw new Error('Invalid index or collection argument: string expected'); } if (!this.collections[index]) { @@ -1000,10 +965,8 @@ Kuzzle.prototype.listCollections = function () { return cb(err); } - return cb(null, res.result.collections); + cb(null, res.result.collections); }); - - return this; }; /** @@ -1022,14 +985,8 @@ Kuzzle.prototype.listIndexes = function (options, cb) { this.callbackRequired('Kuzzle.listIndexes', cb); this.query({controller: 'read', action: 'listIndexes'}, {}, options, function (err, res) { - if (err) { - return cb(err); - } - - return cb(null, res.result.indexes); + cb(err, err ? undefined : res.result.indexes); }); - - return this; }; /** @@ -1072,8 +1029,6 @@ Kuzzle.prototype.getServerInfo = function (options, cb) { cb(null, res.result.serverInfo); }); - - return this; }; /** @@ -1153,8 +1108,6 @@ Kuzzle.prototype.getAutoRefresh = function () { this.callbackRequired('Kuzzle.getAutoRefresh', cb); this.query({ index: index, controller: 'admin', action: 'getAutoRefresh'}, {}, options, cb); - - return this; }; /** @@ -1221,14 +1174,8 @@ Kuzzle.prototype.now = function (options, cb) { this.callbackRequired('Kuzzle.now', cb); this.query({controller: 'read', action: 'now'}, {}, options, function (err, res) { - if (err) { - return cb(err); - } - - cb(null, res.result.now); + cb(err, res && res.result.now); }); - - return this; }; /** @@ -1351,6 +1298,8 @@ Kuzzle.prototype.removeAllListeners = function (event) { self.eventListeners[eventName].listeners = []; }); } + + return this; }; /** @@ -1373,6 +1322,8 @@ Kuzzle.prototype.removeListener = function (event, listenerId) { self.eventListeners[event].listeners.splice(index, 1); } }); + + return this; }; /** diff --git a/src/kuzzleDataCollection.js b/src/kuzzleDataCollection.js index bbb9bebfd..693d330c3 100644 --- a/src/kuzzleDataCollection.js +++ b/src/kuzzleDataCollection.js @@ -115,8 +115,6 @@ KuzzleDataCollection.prototype.advancedSearch = function (filters, options, cb) cb(null, { total: result.result.total, documents: documents }); }); - - return this; }; /** @@ -145,14 +143,8 @@ KuzzleDataCollection.prototype.count = function (filters, options, cb) { query = this.kuzzle.addHeaders({body: filters}, this.headers); this.kuzzle.query(this.buildQueryArgs('read', 'count'), query, options, function (error, result) { - if (error) { - return cb(error); - } - - cb(null, result.result.count); + cb(error, result && result.result.count); }); - - return this; }; /** @@ -228,21 +220,17 @@ KuzzleDataCollection.prototype.createDocument = function (id, document, options, data = self.kuzzle.addHeaders(data, self.headers); - if (cb) { - self.kuzzle.query(this.buildQueryArgs('write', action), data, options, function (err, res) { - var doc; + self.kuzzle.query(this.buildQueryArgs('write', action), data, options, cb && function (err, res) { + var doc; - if (err) { - return cb(err); - } + if (err) { + return cb(err); + } - doc = new KuzzleDocument(self, res.result._id, res.result._source); - doc.version = res.result._version; - cb(null, doc); - }); - } else { - self.kuzzle.query(this.buildQueryArgs('write', action), data, options); - } + doc = new KuzzleDocument(self, res.result._id, res.result._source); + doc.version = res.result._version; + cb(null, doc); + }); return this; }; @@ -283,21 +271,11 @@ KuzzleDataCollection.prototype.deleteDocument = function (arg, options, cb) { data = this.kuzzle.addHeaders(data, this.headers); - if (cb) { - this.kuzzle.query(this.buildQueryArgs('write', action), data, options, function (err, res) { - if (err) { - return cb(err); - } + this.kuzzle.query(this.buildQueryArgs('write', action), data, options, cb && function (err, res) { + cb(err, err ? undefined : (action === 'delete' ? [res.result._id] : res.result.ids)); + }); - if (action === 'delete') { - cb(null, [res.result._id]); - } else { - cb(null, res.result.ids); - } - }); - } else { - this.kuzzle.query(this.buildQueryArgs('write', action), data, options); - } + return this; }; /** @@ -332,8 +310,6 @@ KuzzleDataCollection.prototype.fetchDocument = function (documentId, options, cb document.version = res.result._version; cb(null, document); }); - - return this; }; /** @@ -365,8 +341,6 @@ KuzzleDataCollection.prototype.fetchAllDocuments = function (options, cb) { this.kuzzle.callbackRequired('KuzzleDataCollection.fetchAll', cb); this.advancedSearch(filters, options, cb); - - return this; }; @@ -389,8 +363,6 @@ KuzzleDataCollection.prototype.getMapping = function (options, cb) { kuzzleMapping = new KuzzleDataMapping(this); kuzzleMapping.refresh(options, cb); - - return this; }; /** @@ -448,21 +420,17 @@ KuzzleDataCollection.prototype.replaceDocument = function (documentId, content, data = self.kuzzle.addHeaders(data, this.headers); - if (cb) { - self.kuzzle.query(this.buildQueryArgs('write', 'createOrReplace'), data, options, function (err, res) { - var document; + self.kuzzle.query(this.buildQueryArgs('write', 'createOrReplace'), data, options, cb && function (err, res) { + var document; - if (err) { - return cb(err); - } + if (err) { + return cb(err); + } - document = new KuzzleDocument(self, res.result._id, res.result._source); - document.version = res.result._version; - cb(null, document); - }); - } else { - self.kuzzle.query(this.buildQueryArgs('write', 'createOrReplace'), data, options); - } + document = new KuzzleDocument(self, res.result._id, res.result._source); + document.version = res.result._version; + cb(null, document); + }); return this; }; @@ -487,8 +455,9 @@ KuzzleDataCollection.prototype.subscribe = function (filters, options, cb) { this.kuzzle.callbackRequired('KuzzleDataCollection.subscribe', cb); room = new KuzzleRoom(this, options); + room.renew(filters, cb); - return room.renew(filters, cb); + return room; }; /** @@ -542,19 +511,13 @@ KuzzleDataCollection.prototype.updateDocument = function (documentId, content, o data = self.kuzzle.addHeaders(data, this.headers); - if (cb) { - self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options, function (err, res) { - var doc; - if (err) { - return cb(err); - } + self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options, cb && function (err, res) { + if (err) { + return cb(err); + } - doc = new KuzzleDocument(self, res.result._id); - doc.refresh(cb); - }); - } else { - self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options); - } + (new KuzzleDocument(self, res.result._id)).refresh(cb); + }); return self; }; diff --git a/src/kuzzleDataMapping.js b/src/kuzzleDataMapping.js index 69d72c328..28c053c1e 100644 --- a/src/kuzzleDataMapping.js +++ b/src/kuzzleDataMapping.js @@ -75,7 +75,7 @@ KuzzleDataMapping.prototype.apply = function (options, cb) { self.kuzzle.query(this.collection.buildQueryArgs('admin', 'updateMapping'), data, options, function (err) { if (err) { - return cb ? cb(err) : false; + return cb && cb(err); } self.refresh(options, cb); @@ -117,10 +117,10 @@ KuzzleDataMapping.prototype.refresh = function (options, cb) { self.mapping = {}; } } else { - return cb ? cb(new Error('No mapping found for collection ' + self.collection.collection)) : false; + return cb && cb(new Error('No mapping found for collection ' + self.collection.collection)); } } else { - return cb ? cb(new Error('No mapping found for index ' + self.collection.index)) : false; + return cb && cb(new Error('No mapping found for index ' + self.collection.index)); } if (cb) { diff --git a/src/kuzzleDocument.js b/src/kuzzleDocument.js index f76006ad3..4dbcf3d66 100644 --- a/src/kuzzleDocument.js +++ b/src/kuzzleDocument.js @@ -146,17 +146,9 @@ KuzzleDocument.prototype.delete = function (options, cb) { throw new Error('KuzzleDocument.delete: cannot delete a document without a document ID'); } - if (cb) { - this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'delete'), this.serialize(), options, function (err) { - if (err) { - return cb(err); - } - - cb(null, self.id); - }); - } else { - this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'delete'), this.serialize(), options); - } + this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'delete'), this.serialize(), options, cb && function (err) { + cb(err, err ? undefined : self.id); + }); }; /** @@ -221,7 +213,7 @@ KuzzleDocument.prototype.save = function (options, cb) { self.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'createOrReplace'), data, options, function (error, res) { if (error) { - return cb ? cb(error) : false; + return cb && cb(error); } self.id = res.result._id; diff --git a/src/kuzzleRoom.js b/src/kuzzleRoom.js index 6966607aa..b43f882b0 100644 --- a/src/kuzzleRoom.js +++ b/src/kuzzleRoom.js @@ -131,7 +131,7 @@ KuzzleRoom.prototype.count = function (cb) { if (!isReady.call(this)) { this.queue.push({action: 'count', args: [cb]}); - return this; + return; } if (!this.roomId) { @@ -139,14 +139,8 @@ KuzzleRoom.prototype.count = function (cb) { } this.kuzzle.query(this.collection.buildQueryArgs('subscribe', 'count'), data, function (err, res) { - if (err) { - return cb(err); - } - - cb(null, res.result.count); + cb(err, res && res.result.count); }); - - return this; }; /** @@ -176,7 +170,7 @@ KuzzleRoom.prototype.renew = function (filters, cb) { Skip subscription renewal if another one was performed a moment before */ if (self.lastRenewal && (now - self.lastRenewal) <= self.renewalDelay) { - return self; + return; } if (filters) { @@ -190,12 +184,12 @@ KuzzleRoom.prototype.renew = function (filters, cb) { if (self.kuzzle.state !== 'connected') { self.callback = cb; self.kuzzle.subscriptions.pending[self.id] = self; - return self; + return; } if (self.subscribing) { self.queue.push({action: 'renew', args: [filters, cb]}); - return self; + return; } self.unsubscribe(); @@ -231,8 +225,6 @@ KuzzleRoom.prototype.renew = function (filters, cb) { dequeue.call(self); }); - - return self; }; /** @@ -339,10 +331,7 @@ function dequeue () { } function isReady() { - if (this.kuzzle.state !== 'connected' || this.subscribing) { - return false; - } - return true; + return this.kuzzle.state === 'connected' && !this.subscribing; } module.exports = KuzzleRoom; diff --git a/src/security/kuzzleProfile.js b/src/security/kuzzleProfile.js index a98f10a0b..ed507f29f 100644 --- a/src/security/kuzzleProfile.js +++ b/src/security/kuzzleProfile.js @@ -59,14 +59,8 @@ KuzzleProfile.prototype.save = function (options, cb) { data = this.serialize(); - self.kuzzle.query(self.kuzzleSecurity.buildQueryArgs('createOrReplaceProfile'), data, options, function (error) { - if (error) { - return cb ? cb(error) : false; - } - - if (cb) { - cb(null, self); - } + self.kuzzle.query(self.kuzzleSecurity.buildQueryArgs('createOrReplaceProfile'), data, options, cb && function (error) { + cb(error, error ? undefined : self); }); return self; diff --git a/src/security/kuzzleRole.js b/src/security/kuzzleRole.js index df51b2396..c619b5b11 100644 --- a/src/security/kuzzleRole.js +++ b/src/security/kuzzleRole.js @@ -55,15 +55,11 @@ KuzzleRole.prototype.save = function (options, cb) { options = null; } - self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs('createOrReplaceRole'), data, options, function (error) { - if (error) { - return cb ? cb(error) : false; - } - - if (cb) { - cb(null, self); - } + self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs('createOrReplaceRole'), data, options, cb && function (error) { + cb(error, error ? undefined : self); }); + + return this; }; module.exports = KuzzleRole; \ No newline at end of file diff --git a/src/security/kuzzleSecurity.js b/src/security/kuzzleSecurity.js index 26f1fd65d..8da9c9280 100644 --- a/src/security/kuzzleSecurity.js +++ b/src/security/kuzzleSecurity.js @@ -66,11 +66,7 @@ KuzzleSecurity.prototype.getRole = function (id, options, cb) { self.kuzzle.callbackRequired('KuzzleSecurity.getRole', cb); self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) { - if (err) { - return cb(err); - } - - cb(null, new KuzzleRole(self, response.result._id, response.result._source)); + cb(err, err ? undefined : new KuzzleRole(self, response.result._id, response.result._source)); }); }; @@ -147,20 +143,9 @@ KuzzleSecurity.prototype.createRole = function (id, content, options, cb) { action = options.replaceIfExist ? 'createOrReplaceRole' : 'createRole'; } - if (cb) { - self.kuzzle.query(this.buildQueryArgs(action), data, options, function (err, res) { - var doc; - - if (err) { - return cb(err); - } - - doc = new KuzzleRole(self, res.result._id, res.result._source); - cb(null, doc); - }); - } else { - self.kuzzle.query(this.buildQueryArgs(action), data); - } + self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) { + cb(err, err ? undefined : new KuzzleRole(self, res.result._id, res.result._source)); + }); }; @@ -175,7 +160,7 @@ KuzzleSecurity.prototype.createRole = function (id, content, options, cb) { KuzzleSecurity.prototype.updateRole = function (id, content, options, cb) { var self = this, - data = {}, + data = {_id: id, body: content}, action = 'updateRole'; if (!id || typeof id !== 'string') { @@ -187,20 +172,11 @@ KuzzleSecurity.prototype.updateRole = function (id, content, options, cb) { options = null; } - data._id = id; - data.body = content; - - if (cb) { - self.kuzzle.query(this.buildQueryArgs(action), data, options, function (err) { - if (err) { - return cb(err); - } + self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err) { + cb(err, err ? undefined : new KuzzleRole(self, id, content)); + }); - cb(null, new KuzzleRole(self, id, content)); - }); - } else { - self.kuzzle.query(this.buildQueryArgs(action), data); - } + return this; }; /** @@ -223,17 +199,11 @@ KuzzleSecurity.prototype.deleteRole = function (id, options, cb) { options = null; } - if (cb) { - this.kuzzle.query(this.buildQueryArgs('deleteRole'), data, options, function (err, res) { - if (err) { - return cb(err); - } + this.kuzzle.query(this.buildQueryArgs('deleteRole'), data, options, cb && function (err, res) { + cb(err, err ? undefined : res.result._id); + }); - cb(null, res.result._id); - }); - } else { - this.kuzzle.query(this.buildQueryArgs('deleteRole'), data, options); - } + return this; }; /** @@ -277,11 +247,7 @@ KuzzleSecurity.prototype.getProfile = function (id, options, cb) { self.kuzzle.callbackRequired('KuzzleSecurity.getProfile', cb); self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) { - if (error) { - return cb(error); - } - - cb(null, new KuzzleProfile(self, response.result._id, response.result._source)); + cb(error, error ? undefined : new KuzzleProfile(self, response.result._id, response.result._source)); }); }; @@ -358,20 +324,9 @@ KuzzleSecurity.prototype.createProfile = function (id, content, options, cb) { action = options.replaceIfExist ? 'createOrReplaceProfile' : 'createProfile'; } - if (cb) { - self.kuzzle.query(this.buildQueryArgs(action), data, options, function (err, res) { - var doc; - - if (err) { - return cb(err); - } - - doc = new KuzzleProfile(self, res.result._id, res.result._source); - cb(null, doc); - }); - } else { - self.kuzzle.query(this.buildQueryArgs(action), data); - } + self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) { + cb(err, err ? undefined : new KuzzleProfile(self, res.result._id, res.result._source)); + }); }; @@ -401,23 +356,21 @@ KuzzleSecurity.prototype.updateProfile = function (id, content, options, cb) { data._id = id; data.body = content; - if (cb) { - self.kuzzle.query(this.buildQueryArgs(action), data, options, function (err, res) { - var updatedContent = {}; - - if (err) { - return cb(err); - } + self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) { + var updatedContent = {}; - Object.keys(res.result._source).forEach(function (property) { - updatedContent[property] = res.result._source[property]; - }); + if (err) { + return cb(err); + } - cb(null, new KuzzleProfile(self, res.result._id, updatedContent)); + Object.keys(res.result._source).forEach(function (property) { + updatedContent[property] = res.result._source[property]; }); - } else { - self.kuzzle.query(this.buildQueryArgs(action), data); - } + + cb(null, new KuzzleProfile(self, res.result._id, updatedContent)); + }); + + return this; }; /** @@ -440,17 +393,11 @@ KuzzleSecurity.prototype.deleteProfile = function (id, options, cb) { options = null; } - if (cb) { - this.kuzzle.query(this.buildQueryArgs('deleteProfile'), data, options, function (err, res) { - if (err) { - return cb(err); - } + this.kuzzle.query(this.buildQueryArgs('deleteProfile'), data, options, cb && function (err, res) { + cb(err, err ? undefined : res.result._id); + }); - cb(null, res.result._id); - }); - } else { - this.kuzzle.query(this.buildQueryArgs('deleteProfile'), data, options); - } + return this; }; /** @@ -474,7 +421,7 @@ KuzzleSecurity.prototype.profileFactory = function(id, content) { */ KuzzleSecurity.prototype.getUser = function (id, options, cb) { var - data, + data = {_id: id}, self = this; if (!id || typeof id !== 'string') { @@ -486,16 +433,10 @@ KuzzleSecurity.prototype.getUser = function (id, options, cb) { options = null; } - data = {_id: id}; - self.kuzzle.callbackRequired('KuzzleSecurity.getUser', cb); self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) { - if (err) { - return cb(err); - } - - cb(null, new KuzzleUser(self, response.result._id, response.result._source)); + cb(err, err ? undefined : new KuzzleUser(self, response.result._id, response.result._source)); }); }; @@ -552,7 +493,7 @@ KuzzleSecurity.prototype.searchUsers = function (filters, options, cb) { KuzzleSecurity.prototype.createUser = function (id, content, options, cb) { var self = this, - data = {}, + data = {_id: id, body: content}, action = 'createUser'; if (!id || typeof id !== 'string') { @@ -564,27 +505,13 @@ KuzzleSecurity.prototype.createUser = function (id, content, options, cb) { options = null; } - data._id = id; - data.body = content; - if (options) { action = options.replaceIfExist ? 'createOrReplaceUser' : 'createUser'; } - if (cb) { - self.kuzzle.query(this.buildQueryArgs(action), data, null, function (err, res) { - var doc; - - if (err) { - return cb(err); - } - - doc = new KuzzleUser(self, res.result._id, res.result._source); - cb(null, doc); - }); - } else { - self.kuzzle.query(this.buildQueryArgs(action), data); - } + self.kuzzle.query(this.buildQueryArgs(action), data, null, cb && function (err, res) { + cb(err, err ? undefined : new KuzzleUser(self, res.result._id, res.result._source)); + }); }; @@ -614,17 +541,11 @@ KuzzleSecurity.prototype.updateUser = function (id, content, options, cb) { data._id = id; data.body = content; - if (cb) { - self.kuzzle.query(this.buildQueryArgs(action), data, options, function (err, res) { - if (err) { - return cb(err); - } + self.kuzzle.query(this.buildQueryArgs(action), data, options, cb && function (err, res) { + cb(err, err ? undefined : new KuzzleUser(self, res.result._id, res.result._source)); + }); - cb(null, new KuzzleUser(self, res.result._id, res.result._source)); - }); - } else { - self.kuzzle.query(this.buildQueryArgs(action), data, options); - } + return this; }; /** @@ -647,17 +568,11 @@ KuzzleSecurity.prototype.deleteUser = function (id, options, cb) { options = null; } - if (cb) { - this.kuzzle.query(this.buildQueryArgs('deleteUser'), data, options, function (err, res) { - if (err) { - return cb(err); - } + this.kuzzle.query(this.buildQueryArgs('deleteUser'), data, options, cb && function (err, res) { + cb(err, err ? undefined : res.result._id); + }); - cb(null, res.result._id); - }); - } else { - this.kuzzle.query(this.buildQueryArgs('deleteUser'), data, options); - } + return this; }; /** @@ -702,18 +617,19 @@ KuzzleSecurity.prototype.isActionAllowed = function(rights, controller, action, } // We filter in all the rights that match the request (including wildcards). - filteredRights = rights.filter(function (right) { - return right.controller === controller || right.controller === '*'; - }) - .filter(function (right) { - return right.action === action || right.action === '*'; - }) - .filter(function (right) { - return right.index === index || right.index === '*'; - }) - .filter(function (right) { - return right.collection === collection || right.collection === '*'; - }); + filteredRights = rights + .filter(function (right) { + return right.controller === controller || right.controller === '*'; + }) + .filter(function (right) { + return right.action === action || right.action === '*'; + }) + .filter(function (right) { + return right.index === index || right.index === '*'; + }) + .filter(function (right) { + return right.collection === collection || right.collection === '*'; + }); // Then, if at least one right allows the action, we return 'allowed' if (filteredRights.some(function (item) { return item.value === 'allowed'; })) { @@ -751,12 +667,8 @@ KuzzleSecurity.prototype.getUserRights = function (userId, options, cb) { self.kuzzle.callbackRequired('Kuzzle.getUserRights', cb); - this.kuzzle.query(this.buildQueryArgs('getUserRights'), data, options, function (err, res) { - if (err) { - return cb(err); - } - - cb(null, res.result.hits); + this.kuzzle.query(this.buildQueryArgs('getUserRights'), data, options, cb && function (err, res) { + cb(err, err ? undefined : res.result.hits); }); }; diff --git a/src/security/kuzzleSecurityDocument.js b/src/security/kuzzleSecurityDocument.js index 39726f997..75bc9c48d 100644 --- a/src/security/kuzzleSecurityDocument.js +++ b/src/security/kuzzleSecurityDocument.js @@ -134,6 +134,8 @@ KuzzleSecurityDocument.prototype.update = function (content, options, cb) { cb(null, self); } }); + + return this; }; module.exports = KuzzleSecurityDocument; \ No newline at end of file diff --git a/src/security/kuzzleUser.js b/src/security/kuzzleUser.js index 5b2d8260c..d91a8b07d 100644 --- a/src/security/kuzzleUser.js +++ b/src/security/kuzzleUser.js @@ -94,14 +94,8 @@ KuzzleUser.prototype.save = function (options, cb) { options = null; } - self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs('createOrReplaceUser'), data, options, function (error) { - if (error) { - return cb ? cb(error) : false; - } - - if (cb) { - cb(null, self); - } + self.kuzzle.query(this.kuzzleSecurity.buildQueryArgs('createOrReplaceUser'), data, options, cb && function (error) { + cb(error, error ? undefined : self); }); return self; @@ -113,16 +107,7 @@ KuzzleUser.prototype.save = function (options, cb) { * @return {object} JSON object representing this User */ KuzzleUser.prototype.serialize = function () { - var - data = {}; - - if (this.id) { - data._id = this.id; - } - - data.body = this.content; - - return data; + return {_id: this.id, body: this.content}; }; /** diff --git a/test/kuzzle/methods.test.js b/test/kuzzle/methods.test.js index 3885c66e7..37a1766c9 100644 --- a/test/kuzzle/methods.test.js +++ b/test/kuzzle/methods.test.js @@ -59,10 +59,6 @@ describe('Kuzzle methods', function () { }; }); - it('should return the kuzzle instance when called', function () { - should(kuzzle.getAllStatistics(function () {})).be.exactly(kuzzle); - }); - it('should throw an error if no callback is provided', function () { should(function () { kuzzle.getAllStatistics(); }).throw(Error); should(emitted).be.false(); @@ -113,7 +109,7 @@ describe('Kuzzle methods', function () { }); it('should return the last statistics frame if no timestamp is provided', function () { - should(kuzzle.getStatistics(function () {})).be.exactly(kuzzle); + kuzzle.getStatistics(function () {}); should(emitted).be.true(); }); @@ -265,10 +261,10 @@ describe('Kuzzle methods', function () { }); it('should behave correctly when invoked', function () { - should(kuzzle.getServerInfo(function (err, res) { + kuzzle.getServerInfo(function (err, res) { should(err).be.null(); should(res).be.eql(result.result.serverInfo); - })).be.eql(kuzzle); + }); }); it('should throw an error if no callback is provided', function () { @@ -307,10 +303,6 @@ describe('Kuzzle methods', function () { }; }); - it('should return the kuzzle instance when called', function () { - should(kuzzle.listCollections('foo', function () {})).be.exactly(kuzzle); - }); - it('should throw an error if no callback has been provided', function () { should(function () { kuzzle.listCollections('foo'); }).throw(Error); should(emitted).be.false(); @@ -354,11 +346,11 @@ describe('Kuzzle methods', function () { it('should use the default index if none is provided', function () { kuzzle.setDefaultIndex('foo'); - should(kuzzle.listCollections(function () {})).be.exactly(kuzzle); + kuzzle.listCollections(function () {}); should(emitted).be.true(); emitted = false; - should(kuzzle.listCollections({some: 'options'}, function () {})).be.exactly(kuzzle); + kuzzle.listCollections({some: 'options'}, function () {}); should(emitted).be.true(); }); }); @@ -377,13 +369,6 @@ describe('Kuzzle methods', function () { }; }); - it('should return the kuzzle instance when called', function () { - should(kuzzle.listIndexes(function (err, res) { - should(err).be.null(); - should(res).be.eql(result.result.indexes); - })).be.eql(kuzzle); - }); - it('should throw an error if no callback is provided', function () { should(function () { kuzzle.listIndexes(); }).throw(Error); should(emitted).be.false(); @@ -434,10 +419,6 @@ describe('Kuzzle methods', function () { }; }); - it('should return the kuzzle instance when called', function () { - should(kuzzle.now(function () {})).be.exactly(kuzzle); - }); - it('should throw an error if called without a callback', function () { should(function () { kuzzle.now(); }).throw(Error); should(emitted).be.false(); diff --git a/test/kuzzleDataCollection/methods.test.js b/test/kuzzleDataCollection/methods.test.js index 4437682f6..775380c20 100644 --- a/test/kuzzleDataCollection/methods.test.js +++ b/test/kuzzleDataCollection/methods.test.js @@ -76,7 +76,7 @@ describe('KuzzleDataCollection methods', function () { expectedQuery.options = options; expectedQuery.body = filters; - should(collection.advancedSearch(filters, options, function (err, res) { + collection.advancedSearch(filters, options, function (err, res) { should(err).be.null(); should(res).be.an.Object(); should(res.total).be.a.Number().and.be.exactly(result.result.total); @@ -87,7 +87,7 @@ describe('KuzzleDataCollection methods', function () { should(item).be.instanceof(KuzzleDocument); }); done(); - })).be.exactly(collection); + }); should(emitted).be.true(); }); @@ -149,11 +149,11 @@ describe('KuzzleDataCollection methods', function () { expectedQuery.options = options; expectedQuery.body = filters; - should(collection.count(filters, options, function (err, res) { + collection.count(filters, options, function (err, res) { should(err).be.null(); should(res).be.a.Number().and.be.exactly(result.result.count); done(); - })).be.exactly(collection); + }); should(emitted).be.true(); }); @@ -460,11 +460,11 @@ describe('KuzzleDataCollection methods', function () { expectedQuery.options = options; - should(collection.fetchDocument(result.result._id, options, function (err, res) { + collection.fetchDocument(result.result._id, options, function (err, res) { should(err).be.null(); should(res).be.instanceof(KuzzleDocument); done(); - })).be.exactly(collection); + }); should(emitted).be.true(); }); @@ -516,7 +516,7 @@ describe('KuzzleDataCollection methods', function () { collection.advancedSearch = function () { emitted = true; }; expectedQuery.options = options; - should(collection.fetchAllDocuments(options, function () {})).be.exactly(collection); + collection.fetchAllDocuments(options, function () {}); should(emitted).be.true(); }); @@ -576,11 +576,11 @@ describe('KuzzleDataCollection methods', function () { expectedQuery.options = options; - should(collection.getMapping(options, function (err, res) { + collection.getMapping(options, function (err, res) { should(err).be.null(); should(res).be.instanceof(KuzzleDataMapping); done(); - })).be.exactly(collection); + }); should(emitted).be.true(); }); diff --git a/test/kuzzleRoom/methods.test.js b/test/kuzzleRoom/methods.test.js index 332b1f7cb..6192de1ef 100644 --- a/test/kuzzleRoom/methods.test.js +++ b/test/kuzzleRoom/methods.test.js @@ -76,7 +76,7 @@ describe('KuzzleRoom methods', function () { }); it('should send the right query to Kuzzle', function () { - should(room.count(function () {})).be.exactly(room); + room.count(function () {}); should(emitted).be.true(); }); @@ -88,7 +88,7 @@ describe('KuzzleRoom methods', function () { it('should delay the request until after subscribing', function () { var cb = function () {}; room.subscribing = true; - should(room.count(cb)).be.exactly(room); + room.count(cb); should(emitted).be.false(); should(room.queue).match([{action: 'count', args: [cb]}]); }); @@ -154,7 +154,7 @@ describe('KuzzleRoom methods', function () { var before = Date.now(); - should(room.renew({}, function () {})).be.exactly(room); + room.renew({}, function () {}); should(emitted).be.true(); should(room.lastRenewal).be.within(before, Date.now()); }); @@ -172,7 +172,7 @@ describe('KuzzleRoom methods', function () { it('should delay the request until after subscribing', function () { var cb = function () {}; room.subscribing = true; - should(room.renew({}, cb)).be.exactly(room); + room.renew({}, cb); should(emitted).be.false(); should(room.queue).match([{action: 'renew', args: [{}, cb]}]); }); @@ -203,7 +203,7 @@ describe('KuzzleRoom methods', function () { it('should register itself to Kuzzle and skip subscription if not connected', function (done) { kuzzle.state = 'foo'; - should(room.renew({}, function () {})).be.eql(room); + room.renew({}, function () {}); setTimeout(() => { should(dequeued).be.false(); should(emitted).be.false(); diff --git a/test/security/kuzzleProfile/methods.test.js b/test/security/kuzzleProfile/methods.test.js index fea133e11..ca868e919 100644 --- a/test/security/kuzzleProfile/methods.test.js +++ b/test/security/kuzzleProfile/methods.test.js @@ -6,13 +6,13 @@ var KuzzleProfile = require('../../../src/security/kuzzleProfile'), KuzzleRole = require('../../../src/security/kuzzleRole'); -describe('KuzzleRole methods', function () { +describe('KuzzleProfile methods', function () { var kuzzle, kuzzleProfile, result, expectedQuery, - error = false, + error = null, queryStub = function (args, query, options, cb) { should(args.controller).be.exactly(expectedQuery.controller); should(args.action).be.exactly(expectedQuery.action); @@ -48,7 +48,7 @@ describe('KuzzleRole methods', function () { beforeEach(function () { kuzzle = new Kuzzle('http://localhost:7512'); kuzzle.query = queryStub; - error = false; + error = null; result = { result: {_id: 'myProfile', _source: {policies : []}} }; kuzzleProfile = new KuzzleProfile(kuzzle.security, result.result._id, result.result._source); @@ -97,7 +97,7 @@ describe('KuzzleRole methods', function () { before(function () { kuzzle = new Kuzzle('http://localhost:7512'); kuzzle.query = queryStub; - error = false; + error = null; result = { result: {_id: 'myProfile', _index: '%kuzzle', _type: 'profiles'} }; kuzzleRole = new KuzzleRole(kuzzle.security, result.result._id, {indexes : {}}); @@ -256,7 +256,7 @@ describe('KuzzleRole methods', function () { before(function () { kuzzle = new Kuzzle('http://localhost:7512'); kuzzle.query = queryStub; - error = false; + error = null; result = { result: {_id: 'myProfile'} }; kuzzleProfile = new KuzzleProfile(kuzzle.security, 'myProfile', {some: 'content', roles: [{roleId:'role1'}]}); diff --git a/test/security/kuzzleRole/methods.test.js b/test/security/kuzzleRole/methods.test.js index 70d831647..1e56af283 100644 --- a/test/security/kuzzleRole/methods.test.js +++ b/test/security/kuzzleRole/methods.test.js @@ -11,7 +11,7 @@ describe('KuzzleRole methods', function () { kuzzleRole, result, expectedQuery, - error = false, + error = null, queryStub = function (args, query, options, cb) { should(args.controller).be.exactly(expectedQuery.controller); should(args.action).be.exactly(expectedQuery.action); @@ -47,7 +47,7 @@ describe('KuzzleRole methods', function () { before(function () { kuzzle = new Kuzzle('http://localhost:7512'); kuzzle.query = queryStub; - error = false; + error = null; result = { result: {_id: 'myRole', _source: {indexes : {}}} }; kuzzleRole = new KuzzleRole(kuzzle.security, result.result._id, result.result._source); @@ -87,7 +87,7 @@ describe('KuzzleRole methods', function () { before(function () { kuzzle = new Kuzzle('http://localhost:7512'); kuzzle.query = queryStub; - error = false; + error = null; result = { result: {_id: 'myRole', _index: '%kuzzle', _type: 'roles'} }; kuzzleRole = new KuzzleRole(kuzzle.security, result.result._id, {indexes : {}}); @@ -142,7 +142,7 @@ describe('KuzzleRole methods', function () { before(function () { kuzzle = new Kuzzle('http://localhost:7512'); kuzzle.query = queryStub; - error = false; + error = null; result = { result: {_id: 'myRole'} }; kuzzleRole = new KuzzleRole(kuzzle.security, result.result._id, result.result._source); diff --git a/test/security/kuzzleSecurity/profilesMethods.test.js b/test/security/kuzzleSecurity/profilesMethods.test.js index a820ad0d3..081725018 100644 --- a/test/security/kuzzleSecurity/profilesMethods.test.js +++ b/test/security/kuzzleSecurity/profilesMethods.test.js @@ -377,7 +377,7 @@ describe('KuzzleSecurity profiles methods', function () { }); }); - describe('#deleteRole', function () { + describe('#deleteProfile', function () { beforeEach(function () { kuzzle = new Kuzzle('foo', {defaultIndex: 'bar'}); kuzzle.query = queryStub; diff --git a/test/security/kuzzleUser/methods.test.js b/test/security/kuzzleUser/methods.test.js index 9ab354f9f..14975729e 100644 --- a/test/security/kuzzleUser/methods.test.js +++ b/test/security/kuzzleUser/methods.test.js @@ -13,7 +13,7 @@ describe('KuzzleUser methods', function () { kuzzleUser, result, expectedQuery, - error = false, + error = null, queryStub = function (args, query, options, cb) { should(args.controller).be.exactly(expectedQuery.controller); should(args.action).be.exactly(expectedQuery.action); @@ -36,20 +36,14 @@ describe('KuzzleUser methods', function () { should(query._id).be.exactly(expectedQuery._id); } - if (cb) { - if (error) { - return cb(error); - } - - cb(error, result); - } + cb && cb(error, result); }; describe('#save', function () { beforeEach(function () { kuzzle = new Kuzzle('http://localhost:7512'); kuzzle.query = queryStub; - error = false; + error = null; result = { result: {_id: 'myUser', _source: {some: 'content', profileIds: ['myProfile']}} }; kuzzleUser = new KuzzleUser(kuzzle.security, result.result._id, result.result._source); @@ -97,7 +91,7 @@ describe('KuzzleUser methods', function () { before(function () { kuzzle = new Kuzzle('http://localhost:7512'); kuzzle.query = queryStub; - error = false; + error = null; result = { result: {_id: 'myUser', _index: '%kuzzle', _type: 'users'} }; kuzzleRole = new KuzzleRole(kuzzle.security, result.result._id, {indexes : {}}); @@ -251,7 +245,7 @@ describe('KuzzleUser methods', function () { before(function () { kuzzle = new Kuzzle('http://localhost:7512'); kuzzle.query = queryStub; - error = false; + error = null; result = { result: {_id: 'user'} }; kuzzleUser = new KuzzleUser(kuzzle.security, 'user', {some: 'content', profileIds: ['profile']}); From c3bff8ac852bff0132d74332010eef0e72790dcb Mon Sep 17 00:00:00 2001 From: scottinet Date: Fri, 9 Sep 2016 16:03:27 +0200 Subject: [PATCH 2/4] added options handling in Kuzzle.getMyRights --- src/kuzzle.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/kuzzle.js b/src/kuzzle.js index 3c9699e77..6dd5e10f5 100644 --- a/src/kuzzle.js +++ b/src/kuzzle.js @@ -593,7 +593,7 @@ Kuzzle.prototype.getMyRights = function (options, cb) { self.callbackRequired('Kuzzle.getMyRights', cb); - self.query({controller: 'auth', action:'getMyRights'}, {}, null, function (err, res) { + self.query({controller: 'auth', action:'getMyRights'}, {}, options, function (err, res) { if (err) { return cb(err); } From 701a963dc33169c1dfd7f782e51f99c6479a9520 Mon Sep 17 00:00:00 2001 From: scottinet Date: Fri, 9 Sep 2016 16:05:50 +0200 Subject: [PATCH 3/4] fixed webpack build --- src/kuzzleDataCollection.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/kuzzleDataCollection.js b/src/kuzzleDataCollection.js index 4c0d0b9a7..39c970775 100644 --- a/src/kuzzleDataCollection.js +++ b/src/kuzzleDataCollection.js @@ -272,8 +272,12 @@ KuzzleDataCollection.prototype.deleteDocument = function (arg, options, cb) { data = this.kuzzle.addHeaders(data, this.headers); this.kuzzle.query(this.buildQueryArgs('write', action), data, options, cb && function (err, res) { - var result = action === 'delete' ? [res.result._id] : res.result.ids; - cb(err, err ? undefined : result); + if (err) { + cb(err); + } + else { + cb(null, (action === 'delete' ? [res.result._id] : res.result.ids)); + } }); return this; From 25eeab5780119f93effe61378f1d1e5c83368044 Mon Sep 17 00:00:00 2001 From: scottinet Date: Fri, 9 Sep 2016 16:44:52 +0200 Subject: [PATCH 4/4] updated jsdoc --- dist/kuzzle.js | 2 +- dist/kuzzle.js.map | 2 +- src/kuzzle.js | 13 +++---------- src/kuzzleDataCollection.js | 7 +------ src/security/kuzzleProfile.js | 2 +- src/security/kuzzleRole.js | 1 + src/security/kuzzleSecurity.js | 6 ++++++ src/security/kuzzleSecurityDocument.js | 3 ++- src/security/kuzzleUser.js | 2 +- 9 files changed, 17 insertions(+), 21 deletions(-) diff --git a/dist/kuzzle.js b/dist/kuzzle.js index e719c5c4e..06f146f77 100644 --- a/dist/kuzzle.js +++ b/dist/kuzzle.js @@ -1,3 +1,3 @@ -!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var r in n)("object"==typeof exports?exports:e)[r]=n[r]}}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return e[r].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){function r(){var e=this,t=Date.now(),n=-1;e.queueTTL>0&&(e.offlineQueue.forEach(function(r,i){r.ts0&&e.offlineQueue.length>e.queueMaxSize&&e.offlineQueue.splice(0,e.offlineQueue.length-e.queueMaxSize).forEach(function(t){e.emitEvent("offlineQueuePop",t.query)})}function i(e){var t=Date.now();Object.keys(e).forEach(function(n){e[n]0?(o.call(t,t.offlineQueue[0].query,t.offlineQueue[0].cb),t.emitEvent("offlineQueuePop",t.offlineQueue.shift()),setTimeout(function(){r()},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!n.hasOwnProperty(e.query.requestId)&&(n[e.query.requestId]=!0)})}r()}function s(){var e=this;Object.keys(e.subscriptions).forEach(function(t){Object.keys(e.subscriptions[t]).forEach(function(n){var r=e.subscriptions[t][n];r.renew(r.callback)})})}var l=n(3),c=n(4),a=n(14),f=n(7),d=n(2),h=n(9);e.exports=Kuzzle=function(e,t,n){var r=this;if(!(this instanceof Kuzzle))return new Kuzzle(e,t,n);if(n||"function"!=typeof t||(n=t,t=null),!e||""===e)throw new Error("host argument missing");return Object.defineProperties(this,{collections:{value:{},writable:!0},connectCB:{value:n},eventListeners:{value:{connected:{lastEmitted:null,listeners:[]},error:{lastEmitted:null,listeners:[]},disconnected:{lastEmitted:null,listeners:[]},reconnected:{lastEmitted:null,listeners:[]},jwtTokenExpired:{lastEmitted:null,listeners:[]},loginAttempt:{lastEmitted:null,listeners:[]},offlineQueuePush:{listeners:[]},offlineQueuePop:{listeners:[]}}},eventTimeout:{value:200},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,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,enumerable:!0},host:{value:e,enumerable:!0},wsPort:{value:t&&"number"==typeof t.wsPort?t.wsPort:7513,enumerable:!0},ioPort:{value:t&&"number"==typeof t.ioPort?t.ioPort:7512,enumerable:!0},sslConnection:{value:!(!t||"boolean"!=typeof t.sslConnection)&&t.sslConnection,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},metadata:{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:null,enumerable:!0,writable:!0}}),t&&(Object.keys(t).forEach(function(e){r.hasOwnProperty(e)&&Object.getOwnPropertyDescriptor(r,e).writable&&(r[e]=t[e])}),"auto"===t.offlineMode&&this.autoReconnect&&(this.autoQueue=this.autoReplay=this.autoResubscribe=!0)),Object.defineProperty(this,"isValid",{value:function(){if("disconnected"===r.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(n){e[n]||(e[n]=t[n])}),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 a(this),enumerable:!0}),Object.defineProperty(this,"emitEvent",{value:function(e){var t=Date.now(),n=Array.prototype.slice.call(arguments,1),r=this.eventListeners[e];return!(r.lastEmitted&&r.lastEmitted>=t-this.eventTimeout)&&(r.listeners.forEach(function(e){process.nextTick(function(){e.fn.apply(void 0,n)})}),void(void 0!==r.lastEmitted&&(r.lastEmitted=t)))}}),Object.defineProperty(this,"memoryStorage",{value:new f(this),enumerable:!0}),t&&t.connect&&"auto"!==t.connect?this.state="ready":this.connect(),i(this.requestHistory),this.bluebird?this.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["getAllStatistics","getServerInfo","getStatistics","listCollections","listIndexes","login","logout","now","query","checkToken","whoAmI","updateSelf","getMyRights","refreshIndex","getAutoRefresh","setAutoRefresh"];return r&&i.indexOf(e)!==-1}}):void 0},Kuzzle.prototype.connect=function(){var e=this;return e.network||(e.network=h(e.host,e.wsPort,e.ioPort,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",s.call(e),u.call(e),e.emitEvent("connected"),e.connectCB&&e.connectCB(null,e)}),e.network.onConnectError(function(t){var n=new Error('Unable to connect to kuzzle server at "'+e.host+'"');n.internal=t,e.state="error",e.emitEvent("error",n),e.connectCB&&e.connectCB(n)}),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&&s.call(e),e.autoReplay&&(r.call(e),u.call(e)),e.emitEvent("reconnected")};e.state="connected",e.jwtToken?e.checkToken(e.jwtToken,function(n,r){!n&&r.valid||(e.jwtToken=void 0,e.emitEvent("jwtTokenExpired")),t()}):t()}),this)},Kuzzle.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 s.call(this),this.emitEvent("loginAttempt",{success:!0}),this},Kuzzle.prototype.getJwtToken=function(){return this.jwtToken},Kuzzle.prototype.login=function(e){var t,n=this,r={strategy:e},i=null;arguments[1]&&("object"==typeof arguments[1]?t=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]),"object"==typeof t&&Object.keys(t).forEach(function(e){r[e]=t[e]}),this.query({controller:"auth",action:"login"},{body:r},{queuable:!1},function(e,t){e?(i&&i(e),n.emitEvent("loginAttempt",{success:!1,error:e.message})):(t.result.jwt&&n.setJwtToken(t.result.jwt),i&&i(null,t.result))})},Kuzzle.prototype.logout=function(e){var t=this,n={action:"logout",controller:"auth",requestId:l.v4(),body:{}};return this.query({controller:"auth",action:"logout"},n,{queuable:!1},"function"!=typeof e?null:function(n){null===n?(t.jwtToken=void 0,e(null,t)):e(n)}),t},Kuzzle.prototype.checkToken=function(e,t){var n={body:{token:e}};this.callbackRequired("Kuzzle.checkToken",t),this.query({controller:"auth",action:"checkToken"},n,{queuable:!1},function(e,n){return e?t(e):void t(null,n.result)})},Kuzzle.prototype.whoAmI=function(e){var t=this;t.callbackRequired("Kuzzle.whoAmI",e),t.query({controller:"auth",action:"getCurrentUser"},{},{},function(n,r){return n?e(n):void e(null,new d(t.security,r.result._id,r.result._source))})},Kuzzle.prototype.getMyRights=function(e,t){var n=this;t||"function"!=typeof e||(t=e,e=null),n.callbackRequired("Kuzzle.getMyRights",t),n.query({controller:"auth",action:"getMyRights"},{},null,function(e,n){return e?t(e):void t(null,n.result.hits)})},Kuzzle.prototype.updateSelf=function(e,t,n){var r=this,i={},o={controller:"auth",action:"updateSelf"};return n||"function"!=typeof t||(n=t,t=null),i.body=e,r.query(o,i,t,n&&function(e,t){n(e,e?void 0:t.result)}),this},Kuzzle.prototype.addListener=function(e,t){var n,r=Object.keys(this.eventListeners),i=typeof t;if(this.isValid(),r.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+r.toString());if("function"!==i)throw new Error("Invalid listener type: expected a function, got a "+i);return n=l.v4(),this.eventListeners[e].listeners.push({id:n,fn:t}),n},Kuzzle.prototype.getAllStatistics=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.getAllStatistics",t),this.query({controller:"admin",action:"getAllStats"},{},e,function(e,n){return e?t(e):void t(null,n.result.hits)})},Kuzzle.prototype.getStatistics=function(e,t,n){var r,i;n||(1===arguments.length?(n=arguments[0],t=null,e=null):(n=arguments[1],"object"==typeof arguments[0]?(t=arguments[0],e=null):(e=arguments[0],t=null))),r=function(t,r){return t?n(t):void n(null,e?r.result.hits:[r.result])},this.callbackRequired("Kuzzle.getStatistics",n),i=e?{body:{startTime:e}}:{},this.query({controller:"admin",action:e?"getStats":"getLastStats"},i,t,r)},Kuzzle.prototype.dataCollectionFactory=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 c(this,t,e)),this.collections[t][e]},Kuzzle.prototype.flushQueue=function(){return this.offlineQueue=[],this},Kuzzle.prototype.listCollections=function(){var e,t,n,r="all",i=Array.prototype.slice.call(arguments);if(i.forEach(function(r){switch(typeof r){case"string":e=r;break;case"object":t=r;break;case"function":n=r}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.listCollections: index required");e=this.defaultIndex}this.callbackRequired("Kuzzle.listCollections",n),t&&t.type&&(r=t.type),this.query({index:e,controller:"read",action:"listCollections"},{body:{type:r}},t,function(e,t){return e?n(e):void n(null,t.result.collections)})},Kuzzle.prototype.listIndexes=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.listIndexes",t),this.query({controller:"read",action:"listIndexes"},{},e,function(e,n){t(e,e?void 0:n.result.indexes)})},Kuzzle.prototype.disconnect=function(){var e;this.logout(),this.state="disconnected",this.network.close();for(e in this.collections)this.collections.hasOwnProperty(e)&&delete this.collections[e]},Kuzzle.prototype.getServerInfo=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.getServerInfo",t),this.query({controller:"read",action:"serverInfo"},{},e,function(e,n){return e?t(e):void t(null,n.result.serverInfo)})},Kuzzle.prototype.refreshIndex=function(){var e,t,n;if(Array.prototype.slice.call(arguments).forEach(function(r){switch(typeof r){case"string":e=r;break;case"object":t=r;break;case"function":n=r}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.refreshIndex: index required");e=this.defaultIndex}return this.query({index:e,controller:"admin",action:"refreshIndex"},{},t,n),this},Kuzzle.prototype.getAutoRefresh=function(){var e,t,n;if(Array.prototype.slice.call(arguments).forEach(function(r){switch(typeof r){case"string":e=r;break;case"object":t=r;break;case"function":n=r}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.getAutoRefresh: index required");e=this.defaultIndex}this.callbackRequired("Kuzzle.getAutoRefresh",n),this.query({index:e,controller:"admin",action:"getAutoRefresh"},{},t,n)},Kuzzle.prototype.setAutoRefresh=function(){var e,t,n,r;if(Array.prototype.slice.call(arguments).forEach(function(i){switch(typeof i){case"string":e=i;break;case"boolean":t=i;break;case"object":n=i;break;case"function":r=i}}),!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:"admin",action:"setAutoRefresh"},{body:{autoRefresh:t}},n,r),this},Kuzzle.prototype.now=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.now",t),this.query({controller:"read",action:"now"},{},e,function(e,n){t(e,n&&n.result.now)})},Kuzzle.prototype.query=function(e,t,n,i){var u,s={action:e.action,controller:e.controller,metadata:this.metadata},c=this;if(this.isValid(),i||"function"!=typeof n||(i=n,n=null),n&&(n.metadata&&Object.keys(n.metadata).forEach(function(e){s.metadata[e]=n.metadata[e]}),n.queuable===!1&&"offline"===c.state))return c;if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("Invalid query parameter: "+t);t.metadata&&Object.keys(t.metadata).forEach(function(e){s.metadata[e]=t.metadata[e]});for(u in t)"metadata"!==u&&t.hasOwnProperty(u)&&(s[u]=t[u]);return s=c.addHeaders(s,this.headers),void 0===c.jwtToken||"auth"===s.controller&&"checkToken"===s.action||(s.headers=s.headers||{},s.headers.authorization="Bearer "+c.jwtToken),e.collection&&(s.collection=e.collection),e.index&&(s.index=e.index),s.requestId||(s.requestId=l.v4()),"connected"===c.state||n&&n.queuable===!1?"connected"===c.state?o.call(this,s,i):i&&i(new Error("Unable to execute request: not connected to a Kuzzle server.\nDiscarded request: "+JSON.stringify(s))):(c.queuing||["initializing","connecting"].indexOf(c.state)!==-1)&&(r.call(this,s,i),c.queueFilter&&!c.queueFilter(s)||(c.offlineQueue.push({ts:Date.now(),query:s,cb:i}),c.emitEvent("offlineQueuePush",{query:s,cb:i}))),c},Kuzzle.prototype.removeAllListeners=function(e){var t=Object.keys(this.eventListeners),n=this;if(e){if(t.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+t.toString());this.eventListeners[e].listeners=[]}else t.forEach(function(e){n.eventListeners[e].listeners=[]});return this},Kuzzle.prototype.removeListener=function(e,t){var n=Object.keys(this.eventListeners),r=this;if(n.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+n.toString());return this.eventListeners[e].listeners.forEach(function(n,i){n.id===t&&r.eventListeners[e].listeners.splice(i,1)}),this},Kuzzle.prototype.replayQueue=function(){return"offline"===this.state||this.autoReplay||(r.call(this),u.call(this)),this},Kuzzle.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},Kuzzle.prototype.setHeaders=function(e,t){var n=this;if("object"!=typeof e||Array.isArray(e))throw new Error("Expected a content object, received a "+typeof e);return t?n.headers=e:Object.keys(e).forEach(function(t){n.headers[t]=e[t]}),n},Kuzzle.prototype.startQueuing=function(){return"offline"!==this.state||this.autoQueue||(this.queuing=!0),this},Kuzzle.prototype.stopQueuing=function(){return"offline"!==this.state||this.autoQueue||(this.queuing=!1),this}},function(e,t){function n(e,t,n){if(!t)throw new Error("A security document must have an id");if(Object.defineProperties(this,{kuzzle:{value:e.kuzzle},kuzzleSecurity:{value:e},id:{value:t,enumerable:!0},content:{value:{},writable:!0,enumerable:!0}}),n&&this.setContent(n,!0),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["delete","update"];return r&&i.indexOf(e)!==-1}})}n.prototype.setContent=function(e){return this.content=e,this},n.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e},n.prototype["delete"]=function(e,t){var n=this;e&&void 0===t&&"function"==typeof e&&(t=e,e=null),n.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.deleteActionName),{_id:this.id},e,function(e,n){return e?!!t&&t(e):void(t&&t(null,n.result._id))})},n.prototype.update=function(e,t,n){var r={},i=this;if("object"!=typeof e)throw new Error('Parameter "content" must be a object');return t&&void 0===n&&"function"==typeof t&&(n=t,t=null),r._id=i.id,r.body=e,i.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.updateActionName),r,t,function(e,t){return e?!!n&&n(e):(i.setContent(t.result._source),void(n&&n(null,i)))}),this},e.exports=n},function(e,t,n){function r(e,t,n){if(i.call(this,e,t,n),Object.defineProperties(this,{deleteActionName:{value:"deleteUser"},updateActionName:{value:"updateUser"}}),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["save"];return r&&i.indexOf(e)!==-1}})}var i=n(1);r.prototype=Object.create(i.prototype,{constructor:{value:r}}),r.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},r.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},r.prototype.save=function(e,t){var n=this.serialize(),r=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createOrReplaceUser"),n,e,t&&function(e){t(e,e?void 0:r)}),r},r.prototype.serialize=function(){return{_id:this.id,body:this.content}},r.prototype.getProfiles=function(){return this.content.profileIds},e.exports=r},function(e,t){!function(t){"use strict";function n(){var e=t.crypto||t.msCrypto;if(!l&&e&&e.getRandomValues)try{var n=new Uint8Array(16);f=l=function(){return e.getRandomValues(n),n},l()}catch(r){}if(!l){var i=new Array(16);c=l=function(){for(var e,t=0;t<16;t++)0===(3&t)&&(e=4294967296*Math.random()),i[t]=e>>>((3&t)<<3)&255;return i},"undefined"!=typeof console&&console.warn&&console.warn("[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()")}}function r(){if("function"==typeof require)try{var e=require("crypto").randomBytes;a=l=e&&function(){return e(16)},l()}catch(t){}}function i(e,t,n){var r=t&&n||0,i=0;for(t=t||[],e.toLowerCase().replace(/[0-9a-f]{2}/g,function(e){i<16&&(t[r+i++]=y[e])});i<16;)t[r+i++]=0;return t}function o(e,t){var n=t||0,r=p;return r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]}function u(e,t,n){var r=t&&n||0,i=t||[];e=e||{};var u=null!=e.clockseq?e.clockseq:m,s=null!=e.msecs?e.msecs:(new Date).getTime(),l=null!=e.nsecs?e.nsecs:k+1,c=s-w+(l-k)/1e4;if(c<0&&null==e.clockseq&&(u=u+1&16383),(c<0||s>w)&&null==e.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");w=s,k=l,m=u,s+=122192928e5;var a=(1e4*(268435455&s)+l)%4294967296;i[r++]=a>>>24&255,i[r++]=a>>>16&255,i[r++]=a>>>8&255,i[r++]=255&a;var f=s/4294967296*1e4&268435455;i[r++]=f>>>8&255,i[r++]=255&f,i[r++]=f>>>24&15|16,i[r++]=f>>>16&255,i[r++]=u>>>8|128,i[r++]=255&u;for(var d=e.node||v,h=0;h<6;h++)i[r+h]=d[h];return t?t:o(i)}function s(e,t,n){var r=t&&n||0;"string"==typeof e&&(t="binary"===e?new h(16):null,e=null),e=e||{};var i=e.random||(e.rng||l)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t)for(var u=0;u<16;u++)t[r+u]=i[u];return t||o(i)}var l,c,a,f,d;t?n():r();for(var h="function"==typeof Buffer?Buffer:Array,p=[],y={},b=0;b<256;b++)p[b]=(b+256).toString(16).substr(1),y[p[b]]=b;var z=l(),v=[1|z[0],z[1],z[2],z[3],z[4],z[5]],m=16383&(z[6]<<8|z[7]),w=0,k=0,g=s;g.v1=u,g.v4=s,g.parse=i,g.unparse=o,g.BufferClass=h,g._rng=l,g._mathRNG=c,g._nodeRNG=a,g._whatwgRNG=f,"undefined"!=typeof e&&e.exports?e.exports=g:"function"==typeof define&&define.amd?define(function(){return g}):(d=t.uuid,g.noConflict=function(){return t.uuid=d,g},t.uuid=g)}("undefined"!=typeof window?window:null)},function(e,t,n){function r(e,t,n){if(!t||!n)throw new Error("The KuzzleDataCollection object constructor needs an index and a collection arguments");return Object.defineProperties(this,{collection:{value:n,enumerable:!0},index:{value:t,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,n,r){var i=["publishMessage","setHeaders","subscribe"];return r&&i.indexOf(e)===-1}}):this}var i=n(6),o=n(5),u=n(8);r.prototype.advancedSearch=function(e,t,n){var r,o=this;n||"function"!=typeof t||(n=t,t=null),o.kuzzle.callbackRequired("KuzzleDataCollection.advancedSearch",n),r=o.kuzzle.addHeaders({body:e},this.headers),o.kuzzle.query(this.buildQueryArgs("read","search"),r,t,function(e,t){var r=[];return e?n(e):(t.result.hits.forEach(function(e){var t=new i(o,e._id,e._source);t.version=e._version,r.push(t)}),void n(null,{total:t.result.total,documents:r}))})},r.prototype.count=function(e,t,n){var r;n||"function"!=typeof t||(n=t,t=null),this.kuzzle.callbackRequired("KuzzleDataCollection.count",n),r=this.kuzzle.addHeaders({body:e},this.headers),this.kuzzle.query(this.buildQueryArgs("read","count"),r,t,function(e,t){n(e,t&&t.result.count)})},r.prototype.create=function(e,t){var n={};return t||"function"!=typeof e||(t=e,e=null),n=this.kuzzle.addHeaders(n,this.headers),this.kuzzle.query(this.buildQueryArgs("write","createCollection"),n,e,t),this},r.prototype.createDocument=function(e,t,n,r){var o=this,u={},s="create";return e&&"string"!=typeof e&&(r=n,n=t,t=e,e=null),r||"function"!=typeof n||(r=n,n=null),t instanceof i?u=t.serialize():u.body=t,n&&(s=n.updateIfExist?"createOrReplace":"create"),e&&(u._id=e),u=o.kuzzle.addHeaders(u,o.headers),o.kuzzle.query(this.buildQueryArgs("write",s),u,n,r&&function(e,t){var n;return e?r(e):(n=new i(o,t.result._id,t.result._source),n.version=t.result._version,void r(null,n))}),this},r.prototype.deleteDocument=function(e,t,n){var r,i={};return"string"==typeof e?(i._id=e,r="delete"):(i.body=e,r="deleteByQuery"),n||"function"!=typeof t||(n=t,t=null),i=this.kuzzle.addHeaders(i,this.headers),this.kuzzle.query(this.buildQueryArgs("write",r),i,t,n&&function(e,t){var i="delete"===r?[t.result._id]:t.result.ids;n(e,e?void 0:i)}),this},r.prototype.fetchDocument=function(e,t,n){var r={_id:e},o=this;n||"function"!=typeof t||(n=t,t=null),o.kuzzle.callbackRequired("KuzzleDataCollection.fetch",n),r=o.kuzzle.addHeaders(r,this.headers),o.kuzzle.query(this.buildQueryArgs("read","get"),r,t,function(e,t){var r;return e?n(e):(r=new i(o,t.result._id,t.result._source),r.version=t.result._version,void n(null,r))})},r.prototype.fetchAllDocuments=function(e,t){var n={};t||"function"!=typeof e||(t=e,e=null),e&&(e.from&&(n.from=e.from),e.size&&(n.size=e.size)),this.kuzzle.callbackRequired("KuzzleDataCollection.fetchAll",t),this.advancedSearch(n,e,t)},r.prototype.getMapping=function(e,t){var n;t||"function"!=typeof e||(t=e,e=null),this.kuzzle.callbackRequired("KuzzleDataCollection.getMapping",t),n=new o(this),n.refresh(e,t)},r.prototype.publishMessage=function(e,t,n){var r={};return e instanceof i?r=e.serialize():r.body=e,r=this.kuzzle.addHeaders(r,this.headers),this.kuzzle.query(this.buildQueryArgs("write","publish"),r,t,n),this},r.prototype.replaceDocument=function(e,t,n,r){var o=this,u={_id:e,body:t};return r||"function"!=typeof n||(r=n,n=null),u=o.kuzzle.addHeaders(u,this.headers),o.kuzzle.query(this.buildQueryArgs("write","createOrReplace"),u,n,r&&function(e,t){var n;return e?r(e):(n=new i(o,t.result._id,t.result._source),n.version=t.result._version,void r(null,n))}),this},r.prototype.subscribe=function(e,t,n){var r;return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.callbackRequired("KuzzleDataCollection.subscribe",n),r=new u(this,t),r.renew(e,n),r},r.prototype.truncate=function(e,t){var n={};return t||"function"!=typeof e||(t=e,e=null),n=this.kuzzle.addHeaders(n,this.headers),this.kuzzle.query(this.buildQueryArgs("admin","truncateCollection"),n,e,t),this},r.prototype.updateDocument=function(e,t,n,r){var o={_id:e,body:t},u=this;return r||"function"!=typeof n||(r=n,n=null),o=u.kuzzle.addHeaders(o,this.headers),u.kuzzle.query(this.buildQueryArgs("write","update"),o,n,r&&function(e,t){return e?r(e):void new i(u,t.result._id).refresh(r)}),u},r.prototype.documentFactory=function(e,t){return new i(this,e,t)},r.prototype.roomFactory=function(e){return new u(this,e)},r.prototype.dataMappingFactory=function(e){return new o(this,e)},r.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=r},function(e,t){function n(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,n,r){var i=["set","setHeaders"];return r&&i.indexOf(e)===-1}}):this}n.prototype.apply=function(e,t){var n=this,r=this.kuzzle.addHeaders({body:{properties:this.mapping}},this.headers);return t||"function"!=typeof e||(t=e,e=null),n.kuzzle.query(this.collection.buildQueryArgs("admin","updateMapping"),r,e,function(r){return r?t&&t(r):void n.refresh(e,t)}),this},n.prototype.refresh=function(e,t){var n=this,r=this.kuzzle.addHeaders({},this.headers);return t||"function"!=typeof e||(t=e,e=null),this.kuzzle.query(this.collection.buildQueryArgs("admin","getMapping"),r,e,function(e,r){return e?!!t&&t(e):r.result[n.collection.index]?r.result[n.collection.index].mappings[n.collection.collection]?(n.mapping=r.result[n.collection.index].mappings[n.collection.collection].properties,void 0===n.mapping&&(n.mapping={}),void(t&&t(null,n))):t&&t(new Error("No mapping found for collection "+n.collection.collection)):t&&t(new Error("No mapping found for index "+n.collection.index))}),this},n.prototype.set=function(e,t){return this.mapping[e]=t,this},n.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=n},function(e,t){function n(e,t,n){return Object.defineProperties(this,{collection:{value:e.collection,enumerable:!0},dataCollection:{value:e,enumerable:!0},kuzzle:{value:e.kuzzle,enumerable:!0},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}}),!n&&t&&"object"==typeof t&&(n=t,t=null),n&&(n._version&&(this.version=n._version,delete n._version),this.setContent(n,!0)),t&&Object.defineProperty(this,"id",{value:t,enumerable:!0}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["delete","refresh","save"];return r&&i.indexOf(e)!==-1}}):this}n.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e._version=this.version,e=this.kuzzle.addHeaders(e,this.headers)},n.prototype.toString=function(){return JSON.stringify(this.serialize())},n.prototype["delete"]=function(e,t){var n=this;if(t||"function"!=typeof e||(t=e,e=null),!n.id)throw new Error("KuzzleDocument.delete: cannot delete a document without a document ID");this.kuzzle.query(this.dataCollection.buildQueryArgs("write","delete"),this.serialize(),e,t&&function(e){t(e,e?void 0:n.id)})},n.prototype.refresh=function(e,t){var r=this;if(t||"function"!=typeof e||(t=e,e=null),!r.id)throw new Error("KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided");this.kuzzle.callbackRequired("KuzzleDocument.refresh",t),r.kuzzle.query(r.dataCollection.buildQueryArgs("read","get"),{_id:r.id},e,function(e,i){var o;return e?t(e):(o=new n(r.dataCollection,r.id,i.result._source),o.version=i.result._version,void t(null,o))})},n.prototype.save=function(e,t){var n=this.serialize(),r=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r.kuzzle.query(this.dataCollection.buildQueryArgs("write","createOrReplace"),n,e,function(e,n){return e?t&&t(e):(r.id=n.result._id,r.version=n.result._version,void(t&&t(null,r)))}),r},n.prototype.publish=function(e){var t=this.serialize();return this.kuzzle.query(this.dataCollection.buildQueryArgs("write","publish"),t,e),this},n.prototype.setContent=function(e,t){var n=this;return t?this.content=e:Object.keys(e).forEach(function(t){n.content[t]=e[t]}),this},n.prototype.subscribe=function(e,t){var n;if(e&&!t&&"function"==typeof e&&(t=e,e=null),this.kuzzle.callbackRequired("KuzzleDocument.subscribe",t),!this.id)throw new Error("KuzzleDocument.subscribe: cannot subscribe to a document if no ID has been provided");return n={ids:{values:[this.id]}},this.dataCollection.subscribe(n,e,t)},n.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=n},function(e,t){function n(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,n,r){var i=["setHeaders"];return r&&i.indexOf(e)===-1}}):this}!function(){var e=["id","value"],t=["id","keys"],r={append:e,bgrewriteaof:[],bgsave:[],bitcount:["id","start","end"],bitop:["operation","destkey",t],bitpos:["id","bit",{__opts__:["start","end"]}],blpop:[t,"timeout"],brpoplpush:["source","destination"],dbsize:[],decrby:e,del:[t],discard:[],exec:[],exists:[t],expire:["id","seconds"],expireat:["id","timestamp"],flushdb:[],getbit:["id","offset"],getrange:["id","start","end"],hdel:["id",["field","fields"]],hexists:["id","field"],hincrby:["id","field","value"],hmset:["id","values"],hset:["id","field","value"],info:["section"],keys:["pattern"],lastsave:[],lindex:["id","idx"],linsert:["id","position","pivot","value"],lpush:["id",["value","values"]],lrange:["id","start","stop"],lrem:["id","count","value"],lset:["id","idx","value"],ltrim:["id","start","stop"],mset:["values"],multi:[],object:["subcommand","args"],pexpire:["id","milliseconds"],pexpireat:["id","timestamp"],pfadd:["id",["element","elements"]],pfmerge:["destkey",["sourcekey","sourcekeys"]],ping:[],psetex:["id","milliseconds","value"], +!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var r in n)("object"==typeof exports?exports:e)[r]=n[r]}}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return e[r].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){function r(){var e=this,t=Date.now(),n=-1;e.queueTTL>0&&(e.offlineQueue.forEach(function(r,i){r.ts0&&e.offlineQueue.length>e.queueMaxSize&&e.offlineQueue.splice(0,e.offlineQueue.length-e.queueMaxSize).forEach(function(t){e.emitEvent("offlineQueuePop",t.query)})}function i(e){var t=Date.now();Object.keys(e).forEach(function(n){e[n]0?(o.call(t,t.offlineQueue[0].query,t.offlineQueue[0].cb),t.emitEvent("offlineQueuePop",t.offlineQueue.shift()),setTimeout(function(){r()},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!n.hasOwnProperty(e.query.requestId)&&(n[e.query.requestId]=!0)})}r()}function s(){var e=this;Object.keys(e.subscriptions).forEach(function(t){Object.keys(e.subscriptions[t]).forEach(function(n){var r=e.subscriptions[t][n];r.renew(r.callback)})})}var l=n(3),c=n(4),a=n(14),f=n(7),d=n(2),h=n(9);e.exports=Kuzzle=function(e,t,n){var r=this;if(!(this instanceof Kuzzle))return new Kuzzle(e,t,n);if(n||"function"!=typeof t||(n=t,t=null),!e||""===e)throw new Error("host argument missing");return Object.defineProperties(this,{collections:{value:{},writable:!0},connectCB:{value:n},eventListeners:{value:{connected:{lastEmitted:null,listeners:[]},error:{lastEmitted:null,listeners:[]},disconnected:{lastEmitted:null,listeners:[]},reconnected:{lastEmitted:null,listeners:[]},jwtTokenExpired:{lastEmitted:null,listeners:[]},loginAttempt:{lastEmitted:null,listeners:[]},offlineQueuePush:{listeners:[]},offlineQueuePop:{listeners:[]}}},eventTimeout:{value:200},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,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,enumerable:!0},host:{value:e,enumerable:!0},wsPort:{value:t&&"number"==typeof t.wsPort?t.wsPort:7513,enumerable:!0},ioPort:{value:t&&"number"==typeof t.ioPort?t.ioPort:7512,enumerable:!0},sslConnection:{value:!(!t||"boolean"!=typeof t.sslConnection)&&t.sslConnection,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},metadata:{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:null,enumerable:!0,writable:!0}}),t&&(Object.keys(t).forEach(function(e){r.hasOwnProperty(e)&&Object.getOwnPropertyDescriptor(r,e).writable&&(r[e]=t[e])}),"auto"===t.offlineMode&&this.autoReconnect&&(this.autoQueue=this.autoReplay=this.autoResubscribe=!0)),Object.defineProperty(this,"isValid",{value:function(){if("disconnected"===r.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(n){e[n]||(e[n]=t[n])}),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 a(this),enumerable:!0}),Object.defineProperty(this,"emitEvent",{value:function(e){var t=Date.now(),n=Array.prototype.slice.call(arguments,1),r=this.eventListeners[e];return!(r.lastEmitted&&r.lastEmitted>=t-this.eventTimeout)&&(r.listeners.forEach(function(e){process.nextTick(function(){e.fn.apply(void 0,n)})}),void(void 0!==r.lastEmitted&&(r.lastEmitted=t)))}}),Object.defineProperty(this,"memoryStorage",{value:new f(this),enumerable:!0}),t&&t.connect&&"auto"!==t.connect?this.state="ready":this.connect(),i(this.requestHistory),this.bluebird?this.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["getAllStatistics","getServerInfo","getStatistics","listCollections","listIndexes","login","logout","now","query","checkToken","whoAmI","updateSelf","getMyRights","refreshIndex","getAutoRefresh","setAutoRefresh"];return r&&i.indexOf(e)!==-1}}):void 0},Kuzzle.prototype.connect=function(){var e=this;return e.network||(e.network=h(e.host,e.wsPort,e.ioPort,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",s.call(e),u.call(e),e.emitEvent("connected"),e.connectCB&&e.connectCB(null,e)}),e.network.onConnectError(function(t){var n=new Error('Unable to connect to kuzzle server at "'+e.host+'"');n.internal=t,e.state="error",e.emitEvent("error",n),e.connectCB&&e.connectCB(n)}),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&&s.call(e),e.autoReplay&&(r.call(e),u.call(e)),e.emitEvent("reconnected")};e.state="connected",e.jwtToken?e.checkToken(e.jwtToken,function(n,r){!n&&r.valid||(e.jwtToken=void 0,e.emitEvent("jwtTokenExpired")),t()}):t()}),this)},Kuzzle.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 s.call(this),this.emitEvent("loginAttempt",{success:!0}),this},Kuzzle.prototype.getJwtToken=function(){return this.jwtToken},Kuzzle.prototype.login=function(e){var t,n=this,r={strategy:e},i=null;arguments[1]&&("object"==typeof arguments[1]?t=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]),"object"==typeof t&&Object.keys(t).forEach(function(e){r[e]=t[e]}),this.query({controller:"auth",action:"login"},{body:r},{queuable:!1},function(e,t){e?(i&&i(e),n.emitEvent("loginAttempt",{success:!1,error:e.message})):(t.result.jwt&&n.setJwtToken(t.result.jwt),i&&i(null,t.result))})},Kuzzle.prototype.logout=function(e){var t=this,n={action:"logout",controller:"auth",requestId:l.v4(),body:{}};return this.query({controller:"auth",action:"logout"},n,{queuable:!1},"function"!=typeof e?null:function(n){null===n?(t.jwtToken=void 0,e(null,t)):e(n)}),t},Kuzzle.prototype.checkToken=function(e,t){var n={body:{token:e}};this.callbackRequired("Kuzzle.checkToken",t),this.query({controller:"auth",action:"checkToken"},n,{queuable:!1},function(e,n){return e?t(e):void t(null,n.result)})},Kuzzle.prototype.whoAmI=function(e){var t=this;t.callbackRequired("Kuzzle.whoAmI",e),t.query({controller:"auth",action:"getCurrentUser"},{},{},function(n,r){return n?e(n):void e(null,new d(t.security,r.result._id,r.result._source))})},Kuzzle.prototype.getMyRights=function(e,t){var n=this;t||"function"!=typeof e||(t=e,e=null),n.callbackRequired("Kuzzle.getMyRights",t),n.query({controller:"auth",action:"getMyRights"},{},e,function(e,n){return e?t(e):void t(null,n.result.hits)})},Kuzzle.prototype.updateSelf=function(e,t,n){var r=this,i={},o={controller:"auth",action:"updateSelf"};return n||"function"!=typeof t||(n=t,t=null),i.body=e,r.query(o,i,t,n&&function(e,t){n(e,e?void 0:t.result)}),this},Kuzzle.prototype.addListener=function(e,t){var n,r=Object.keys(this.eventListeners),i=typeof t;if(this.isValid(),r.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+r.toString());if("function"!==i)throw new Error("Invalid listener type: expected a function, got a "+i);return n=l.v4(),this.eventListeners[e].listeners.push({id:n,fn:t}),n},Kuzzle.prototype.getAllStatistics=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.getAllStatistics",t),this.query({controller:"admin",action:"getAllStats"},{},e,function(e,n){return e?t(e):void t(null,n.result.hits)})},Kuzzle.prototype.getStatistics=function(e,t,n){var r,i;n||(1===arguments.length?(n=arguments[0],t=null,e=null):(n=arguments[1],"object"==typeof arguments[0]?(t=arguments[0],e=null):(e=arguments[0],t=null))),r=function(t,r){return t?n(t):void n(null,e?r.result.hits:[r.result])},this.callbackRequired("Kuzzle.getStatistics",n),i=e?{body:{startTime:e}}:{},this.query({controller:"admin",action:e?"getStats":"getLastStats"},i,t,r)},Kuzzle.prototype.dataCollectionFactory=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 c(this,t,e)),this.collections[t][e]},Kuzzle.prototype.flushQueue=function(){return this.offlineQueue=[],this},Kuzzle.prototype.listCollections=function(){var e,t,n,r="all",i=Array.prototype.slice.call(arguments);if(i.forEach(function(r){switch(typeof r){case"string":e=r;break;case"object":t=r;break;case"function":n=r}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.listCollections: index required");e=this.defaultIndex}this.callbackRequired("Kuzzle.listCollections",n),t&&t.type&&(r=t.type),this.query({index:e,controller:"read",action:"listCollections"},{body:{type:r}},t,function(e,t){return e?n(e):void n(null,t.result.collections)})},Kuzzle.prototype.listIndexes=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.listIndexes",t),this.query({controller:"read",action:"listIndexes"},{},e,function(e,n){t(e,e?void 0:n.result.indexes)})},Kuzzle.prototype.disconnect=function(){var e;this.logout(),this.state="disconnected",this.network.close();for(e in this.collections)this.collections.hasOwnProperty(e)&&delete this.collections[e]},Kuzzle.prototype.getServerInfo=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.getServerInfo",t),this.query({controller:"read",action:"serverInfo"},{},e,function(e,n){return e?t(e):void t(null,n.result.serverInfo)})},Kuzzle.prototype.refreshIndex=function(){var e,t,n;if(Array.prototype.slice.call(arguments).forEach(function(r){switch(typeof r){case"string":e=r;break;case"object":t=r;break;case"function":n=r}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.refreshIndex: index required");e=this.defaultIndex}return this.query({index:e,controller:"admin",action:"refreshIndex"},{},t,n),this},Kuzzle.prototype.getAutoRefresh=function(){var e,t,n;if(Array.prototype.slice.call(arguments).forEach(function(r){switch(typeof r){case"string":e=r;break;case"object":t=r;break;case"function":n=r}}),!e){if(!this.defaultIndex)throw new Error("Kuzzle.getAutoRefresh: index required");e=this.defaultIndex}this.callbackRequired("Kuzzle.getAutoRefresh",n),this.query({index:e,controller:"admin",action:"getAutoRefresh"},{},t,n)},Kuzzle.prototype.setAutoRefresh=function(){var e,t,n,r;if(Array.prototype.slice.call(arguments).forEach(function(i){switch(typeof i){case"string":e=i;break;case"boolean":t=i;break;case"object":n=i;break;case"function":r=i}}),!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:"admin",action:"setAutoRefresh"},{body:{autoRefresh:t}},n,r),this},Kuzzle.prototype.now=function(e,t){t||"function"!=typeof e||(t=e,e=null),this.callbackRequired("Kuzzle.now",t),this.query({controller:"read",action:"now"},{},e,function(e,n){t(e,n&&n.result.now)})},Kuzzle.prototype.query=function(e,t,n,i){var u,s={action:e.action,controller:e.controller,metadata:this.metadata},c=this;if(this.isValid(),i||"function"!=typeof n||(i=n,n=null),n&&(n.metadata&&Object.keys(n.metadata).forEach(function(e){s.metadata[e]=n.metadata[e]}),n.queuable===!1&&"offline"===c.state))return c;if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("Invalid query parameter: "+t);t.metadata&&Object.keys(t.metadata).forEach(function(e){s.metadata[e]=t.metadata[e]});for(u in t)"metadata"!==u&&t.hasOwnProperty(u)&&(s[u]=t[u]);return s=c.addHeaders(s,this.headers),void 0===c.jwtToken||"auth"===s.controller&&"checkToken"===s.action||(s.headers=s.headers||{},s.headers.authorization="Bearer "+c.jwtToken),e.collection&&(s.collection=e.collection),e.index&&(s.index=e.index),s.requestId||(s.requestId=l.v4()),"connected"===c.state||n&&n.queuable===!1?"connected"===c.state?o.call(this,s,i):i&&i(new Error("Unable to execute request: not connected to a Kuzzle server.\nDiscarded request: "+JSON.stringify(s))):(c.queuing||["initializing","connecting"].indexOf(c.state)!==-1)&&(r.call(this,s,i),c.queueFilter&&!c.queueFilter(s)||(c.offlineQueue.push({ts:Date.now(),query:s,cb:i}),c.emitEvent("offlineQueuePush",{query:s,cb:i}))),c},Kuzzle.prototype.removeAllListeners=function(e){var t=Object.keys(this.eventListeners),n=this;if(e){if(t.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+t.toString());this.eventListeners[e].listeners=[]}else t.forEach(function(e){n.eventListeners[e].listeners=[]});return this},Kuzzle.prototype.removeListener=function(e,t){var n=Object.keys(this.eventListeners),r=this;if(n.indexOf(e)===-1)throw new Error("["+e+"] is not a known event. Known events: "+n.toString());return this.eventListeners[e].listeners.forEach(function(n,i){n.id===t&&r.eventListeners[e].listeners.splice(i,1)}),this},Kuzzle.prototype.replayQueue=function(){return"offline"===this.state||this.autoReplay||(r.call(this),u.call(this)),this},Kuzzle.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},Kuzzle.prototype.setHeaders=function(e,t){var n=this;if("object"!=typeof e||Array.isArray(e))throw new Error("Expected a content object, received a "+typeof e);return t?n.headers=e:Object.keys(e).forEach(function(t){n.headers[t]=e[t]}),n},Kuzzle.prototype.startQueuing=function(){return"offline"!==this.state||this.autoQueue||(this.queuing=!0),this},Kuzzle.prototype.stopQueuing=function(){return"offline"!==this.state||this.autoQueue||(this.queuing=!1),this}},function(e,t){function n(e,t,n){if(!t)throw new Error("A security document must have an id");if(Object.defineProperties(this,{kuzzle:{value:e.kuzzle},kuzzleSecurity:{value:e},id:{value:t,enumerable:!0},content:{value:{},writable:!0,enumerable:!0}}),n&&this.setContent(n,!0),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["delete","update"];return r&&i.indexOf(e)!==-1}})}n.prototype.setContent=function(e){return this.content=e,this},n.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e},n.prototype["delete"]=function(e,t){var n=this;e&&void 0===t&&"function"==typeof e&&(t=e,e=null),n.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.deleteActionName),{_id:this.id},e,function(e,n){return e?!!t&&t(e):void(t&&t(null,n.result._id))})},n.prototype.update=function(e,t,n){var r={},i=this;if("object"!=typeof e)throw new Error('Parameter "content" must be a object');return t&&void 0===n&&"function"==typeof t&&(n=t,t=null),r._id=i.id,r.body=e,i.kuzzle.query(this.kuzzleSecurity.buildQueryArgs(this.updateActionName),r,t,function(e,t){return e?!!n&&n(e):(i.setContent(t.result._source),void(n&&n(null,i)))}),this},e.exports=n},function(e,t,n){function r(e,t,n){if(i.call(this,e,t,n),Object.defineProperties(this,{deleteActionName:{value:"deleteUser"},updateActionName:{value:"updateUser"}}),e.kuzzle.bluebird)return e.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["save"];return r&&i.indexOf(e)!==-1}})}var i=n(1);r.prototype=Object.create(i.prototype,{constructor:{value:r}}),r.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},r.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},r.prototype.save=function(e,t){var n=this.serialize(),r=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createOrReplaceUser"),n,e,t&&function(e){t(e,e?void 0:r)}),r},r.prototype.serialize=function(){return{_id:this.id,body:this.content}},r.prototype.getProfiles=function(){return this.content.profileIds},e.exports=r},function(e,t){!function(t){"use strict";function n(){var e=t.crypto||t.msCrypto;if(!l&&e&&e.getRandomValues)try{var n=new Uint8Array(16);f=l=function(){return e.getRandomValues(n),n},l()}catch(r){}if(!l){var i=new Array(16);c=l=function(){for(var e,t=0;t<16;t++)0===(3&t)&&(e=4294967296*Math.random()),i[t]=e>>>((3&t)<<3)&255;return i},"undefined"!=typeof console&&console.warn&&console.warn("[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()")}}function r(){if("function"==typeof require)try{var e=require("crypto").randomBytes;a=l=e&&function(){return e(16)},l()}catch(t){}}function i(e,t,n){var r=t&&n||0,i=0;for(t=t||[],e.toLowerCase().replace(/[0-9a-f]{2}/g,function(e){i<16&&(t[r+i++]=y[e])});i<16;)t[r+i++]=0;return t}function o(e,t){var n=t||0,r=p;return r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]}function u(e,t,n){var r=t&&n||0,i=t||[];e=e||{};var u=null!=e.clockseq?e.clockseq:m,s=null!=e.msecs?e.msecs:(new Date).getTime(),l=null!=e.nsecs?e.nsecs:k+1,c=s-w+(l-k)/1e4;if(c<0&&null==e.clockseq&&(u=u+1&16383),(c<0||s>w)&&null==e.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");w=s,k=l,m=u,s+=122192928e5;var a=(1e4*(268435455&s)+l)%4294967296;i[r++]=a>>>24&255,i[r++]=a>>>16&255,i[r++]=a>>>8&255,i[r++]=255&a;var f=s/4294967296*1e4&268435455;i[r++]=f>>>8&255,i[r++]=255&f,i[r++]=f>>>24&15|16,i[r++]=f>>>16&255,i[r++]=u>>>8|128,i[r++]=255&u;for(var d=e.node||v,h=0;h<6;h++)i[r+h]=d[h];return t?t:o(i)}function s(e,t,n){var r=t&&n||0;"string"==typeof e&&(t="binary"===e?new h(16):null,e=null),e=e||{};var i=e.random||(e.rng||l)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t)for(var u=0;u<16;u++)t[r+u]=i[u];return t||o(i)}var l,c,a,f,d;t?n():r();for(var h="function"==typeof Buffer?Buffer:Array,p=[],y={},b=0;b<256;b++)p[b]=(b+256).toString(16).substr(1),y[p[b]]=b;var z=l(),v=[1|z[0],z[1],z[2],z[3],z[4],z[5]],m=16383&(z[6]<<8|z[7]),w=0,k=0,g=s;g.v1=u,g.v4=s,g.parse=i,g.unparse=o,g.BufferClass=h,g._rng=l,g._mathRNG=c,g._nodeRNG=a,g._whatwgRNG=f,"undefined"!=typeof e&&e.exports?e.exports=g:"function"==typeof define&&define.amd?define(function(){return g}):(d=t.uuid,g.noConflict=function(){return t.uuid=d,g},t.uuid=g)}("undefined"!=typeof window?window:null)},function(e,t,n){function r(e,t,n){if(!t||!n)throw new Error("The KuzzleDataCollection object constructor needs an index and a collection arguments");return Object.defineProperties(this,{collection:{value:n,enumerable:!0},index:{value:t,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,n,r){var i=["publishMessage","setHeaders","subscribe"];return r&&i.indexOf(e)===-1}}):this}var i=n(6),o=n(5),u=n(8);r.prototype.advancedSearch=function(e,t,n){var r,o=this;n||"function"!=typeof t||(n=t,t=null),o.kuzzle.callbackRequired("KuzzleDataCollection.advancedSearch",n),r=o.kuzzle.addHeaders({body:e},this.headers),o.kuzzle.query(this.buildQueryArgs("read","search"),r,t,function(e,t){var r=[];return e?n(e):(t.result.hits.forEach(function(e){var t=new i(o,e._id,e._source);t.version=e._version,r.push(t)}),void n(null,{total:t.result.total,documents:r}))})},r.prototype.count=function(e,t,n){var r;n||"function"!=typeof t||(n=t,t=null),this.kuzzle.callbackRequired("KuzzleDataCollection.count",n),r=this.kuzzle.addHeaders({body:e},this.headers),this.kuzzle.query(this.buildQueryArgs("read","count"),r,t,function(e,t){n(e,t&&t.result.count)})},r.prototype.create=function(e,t){var n={};return t||"function"!=typeof e||(t=e,e=null),n=this.kuzzle.addHeaders(n,this.headers),this.kuzzle.query(this.buildQueryArgs("write","createCollection"),n,e,t),this},r.prototype.createDocument=function(e,t,n,r){var o=this,u={},s="create";return e&&"string"!=typeof e&&(r=n,n=t,t=e,e=null),r||"function"!=typeof n||(r=n,n=null),t instanceof i?u=t.serialize():u.body=t,n&&(s=n.updateIfExist?"createOrReplace":"create"),e&&(u._id=e),u=o.kuzzle.addHeaders(u,o.headers),o.kuzzle.query(this.buildQueryArgs("write",s),u,n,r&&function(e,t){var n;return e?r(e):(n=new i(o,t.result._id,t.result._source),n.version=t.result._version,void r(null,n))}),this},r.prototype.deleteDocument=function(e,t,n){var r,i={};return"string"==typeof e?(i._id=e,r="delete"):(i.body=e,r="deleteByQuery"),n||"function"!=typeof t||(n=t,t=null),i=this.kuzzle.addHeaders(i,this.headers),this.kuzzle.query(this.buildQueryArgs("write",r),i,t,n&&function(e,t){e?n(e):n(null,"delete"===r?[t.result._id]:t.result.ids)}),this},r.prototype.fetchDocument=function(e,t,n){var r={_id:e},o=this;n||"function"!=typeof t||(n=t,t=null),o.kuzzle.callbackRequired("KuzzleDataCollection.fetch",n),r=o.kuzzle.addHeaders(r,this.headers),o.kuzzle.query(this.buildQueryArgs("read","get"),r,t,function(e,t){var r;return e?n(e):(r=new i(o,t.result._id,t.result._source),r.version=t.result._version,void n(null,r))})},r.prototype.fetchAllDocuments=function(e,t){var n={};t||"function"!=typeof e||(t=e,e=null),e&&(e.from&&(n.from=e.from),e.size&&(n.size=e.size)),this.kuzzle.callbackRequired("KuzzleDataCollection.fetchAll",t),this.advancedSearch(n,e,t)},r.prototype.getMapping=function(e,t){var n;t||"function"!=typeof e||(t=e,e=null),this.kuzzle.callbackRequired("KuzzleDataCollection.getMapping",t),n=new o(this),n.refresh(e,t)},r.prototype.publishMessage=function(e,t,n){var r={};return e instanceof i?r=e.serialize():r.body=e,r=this.kuzzle.addHeaders(r,this.headers),this.kuzzle.query(this.buildQueryArgs("write","publish"),r,t,n),this},r.prototype.replaceDocument=function(e,t,n,r){var o=this,u={_id:e,body:t};return r||"function"!=typeof n||(r=n,n=null),u=o.kuzzle.addHeaders(u,this.headers),o.kuzzle.query(this.buildQueryArgs("write","createOrReplace"),u,n,r&&function(e,t){var n;return e?r(e):(n=new i(o,t.result._id,t.result._source),n.version=t.result._version,void r(null,n))}),this},r.prototype.subscribe=function(e,t,n){var r;return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.callbackRequired("KuzzleDataCollection.subscribe",n),r=new u(this,t),r.renew(e,n),r},r.prototype.truncate=function(e,t){var n={};return t||"function"!=typeof e||(t=e,e=null),n=this.kuzzle.addHeaders(n,this.headers),this.kuzzle.query(this.buildQueryArgs("admin","truncateCollection"),n,e,t),this},r.prototype.updateDocument=function(e,t,n,r){var o={_id:e,body:t},u=this;return r||"function"!=typeof n||(r=n,n=null),o=u.kuzzle.addHeaders(o,this.headers),u.kuzzle.query(this.buildQueryArgs("write","update"),o,n,r&&function(e,t){return e?r(e):void new i(u,t.result._id).refresh(r)}),u},r.prototype.documentFactory=function(e,t){return new i(this,e,t)},r.prototype.roomFactory=function(e){return new u(this,e)},r.prototype.dataMappingFactory=function(e){return new o(this,e)},r.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=r},function(e,t){function n(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,n,r){var i=["set","setHeaders"];return r&&i.indexOf(e)===-1}}):this}n.prototype.apply=function(e,t){var n=this,r=this.kuzzle.addHeaders({body:{properties:this.mapping}},this.headers);return t||"function"!=typeof e||(t=e,e=null),n.kuzzle.query(this.collection.buildQueryArgs("admin","updateMapping"),r,e,function(r){return r?t&&t(r):void n.refresh(e,t)}),this},n.prototype.refresh=function(e,t){var n=this,r=this.kuzzle.addHeaders({},this.headers);return t||"function"!=typeof e||(t=e,e=null),this.kuzzle.query(this.collection.buildQueryArgs("admin","getMapping"),r,e,function(e,r){return e?!!t&&t(e):r.result[n.collection.index]?r.result[n.collection.index].mappings[n.collection.collection]?(n.mapping=r.result[n.collection.index].mappings[n.collection.collection].properties,void 0===n.mapping&&(n.mapping={}),void(t&&t(null,n))):t&&t(new Error("No mapping found for collection "+n.collection.collection)):t&&t(new Error("No mapping found for index "+n.collection.index))}),this},n.prototype.set=function(e,t){return this.mapping[e]=t,this},n.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=n},function(e,t){function n(e,t,n){return Object.defineProperties(this,{collection:{value:e.collection,enumerable:!0},dataCollection:{value:e,enumerable:!0},kuzzle:{value:e.kuzzle,enumerable:!0},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}}),!n&&t&&"object"==typeof t&&(n=t,t=null),n&&(n._version&&(this.version=n._version,delete n._version),this.setContent(n,!0)),t&&Object.defineProperty(this,"id",{value:t,enumerable:!0}),this.kuzzle.bluebird?this.kuzzle.bluebird.promisifyAll(this,{suffix:"Promise",filter:function(e,t,n,r){var i=["delete","refresh","save"];return r&&i.indexOf(e)!==-1}}):this}n.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e._version=this.version,e=this.kuzzle.addHeaders(e,this.headers)},n.prototype.toString=function(){return JSON.stringify(this.serialize())},n.prototype["delete"]=function(e,t){var n=this;if(t||"function"!=typeof e||(t=e,e=null),!n.id)throw new Error("KuzzleDocument.delete: cannot delete a document without a document ID");this.kuzzle.query(this.dataCollection.buildQueryArgs("write","delete"),this.serialize(),e,t&&function(e){t(e,e?void 0:n.id)})},n.prototype.refresh=function(e,t){var r=this;if(t||"function"!=typeof e||(t=e,e=null),!r.id)throw new Error("KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided");this.kuzzle.callbackRequired("KuzzleDocument.refresh",t),r.kuzzle.query(r.dataCollection.buildQueryArgs("read","get"),{_id:r.id},e,function(e,i){var o;return e?t(e):(o=new n(r.dataCollection,r.id,i.result._source),o.version=i.result._version,void t(null,o))})},n.prototype.save=function(e,t){var n=this.serialize(),r=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r.kuzzle.query(this.dataCollection.buildQueryArgs("write","createOrReplace"),n,e,function(e,n){return e?t&&t(e):(r.id=n.result._id,r.version=n.result._version,void(t&&t(null,r)))}),r},n.prototype.publish=function(e){var t=this.serialize();return this.kuzzle.query(this.dataCollection.buildQueryArgs("write","publish"),t,e),this},n.prototype.setContent=function(e,t){var n=this;return t?this.content=e:Object.keys(e).forEach(function(t){n.content[t]=e[t]}),this},n.prototype.subscribe=function(e,t){var n;if(e&&!t&&"function"==typeof e&&(t=e,e=null),this.kuzzle.callbackRequired("KuzzleDocument.subscribe",t),!this.id)throw new Error("KuzzleDocument.subscribe: cannot subscribe to a document if no ID has been provided");return n={ids:{values:[this.id]}},this.dataCollection.subscribe(n,e,t)},n.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=n},function(e,t){function n(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,n,r){var i=["setHeaders"];return r&&i.indexOf(e)===-1}}):this}!function(){var e=["id","value"],t=["id","keys"],r={append:e,bgrewriteaof:[],bgsave:[],bitcount:["id","start","end"],bitop:["operation","destkey",t],bitpos:["id","bit",{__opts__:["start","end"]}],blpop:[t,"timeout"],brpoplpush:["source","destination"],dbsize:[],decrby:e,del:[t],discard:[],exec:[],exists:[t],expire:["id","seconds"],expireat:["id","timestamp"],flushdb:[],getbit:["id","offset"],getrange:["id","start","end"],hdel:["id",["field","fields"]],hexists:["id","field"],hincrby:["id","field","value"],hmset:["id","values"],hset:["id","field","value"],info:["section"],keys:["pattern"],lastsave:[],lindex:["id","idx"],linsert:["id","position","pivot","value"],lpush:["id",["value","values"]],lrange:["id","start","stop"],lrem:["id","count","value"],lset:["id","idx","value"],ltrim:["id","start","stop"],mset:["values"],multi:[],object:["subcommand","args"],pexpire:["id","milliseconds"],pexpireat:["id","timestamp"],pfadd:["id",["element","elements"]],pfmerge:["destkey",["sourcekey","sourcekeys"]],ping:[],psetex:["id","milliseconds","value"], publish:["channel","message"],randomkey:[],rename:["id","newkey"],renamenx:["id","newkey"],restore:["id","ttl","content"],rpoplpush:["source","destination"],sadd:["id",["member","members"]],save:[],set:["id","value",{__opts__:["ex","px","nx","xx"]}],sdiffstore:["destination",t],setbit:["id","offset","value"],setex:["id","seconds","value"],setrange:["id","offset","value"],sinterstore:["destination",t],sismember:["id","member"],smove:["id","destination","member"],sort:["id",{__opts__:["by","offset","count","get","direction","alpha","store"]}],spop:["id","count"],srem:["id",["member","members"]],sunionstore:["destination",t],unwatch:[],wait:["numslaves","timeout"],zadd:["id",{__opts__:["nx","xx","ch","incr","score","member","members"]}],zcount:["id","min","max"],zincrby:["id","value","member"],zinterstore:["destination",t,{__opts__:["weight","weights","aggregate"]}],zlexcount:["id","min","max"],zrange:["id","start","stop",{__opts__:["withscores"]}],zrangebylex:["id","min","max",{__opts__:["offset","count"]}],zrangebyscore:["id","min","max",{__opts__:["withscores","offset","count"]}],zrem:["id","member"],zremrangebylex:["id","min","max"],zremrangebyscore:["id","min","max"],zrevrangebylex:["id","max","min",{__opts__:["offset","count"]}],zrevrangebyscore:["id","max","min",{__opts__:["withscores","offset","count"]}],zrevrank:["id","member"]};r.decr=r.get=r.dump=r.hgetall=r.hkeys=r.hlen=r.hstrlen=r.hvals=r.incr=r.llen=r.lpop=r.persist=r.pttl=r.rpop=r.scard=r.smembers=r.strlen=r.ttl=r.type=r.zcard=["id"],r.getset=r.lpushx=e,r.del=r.exists=r.mget=r.pfcount=r.sdiff=r.sinter=r.sunion=r.watch=[t],r.incrby=r.incrbyfloat=r.decrby,r.brpop=r.blpop,r.hget=r.hexists,r.hmget=r.hdel,r.hsetnx=r.hset,r.msetnx=r.mset,r.rpush=r.lpush,r.hincrbyfloat=r.hincrby,r.srandmember=r.spop,r.zrevrange=r.zrange,r.zscore=r.zrevrank,Object.keys(r).forEach(function(e){n.prototype[e]=function(){var t,n=Array.prototype.slice.call(arguments),i=null,o={controller:"ms",action:e},u={};return"function"==typeof n[n.length-1]&&(t=n.pop()),n.length&&"object"==typeof n[n.length-1]&&1===Object.keys(n[n.length-1]).length&&void 0!==n[n.length-1].queuable&&(i=n.pop()),r[e].forEach(function(e,t){void 0!==n[t]&&(Array.isArray(e)&&(e=Array.isArray(n[t])?e[1]:e[0]),"id"===e?u._id=n[t]:(u.body||(u.body={}),"object"==typeof e&&void 0!==e.__opts__?e.__opts__.forEach(function(e){void 0!==n[t][e]&&(u.body[e]=n[t][e])}):u.body[e]=n[t]))}),this.kuzzle.query(o,u,i,t),this}})}(),e.exports=n},function(e,t,n){function r(e,t){return Object.defineProperties(this,{callback:{value:null,writable:!0},channel:{value:null,writable:!0},id:{value:s.v4()},lastRenewal:{value:null,writable:!0},notifier:{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},metadata:{value:t&&t.metadata?t.metadata:{},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,n,r){var i=["count"];return r&&i.indexOf(e)!==-1}}):this}function i(e){return e.error?this.callback(e.error):"jwtTokenExpired"===e.action?(this.kuzzle.jwtToken=void 0,this.kuzzle.emitEvent("jwtTokenExpired")):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 u(){return"connected"===this.kuzzle.state&&!this.subscribing}var s=n(3);r.prototype.count=function(e){var t;if(this.kuzzle.callbackRequired("KuzzleRoom.count",e),t=this.kuzzle.addHeaders({body:{roomId:this.roomId}},this.headers),!u.call(this))return void this.queue.push({action:"count",args:[e]});if(!this.roomId)throw new Error("KuzzleRoom.count: cannot count subscriptions on an inactive room");this.kuzzle.query(this.collection.buildQueryArgs("subscribe","count"),t,function(t,n){e(t,n&&n.result.count)})},r.prototype.renew=function(e,t){var n=Date.now(),r={scope:this.scope,state:this.state,users:this.users},u=this;if(!t&&e&&"function"==typeof e&&(t=e,e=null),u.kuzzle.callbackRequired("KuzzleRoom.renew",t),!(u.lastRenewal&&n-u.lastRenewal<=u.renewalDelay)){if(e&&(u.filters=e),"connected"!==u.kuzzle.state)return u.callback=t,void(u.kuzzle.subscriptions.pending[u.id]=u);if(u.subscribing)return void u.queue.push({action:"renew",args:[e,t]});u.unsubscribe(),u.roomId=null,u.subscribing=!0,u.callback=t,u.kuzzle.subscriptions.pending[u.id]=u,r.body=u.filters,r=u.kuzzle.addHeaders(r,this.headers),u.kuzzle.query(u.collection.buildQueryArgs("subscribe","on"),r,{metadata:u.metadata},function(e,t){if(delete u.kuzzle.subscriptions.pending[u.id],u.subscribing=!1,e)throw u.queue=[],new Error("Error during Kuzzle subscription: "+e.message);u.lastRenewal=n,u.roomId=t.result.roomId,u.channel=t.result.channel,u.kuzzle.subscriptions[u.roomId]||(u.kuzzle.subscriptions[u.roomId]={}),u.kuzzle.subscriptions[u.roomId][u.id]=u,u.notifier=i.bind(u),u.kuzzle.network.on(u.channel,u.notifier),o.call(u)})}},r.prototype.unsubscribe=function(){var e,t=this,n=t.roomId;return u.call(this)?(n&&(t.kuzzle.network.off(t.channel,this.notifier),1===Object.keys(t.kuzzle.subscriptions[n]).length?(delete t.kuzzle.subscriptions[n],0===Object.keys(t.kuzzle.subscriptions.pending).length?t.kuzzle.query(t.collection.buildQueryArgs("subscribe","off"),{body:{roomId:n}}):e=setInterval(function(){0===Object.keys(t.kuzzle.subscriptions.pending).length&&(t.kuzzle.subscriptions[n]||t.kuzzle.query(t.collection.buildQueryArgs("subscribe","off"),{body:{roomId:n}}),clearInterval(e))},100)):delete t.kuzzle.subscriptions[n][t.id],t.roomId=null),t):(t.queue.push({action:"unsubscribe",args:[]}),t)},r.prototype.setHeaders=function(e,t){return this.kuzzle.setHeaders.call(this,e,t),this},e.exports=r},function(e,t,n){function r(e,t,r,i){if("undefined"!=typeof window){if("undefined"!=typeof WebSocket)return new(n(11))(e,t,i);if(window.io)return new(n(10))(e,r,i);throw new Error("Aborting: no websocket support detected and no socket.io library loaded either.")}return new(n(!function(){var e=new Error('Cannot find module "./wrappers/wsnode"');throw e.code="MODULE_NOT_FOUND",e}()))(e,t,i)}e.exports=r},function(e,t){function n(e,t,n){this.host=e,this.port=t,this.ssl=n,this.socket=null,this.connect=function(e,t){this.socket=window.io((this.ssl?"https://":"http://")+this.host+":"+this.port,{reconnection:e,reconnectionDelay:t,forceNew:!0})},this.onConnect=function(e){this.socket.on("connect",e)},this.onConnectError=function(e){this.socket.on("connect_error",e)},this.onDisconnect=function(e){this.socket.on("disconnect",e)},this.onReconnect=function(e){this.socket.on("reconnect",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.socket.close(),this.socket=null}}e.exports=n},function(e,t){function n(e,t,n){var i=this;this.host=e,this.port=t,this.ssl=n,this.client=null,this.retrying=!1,this.listeners={error:[],connect:[],disconnect:[],reconnect:[]},this.connect=function(e,t){this.client=new WebSocket((this.ssl?"wss://":"ws://")+this.host+":"+this.port),this.client.onopen=function(){i.retrying?r(i.listeners,"reconnect"):r(i.listeners,"connect")},this.client.onclose=function(){r(i.listeners,"disconnect")},this.client.onerror=function(){e&&(i.retrying=!0,setTimeout(function(){i.connect(e,t)},t)),r(i.listeners,"error")},this.client.onmessage=function(e){var t=JSON.parse(e.data);t.room&&i.listeners[t.room]&&r(i.listeners,t.room,t)}},this.onConnect=function(e){this.listeners.connect.push({fn:e,keep:!0})},this.onConnectError=function(e){this.listeners.error.push({fn:e,keep:!0})},this.onDisconnect=function(e){this.listeners.disconnect.push({fn:e,keep:!0})},this.onReconnect=function(e){this.listeners.reconnect.push({fn:e,keep:!0})},this.once=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,keep:!1})},this.on=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,keep:!0})},this.off=function(e,t){var n;this.listeners[e]&&(n=this.listeners[e].findIndex(function(e){return e.fn===t}),n!==-1&&(1===this.listeners[e].length&&["error","connect","disconnect","reconnect"].indexOf(e)===-1?delete this.listeners[e]:this.listeners[e].splice(n,1)))},this.send=function(e){this.client&&this.client.readyState===this.client.OPEN&&this.client.send(JSON.stringify(e))},this.close=function(){this.listeners={error:[],connect:[],disconnect:[],reconnect:[]},this.retrying=!1,this.client.close(),this.client=null}}function r(e,t,n){var r,i=e[t].length;for(r=0;r1?(e[t].splice(r,1),--r,--i):delete e[t])}e.exports=n},function(e,t,n){function r(e,t,n){if(i.call(this,e,t,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,n,r){var i=["hydrate","save"];return r&&i.indexOf(e)!==-1}})}var i=n(1);r.prototype=Object.create(i.prototype,{constructor:{value:r}}),r.prototype.save=function(e,t){var n,r=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),n=this.serialize(),r.kuzzle.query(r.kuzzleSecurity.buildQueryArgs("createOrReplaceProfile"),n,e,t&&function(e){t(e,e?void 0:r)}),r},r.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},r.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},r.prototype.serialize=function(){var e={};return this.id&&(e._id=this.id),e.body=this.content,e},r.prototype.getPolicies=function(){return this.content.policies},e.exports=r},function(e,t,n){function r(e,t,n){if(i.call(this,e,t,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,n,r){var i=["save"];return r&&i.indexOf(e)!==-1}})}var i=n(1);r.prototype=Object.create(i.prototype,{constructor:{value:r}}),r.prototype.save=function(e,t){var n=this.serialize(),r=this;return e&&void 0===t&&"function"==typeof e&&(t=e,e=null),r.kuzzle.query(this.kuzzleSecurity.buildQueryArgs("createOrReplaceRole"),n,e,t&&function(e){t(e,e?void 0:r)}),this},e.exports=r},function(e,t,n){function r(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,n,r){var i=["roleFactory","profileFactory","userFactory","isActionAllowed"];return r&&i.indexOf(e)===-1}}):this}var i=n(13),o=n(12),u=n(2);r.prototype.getRole=function(e,t,n){var r,o=this;if(!e)throw new Error("Id parameter is mandatory for getRole function");n||"function"!=typeof t||(n=t,t=null),r={_id:e},o.kuzzle.callbackRequired("KuzzleSecurity.getRole",n),o.kuzzle.query(this.buildQueryArgs("getRole"),r,t,function(e,t){n(e,e?void 0:new i(o,t.result._id,t.result._source))})},r.prototype.searchRoles=function(e,t,n){var r=this;n||"function"!=typeof t||(n=t,t=null),r.kuzzle.callbackRequired("KuzzleSecurity.searchRoles",n),r.kuzzle.query(this.buildQueryArgs("searchRoles"),{body:e},t,function(e,t){var o;return e?n(e):(o=t.result.hits.map(function(e){return new i(r,e._id,e._source)}),void n(null,{total:t.result.total,roles:o}))})},r.prototype.createRole=function(e,t,n,r){var o=this,u={},s="createRole";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.createRole: cannot create a role without a role ID");r||"function"!=typeof n||(r=n,n=null),u._id=e,u.body=t,n&&(s=n.replaceIfExist?"createOrReplaceRole":"createRole"),o.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(e,t){r(e,e?void 0:new i(o,t.result._id,t.result._source))})},r.prototype.updateRole=function(e,t,n,r){var o=this,u={_id:e,body:t},s="updateRole";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.updateRole: cannot update a role without a role ID");return r||"function"!=typeof n||(r=n,n=null),o.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(n){r(n,n?void 0:new i(o,e,t))}),this},r.prototype.deleteRole=function(e,t,n){var r={_id:e};return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteRole"),r,t,n&&function(e,t){n(e,e?void 0:t.result._id)}),this},r.prototype.roleFactory=function(e,t){return new i(this,e,t)},r.prototype.getProfile=function(e,t,n){var r,i=this;if(n||"function"!=typeof t||(n=t,t=null),!e||"string"!=typeof e)throw new Error("Id parameter is mandatory for getProfile function");r={_id:e},i.kuzzle.callbackRequired("KuzzleSecurity.getProfile",n),i.kuzzle.query(this.buildQueryArgs("getProfile"),r,t,function(e,t){n(e,e?void 0:new o(i,t.result._id,t.result._source))})},r.prototype.searchProfiles=function(e,t,n){var r=this;n||"function"!=typeof t||(n=t,t=null),r.kuzzle.callbackRequired("KuzzleSecurity.searchProfiles",n),r.kuzzle.query(this.buildQueryArgs("searchProfiles"),{body:e},t,function(e,t){var i;return e?n(e):(i=t.result.hits.map(function(e){return new o(r,e._id,e._source)}),void n(null,{total:t.result.total,profiles:i}))})},r.prototype.createProfile=function(e,t,n,r){var i=this,u={},s="createProfile";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.createProfile: cannot create a profile without a profile ID");r||"function"!=typeof n||(r=n,n=null),u._id=e,u.body=t,n&&(s=n.replaceIfExist?"createOrReplaceProfile":"createProfile"),i.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(e,t){r(e,e?void 0:new o(i,t.result._id,t.result._source))})},r.prototype.updateProfile=function(e,t,n,r){var i=this,u={},s="updateProfile";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.updateProfile: cannot update a profile without a profile ID");return r||"function"!=typeof n||(r=n,n=null),u._id=e,u.body=t,i.kuzzle.query(this.buildQueryArgs(s),u,n,r&&function(e,t){var n={};return e?r(e):(Object.keys(t.result._source).forEach(function(e){n[e]=t.result._source[e]}),void r(null,new o(i,t.result._id,n)))}),this},r.prototype.deleteProfile=function(e,t,n){var r={_id:e};return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteProfile"),r,t,n&&function(e,t){n(e,e?void 0:t.result._id)}),this},r.prototype.profileFactory=function(e,t){return new o(this,e,t)},r.prototype.getUser=function(e,t,n){var r={_id:e},i=this;if(!e||"string"!=typeof e)throw new Error("Id parameter is mandatory for getUser function");n||"function"!=typeof t||(n=t,t=null),i.kuzzle.callbackRequired("KuzzleSecurity.getUser",n),i.kuzzle.query(this.buildQueryArgs("getUser"),r,t,function(e,t){n(e,e?void 0:new u(i,t.result._id,t.result._source))})},r.prototype.searchUsers=function(e,t,n){var r=this;n||"function"!=typeof t||(n=t,t=null),r.kuzzle.callbackRequired("KuzzleSecurity.searchUsers",n),r.kuzzle.query(this.buildQueryArgs("searchUsers"),{body:e},t,function(e,t){var i;return e?n(e):(i=t.result.hits.map(function(e){return new u(r,e._id,e._source)}),void n(null,{total:t.result.total,users:i}))})},r.prototype.createUser=function(e,t,n,r){var i=this,o={_id:e,body:t},s="createUser";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.createUser: cannot create a user without a user ID");r||"function"!=typeof n||(r=n,n=null),n&&(s=n.replaceIfExist?"createOrReplaceUser":"createUser"),i.kuzzle.query(this.buildQueryArgs(s),o,null,r&&function(e,t){r(e,e?void 0:new u(i,t.result._id,t.result._source))})},r.prototype.updateUser=function(e,t,n,r){var i=this,o={},s="updateUser";if(!e||"string"!=typeof e)throw new Error("KuzzleSecurity.updateUser: cannot update an user without an user ID");return r||"function"!=typeof n||(r=n,n=null),o._id=e,o.body=t,i.kuzzle.query(this.buildQueryArgs(s),o,n,r&&function(e,t){r(e,e?void 0:new u(i,t.result._id,t.result._source))}),this},r.prototype.deleteUser=function(e,t,n){var r={_id:e};return n||"function"!=typeof t||(n=t,t=null),this.kuzzle.query(this.buildQueryArgs("deleteUser"),r,t,n&&function(e,t){n(e,e?void 0:t.result._id)}),this},r.prototype.userFactory=function(e,t){return new u(this,e,t)},r.prototype.isActionAllowed=function(e,t,n,r,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(!n||"string"!=typeof n)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===n||"*"===e.action}).filter(function(e){return e.index===r||"*"===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"},r.prototype.getUserRights=function(e,t,n){var r={_id:e},i=this;if(!e||"string"!=typeof e)throw new Error("userId parameter is mandatory for getUserRights function");n||"function"!=typeof t||(n=t,t=null),i.kuzzle.callbackRequired("Kuzzle.getUserRights",n),this.kuzzle.query(this.buildQueryArgs("getUserRights"),r,t,n&&function(e,t){n(e,e?void 0:t.result.hits)})},e.exports=r}])}); //# sourceMappingURL=kuzzle.js.map \ No newline at end of file diff --git a/dist/kuzzle.js.map b/dist/kuzzle.js.map index 495d15c1c..a786be0ec 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 122e3b23088699ad9003","webpack:///./src/kuzzle.js","webpack:///./src/security/kuzzleSecurityDocument.js","webpack:///./src/security/kuzzleUser.js","webpack:///./~/node-uuid/uuid.js","webpack:///./src/kuzzleDataCollection.js","webpack:///./src/kuzzleDataMapping.js","webpack:///./src/kuzzleDocument.js","webpack:///./src/kuzzleMemoryStorage.js","webpack:///./src/kuzzleRoom.js","webpack:///./src/networkWrapper/index.js","webpack:///./src/networkWrapper/wrappers/socketio.js","webpack:///./src/networkWrapper/wrappers/wsbrowsers.js","webpack:///./src/security/kuzzleProfile.js","webpack:///./src/security/kuzzleRole.js","webpack:///./src/security/kuzzleSecurity.js"],"names":["root","factory","exports","module","define","amd","a","i","this","modules","__webpack_require__","moduleId","installedModules","id","loaded","call","m","c","p","cleanQueue","self","now","Date","lastDocumentIndex","queueTTL","offlineQueue","forEach","query","index","ts","splice","droppedRequest","emitEvent","queueMaxSize","length","cleanHistory","requestHistory","Object","keys","key","setTimeout","emitRequest","request","cb","undefined","jwtToken","network","once","requestId","response","action","error","message","send","dequeue","additionalQueue","uniqueQueue","dequeuingProcess","shift","Math","max","replayInterval","queuing","offlineQueueLoader","Error","Array","isArray","concat","filter","controller","hasOwnProperty","renewAllSubscriptions","subscriptions","roomId","subscriptionId","subscription","renew","callback","uuid","KuzzleDataCollection","KuzzleSecurity","KuzzleMemoryStorage","KuzzleUser","networkWrapper","Kuzzle","host","options","defineProperties","collections","value","writable","connectCB","eventListeners","connected","lastEmitted","listeners","disconnected","reconnected","jwtTokenExpired","loginAttempt","offlineQueuePush","offlineQueuePop","eventTimeout","state","pending","autoReconnect","enumerable","defaultIndex","reconnectionDelay","wsPort","ioPort","sslConnection","autoQueue","autoReplay","autoResubscribe","headers","metadata","queueFilter","opt","getOwnPropertyDescriptor","offlineMode","defineProperty","header","errorMessagePrefix","event","args","prototype","slice","arguments","eventProperties","listener","process","nextTick","fn","apply","connect","bluebird","promisifyAll","suffix","name","func","target","passes","whitelist","indexOf","onConnect","onConnectError","connectionError","internal","onDisconnect","disconnect","onReconnect","reconnect","checkToken","err","res","valid","setJwtToken","token","success","result","jwt","JSON","stringify","getJwtToken","login","strategy","credentials","expiresIn","body","queuable","logout","v4","callbackRequired","whoAmI","security","_id","_source","getMyRights","hits","updateSelf","content","data","queryArgs","addListener","listenerId","knownEvents","listenerType","isValid","toString","push","getAllStatistics","getStatistics","timestamp","queryCB","startTime","dataCollectionFactory","collection","flushQueue","listCollections","collectionType","arg","type","listIndexes","indexes","close","getServerInfo","serverInfo","refreshIndex","getAutoRefresh","setAutoRefresh","autoRefresh","attr","object","meta","addHeaders","authorization","removeAllListeners","eventName","removeListener","replayQueue","setDefaultIndex","setHeaders","replace","startQueuing","stopQueuing","KuzzleSecurityDocument","kuzzleSecurity","kuzzle","setContent","serialize","buildQueryArgs","deleteActionName","update","updateActionName","create","constructor","setProfiles","profileIds","addProfile","profileId","save","getProfiles","_window","setupBrowser","_crypto","crypto","msCrypto","_rng","getRandomValues","_rnds8","Uint8Array","_whatwgRNG","e","_rnds","_mathRNG","r","random","console","warn","setupNode","require","_rb","randomBytes","_nodeRNG","parse","s","buf","offset","ii","toLowerCase","oct","_hexToByte","unparse","bth","_byteToHex","v1","b","clockseq","_clockseq","msecs","getTime","nsecs","_lastNSecs","dt","_lastMSecs","tl","tmh","node","_nodeId","n","BufferClass","rnds","rng","_previousRoot","Buffer","substr","_seedBytes","noConflict","window","blacklist","KuzzleDocument","KuzzleDataMapping","KuzzleRoom","advancedSearch","filters","documents","doc","newDocument","version","_version","total","count","createDocument","document","updateIfExist","deleteDocument","ids","fetchDocument","documentId","fetchAllDocuments","from","size","getMapping","kuzzleMapping","refresh","publishMessage","replaceDocument","subscribe","room","truncate","updateDocument","documentFactory","roomFactory","dataMappingFactory","mapping","kuzzleDataCollection","properties","mappings","set","field","dataCollection","publish","values","bind","keyVal","idOrKeys","commands","append","bgrewriteaof","bgsave","bitcount","bitop","bitpos","__opts__","blpop","brpoplpush","dbsize","decrby","del","discard","exec","exists","expire","expireat","flushdb","getbit","getrange","hdel","hexists","hincrby","hmset","hset","info","lastsave","lindex","linsert","lpush","lrange","lrem","lset","ltrim","mset","multi","pexpire","pexpireat","pfadd","pfmerge","ping","psetex","randomkey","rename","renamenx","restore","rpoplpush","sadd","sdiffstore","setbit","setex","setrange","sinterstore","sismember","smove","sort","spop","srem","sunionstore","unwatch","wait","zadd","zcount","zincrby","zinterstore","zlexcount","zrange","zrangebylex","zrangebyscore","zrem","zremrangebylex","zremrangebyscore","zrevrangebylex","zrevrangebyscore","zrevrank","decr","get","dump","hgetall","hkeys","hlen","hstrlen","hvals","incr","llen","lpop","persist","pttl","rpop","scard","smembers","strlen","ttl","zcard","getset","lpushx","mget","pfcount","sdiff","sinter","sunion","watch","incrby","incrbyfloat","brpop","hget","hmget","hsetnx","msetnx","rpush","hincrbyfloat","srandmember","zrevrange","zscore","command","pop","v","channel","lastRenewal","notifier","queue","renewalDelay","scope","subscribing","users","subscribeToSelf","notificationCallback","element","isReady","subscribeQuery","unsubscribe","on","interval","off","setInterval","clearInterval","WebSocket","io","code","SocketIO","port","ssl","socket","reconnection","forceNew","payload","emit","WSBrowsers","client","retrying","onopen","poke","onclose","onerror","onmessage","keep","findIndex","readyState","OPEN","KuzzleProfile","policies","addPolicy","policy","roleId","setPolicies","map","getPolicies","KuzzleRole","getRole","searchRoles","roles","createRole","replaceIfExist","updateRole","deleteRole","roleFactory","getProfile","searchProfiles","profiles","createProfile","updateProfile","updatedContent","property","deleteProfile","profileFactory","getUser","searchUsers","createUser","updateUser","deleteUser","userFactory","isActionAllowed","rights","filteredRights","right","some","item","getUserRights","userId"],"mappings":"CAAA,SAAAA,EAAAC,GACA,mBAAAC,UAAA,gBAAAC,QACAA,OAAAD,QAAAD,QACA,sBAAAG,gBAAAC,IACAD,UAAAH,OACA,CACA,GAAAK,GAAAL,GACA,QAAAM,KAAAD,IAAA,gBAAAJ,iBAAAF,GAAAO,GAAAD,EAAAC,KAECC,KAAA,WACD,MCAgB,UAAUC,GCN1B,QAAAC,GAAAC,GAGA,GAAAC,EAAAD,GACA,MAAAC,GAAAD,GAAAT,OAGA,IAAAC,GAAAS,EAAAD,IACAT,WACAW,GAAAF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EAAAhG,EAAA3C,GAAA,SAAA+G,EAAAC,GACAhH,EAAA+G,IAAA9G,OAAA+G,EAAAK,OAAAmB,SAIAhL,EAAAD,QAAA8E","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 {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(this, function() {\nreturn \n\n\n/** WEBPACK FOOTER **\n ** webpack/universalModuleDefinition\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 {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\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 uuid = __webpack_require__(3),\n\t KuzzleDataCollection = __webpack_require__(4),\n\t KuzzleSecurity = __webpack_require__(14),\n\t KuzzleMemoryStorage = __webpack_require__(7),\n\t KuzzleUser = __webpack_require__(2),\n\t networkWrapper = __webpack_require__(9);\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 * @constructor\n\t */\n\tmodule.exports = Kuzzle = function (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\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 collections: {\n\t value: {},\n\t writable: true\n\t },\n\t connectCB: {\n\t value: cb\n\t },\n\t eventListeners: {\n\t value: {\n\t connected: {lastEmitted: null, listeners: []},\n\t error: {lastEmitted: null, listeners: []},\n\t disconnected: {lastEmitted: null, listeners: []},\n\t reconnected: {lastEmitted: null, listeners: []},\n\t jwtTokenExpired: {lastEmitted: null, listeners: []},\n\t loginAttempt: {lastEmitted: null, listeners: []},\n\t offlineQueuePush: {listeners: []},\n\t offlineQueuePop: {listeners: []}\n\t }\n\t },\n\t eventTimeout: {\n\t value: 200\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 'roomId': {\n\t kuzzleRoomID_1: kuzzleRoomInstance_1,\n\t kuzzleRoomID_2: kuzzleRoomInstance_2,\n\t kuzzleRoomID_...: 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 // read-only properties\n\t autoReconnect: {\n\t value: (options && typeof options.autoReconnect === 'boolean') ? options.autoReconnect : 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 enumerable: true\n\t },\n\t host: {\n\t value: host,\n\t enumerable: true\n\t },\n\t wsPort: {\n\t value: (options && typeof options.wsPort === 'number') ? options.wsPort : 7513,\n\t enumerable: true\n\t },\n\t ioPort: {\n\t value: (options && typeof options.ioPort === 'number') ? options.ioPort : 7512,\n\t enumerable: true\n\t },\n\t sslConnection: {\n\t value: (options && typeof options.sslConnection === 'boolean') ? options.sslConnection : false,\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 metadata: {\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: 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 (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 KuzzleSecurity(this),\n\t enumerable: true\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 Object.defineProperty(this, 'emitEvent', {\n\t value: function emitEvent(event) {\n\t var\n\t now = Date.now(),\n\t args = Array.prototype.slice.call(arguments, 1),\n\t eventProperties = this.eventListeners[event];\n\t\n\t if (eventProperties.lastEmitted && eventProperties.lastEmitted >= now - this.eventTimeout) {\n\t return false;\n\t }\n\t\n\t eventProperties.listeners.forEach(function (listener) {\n\t process.nextTick(function () {\n\t listener.fn.apply(undefined, args);\n\t });\n\t });\n\t\n\t // Events without the 'lastEmitted' property can be emitted without minimum time between emissions\n\t if (eventProperties.lastEmitted !== undefined) {\n\t eventProperties.lastEmitted = now;\n\t }\n\t }\n\t });\n\t\n\t Object.defineProperty(this, 'memoryStorage', {\n\t value: new KuzzleMemoryStorage(this),\n\t enumerable: true\n\t });\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 cleanHistory(this.requestHistory);\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', 'listIndexes', 'login', 'logout', 'now', 'query',\n\t '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\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.network = networkWrapper(self.host, self.wsPort, self.ioPort, self.sslConnection);\n\t }\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.onConnectError(function (error) {\n\t var connectionError = new Error('Unable to connect to kuzzle server at \"' + self.host + '\"');\n\t\n\t connectionError.internal = error;\n\t self.state = 'error';\n\t self.emitEvent('error', connectionError);\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('jwtTokenExpired');\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 * 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 * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.login = function (strategy) {\n\t var\n\t self = this,\n\t request = {\n\t strategy: strategy\n\t },\n\t credentials,\n\t cb = null;\n\t\n\t // Handle arguments (credentials, expiresIn, cb)\n\t if (arguments[1]) {\n\t if (typeof arguments[1] === 'object') {\n\t credentials = 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 if (typeof credentials === 'object') {\n\t Object.keys(credentials).forEach(function (key) {\n\t request[key] = credentials[key];\n\t });\n\t }\n\t\n\t this.query({controller: 'auth', action: 'login'}, {body: 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 * 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: uuid.v4(),\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 if (error === null) {\n\t self.jwtToken = undefined;\n\t cb(null, self);\n\t }\n\t else {\n\t cb(error);\n\t }\n\t });\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} callback The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t * @return {Kuzzle} The Kuzzle instance to enable chaining.\n\t */\n\tKuzzle.prototype.checkToken = function (token, callback) {\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', callback);\n\t\n\t this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, function (err, response) {\n\t if (err) {\n\t return callback(err);\n\t }\n\t\n\t callback(null, response.result);\n\t });\n\t};\n\t\n\t/**\n\t * Fetches the current user.\n\t *\n\t * @param {function} callback The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t * @return {Kuzzle} The Kuzzle instance to enable chaining.\n\t */\n\tKuzzle.prototype.whoAmI = function (callback) {\n\t var self = this;\n\t\n\t self.callbackRequired('Kuzzle.whoAmI', callback);\n\t\n\t self.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, function (err, response) {\n\t if (err) {\n\t return callback(err);\n\t }\n\t\n\t callback(null, new KuzzleUser(self.security, response.result._id, response.result._source));\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'}, {}, null, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, 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 */\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 setTimeout(function () {\n\t cleanHistory(requestHistory);\n\t }, 1000);\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 if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n\t self.jwtToken = undefined;\n\t self.emitEvent('jwtTokenExpired', request, cb);\n\t }\n\t\n\t cb && cb(response.error, response);\n\t });\n\t }\n\t\n\t this.network.send(request);\n\t\n\t // Track requests made to allow KuzzleRoom.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 * 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 * The ID returned by this function is required to remove this listener at a later time.\n\t *\n\t * @param {string} event - name of the global event to subscribe to (see the 'eventListeners' object property)\n\t * @param {function} listener - callback to invoke each time an event is fired\n\t * @returns {string} Unique listener ID\n\t */\n\tKuzzle.prototype.addListener = function(event, listener) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t listenerType = typeof listener,\n\t listenerId;\n\t\n\t this.isValid();\n\t\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\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 listenerId = uuid.v4();\n\t this.eventListeners[event].listeners.push({id: listenerId, fn: listener});\n\t return listenerId;\n\t};\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 * @returns {object} this\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:'admin', action: 'getAllStats'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, 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 * @returns {object} this\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: 'admin', action: timestamp ? 'getStats' : 'getLastStats'}, body, options, queryCB);\n\t};\n\t\n\t/**\n\t * Create a new instance of a KuzzleDataCollection 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 {object} A KuzzleDataCollection instance\n\t */\n\tKuzzle.prototype.dataCollectionFactory = 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 KuzzleDataCollection(this, index, collection);\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 * @returns {object} this\n\t */\n\tKuzzle.prototype.listCollections = function () {\n\t var\n\t collectionType = 'all',\n\t index,\n\t options,\n\t cb,\n\t args = Array.prototype.slice.call(arguments);\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 if (options && options.type) {\n\t collectionType = options.type;\n\t }\n\t\n\t this.query({index: index, controller: 'read', action: 'listCollections'}, {body: {type: collectionType}}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, 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 * @returns {object} this\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: 'read', action: 'listIndexes'}, {}, 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 this.logout();\n\t\n\t this.state = 'disconnected';\n\t this.network.close();\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 * @returns {object} this\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: 'read', action: 'serverInfo'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, 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: 'admin', action: 'refreshIndex'}, {}, 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 * @returns {object} this\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: 'admin', 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: 'admin', 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 * @returns {object} this\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: 'read', action: 'now'}, {}, options, function (err, res) {\n\t cb(err, res && 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 * - metadata (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 metadata: this.metadata\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.metadata) {\n\t Object.keys(options.metadata).forEach(function (meta) {\n\t object.metadata[meta] = options.metadata[meta];\n\t });\n\t }\n\t\n\t if (options.queuable === false && self.state === 'offline') {\n\t return self;\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.metadata) {\n\t Object.keys(query.metadata).forEach(function (meta) {\n\t object.metadata[meta] = query.metadata[meta];\n\t });\n\t }\n\t\n\t for (attr in query) {\n\t if (attr !== 'metadata' && 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.headers = object.headers || {};\n\t object.headers.authorization = 'Bearer ' + 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 = uuid.v4();\n\t }\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 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 } else if (self.queuing || ['initializing', 'connecting'].indexOf(self.state) !== -1) {\n\t cleanQueue.call(this, object, cb);\n\t\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 }\n\t }\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Removes all listeners, either from a specific event or from all events\n\t *\n\t * @param {string} event - One of the event described in the Event Handling section of this documentation\n\t */\n\tKuzzle.prototype.removeAllListeners = function (event) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t self = this;\n\t\n\t if (event) {\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n\t }\n\t\n\t this.eventListeners[event].listeners = [];\n\t } else {\n\t knownEvents.forEach(function (eventName) {\n\t self.eventListeners[eventName].listeners = [];\n\t });\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Removes a listener from an event.\n\t *\n\t * @param {string} event - One of the event described in the Event Handling section of this documentation\n\t * @param {string} listenerId - The ID returned by addListener\n\t */\n\tKuzzle.prototype.removeListener = function (event, listenerId) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t self = this;\n\t\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n\t }\n\t\n\t this.eventListeners[event].listeners.forEach(function (listener, index) {\n\t if (listener.id === listenerId) {\n\t self.eventListeners[event].listeners.splice(index, 1);\n\t }\n\t });\n\t\n\t return this;\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\n\n/***/ },\n/* 1 */\n/***/ function(module, exports) {\n\n\tfunction KuzzleSecurityDocument(kuzzleSecurity, id, content) {\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: kuzzleSecurity.kuzzle\n\t },\n\t kuzzleSecurity: {\n\t value: kuzzleSecurity\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 });\n\t\n\t if (content) {\n\t this.setContent(content, true);\n\t }\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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 {Object} this\n\t */\n\tKuzzleSecurityDocument.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\tKuzzleSecurityDocument.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\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\tKuzzleSecurityDocument.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.kuzzleSecurity.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 */\n\tKuzzleSecurityDocument.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.kuzzleSecurity.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 = KuzzleSecurityDocument;\n\n/***/ },\n/* 2 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleUser(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 });\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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\tKuzzleUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleUser\n\t }\n\t});\n\t\n\t/**\n\t * Set profiles in content\n\t * @param {array} profile - an array of profiles ids string\n\t *\n\t * @returns {KuzzleUser} this\n\t */\n\tKuzzleUser.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 * Add a profile\n\t * @param {string} profile - a profile ids string\n\t *\n\t * @returns {KuzzleUser} this\n\t */\n\tKuzzleUser.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 * Saves this user into Kuzzle.\n\t *\n\t * If this is a new user, this function will create it in Kuzzle.\n\t * Otherwise, this method will replace the latest version of this user in Kuzzle by the current content\n\t * of this object.\n\t *\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @param {object} [options] - Optional parameters\n\t * @returns {*} this\n\t */\n\tKuzzleUser.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.kuzzleSecurity.buildQueryArgs('createOrReplaceUser'), 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\tKuzzleUser.prototype.serialize = function () {\n\t return {_id: this.id, body: this.content};\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\tKuzzleUser.prototype.getProfiles = function () {\n\t return this.content.profileIds;\n\t};\n\t\n\tmodule.exports = KuzzleUser;\n\n\n/***/ },\n/* 3 */\n/***/ function(module, exports) {\n\n\t// uuid.js\n\t//\n\t// Copyright (c) 2010-2012 Robert Kieffer\n\t// MIT License - http://opensource.org/licenses/mit-license.php\n\t\n\t/*global window, require, define */\n\t(function(_window) {\n\t 'use strict';\n\t\n\t // Unique ID creation requires a high quality random # generator. We feature\n\t // detect to determine the best RNG source, normalizing to a function that\n\t // returns 128-bits of randomness, since that's what's usually required\n\t var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot;\n\t\n\t function setupBrowser() {\n\t // Allow for MSIE11 msCrypto\n\t var _crypto = _window.crypto || _window.msCrypto;\n\t\n\t if (!_rng && _crypto && _crypto.getRandomValues) {\n\t // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto\n\t //\n\t // Moderately fast, high quality\n\t try {\n\t var _rnds8 = new Uint8Array(16);\n\t _whatwgRNG = _rng = function whatwgRNG() {\n\t _crypto.getRandomValues(_rnds8);\n\t return _rnds8;\n\t };\n\t _rng();\n\t } catch(e) {}\n\t }\n\t\n\t if (!_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 _mathRNG = _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 if ('undefined' !== typeof console && console.warn) {\n\t console.warn(\"[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()\");\n\t }\n\t }\n\t }\n\t\n\t function setupNode() {\n\t // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html\n\t //\n\t // Moderately fast, high quality\n\t if ('function' === typeof require) {\n\t try {\n\t var _rb = require('crypto').randomBytes;\n\t _nodeRNG = _rng = _rb && function() {return _rb(16);};\n\t _rng();\n\t } catch(e) {}\n\t }\n\t }\n\t\n\t if (_window) {\n\t setupBrowser();\n\t } else {\n\t setupNode();\n\t }\n\t\n\t // Buffer class to use\n\t var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;\n\t\n\t // Maps for number <-> hex string conversion\n\t var _byteToHex = [];\n\t var _hexToByte = {};\n\t for (var i = 0; i < 256; i++) {\n\t _byteToHex[i] = (i + 0x100).toString(16).substr(1);\n\t _hexToByte[_byteToHex[i]] = i;\n\t }\n\t\n\t // **`parse()` - Parse a UUID into it's component bytes**\n\t function parse(s, buf, offset) {\n\t var i = (buf && offset) || 0, ii = 0;\n\t\n\t buf = buf || [];\n\t s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {\n\t if (ii < 16) { // Don't overflow!\n\t buf[i + ii++] = _hexToByte[oct];\n\t }\n\t });\n\t\n\t // Zero out remaining bytes if string was short\n\t while (ii < 16) {\n\t buf[i + ii++] = 0;\n\t }\n\t\n\t return buf;\n\t }\n\t\n\t // **`unparse()` - Convert UUID byte array (ala parse()) into a string**\n\t function unparse(buf, offset) {\n\t var i = offset || 0, 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\t // **`v1()` - Generate time-based UUID**\n\t //\n\t // Inspired by https://github.com/LiosK/UUID.js\n\t // and http://docs.python.org/library/uuid.html\n\t\n\t // random #'s we need to init node and clockseq\n\t var _seedBytes = _rng();\n\t\n\t // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n\t var _nodeId = [\n\t _seedBytes[0] | 0x01,\n\t _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]\n\t ];\n\t\n\t // Per 4.2.2, randomize (14 bit) clockseq\n\t var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;\n\t\n\t // Previous uuid creation time\n\t var _lastMSecs = 0, _lastNSecs = 0;\n\t\n\t // See https://github.com/broofa/node-uuid for API details\n\t function v1(options, buf, offset) {\n\t var i = buf && offset || 0;\n\t var b = buf || [];\n\t\n\t options = options || {};\n\t\n\t var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;\n\t\n\t // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n\t // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n\t // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n\t // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\t var msecs = (options.msecs != null) ? options.msecs : new Date().getTime();\n\t\n\t // Per 4.2.1.2, use count of uuid's generated during the current clock\n\t // cycle to simulate higher resolution clock\n\t var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;\n\t\n\t // Time since last uuid creation (in msecs)\n\t var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\t\n\t // Per 4.2.1.2, Bump clockseq on clock regression\n\t if (dt < 0 && options.clockseq == null) {\n\t clockseq = clockseq + 1 & 0x3fff;\n\t }\n\t\n\t // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n\t // time interval\n\t if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {\n\t nsecs = 0;\n\t }\n\t\n\t // Per 4.2.1.2 Throw error if too many uuids are requested\n\t if (nsecs >= 10000) {\n\t throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n\t }\n\t\n\t _lastMSecs = msecs;\n\t _lastNSecs = nsecs;\n\t _clockseq = clockseq;\n\t\n\t // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\t msecs += 12219292800000;\n\t\n\t // `time_low`\n\t var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n\t b[i++] = tl >>> 24 & 0xff;\n\t b[i++] = tl >>> 16 & 0xff;\n\t b[i++] = tl >>> 8 & 0xff;\n\t b[i++] = tl & 0xff;\n\t\n\t // `time_mid`\n\t var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n\t b[i++] = tmh >>> 8 & 0xff;\n\t b[i++] = tmh & 0xff;\n\t\n\t // `time_high_and_version`\n\t b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\t b[i++] = tmh >>> 16 & 0xff;\n\t\n\t // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\t b[i++] = clockseq >>> 8 | 0x80;\n\t\n\t // `clock_seq_low`\n\t b[i++] = clockseq & 0xff;\n\t\n\t // `node`\n\t var node = options.node || _nodeId;\n\t for (var n = 0; n < 6; n++) {\n\t b[i + n] = node[n];\n\t }\n\t\n\t return buf ? buf : unparse(b);\n\t }\n\t\n\t // **`v4()` - Generate random UUID**\n\t\n\t // See https://github.com/broofa/node-uuid for API details\n\t function v4(options, buf, offset) {\n\t // Deprecated - 'format' argument, as supported in v1.2\n\t var i = buf && offset || 0;\n\t\n\t if (typeof(options) === 'string') {\n\t buf = (options === 'binary') ? new BufferClass(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 || unparse(rnds);\n\t }\n\t\n\t // Export public API\n\t var uuid = v4;\n\t uuid.v1 = v1;\n\t uuid.v4 = v4;\n\t uuid.parse = parse;\n\t uuid.unparse = unparse;\n\t uuid.BufferClass = BufferClass;\n\t uuid._rng = _rng;\n\t uuid._mathRNG = _mathRNG;\n\t uuid._nodeRNG = _nodeRNG;\n\t uuid._whatwgRNG = _whatwgRNG;\n\t\n\t if (('undefined' !== typeof module) && module.exports) {\n\t // Publish as node.js module\n\t module.exports = uuid;\n\t } else if (typeof define === 'function' && define.amd) {\n\t // Publish as AMD module\n\t define(function() {return uuid;});\n\t\n\t\n\t } else {\n\t // Publish as global (in browsers)\n\t _previousRoot = _window.uuid;\n\t\n\t // **`noConflict()` - (browser only) to reset global 'uuid' var**\n\t uuid.noConflict = function() {\n\t _window.uuid = _previousRoot;\n\t return uuid;\n\t };\n\t\n\t _window.uuid = uuid;\n\t }\n\t})('undefined' !== typeof window ? window : null);\n\n\n/***/ },\n/* 4 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleDocument = __webpack_require__(6),\n\t KuzzleDataMapping = __webpack_require__(5),\n\t KuzzleRoom = __webpack_require__(8);\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 * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @param {string} index - Index containing the data collection\n\t * @param {string} collection - name of the data collection to handle\n\t * @constructor\n\t */\n\tfunction KuzzleDataCollection(kuzzle, index, collection) {\n\t if (!index || !collection) {\n\t throw new Error('The KuzzleDataCollection object constructor needs an index and a collection arguments');\n\t }\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 * 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 * @returns {Object} this\n\t */\n\tKuzzleDataCollection.prototype.advancedSearch = 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 = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleDataCollection.advancedSearch', cb);\n\t\n\t query = self.kuzzle.addHeaders({body: filters}, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('read', '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 KuzzleDocument(self, doc._id, doc._source);\n\t\n\t newDocument.version = doc._version;\n\t\n\t documents.push(newDocument);\n\t });\n\t\n\t cb(null, { total: result.result.total, documents: documents });\n\t });\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 * @returns {Object} this\n\t */\n\tKuzzleDataCollection.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('KuzzleDataCollection.count', cb);\n\t\n\t query = this.kuzzle.addHeaders({body: filters}, this.headers);\n\t\n\t this.kuzzle.query(this.buildQueryArgs('read', 'count'), query, options, function (error, result) {\n\t cb(error, result && result.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\tKuzzleDataCollection.prototype.create = 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('write', 'createCollection'), data, options, cb);\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 * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t * - updateIfExist (boolean, default: false):\n\t * If the same document already exists: throw an error if sets to false.\n\t * Update the existing document otherwise\n\t *\n\t * @param {string} [id] - (optional) document identifier\n\t * @param {object} document - either an instance of a KuzzleDocument 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\tKuzzleDataCollection.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 KuzzleDocument) {\n\t data = document.serialize();\n\t } else {\n\t data.body = document;\n\t }\n\t\n\t if (options) {\n\t action = options.updateIfExist ? 'createOrReplace' : 'create';\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('write', 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 KuzzleDocument(self, res.result._id, res.result._source);\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 * - metadata (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 {Object} this\n\t */\n\tKuzzleDataCollection.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 = 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('write', action), data, options, cb && function (err, res) {\n\t var result = action === 'delete' ? [res.result._id] : res.result.ids;\n\t cb(err, err ? undefined : result);\n\t });\n\t\n\t return this;\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 * @returns {Object} this\n\t */\n\tKuzzleDataCollection.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('KuzzleDataCollection.fetch', cb);\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('read', '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 KuzzleDocument(self, res.result._id, res.result._source);\n\t document.version = res.result._version;\n\t cb(null, document);\n\t });\n\t};\n\t\n\t/**\n\t * Retrieves all documents stored in this data collection\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t * @returns {Object} this\n\t */\n\tKuzzleDataCollection.prototype.fetchAllDocuments = function (options, cb) {\n\t var filters = {};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t // copying pagination options to the search filter\n\t if (options) {\n\t if (options.from) {\n\t filters.from = options.from;\n\t }\n\t\n\t if (options.size) {\n\t filters.size = options.size;\n\t }\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDataCollection.fetchAll', cb);\n\t\n\t this.advancedSearch(filters, options, cb);\n\t};\n\t\n\t\n\t/**\n\t * Instantiates a KuzzleDataMapping 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 KuzzleDataMapping object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.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('KuzzleDataCollection.getMapping', cb);\n\t\n\t kuzzleMapping = new KuzzleDataMapping(this);\n\t kuzzleMapping.refresh(options, cb);\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 * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} document - either a KuzzleDocument 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\tKuzzleDataCollection.prototype.publishMessage = function (document, options, cb) {\n\t var data = {};\n\t\n\t if (document instanceof KuzzleDocument) {\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('write', '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 * - metadata (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 KuzzleDocument object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.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('write', '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 KuzzleDocument(self, res.result._id, res.result._source);\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 * 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 {*} KuzzleRoom object\n\t */\n\tKuzzleDataCollection.prototype.subscribe = function (filters, options, cb) {\n\t var room;\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('KuzzleDataCollection.subscribe', cb);\n\t\n\t room = new KuzzleRoom(this, options);\n\t room.renew(filters, cb);\n\t\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\tKuzzleDataCollection.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('admin', 'truncateCollection'), 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 * - metadata (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 KuzzleDocument object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n\t var\n\t 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 data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options, cb && function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t (new KuzzleDocument(self, res.result._id)).refresh(cb);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t\n\t/**\n\t * Instantiate a new KuzzleDocument 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\tKuzzleDataCollection.prototype.documentFactory = function (id, content) {\n\t return new KuzzleDocument(this, id, content);\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleRoom 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\tKuzzleDataCollection.prototype.roomFactory = function (options) {\n\t return new KuzzleRoom(this, options);\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleDataMapping 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 KuzzleDataMapping object with\n\t * @constructor\n\t */\n\tKuzzleDataCollection.prototype.dataMappingFactory = function (mapping) {\n\t return new KuzzleDataMapping(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\tKuzzleDataCollection.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 = KuzzleDataCollection;\n\n\n/***/ },\n/* 5 */\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 KuzzleDataMapping object allow to get the current mapping of a data collection and to modify it if needed.\n\t *\n\t * @param {object} kuzzleDataCollection - Instance of the inherited KuzzleDataCollection object\n\t * @param {object} mapping - mappings\n\t * @constructor\n\t */\n\tfunction KuzzleDataMapping(kuzzleDataCollection, mapping) {\n\t Object.defineProperties(this, {\n\t //read-only properties\n\t collection: {\n\t value: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzleDataCollection.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\tKuzzleDataMapping.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('admin', '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\tKuzzleDataMapping.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('admin', '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 {KuzzleDataMapping}\n\t */\n\tKuzzleDataMapping.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\tKuzzleDataMapping.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 = KuzzleDataMapping;\n\n\n/***/ },\n/* 6 */\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 * KuzzleDocument 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 {object} kuzzleDataCollection - an instanciated KuzzleDataCollection 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 * @constructor\n\t */\n\tfunction KuzzleDocument(kuzzleDataCollection, documentId, content) {\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t collection: {\n\t value: kuzzleDataCollection.collection,\n\t enumerable: true\n\t },\n\t dataCollection: {\n\t value: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.kuzzle,\n\t enumerable: true\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(kuzzleDataCollection.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 });\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\tKuzzleDocument.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._version = this.version;\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\tKuzzleDocument.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 * - metadata (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\tKuzzleDocument.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('KuzzleDocument.delete: cannot delete a document without a document ID');\n\t }\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('write', '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 * 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\tKuzzleDocument.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('KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided');\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDocument.refresh', cb);\n\t\n\t self.kuzzle.query(self.dataCollection.buildQueryArgs('read', '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 KuzzleDocument(self.dataCollection, self.id, res.result._source);\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 * - metadata (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\tKuzzleDocument.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('write', '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 * - metadata (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\tKuzzleDocument.prototype.publish = function (options) {\n\t var data = this.serialize();\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('write', '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\tKuzzleDocument.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\tKuzzleDocument.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('KuzzleDocument.subscribe', cb);\n\t\n\t if (!this.id) {\n\t throw new Error('KuzzleDocument.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\tKuzzleDocument.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 = KuzzleDocument;\n\n\n/***/ },\n/* 7 */\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 * 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), excepting:\n\t * * all cluster based functions\n\t * * all script based functions\n\t * * all cursors functions\n\t *\n\t * For instance:\n\t * kuzzle.memoryStorage\n\t * .set('myKey', 'myValue')\n\t * .get('myKey', function (err, response) {\n\t * console.log(response.result);\n\t *\n\t * // { _id: 'foo', body: { value: 'myValue' }}\n\t * });\n\t *\n\t *\n\t * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @constructor\n\t */\n\tfunction KuzzleMemoryStorage(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\n\t/**\n\t * constructs the memoryStorage functions.\n\t */\n\t(function() {\n\t\n\t var\n\t keyVal = ['id', 'value'],\n\t idOrKeys = ['id', 'keys'],\n\t commands = {\n\t append: keyVal,\n\t bgrewriteaof: [],\n\t bgsave: [],\n\t bitcount: ['id', 'start', 'end'],\n\t bitop: ['operation', 'destkey', idOrKeys],\n\t bitpos: ['id', 'bit', { __opts__: ['start', 'end']}],\n\t blpop: [idOrKeys, 'timeout'],\n\t brpoplpush: ['source', 'destination'],\n\t dbsize: [],\n\t decrby: keyVal,\n\t del: [idOrKeys],\n\t discard: [],\n\t exec: [],\n\t exists: [idOrKeys],\n\t expire: ['id', 'seconds'],\n\t expireat: ['id', 'timestamp'],\n\t flushdb: [],\n\t // @todo: implement geolocation methods once available in Redis stable release\n\t getbit: ['id', 'offset'],\n\t getrange: ['id', 'start', 'end'],\n\t hdel: ['id', ['field', 'fields']],\n\t hexists: ['id', 'field'],\n\t hincrby: ['id', 'field', 'value'],\n\t hmset: ['id', 'values'],\n\t hset: ['id', 'field', 'value'],\n\t info: ['section'],\n\t keys: [ 'pattern' ],\n\t lastsave: [],\n\t lindex: ['id', 'idx'],\n\t linsert: ['id', 'position', 'pivot', 'value'],\n\t lpush: ['id', ['value', 'values']],\n\t lrange: ['id', 'start', 'stop'],\n\t lrem: ['id', 'count', 'value'],\n\t lset: ['id', 'idx', 'value'],\n\t ltrim: ['id', 'start', 'stop'],\n\t mset: ['values'],\n\t multi: [],\n\t object: ['subcommand', 'args'],\n\t pexpire: ['id', 'milliseconds'],\n\t pexpireat: ['id', 'timestamp'],\n\t pfadd: ['id', ['element', 'elements']],\n\t pfmerge: ['destkey', ['sourcekey', 'sourcekeys']],\n\t ping: [],\n\t psetex: ['id', 'milliseconds', 'value'],\n\t publish: ['channel', 'message'],\n\t randomkey: [],\n\t rename: ['id', 'newkey'],\n\t renamenx: ['id', 'newkey'],\n\t restore: ['id', 'ttl', 'content'],\n\t rpoplpush: ['source', 'destination'],\n\t sadd: ['id', ['member', 'members']],\n\t save: [],\n\t set: ['id', 'value', {__opts__:['ex', 'px', 'nx', 'xx']}],\n\t sdiffstore: ['destination', idOrKeys],\n\t setbit: ['id', 'offset', 'value'],\n\t setex: ['id', 'seconds', 'value'],\n\t setrange: ['id', 'offset', 'value'],\n\t sinterstore: ['destination', idOrKeys],\n\t sismember: ['id', 'member'],\n\t smove: ['id', 'destination', 'member'],\n\t sort: ['id', {__opts__:['by', 'offset', 'count', 'get', 'direction', 'alpha', 'store']}],\n\t spop: ['id', 'count'],\n\t srem: ['id', ['member', 'members']],\n\t sunionstore: ['destination', idOrKeys],\n\t unwatch: [],\n\t wait: ['numslaves', 'timeout'],\n\t zadd: ['id', {__opts__: ['nx', 'xx', 'ch', 'incr', 'score', 'member', 'members']}],\n\t zcount: ['id', 'min', 'max'],\n\t zincrby: ['id', 'value', 'member'],\n\t zinterstore: ['destination', idOrKeys, {__opts__: ['weight', 'weights', 'aggregate']}],\n\t zlexcount: ['id', 'min', 'max'],\n\t zrange: ['id', 'start', 'stop', {__opts__: ['withscores']}],\n\t zrangebylex: ['id', 'min', 'max', {__opts__: ['offset', 'count']}],\n\t zrangebyscore: ['id', 'min', 'max', {__opts__: ['withscores', 'offset', 'count']}],\n\t zrem: ['id', 'member'],\n\t zremrangebylex: ['id', 'min', 'max'],\n\t zremrangebyscore: ['id', 'min', 'max'],\n\t zrevrangebylex: ['id', 'max', 'min', {__opts__: ['offset', 'count']}],\n\t zrevrangebyscore: ['id', 'max', 'min', {__opts__: ['withscores', 'offset', 'count']}],\n\t zrevrank: ['id', 'member']\n\t };\n\t\n\t // unique argument key\n\t commands.decr = commands.get = commands.dump = commands.hgetall = commands.hkeys = commands.hlen = commands.hstrlen = commands.hvals = commands.incr = commands.llen = commands.lpop = commands.persist = commands.pttl = commands.rpop = commands.scard = commands.smembers = commands.strlen = commands.ttl = commands.type = commands.zcard = ['id'];\n\t\n\t // key value\n\t commands.getset = commands.lpushx = keyVal;\n\t\n\t // key key...\n\t commands.del = commands.exists = commands.mget = commands.pfcount = commands.sdiff = commands.sinter = commands.sunion = commands.watch = [idOrKeys];\n\t\n\t commands.incrby = commands.incrbyfloat = commands.decrby;\n\t commands.brpop = commands.blpop;\n\t commands.hget = commands.hexists;\n\t commands.hmget = commands.hdel;\n\t commands.hsetnx = commands.hset;\n\t commands.msetnx = commands.mset;\n\t commands.rpush = commands.lpush;\n\t commands.hincrbyfloat = commands.hincrby;\n\t commands.srandmember = commands.spop;\n\t commands.zrevrange = commands.zrange;\n\t commands.zscore = commands.zrevrank;\n\t\n\t Object.keys(commands).forEach(function (command) {\n\t KuzzleMemoryStorage.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 (typeof args[args.length - 1] === 'function') {\n\t cb = args.pop();\n\t }\n\t\n\t if (args.length && typeof args[args.length - 1] === 'object' && Object.keys(args[args.length - 1]).length === 1 && args[args.length - 1].queuable !== undefined) {\n\t options = args.pop();\n\t }\n\t\n\t commands[command].forEach(function (v, i) {\n\t if (args[i] === undefined) {\n\t return;\n\t }\n\t\n\t if (Array.isArray(v)) {\n\t v = Array.isArray(args[i]) ? v[1] : v[0];\n\t }\n\t\n\t if (v === 'id') {\n\t data._id = args[i];\n\t }\n\t else {\n\t if (!data.body) {\n\t data.body = {};\n\t }\n\t\n\t if (typeof v === 'object' && v.__opts__ !== undefined) {\n\t v.__opts__.forEach(function (arg) {\n\t if (args[i][arg] !== undefined) {\n\t data.body[arg] = args[i][arg];\n\t }\n\t });\n\t }\n\t else {\n\t data.body[v] = args[i];\n\t }\n\t }\n\t });\n\t\n\t this.kuzzle.query(query, data, options, cb);\n\t\n\t return this;\n\t\n\t };\n\t });\n\t\n\t})();\n\t\n\tmodule.exports = KuzzleMemoryStorage;\n\n\n/***/ },\n/* 8 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t uuid = __webpack_require__(3);\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} kuzzleDataCollection - an instantiated and valid kuzzle object\n\t * @param {object} [options] - subscription optional configuration\n\t * @constructor\n\t */\n\tfunction KuzzleRoom(kuzzleDataCollection, 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: uuid.v4()\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 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: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.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(kuzzleDataCollection.headers)),\n\t enumerable: true,\n\t writable: true\n\t },\n\t metadata: {\n\t value: (options && options.metadata) ? options.metadata : {},\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\tKuzzleRoom.prototype.count = function (cb) {\n\t var data;\n\t\n\t this.kuzzle.callbackRequired('KuzzleRoom.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('KuzzleRoom.count: cannot count subscriptions on an inactive room');\n\t }\n\t\n\t this.kuzzle.query(this.collection.buildQueryArgs('subscribe', '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} cb - called for each new notification\n\t */\n\tKuzzleRoom.prototype.renew = function (filters, cb) {\n\t var\n\t now = Date.now(),\n\t subscribeQuery = {\n\t scope: this.scope,\n\t state: this.state,\n\t users: this.users\n\t },\n\t self = this;\n\t\n\t if (!cb && filters && typeof filters === 'function') {\n\t cb = filters;\n\t filters = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleRoom.renew', cb);\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;\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 = 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, 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 = 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, this.headers);\n\t\n\t self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'on'), subscribeQuery, {metadata: self.metadata}, 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 throw 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 });\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\tKuzzleRoom.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('subscribe', 'off'), {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('subscribe', 'off'), {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\tKuzzleRoom.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.error) {\n\t return this.callback(data.error);\n\t }\n\t\n\t if (data.action === 'jwtTokenExpired') {\n\t this.kuzzle.jwtToken = undefined;\n\t return this.kuzzle.emitEvent('jwtTokenExpired');\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 = KuzzleRoom;\n\n\n/***/ },\n/* 9 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/**\n\t *\n\t * @param host\n\t * @param wsPort\n\t * @param ioPort\n\t * @returns {Object} tnstantiated WebSocket/Socket.IO object\n\t */\n\t\n\tfunction network(host, wsPort, ioPort, 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__(11))(host, wsPort, sslConnection);\n\t }\n\t // otherwise fallback to socket.io, if available\n\t else if (window.io) {\n\t return new (__webpack_require__(10))(host, ioPort, 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__(!(function webpackMissingModule() { var e = new Error(\"Cannot find module \\\"./wrappers/wsnode\\\"\"); e.code = 'MODULE_NOT_FOUND'; throw e; }())))(host, wsPort, sslConnection);\n\t}\n\t\n\tmodule.exports = network;\n\n\n/***/ },\n/* 10 */\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\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 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\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.socket.on('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.socket.on('connect_error', 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.socket.on('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.socket.on('reconnect', callback);\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.socket.close();\n\t this.socket = null;\n\t };\n\t}\n\t\n\tmodule.exports = SocketIO;\n\n\n/***/ },\n/* 11 */\n/***/ function(module, exports) {\n\n\tfunction WSBrowsers(host, port, ssl) {\n\t var self = this;\n\t this.host = host;\n\t this.port = port;\n\t this.ssl = ssl;\n\t this.client = null;\n\t this.retrying = false;\n\t\n\t /*\n\t Listeners are stored using the following format:\n\t roomId: {\n\t fn: callback_function,\n\t once: boolean\n\t }\n\t */\n\t this.listeners = {\n\t error: [],\n\t connect: [],\n\t disconnect: [],\n\t reconnect: []\n\t };\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 this.client = new WebSocket((this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port);\n\t\n\t this.client.onopen = function () {\n\t if (self.retrying) {\n\t poke(self.listeners, 'reconnect');\n\t }\n\t else {\n\t poke(self.listeners, 'connect');\n\t }\n\t };\n\t\n\t this.client.onclose = function () {\n\t poke(self.listeners, 'disconnect');\n\t };\n\t\n\t this.client.onerror = function () {\n\t if (autoReconnect) {\n\t self.retrying = true;\n\t setTimeout(function () {\n\t self.connect(autoReconnect, reconnectionDelay);\n\t }, reconnectionDelay);\n\t }\n\t\n\t poke(self.listeners, 'error');\n\t };\n\t\n\t this.client.onmessage = function (payload) {\n\t var data = JSON.parse(payload.data);\n\t\n\t if (data.room && self.listeners[data.room]) {\n\t poke(self.listeners, data.room, 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.listeners.connect.push({\n\t fn: callback,\n\t keep: true\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 this.listeners.error.push({\n\t fn: callback,\n\t keep: true\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 this.listeners.disconnect.push({\n\t fn: callback,\n\t keep: true\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 this.listeners.reconnect.push({\n\t fn: callback,\n\t keep: true\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 if (!this.listeners[roomId]) {\n\t this.listeners[roomId] = [];\n\t }\n\t\n\t this.listeners[roomId].push({\n\t fn: callback,\n\t keep: false\n\t });\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 if (!this.listeners[roomId]) {\n\t this.listeners[roomId] = [];\n\t }\n\t\n\t this.listeners[roomId].push({\n\t fn: callback,\n\t keep: true\n\t });\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 var index;\n\t\n\t if (this.listeners[roomId]) {\n\t index = this.listeners[roomId].findIndex(function (listener) {\n\t return listener.fn === callback;\n\t });\n\t\n\t if (index !== -1) {\n\t if (this.listeners[roomId].length === 1 && ['error', 'connect', 'disconnect', 'reconnect'].indexOf(roomId) === -1) {\n\t delete this.listeners[roomId];\n\t }\n\t else {\n\t this.listeners[roomId].splice(index, 1);\n\t }\n\t }\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 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.listeners = {\n\t error: [],\n\t connect: [],\n\t disconnect: [],\n\t reconnect: []\n\t };\n\t\n\t this.retrying = false;\n\t this.client.close();\n\t this.client = null;\n\t };\n\t}\n\t\n\t/**\n\t * Executes all registered listeners in the provided\n\t * \"listeners\" structure.\n\t *\n\t * Listeners are of the following format:\n\t * [\n\t * { fn: callback, once: boolean },\n\t * ...\n\t * ]\n\t *\n\t * @private\n\t * @param {Object} listeners\n\t * @param {string} roomId\n\t * @param {Object} [payload]\n\t */\n\tfunction poke (listeners, roomId, payload) {\n\t var\n\t i,\n\t length = listeners[roomId].length;\n\t\n\t for (i = 0; i < length; ++i) {\n\t listeners[roomId][i].fn(payload);\n\t\n\t if (!listeners[roomId][i].keep) {\n\t if (listeners[roomId].length > 1) {\n\t listeners[roomId].splice(i, 1);\n\t --i;\n\t --length;\n\t }\n\t else {\n\t delete listeners[roomId];\n\t }\n\t }\n\t }\n\t}\n\t\n\tmodule.exports = WSBrowsers;\n\n\n/***/ },\n/* 12 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleProfile(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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\tKuzzleProfile.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleProfile\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 {Object} this\n\t */\n\tKuzzleProfile.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.kuzzleSecurity.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 {KuzzleProfile} this\n\t */\n\tKuzzleProfile.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 {KuzzleProfile} this\n\t */\n\tKuzzleProfile.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\tKuzzleProfile.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\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\tKuzzleProfile.prototype.getPolicies = function () {\n\t return this.content.policies;\n\t};\n\t\n\tmodule.exports = KuzzleProfile;\n\n\n/***/ },\n/* 13 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleRole(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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\tKuzzleRole.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleRole\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 */\n\tKuzzleRole.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.kuzzleSecurity.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 = KuzzleRole;\n\n/***/ },\n/* 14 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleRole = __webpack_require__(13),\n\t KuzzleProfile = __webpack_require__(12),\n\t KuzzleUser = __webpack_require__(2);\n\t\n\t/**\n\t * Kuzzle security constructor\n\t *\n\t * @param kuzzle\n\t * @returns {KuzzleSecurity}\n\t * @constructor\n\t */\n\tfunction KuzzleSecurity(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 = ['roleFactory', 'profileFactory', 'userFactory', '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} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getRole = 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 getRole 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('KuzzleSecurity.getRole', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n\t cb(err, err ? undefined : new KuzzleRole(self, response.result._id, response.result._source));\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} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t *\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.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 KuzzleRole(self, doc._id, doc._source);\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.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 KuzzleRole(self, res.result._id, res.result._source));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.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) {\n\t cb(err, err ? undefined : new KuzzleRole(self, id, content));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleSecurity.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 KuzzleRole 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 * @constructor\n\t */\n\tKuzzleSecurity.prototype.roleFactory = function(id, content) {\n\t return new KuzzleRole(this, id, content);\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} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getProfile = 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 getProfile function');\n\t }\n\t\n\t\n\t data = {_id: id};\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.getProfile', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n\t cb(error, error ? undefined : new KuzzleProfile(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.searchProfiles', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n\t var documents;\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 KuzzleProfile(self, doc._id, doc._source);\n\t });\n\t\n\t cb(null, { total: response.result.total, profiles: documents });\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 {object} content - attribute `roles` in `content` must only contains an array of role id\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.createProfile = function (id, content, 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('KuzzleSecurity.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 data.body = content;\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 KuzzleProfile(self, res.result._id, res.result._source));\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 {object} content - a plain javascript object representing the profile's modification\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.updateProfile = function (id, content, 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('KuzzleSecurity.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 data.body = content;\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 KuzzleProfile(self, res.result._id, updatedContent));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleSecurity.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 * Instantiate a new KuzzleProfile 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 * @constructor\n\t */\n\tKuzzleSecurity.prototype.profileFactory = function(id, content) {\n\t return new KuzzleProfile(this, id, content);\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} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getUser = 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 getUser 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('KuzzleSecurity.getUser', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n\t cb(err, err ? undefined : new KuzzleUser(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.searchUsers', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n\t var documents;\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 KuzzleUser(self, doc._id, doc._source);\n\t });\n\t\n\t cb(null, { total: response.result.total, users: documents });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new user 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 user already exists: throw an error if sets to false.\n\t * Replace the existing user otherwise\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.createUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {_id: id, body: content},\n\t action = 'createUser';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.createUser: cannot create 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 if (options) {\n\t action = options.replaceIfExist ? 'createOrReplaceUser' : 'createUser';\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, null, cb && function (err, res) {\n\t cb(err, err ? undefined : new KuzzleUser(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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.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 KuzzleUser(self, res.result._id, res.result._source));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleSecurity.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 * Instantiate a new KuzzleUser 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 * @constructor\n\t */\n\tKuzzleSecurity.prototype.userFactory = function(id, content) {\n\t return new KuzzleUser(this, id, content);\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\tKuzzleSecurity.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} [options] - (optional) arguments\n\t * @param {function} cb The callback containing the normalized array of rights.\n\t */\n\tKuzzleSecurity.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\tmodule.exports = KuzzleSecurity;\n\n\n/***/ }\n/******/ ])\n});\n;\n\n\n/** WEBPACK FOOTER **\n ** kuzzle.js\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/** WEBPACK FOOTER **\n ** webpack/bootstrap 122e3b23088699ad9003\n **/","var\n uuid = require('node-uuid'),\n KuzzleDataCollection = require('./kuzzleDataCollection'),\n KuzzleSecurity = require('./security/kuzzleSecurity'),\n KuzzleMemoryStorage = require('./kuzzleMemoryStorage'),\n KuzzleUser = require('./security/kuzzleUser'),\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 * @constructor\n */\nmodule.exports = Kuzzle = function (host, options, cb) {\n var self = this;\n\n if (!(this instanceof Kuzzle)) {\n return new Kuzzle(host, options, cb);\n }\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 collections: {\n value: {},\n writable: true\n },\n connectCB: {\n value: cb\n },\n eventListeners: {\n value: {\n connected: {lastEmitted: null, listeners: []},\n error: {lastEmitted: null, listeners: []},\n disconnected: {lastEmitted: null, listeners: []},\n reconnected: {lastEmitted: null, listeners: []},\n jwtTokenExpired: {lastEmitted: null, listeners: []},\n loginAttempt: {lastEmitted: null, listeners: []},\n offlineQueuePush: {listeners: []},\n offlineQueuePop: {listeners: []}\n }\n },\n eventTimeout: {\n value: 200\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 'roomId': {\n kuzzleRoomID_1: kuzzleRoomInstance_1,\n kuzzleRoomID_2: kuzzleRoomInstance_2,\n kuzzleRoomID_...: 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 // read-only properties\n autoReconnect: {\n value: (options && typeof options.autoReconnect === 'boolean') ? options.autoReconnect : 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 enumerable: true\n },\n host: {\n value: host,\n enumerable: true\n },\n wsPort: {\n value: (options && typeof options.wsPort === 'number') ? options.wsPort : 7513,\n enumerable: true\n },\n ioPort: {\n value: (options && typeof options.ioPort === 'number') ? options.ioPort : 7512,\n enumerable: true\n },\n sslConnection: {\n value: (options && typeof options.sslConnection === 'boolean') ? options.sslConnection : false,\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 metadata: {\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: null,\n enumerable: true,\n writable: true\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 KuzzleSecurity(this),\n enumerable: true\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 Object.defineProperty(this, 'emitEvent', {\n value: function emitEvent(event) {\n var\n now = Date.now(),\n args = Array.prototype.slice.call(arguments, 1),\n eventProperties = this.eventListeners[event];\n\n if (eventProperties.lastEmitted && eventProperties.lastEmitted >= now - this.eventTimeout) {\n return false;\n }\n\n eventProperties.listeners.forEach(function (listener) {\n process.nextTick(function () {\n listener.fn.apply(undefined, args);\n });\n });\n\n // Events without the 'lastEmitted' property can be emitted without minimum time between emissions\n if (eventProperties.lastEmitted !== undefined) {\n eventProperties.lastEmitted = now;\n }\n }\n });\n\n Object.defineProperty(this, 'memoryStorage', {\n value: new KuzzleMemoryStorage(this),\n enumerable: true\n });\n\n\n if (!options || !options.connect || options.connect === 'auto') {\n this.connect();\n } else {\n this.state = 'ready';\n }\n\n cleanHistory(this.requestHistory);\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', 'listIndexes', 'login', 'logout', 'now', 'query',\n 'checkToken', 'whoAmI', 'updateSelf', 'getMyRights',\n 'refreshIndex', 'getAutoRefresh', 'setAutoRefresh'\n ];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n};\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.network = networkWrapper(self.host, self.wsPort, self.ioPort, self.sslConnection);\n }\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.onConnectError(function (error) {\n var connectionError = new Error('Unable to connect to kuzzle server at \"' + self.host + '\"');\n\n connectionError.internal = error;\n self.state = 'error';\n self.emitEvent('error', connectionError);\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('jwtTokenExpired');\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 * 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 * @returns {Kuzzle}\n */\nKuzzle.prototype.login = function (strategy) {\n var\n self = this,\n request = {\n strategy: strategy\n },\n credentials,\n cb = null;\n\n // Handle arguments (credentials, expiresIn, cb)\n if (arguments[1]) {\n if (typeof arguments[1] === 'object') {\n credentials = 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 if (typeof credentials === 'object') {\n Object.keys(credentials).forEach(function (key) {\n request[key] = credentials[key];\n });\n }\n\n this.query({controller: 'auth', action: 'login'}, {body: 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 * 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: uuid.v4(),\n body: {}\n };\n\n this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, typeof cb !== 'function' ? null : function(error) {\n if (error === null) {\n self.jwtToken = undefined;\n cb(null, self);\n }\n else {\n cb(error);\n }\n });\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} callback The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n * @return {Kuzzle} The Kuzzle instance to enable chaining.\n */\nKuzzle.prototype.checkToken = function (token, callback) {\n var\n request = {\n body: {\n token: token\n }\n };\n\n this.callbackRequired('Kuzzle.checkToken', callback);\n\n this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, function (err, response) {\n if (err) {\n return callback(err);\n }\n\n callback(null, response.result);\n });\n};\n\n/**\n * Fetches the current user.\n *\n * @param {function} callback The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n * @return {Kuzzle} The Kuzzle instance to enable chaining.\n */\nKuzzle.prototype.whoAmI = function (callback) {\n var self = this;\n\n self.callbackRequired('Kuzzle.whoAmI', callback);\n\n self.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, function (err, response) {\n if (err) {\n return callback(err);\n }\n\n callback(null, new KuzzleUser(self.security, response.result._id, response.result._source));\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'}, {}, null, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, 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 */\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 setTimeout(function () {\n cleanHistory(requestHistory);\n }, 1000);\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 if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n self.jwtToken = undefined;\n self.emitEvent('jwtTokenExpired', request, cb);\n }\n\n cb && cb(response.error, response);\n });\n }\n\n this.network.send(request);\n\n // Track requests made to allow KuzzleRoom.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 * 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 * The ID returned by this function is required to remove this listener at a later time.\n *\n * @param {string} event - name of the global event to subscribe to (see the 'eventListeners' object property)\n * @param {function} listener - callback to invoke each time an event is fired\n * @returns {string} Unique listener ID\n */\nKuzzle.prototype.addListener = function(event, listener) {\n var\n knownEvents = Object.keys(this.eventListeners),\n listenerType = typeof listener,\n listenerId;\n\n this.isValid();\n\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n if (listenerType !== 'function') {\n throw new Error('Invalid listener type: expected a function, got a ' + listenerType);\n }\n\n listenerId = uuid.v4();\n this.eventListeners[event].listeners.push({id: listenerId, fn: listener});\n return listenerId;\n};\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 * @returns {object} this\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:'admin', action: 'getAllStats'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, 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 * @returns {object} this\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: 'admin', action: timestamp ? 'getStats' : 'getLastStats'}, body, options, queryCB);\n};\n\n/**\n * Create a new instance of a KuzzleDataCollection 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 {object} A KuzzleDataCollection instance\n */\nKuzzle.prototype.dataCollectionFactory = 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 KuzzleDataCollection(this, index, collection);\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 * @returns {object} this\n */\nKuzzle.prototype.listCollections = function () {\n var\n collectionType = 'all',\n index,\n options,\n cb,\n args = Array.prototype.slice.call(arguments);\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 if (options && options.type) {\n collectionType = options.type;\n }\n\n this.query({index: index, controller: 'read', action: 'listCollections'}, {body: {type: collectionType}}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, 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 * @returns {object} this\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: 'read', action: 'listIndexes'}, {}, 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 this.logout();\n\n this.state = 'disconnected';\n this.network.close();\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 * @returns {object} this\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: 'read', action: 'serverInfo'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, 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: 'admin', action: 'refreshIndex'}, {}, 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 * @returns {object} this\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: 'admin', 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: 'admin', 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 * @returns {object} this\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: 'read', action: 'now'}, {}, options, function (err, res) {\n cb(err, res && 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 * - metadata (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 metadata: this.metadata\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.metadata) {\n Object.keys(options.metadata).forEach(function (meta) {\n object.metadata[meta] = options.metadata[meta];\n });\n }\n\n if (options.queuable === false && self.state === 'offline') {\n return self;\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.metadata) {\n Object.keys(query.metadata).forEach(function (meta) {\n object.metadata[meta] = query.metadata[meta];\n });\n }\n\n for (attr in query) {\n if (attr !== 'metadata' && 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.headers = object.headers || {};\n object.headers.authorization = 'Bearer ' + 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 = uuid.v4();\n }\n\n if (self.state === 'connected' || (options && options.queuable === false)) {\n if (self.state === 'connected') {\n emitRequest.call(this, object, cb);\n } else if (cb) {\n cb(new Error('Unable to execute request: not connected to a Kuzzle server.\\nDiscarded request: ' + JSON.stringify(object)));\n }\n } else if (self.queuing || ['initializing', 'connecting'].indexOf(self.state) !== -1) {\n cleanQueue.call(this, object, cb);\n\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 }\n }\n\n return self;\n};\n\n/**\n * Removes all listeners, either from a specific event or from all events\n *\n * @param {string} event - One of the event described in the Event Handling section of this documentation\n */\nKuzzle.prototype.removeAllListeners = function (event) {\n var\n knownEvents = Object.keys(this.eventListeners),\n self = this;\n\n if (event) {\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n this.eventListeners[event].listeners = [];\n } else {\n knownEvents.forEach(function (eventName) {\n self.eventListeners[eventName].listeners = [];\n });\n }\n\n return this;\n};\n\n/**\n * Removes a listener from an event.\n *\n * @param {string} event - One of the event described in the Event Handling section of this documentation\n * @param {string} listenerId - The ID returned by addListener\n */\nKuzzle.prototype.removeListener = function (event, listenerId) {\n var\n knownEvents = Object.keys(this.eventListeners),\n self = this;\n\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n this.eventListeners[event].listeners.forEach(function (listener, index) {\n if (listener.id === listenerId) {\n self.eventListeners[event].listeners.splice(index, 1);\n }\n });\n\n return this;\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\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzle.js\n ** module id = 0\n ** module chunks = 0\n **/","function KuzzleSecurityDocument(kuzzleSecurity, id, content) {\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: kuzzleSecurity.kuzzle\n },\n kuzzleSecurity: {\n value: kuzzleSecurity\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 });\n\n if (content) {\n this.setContent(content, true);\n }\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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 {Object} this\n */\nKuzzleSecurityDocument.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 */\nKuzzleSecurityDocument.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\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 */\nKuzzleSecurityDocument.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.kuzzleSecurity.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 */\nKuzzleSecurityDocument.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.kuzzleSecurity.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 = KuzzleSecurityDocument;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleSecurityDocument.js\n ** module id = 1\n ** module chunks = 0\n **/","var\n KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleUser(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteUser'\n },\n updateActionName: {\n value: 'updateUser'\n }\n });\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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\nKuzzleUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleUser\n }\n});\n\n/**\n * Set profiles in content\n * @param {array} profile - an array of profiles ids string\n *\n * @returns {KuzzleUser} this\n */\nKuzzleUser.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 * Add a profile\n * @param {string} profile - a profile ids string\n *\n * @returns {KuzzleUser} this\n */\nKuzzleUser.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 * Saves this user into Kuzzle.\n *\n * If this is a new user, this function will create it in Kuzzle.\n * Otherwise, this method will replace the latest version of this user in Kuzzle by the current content\n * of this object.\n *\n * @param {responseCallback} [cb] - Handles the query response\n * @param {object} [options] - Optional parameters\n * @returns {*} this\n */\nKuzzleUser.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.kuzzleSecurity.buildQueryArgs('createOrReplaceUser'), 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 */\nKuzzleUser.prototype.serialize = function () {\n return {_id: this.id, body: this.content};\n};\n\n/**\n * Return the associated profiles IDs\n *\n * @return {array} the associated profiles IDs\n */\nKuzzleUser.prototype.getProfiles = function () {\n return this.content.profileIds;\n};\n\nmodule.exports = KuzzleUser;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleUser.js\n ** module id = 2\n ** module chunks = 0\n **/","// uuid.js\n//\n// Copyright (c) 2010-2012 Robert Kieffer\n// MIT License - http://opensource.org/licenses/mit-license.php\n\n/*global window, require, define */\n(function(_window) {\n 'use strict';\n\n // Unique ID creation requires a high quality random # generator. We feature\n // detect to determine the best RNG source, normalizing to a function that\n // returns 128-bits of randomness, since that's what's usually required\n var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot;\n\n function setupBrowser() {\n // Allow for MSIE11 msCrypto\n var _crypto = _window.crypto || _window.msCrypto;\n\n if (!_rng && _crypto && _crypto.getRandomValues) {\n // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto\n //\n // Moderately fast, high quality\n try {\n var _rnds8 = new Uint8Array(16);\n _whatwgRNG = _rng = function whatwgRNG() {\n _crypto.getRandomValues(_rnds8);\n return _rnds8;\n };\n _rng();\n } catch(e) {}\n }\n\n if (!_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 _mathRNG = _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 if ('undefined' !== typeof console && console.warn) {\n console.warn(\"[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()\");\n }\n }\n }\n\n function setupNode() {\n // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html\n //\n // Moderately fast, high quality\n if ('function' === typeof require) {\n try {\n var _rb = require('crypto').randomBytes;\n _nodeRNG = _rng = _rb && function() {return _rb(16);};\n _rng();\n } catch(e) {}\n }\n }\n\n if (_window) {\n setupBrowser();\n } else {\n setupNode();\n }\n\n // Buffer class to use\n var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;\n\n // Maps for number <-> hex string conversion\n var _byteToHex = [];\n var _hexToByte = {};\n for (var i = 0; i < 256; i++) {\n _byteToHex[i] = (i + 0x100).toString(16).substr(1);\n _hexToByte[_byteToHex[i]] = i;\n }\n\n // **`parse()` - Parse a UUID into it's component bytes**\n function parse(s, buf, offset) {\n var i = (buf && offset) || 0, ii = 0;\n\n buf = buf || [];\n s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {\n if (ii < 16) { // Don't overflow!\n buf[i + ii++] = _hexToByte[oct];\n }\n });\n\n // Zero out remaining bytes if string was short\n while (ii < 16) {\n buf[i + ii++] = 0;\n }\n\n return buf;\n }\n\n // **`unparse()` - Convert UUID byte array (ala parse()) into a string**\n function unparse(buf, offset) {\n var i = offset || 0, 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\n // **`v1()` - Generate time-based UUID**\n //\n // Inspired by https://github.com/LiosK/UUID.js\n // and http://docs.python.org/library/uuid.html\n\n // random #'s we need to init node and clockseq\n var _seedBytes = _rng();\n\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n var _nodeId = [\n _seedBytes[0] | 0x01,\n _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]\n ];\n\n // Per 4.2.2, randomize (14 bit) clockseq\n var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;\n\n // Previous uuid creation time\n var _lastMSecs = 0, _lastNSecs = 0;\n\n // See https://github.com/broofa/node-uuid for API details\n function v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || [];\n\n options = options || {};\n\n var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;\n\n // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n var msecs = (options.msecs != null) ? options.msecs : new Date().getTime();\n\n // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;\n\n // Time since last uuid creation (in msecs)\n var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\n // Per 4.2.1.2, Bump clockseq on clock regression\n if (dt < 0 && options.clockseq == null) {\n clockseq = clockseq + 1 & 0x3fff;\n }\n\n // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {\n nsecs = 0;\n }\n\n // Per 4.2.1.2 Throw error if too many uuids are requested\n if (nsecs >= 10000) {\n throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq;\n\n // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n msecs += 12219292800000;\n\n // `time_low`\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff;\n\n // `time_mid`\n var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff;\n\n // `time_high_and_version`\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n b[i++] = tmh >>> 16 & 0xff;\n\n // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n b[i++] = clockseq >>> 8 | 0x80;\n\n // `clock_seq_low`\n b[i++] = clockseq & 0xff;\n\n // `node`\n var node = options.node || _nodeId;\n for (var n = 0; n < 6; n++) {\n b[i + n] = node[n];\n }\n\n return buf ? buf : unparse(b);\n }\n\n // **`v4()` - Generate random UUID**\n\n // See https://github.com/broofa/node-uuid for API details\n function v4(options, buf, offset) {\n // Deprecated - 'format' argument, as supported in v1.2\n var i = buf && offset || 0;\n\n if (typeof(options) === 'string') {\n buf = (options === 'binary') ? new BufferClass(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 || unparse(rnds);\n }\n\n // Export public API\n var uuid = v4;\n uuid.v1 = v1;\n uuid.v4 = v4;\n uuid.parse = parse;\n uuid.unparse = unparse;\n uuid.BufferClass = BufferClass;\n uuid._rng = _rng;\n uuid._mathRNG = _mathRNG;\n uuid._nodeRNG = _nodeRNG;\n uuid._whatwgRNG = _whatwgRNG;\n\n if (('undefined' !== typeof module) && module.exports) {\n // Publish as node.js module\n module.exports = uuid;\n } else if (typeof define === 'function' && define.amd) {\n // Publish as AMD module\n define(function() {return uuid;});\n\n\n } else {\n // Publish as global (in browsers)\n _previousRoot = _window.uuid;\n\n // **`noConflict()` - (browser only) to reset global 'uuid' var**\n uuid.noConflict = function() {\n _window.uuid = _previousRoot;\n return uuid;\n };\n\n _window.uuid = uuid;\n }\n})('undefined' !== typeof window ? window : null);\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/node-uuid/uuid.js\n ** module id = 3\n ** module chunks = 0\n **/","var\n KuzzleDocument = require('./kuzzleDocument'),\n KuzzleDataMapping = require('./kuzzleDataMapping'),\n KuzzleRoom = require('./kuzzleRoom');\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 * @param {object} kuzzle - Kuzzle instance to inherit from\n * @param {string} index - Index containing the data collection\n * @param {string} collection - name of the data collection to handle\n * @constructor\n */\nfunction KuzzleDataCollection(kuzzle, index, collection) {\n if (!index || !collection) {\n throw new Error('The KuzzleDataCollection object constructor needs an index and a collection arguments');\n }\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 * 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 * @returns {Object} this\n */\nKuzzleDataCollection.prototype.advancedSearch = function (filters, options, cb) {\n var\n query,\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleDataCollection.advancedSearch', cb);\n\n query = self.kuzzle.addHeaders({body: filters}, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('read', '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 KuzzleDocument(self, doc._id, doc._source);\n\n newDocument.version = doc._version;\n\n documents.push(newDocument);\n });\n\n cb(null, { total: result.result.total, documents: documents });\n });\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 * @returns {Object} this\n */\nKuzzleDataCollection.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('KuzzleDataCollection.count', cb);\n\n query = this.kuzzle.addHeaders({body: filters}, this.headers);\n\n this.kuzzle.query(this.buildQueryArgs('read', 'count'), query, options, function (error, result) {\n cb(error, result && result.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 */\nKuzzleDataCollection.prototype.create = 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('write', 'createCollection'), data, options, cb);\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 * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n * - updateIfExist (boolean, default: false):\n * If the same document already exists: throw an error if sets to false.\n * Update the existing document otherwise\n *\n * @param {string} [id] - (optional) document identifier\n * @param {object} document - either an instance of a KuzzleDocument object, or a document\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Object} this\n */\nKuzzleDataCollection.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 KuzzleDocument) {\n data = document.serialize();\n } else {\n data.body = document;\n }\n\n if (options) {\n action = options.updateIfExist ? 'createOrReplace' : 'create';\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('write', action), data, options, cb && function (err, res) {\n var doc;\n\n if (err) {\n return cb(err);\n }\n\n doc = new KuzzleDocument(self, res.result._id, res.result._source);\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 * - metadata (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 {Object} this\n */\nKuzzleDataCollection.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 = 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('write', action), data, options, cb && function (err, res) {\n var result = action === 'delete' ? [res.result._id] : res.result.ids;\n cb(err, err ? undefined : result);\n });\n\n return this;\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 * @returns {Object} this\n */\nKuzzleDataCollection.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('KuzzleDataCollection.fetch', cb);\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('read', 'get'), data, options, function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new KuzzleDocument(self, res.result._id, res.result._source);\n document.version = res.result._version;\n cb(null, document);\n });\n};\n\n/**\n * Retrieves all documents stored in this data collection\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n * @returns {Object} this\n */\nKuzzleDataCollection.prototype.fetchAllDocuments = function (options, cb) {\n var filters = {};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n // copying pagination options to the search filter\n if (options) {\n if (options.from) {\n filters.from = options.from;\n }\n\n if (options.size) {\n filters.size = options.size;\n }\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.fetchAll', cb);\n\n this.advancedSearch(filters, options, cb);\n};\n\n\n/**\n * Instantiates a KuzzleDataMapping object containing the current mapping of this collection.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated KuzzleDataMapping object\n * @return {object} this\n */\nKuzzleDataCollection.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('KuzzleDataCollection.getMapping', cb);\n\n kuzzleMapping = new KuzzleDataMapping(this);\n kuzzleMapping.refresh(options, cb);\n};\n\n/**\n * Publish a realtime message\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} document - either a KuzzleDocument instance or a JSON object\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Returns a raw Kuzzle response\n * @returns {*} this\n */\nKuzzleDataCollection.prototype.publishMessage = function (document, options, cb) {\n var data = {};\n\n if (document instanceof KuzzleDocument) {\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('write', '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 * - metadata (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 KuzzleDocument object\n * @return {object} this\n */\nKuzzleDataCollection.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('write', 'createOrReplace'), data, options, cb && function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new KuzzleDocument(self, res.result._id, res.result._source);\n document.version = res.result._version;\n cb(null, document);\n });\n\n return this;\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 {*} KuzzleRoom object\n */\nKuzzleDataCollection.prototype.subscribe = function (filters, options, cb) {\n var room;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.subscribe', cb);\n\n room = new KuzzleRoom(this, options);\n room.renew(filters, cb);\n\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 */\nKuzzleDataCollection.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('admin', 'truncateCollection'), 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 * - metadata (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 KuzzleDocument object\n * @return {object} this\n */\nKuzzleDataCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n var\n 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 data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options, cb && function (err, res) {\n if (err) {\n return cb(err);\n }\n\n (new KuzzleDocument(self, res.result._id)).refresh(cb);\n });\n\n return self;\n};\n\n\n/**\n * Instantiate a new KuzzleDocument 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 */\nKuzzleDataCollection.prototype.documentFactory = function (id, content) {\n return new KuzzleDocument(this, id, content);\n};\n\n/**\n * Instantiate a new KuzzleRoom 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 */\nKuzzleDataCollection.prototype.roomFactory = function (options) {\n return new KuzzleRoom(this, options);\n};\n\n/**\n * Instantiate a new KuzzleDataMapping 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 KuzzleDataMapping object with\n * @constructor\n */\nKuzzleDataCollection.prototype.dataMappingFactory = function (mapping) {\n return new KuzzleDataMapping(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 */\nKuzzleDataCollection.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\nmodule.exports = KuzzleDataCollection;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDataCollection.js\n ** module id = 4\n ** module chunks = 0\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 * 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 KuzzleDataMapping object allow to get the current mapping of a data collection and to modify it if needed.\n *\n * @param {object} kuzzleDataCollection - Instance of the inherited KuzzleDataCollection object\n * @param {object} mapping - mappings\n * @constructor\n */\nfunction KuzzleDataMapping(kuzzleDataCollection, mapping) {\n Object.defineProperties(this, {\n //read-only properties\n collection: {\n value: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.kuzzle,\n enumerable: true\n },\n // writable properties\n headers: {\n value: JSON.parse(JSON.stringify(kuzzleDataCollection.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 */\nKuzzleDataMapping.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('admin', '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 */\nKuzzleDataMapping.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('admin', '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 {KuzzleDataMapping}\n */\nKuzzleDataMapping.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 */\nKuzzleDataMapping.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\nmodule.exports = KuzzleDataMapping;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDataMapping.js\n ** module id = 5\n ** module chunks = 0\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 handles documents either as realtime messages or as stored documents.\n * KuzzleDocument 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 {object} kuzzleDataCollection - an instanciated KuzzleDataCollection object\n * @param {string} [documentId] - ID of an existing document\n * @param {object} [content] - Initializes this document with the provided content\n * @constructor\n */\nfunction KuzzleDocument(kuzzleDataCollection, documentId, content) {\n Object.defineProperties(this, {\n // read-only properties\n collection: {\n value: kuzzleDataCollection.collection,\n enumerable: true\n },\n dataCollection: {\n value: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.kuzzle,\n enumerable: true\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(kuzzleDataCollection.headers)),\n enumerable: true,\n writable: true\n },\n version: {\n value: undefined,\n enumerable: true,\n writable: true\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 */\nKuzzleDocument.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._version = this.version;\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 */\nKuzzleDocument.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 * - metadata (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 */\nKuzzleDocument.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('KuzzleDocument.delete: cannot delete a document without a document ID');\n }\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'delete'), this.serialize(), options, cb && function (err) {\n cb(err, err ? undefined : self.id);\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 */\nKuzzleDocument.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('KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided');\n }\n\n this.kuzzle.callbackRequired('KuzzleDocument.refresh', cb);\n\n self.kuzzle.query(self.dataCollection.buildQueryArgs('read', 'get'), {_id: self.id}, options, function (error, res) {\n var newDocument;\n\n if (error) {\n return cb(error);\n }\n\n newDocument = new KuzzleDocument(self.dataCollection, self.id, res.result._source);\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 * - metadata (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 */\nKuzzleDocument.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('write', '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 * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @returns {*} this\n */\nKuzzleDocument.prototype.publish = function (options) {\n var data = this.serialize();\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('write', '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 */\nKuzzleDocument.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 */\nKuzzleDocument.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('KuzzleDocument.subscribe', cb);\n\n if (!this.id) {\n throw new Error('KuzzleDocument.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 */\nKuzzleDocument.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\n\nmodule.exports = KuzzleDocument;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDocument.js\n ** module id = 6\n ** module chunks = 0\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), excepting:\n * * all cluster based functions\n * * all script based functions\n * * all cursors functions\n *\n * For instance:\n * kuzzle.memoryStorage\n * .set('myKey', 'myValue')\n * .get('myKey', function (err, response) {\n * console.log(response.result);\n *\n * // { _id: 'foo', body: { value: 'myValue' }}\n * });\n *\n *\n * @param {object} kuzzle - Kuzzle instance to inherit from\n * @constructor\n */\nfunction KuzzleMemoryStorage(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\n/**\n * constructs the memoryStorage functions.\n */\n(function() {\n\n var\n keyVal = ['id', 'value'],\n idOrKeys = ['id', 'keys'],\n commands = {\n append: keyVal,\n bgrewriteaof: [],\n bgsave: [],\n bitcount: ['id', 'start', 'end'],\n bitop: ['operation', 'destkey', idOrKeys],\n bitpos: ['id', 'bit', { __opts__: ['start', 'end']}],\n blpop: [idOrKeys, 'timeout'],\n brpoplpush: ['source', 'destination'],\n dbsize: [],\n decrby: keyVal,\n del: [idOrKeys],\n discard: [],\n exec: [],\n exists: [idOrKeys],\n expire: ['id', 'seconds'],\n expireat: ['id', 'timestamp'],\n flushdb: [],\n // @todo: implement geolocation methods once available in Redis stable release\n getbit: ['id', 'offset'],\n getrange: ['id', 'start', 'end'],\n hdel: ['id', ['field', 'fields']],\n hexists: ['id', 'field'],\n hincrby: ['id', 'field', 'value'],\n hmset: ['id', 'values'],\n hset: ['id', 'field', 'value'],\n info: ['section'],\n keys: [ 'pattern' ],\n lastsave: [],\n lindex: ['id', 'idx'],\n linsert: ['id', 'position', 'pivot', 'value'],\n lpush: ['id', ['value', 'values']],\n lrange: ['id', 'start', 'stop'],\n lrem: ['id', 'count', 'value'],\n lset: ['id', 'idx', 'value'],\n ltrim: ['id', 'start', 'stop'],\n mset: ['values'],\n multi: [],\n object: ['subcommand', 'args'],\n pexpire: ['id', 'milliseconds'],\n pexpireat: ['id', 'timestamp'],\n pfadd: ['id', ['element', 'elements']],\n pfmerge: ['destkey', ['sourcekey', 'sourcekeys']],\n ping: [],\n psetex: ['id', 'milliseconds', 'value'],\n publish: ['channel', 'message'],\n randomkey: [],\n rename: ['id', 'newkey'],\n renamenx: ['id', 'newkey'],\n restore: ['id', 'ttl', 'content'],\n rpoplpush: ['source', 'destination'],\n sadd: ['id', ['member', 'members']],\n save: [],\n set: ['id', 'value', {__opts__:['ex', 'px', 'nx', 'xx']}],\n sdiffstore: ['destination', idOrKeys],\n setbit: ['id', 'offset', 'value'],\n setex: ['id', 'seconds', 'value'],\n setrange: ['id', 'offset', 'value'],\n sinterstore: ['destination', idOrKeys],\n sismember: ['id', 'member'],\n smove: ['id', 'destination', 'member'],\n sort: ['id', {__opts__:['by', 'offset', 'count', 'get', 'direction', 'alpha', 'store']}],\n spop: ['id', 'count'],\n srem: ['id', ['member', 'members']],\n sunionstore: ['destination', idOrKeys],\n unwatch: [],\n wait: ['numslaves', 'timeout'],\n zadd: ['id', {__opts__: ['nx', 'xx', 'ch', 'incr', 'score', 'member', 'members']}],\n zcount: ['id', 'min', 'max'],\n zincrby: ['id', 'value', 'member'],\n zinterstore: ['destination', idOrKeys, {__opts__: ['weight', 'weights', 'aggregate']}],\n zlexcount: ['id', 'min', 'max'],\n zrange: ['id', 'start', 'stop', {__opts__: ['withscores']}],\n zrangebylex: ['id', 'min', 'max', {__opts__: ['offset', 'count']}],\n zrangebyscore: ['id', 'min', 'max', {__opts__: ['withscores', 'offset', 'count']}],\n zrem: ['id', 'member'],\n zremrangebylex: ['id', 'min', 'max'],\n zremrangebyscore: ['id', 'min', 'max'],\n zrevrangebylex: ['id', 'max', 'min', {__opts__: ['offset', 'count']}],\n zrevrangebyscore: ['id', 'max', 'min', {__opts__: ['withscores', 'offset', 'count']}],\n zrevrank: ['id', 'member']\n };\n\n // unique argument key\n commands.decr = commands.get = commands.dump = commands.hgetall = commands.hkeys = commands.hlen = commands.hstrlen = commands.hvals = commands.incr = commands.llen = commands.lpop = commands.persist = commands.pttl = commands.rpop = commands.scard = commands.smembers = commands.strlen = commands.ttl = commands.type = commands.zcard = ['id'];\n\n // key value\n commands.getset = commands.lpushx = keyVal;\n\n // key key...\n commands.del = commands.exists = commands.mget = commands.pfcount = commands.sdiff = commands.sinter = commands.sunion = commands.watch = [idOrKeys];\n\n commands.incrby = commands.incrbyfloat = commands.decrby;\n commands.brpop = commands.blpop;\n commands.hget = commands.hexists;\n commands.hmget = commands.hdel;\n commands.hsetnx = commands.hset;\n commands.msetnx = commands.mset;\n commands.rpush = commands.lpush;\n commands.hincrbyfloat = commands.hincrby;\n commands.srandmember = commands.spop;\n commands.zrevrange = commands.zrange;\n commands.zscore = commands.zrevrank;\n\n Object.keys(commands).forEach(function (command) {\n KuzzleMemoryStorage.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 (typeof args[args.length - 1] === 'function') {\n cb = args.pop();\n }\n\n if (args.length && typeof args[args.length - 1] === 'object' && Object.keys(args[args.length - 1]).length === 1 && args[args.length - 1].queuable !== undefined) {\n options = args.pop();\n }\n\n commands[command].forEach(function (v, i) {\n if (args[i] === undefined) {\n return;\n }\n\n if (Array.isArray(v)) {\n v = Array.isArray(args[i]) ? v[1] : v[0];\n }\n\n if (v === 'id') {\n data._id = args[i];\n }\n else {\n if (!data.body) {\n data.body = {};\n }\n\n if (typeof v === 'object' && v.__opts__ !== undefined) {\n v.__opts__.forEach(function (arg) {\n if (args[i][arg] !== undefined) {\n data.body[arg] = args[i][arg];\n }\n });\n }\n else {\n data.body[v] = args[i];\n }\n }\n });\n\n this.kuzzle.query(query, data, options, cb);\n\n return this;\n\n };\n });\n\n})();\n\nmodule.exports = KuzzleMemoryStorage;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleMemoryStorage.js\n ** module id = 7\n ** module chunks = 0\n **/","var\n uuid = require('node-uuid');\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} kuzzleDataCollection - an instantiated and valid kuzzle object\n * @param {object} [options] - subscription optional configuration\n * @constructor\n */\nfunction KuzzleRoom(kuzzleDataCollection, 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: uuid.v4()\n },\n lastRenewal: {\n value: null,\n writable: true\n },\n notifier: {\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: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.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(kuzzleDataCollection.headers)),\n enumerable: true,\n writable: true\n },\n metadata: {\n value: (options && options.metadata) ? options.metadata : {},\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 */\nKuzzleRoom.prototype.count = function (cb) {\n var data;\n\n this.kuzzle.callbackRequired('KuzzleRoom.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('KuzzleRoom.count: cannot count subscriptions on an inactive room');\n }\n\n this.kuzzle.query(this.collection.buildQueryArgs('subscribe', '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} cb - called for each new notification\n */\nKuzzleRoom.prototype.renew = function (filters, cb) {\n var\n now = Date.now(),\n subscribeQuery = {\n scope: this.scope,\n state: this.state,\n users: this.users\n },\n self = this;\n\n if (!cb && filters && typeof filters === 'function') {\n cb = filters;\n filters = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleRoom.renew', cb);\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;\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 = 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, cb]});\n return;\n }\n\n self.unsubscribe();\n self.roomId = null;\n self.subscribing = true;\n self.callback = cb;\n self.kuzzle.subscriptions.pending[self.id] = self;\n\n subscribeQuery.body = self.filters;\n subscribeQuery = self.kuzzle.addHeaders(subscribeQuery, this.headers);\n\n self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'on'), subscribeQuery, {metadata: self.metadata}, function (error, response) {\n delete self.kuzzle.subscriptions.pending[self.id];\n self.subscribing = false;\n\n if (error) {\n self.queue = [];\n throw 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 });\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 */\nKuzzleRoom.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('subscribe', 'off'), {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('subscribe', 'off'), {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 */\nKuzzleRoom.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.error) {\n return this.callback(data.error);\n }\n\n if (data.action === 'jwtTokenExpired') {\n this.kuzzle.jwtToken = undefined;\n return this.kuzzle.emitEvent('jwtTokenExpired');\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 = KuzzleRoom;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleRoom.js\n ** module id = 8\n ** module chunks = 0\n **/","/**\n *\n * @param host\n * @param wsPort\n * @param ioPort\n * @returns {Object} tnstantiated WebSocket/Socket.IO object\n */\n\nfunction network(host, wsPort, ioPort, 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/wsbrowsers'))(host, wsPort, sslConnection);\n }\n // otherwise fallback to socket.io, if available\n else if (window.io) {\n return new (require('./wrappers/socketio'))(host, ioPort, 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/wsnode'))(host, wsPort, sslConnection);\n}\n\nmodule.exports = network;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/index.js\n ** module id = 9\n ** module chunks = 0\n **/","function SocketIO(host, port, ssl) {\n this.host = host;\n this.port = port;\n this.ssl = ssl;\n this.socket = null;\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 this.socket = window.io((this.ssl ? 'https://' : 'http://') + this.host + ':' + this.port, {\n reconnection: autoReconnect,\n reconnectionDelay: reconnectionDelay,\n forceNew: true\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.socket.on('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.socket.on('connect_error', 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.socket.on('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.socket.on('reconnect', callback);\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.socket.close();\n this.socket = null;\n };\n}\n\nmodule.exports = SocketIO;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/wrappers/socketio.js\n ** module id = 10\n ** module chunks = 0\n **/","function WSBrowsers(host, port, ssl) {\n var self = this;\n this.host = host;\n this.port = port;\n this.ssl = ssl;\n this.client = null;\n this.retrying = false;\n\n /*\n Listeners are stored using the following format:\n roomId: {\n fn: callback_function,\n once: boolean\n }\n */\n this.listeners = {\n error: [],\n connect: [],\n disconnect: [],\n reconnect: []\n };\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 this.client = new WebSocket((this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port);\n\n this.client.onopen = function () {\n if (self.retrying) {\n poke(self.listeners, 'reconnect');\n }\n else {\n poke(self.listeners, 'connect');\n }\n };\n\n this.client.onclose = function () {\n poke(self.listeners, 'disconnect');\n };\n\n this.client.onerror = function () {\n if (autoReconnect) {\n self.retrying = true;\n setTimeout(function () {\n self.connect(autoReconnect, reconnectionDelay);\n }, reconnectionDelay);\n }\n\n poke(self.listeners, 'error');\n };\n\n this.client.onmessage = function (payload) {\n var data = JSON.parse(payload.data);\n\n if (data.room && self.listeners[data.room]) {\n poke(self.listeners, data.room, 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.listeners.connect.push({\n fn: callback,\n keep: true\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 this.listeners.error.push({\n fn: callback,\n keep: true\n });\n };\n\n /**\n * Fires the provided callback whenever a disconnection occurred\n * @param {function} callback\n */\n this.onDisconnect = function (callback) {\n this.listeners.disconnect.push({\n fn: callback,\n keep: true\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 this.listeners.reconnect.push({\n fn: callback,\n keep: true\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 if (!this.listeners[roomId]) {\n this.listeners[roomId] = [];\n }\n\n this.listeners[roomId].push({\n fn: callback,\n keep: false\n });\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 if (!this.listeners[roomId]) {\n this.listeners[roomId] = [];\n }\n\n this.listeners[roomId].push({\n fn: callback,\n keep: true\n });\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 var index;\n\n if (this.listeners[roomId]) {\n index = this.listeners[roomId].findIndex(function (listener) {\n return listener.fn === callback;\n });\n\n if (index !== -1) {\n if (this.listeners[roomId].length === 1 && ['error', 'connect', 'disconnect', 'reconnect'].indexOf(roomId) === -1) {\n delete this.listeners[roomId];\n }\n else {\n this.listeners[roomId].splice(index, 1);\n }\n }\n }\n };\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.listeners = {\n error: [],\n connect: [],\n disconnect: [],\n reconnect: []\n };\n\n this.retrying = false;\n this.client.close();\n this.client = null;\n };\n}\n\n/**\n * Executes all registered listeners in the provided\n * \"listeners\" structure.\n *\n * Listeners are of the following format:\n * [\n * { fn: callback, once: boolean },\n * ...\n * ]\n *\n * @private\n * @param {Object} listeners\n * @param {string} roomId\n * @param {Object} [payload]\n */\nfunction poke (listeners, roomId, payload) {\n var\n i,\n length = listeners[roomId].length;\n\n for (i = 0; i < length; ++i) {\n listeners[roomId][i].fn(payload);\n\n if (!listeners[roomId][i].keep) {\n if (listeners[roomId].length > 1) {\n listeners[roomId].splice(i, 1);\n --i;\n --length;\n }\n else {\n delete listeners[roomId];\n }\n }\n }\n}\n\nmodule.exports = WSBrowsers;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/wrappers/wsbrowsers.js\n ** module id = 11\n ** module chunks = 0\n **/","var\n KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleProfile(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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\nKuzzleProfile.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleProfile\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 {Object} this\n */\nKuzzleProfile.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.kuzzleSecurity.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 {KuzzleProfile} this\n */\nKuzzleProfile.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 {KuzzleProfile} this\n */\nKuzzleProfile.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 */\nKuzzleProfile.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\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 */\nKuzzleProfile.prototype.getPolicies = function () {\n return this.content.policies;\n};\n\nmodule.exports = KuzzleProfile;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleProfile.js\n ** module id = 12\n ** module chunks = 0\n **/","var KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleRole(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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\nKuzzleRole.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleRole\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 */\nKuzzleRole.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.kuzzleSecurity.buildQueryArgs('createOrReplaceRole'), data, options, cb && function (error) {\n cb(error, error ? undefined : self);\n });\n\n return this;\n};\n\nmodule.exports = KuzzleRole;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleRole.js\n ** module id = 13\n ** module chunks = 0\n **/","var\n KuzzleRole = require('./kuzzleRole'),\n KuzzleProfile = require('./kuzzleProfile'),\n KuzzleUser = require('./kuzzleUser');\n\n/**\n * Kuzzle security constructor\n *\n * @param kuzzle\n * @returns {KuzzleSecurity}\n * @constructor\n */\nfunction KuzzleSecurity(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 = ['roleFactory', 'profileFactory', 'userFactory', '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} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getRole = function (id, options, cb) {\n var\n data,\n self = this;\n\n if (!id) {\n throw new Error('Id parameter is mandatory for getRole 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('KuzzleSecurity.getRole', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n cb(err, err ? undefined : new KuzzleRole(self, response.result._id, response.result._source));\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} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n *\n */\nKuzzleSecurity.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('KuzzleSecurity.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 KuzzleRole(self, doc._id, doc._source);\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.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('KuzzleSecurity.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 KuzzleRole(self, res.result._id, res.result._source));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.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('KuzzleSecurity.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) {\n cb(err, err ? undefined : new KuzzleRole(self, id, content));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleSecurity.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 KuzzleRole 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 * @constructor\n */\nKuzzleSecurity.prototype.roleFactory = function(id, content) {\n return new KuzzleRole(this, id, content);\n};\n\n\n/**\n * Get a specific profile from kuzzle\n *\n *\n * @param {string} id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getProfile = 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 getProfile function');\n }\n\n\n data = {_id: id};\n\n self.kuzzle.callbackRequired('KuzzleSecurity.getProfile', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n cb(error, error ? undefined : new KuzzleProfile(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.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('KuzzleSecurity.searchProfiles', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new KuzzleProfile(self, doc._id, doc._source);\n });\n\n cb(null, { total: response.result.total, profiles: documents });\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 {object} content - attribute `roles` in `content` must only contains an array of role id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.createProfile = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'createProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.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 data.body = content;\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 KuzzleProfile(self, res.result._id, res.result._source));\n });\n};\n\n\n/**\n * Update a profile in Kuzzle.\n *\n * @param {string} id - profile identifier\n * @param {object} content - a plain javascript object representing the profile's modification\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.updateProfile = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'updateProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.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 data.body = content;\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 KuzzleProfile(self, res.result._id, updatedContent));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleSecurity.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 * Instantiate a new KuzzleProfile 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 * @constructor\n */\nKuzzleSecurity.prototype.profileFactory = function(id, content) {\n return new KuzzleProfile(this, id, content);\n};\n\n/**\n * Get a specific user from kuzzle using its unique ID\n *\n * @param {string} id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getUser = 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 getUser function');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleSecurity.getUser', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n cb(err, err ? undefined : new KuzzleUser(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.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('KuzzleSecurity.searchUsers', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new KuzzleUser(self, doc._id, doc._source);\n });\n\n cb(null, { total: response.result.total, users: documents });\n });\n};\n\n/**\n * Create a new user in Kuzzle.\n *\n * Takes an optional argument object with the following property:\n * - replaceIfExist (boolean, default: false):\n * If the same user already exists: throw an error if sets to false.\n * Replace the existing user otherwise\n *\n * @param {string} id - user identifier\n * @param {object} content - attribute `profile` in `content` must only contains the profile id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.createUser = function (id, content, options, cb) {\n var\n self = this,\n data = {_id: id, body: content},\n action = 'createUser';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.createUser: cannot create a user without a user ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (options) {\n action = options.replaceIfExist ? 'createOrReplaceUser' : 'createUser';\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, null, cb && function (err, res) {\n cb(err, err ? undefined : new KuzzleUser(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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.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('KuzzleSecurity.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 KuzzleUser(self, res.result._id, res.result._source));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleSecurity.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 * Instantiate a new KuzzleUser 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 * @constructor\n */\nKuzzleSecurity.prototype.userFactory = function(id, content) {\n return new KuzzleUser(this, id, content);\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 */\nKuzzleSecurity.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} [options] - (optional) arguments\n * @param {function} cb The callback containing the normalized array of rights.\n */\nKuzzleSecurity.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\nmodule.exports = KuzzleSecurity;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleSecurity.js\n ** module id = 14\n ** module chunks = 0\n **/"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///kuzzle.js","webpack:///webpack/bootstrap 4491e1be4c84512d1594","webpack:///./src/kuzzle.js","webpack:///./src/security/kuzzleSecurityDocument.js","webpack:///./src/security/kuzzleUser.js","webpack:///./~/node-uuid/uuid.js","webpack:///./src/kuzzleDataCollection.js","webpack:///./src/kuzzleDataMapping.js","webpack:///./src/kuzzleDocument.js","webpack:///./src/kuzzleMemoryStorage.js","webpack:///./src/kuzzleRoom.js","webpack:///./src/networkWrapper/index.js","webpack:///./src/networkWrapper/wrappers/socketio.js","webpack:///./src/networkWrapper/wrappers/wsbrowsers.js","webpack:///./src/security/kuzzleProfile.js","webpack:///./src/security/kuzzleRole.js","webpack:///./src/security/kuzzleSecurity.js"],"names":["root","factory","exports","module","define","amd","a","i","this","modules","__webpack_require__","moduleId","installedModules","id","loaded","call","m","c","p","cleanQueue","self","now","Date","lastDocumentIndex","queueTTL","offlineQueue","forEach","query","index","ts","splice","droppedRequest","emitEvent","queueMaxSize","length","cleanHistory","requestHistory","Object","keys","key","setTimeout","emitRequest","request","cb","undefined","jwtToken","network","once","requestId","response","action","error","message","send","dequeue","additionalQueue","uniqueQueue","dequeuingProcess","shift","Math","max","replayInterval","queuing","offlineQueueLoader","Error","Array","isArray","concat","filter","controller","hasOwnProperty","renewAllSubscriptions","subscriptions","roomId","subscriptionId","subscription","renew","callback","uuid","KuzzleDataCollection","KuzzleSecurity","KuzzleMemoryStorage","KuzzleUser","networkWrapper","Kuzzle","host","options","defineProperties","collections","value","writable","connectCB","eventListeners","connected","lastEmitted","listeners","disconnected","reconnected","jwtTokenExpired","loginAttempt","offlineQueuePush","offlineQueuePop","eventTimeout","state","pending","autoReconnect","enumerable","defaultIndex","reconnectionDelay","wsPort","ioPort","sslConnection","autoQueue","autoReplay","autoResubscribe","headers","metadata","queueFilter","opt","getOwnPropertyDescriptor","offlineMode","defineProperty","header","errorMessagePrefix","event","args","prototype","slice","arguments","eventProperties","listener","process","nextTick","fn","apply","connect","bluebird","promisifyAll","suffix","name","func","target","passes","whitelist","indexOf","onConnect","onConnectError","connectionError","internal","onDisconnect","disconnect","onReconnect","reconnect","checkToken","err","res","valid","setJwtToken","token","success","result","jwt","JSON","stringify","getJwtToken","login","strategy","credentials","expiresIn","body","queuable","logout","v4","callbackRequired","whoAmI","security","_id","_source","getMyRights","hits","updateSelf","content","data","queryArgs","addListener","listenerId","knownEvents","listenerType","isValid","toString","push","getAllStatistics","getStatistics","timestamp","queryCB","startTime","dataCollectionFactory","collection","flushQueue","listCollections","collectionType","arg","type","listIndexes","indexes","close","getServerInfo","serverInfo","refreshIndex","getAutoRefresh","setAutoRefresh","autoRefresh","attr","object","meta","addHeaders","authorization","removeAllListeners","eventName","removeListener","replayQueue","setDefaultIndex","setHeaders","replace","startQueuing","stopQueuing","KuzzleSecurityDocument","kuzzleSecurity","kuzzle","setContent","serialize","buildQueryArgs","deleteActionName","update","updateActionName","create","constructor","setProfiles","profileIds","addProfile","profileId","save","getProfiles","_window","setupBrowser","_crypto","crypto","msCrypto","_rng","getRandomValues","_rnds8","Uint8Array","_whatwgRNG","e","_rnds","_mathRNG","r","random","console","warn","setupNode","require","_rb","randomBytes","_nodeRNG","parse","s","buf","offset","ii","toLowerCase","oct","_hexToByte","unparse","bth","_byteToHex","v1","b","clockseq","_clockseq","msecs","getTime","nsecs","_lastNSecs","dt","_lastMSecs","tl","tmh","node","_nodeId","n","BufferClass","rnds","rng","_previousRoot","Buffer","substr","_seedBytes","noConflict","window","blacklist","KuzzleDocument","KuzzleDataMapping","KuzzleRoom","advancedSearch","filters","documents","doc","newDocument","version","_version","total","count","createDocument","document","updateIfExist","deleteDocument","ids","fetchDocument","documentId","fetchAllDocuments","from","size","getMapping","kuzzleMapping","refresh","publishMessage","replaceDocument","subscribe","room","truncate","updateDocument","documentFactory","roomFactory","dataMappingFactory","mapping","kuzzleDataCollection","properties","mappings","set","field","dataCollection","publish","values","bind","keyVal","idOrKeys","commands","append","bgrewriteaof","bgsave","bitcount","bitop","bitpos","__opts__","blpop","brpoplpush","dbsize","decrby","del","discard","exec","exists","expire","expireat","flushdb","getbit","getrange","hdel","hexists","hincrby","hmset","hset","info","lastsave","lindex","linsert","lpush","lrange","lrem","lset","ltrim","mset","multi","pexpire","pexpireat","pfadd","pfmerge","ping","psetex","randomkey","rename","renamenx","restore","rpoplpush","sadd","sdiffstore","setbit","setex","setrange","sinterstore","sismember","smove","sort","spop","srem","sunionstore","unwatch","wait","zadd","zcount","zincrby","zinterstore","zlexcount","zrange","zrangebylex","zrangebyscore","zrem","zremrangebylex","zremrangebyscore","zrevrangebylex","zrevrangebyscore","zrevrank","decr","get","dump","hgetall","hkeys","hlen","hstrlen","hvals","incr","llen","lpop","persist","pttl","rpop","scard","smembers","strlen","ttl","zcard","getset","lpushx","mget","pfcount","sdiff","sinter","sunion","watch","incrby","incrbyfloat","brpop","hget","hmget","hsetnx","msetnx","rpush","hincrbyfloat","srandmember","zrevrange","zscore","command","pop","v","channel","lastRenewal","notifier","queue","renewalDelay","scope","subscribing","users","subscribeToSelf","notificationCallback","element","isReady","subscribeQuery","unsubscribe","on","interval","off","setInterval","clearInterval","WebSocket","io","code","SocketIO","port","ssl","socket","reconnection","forceNew","payload","emit","WSBrowsers","client","retrying","onopen","poke","onclose","onerror","onmessage","keep","findIndex","readyState","OPEN","KuzzleProfile","policies","addPolicy","policy","roleId","setPolicies","map","getPolicies","KuzzleRole","getRole","searchRoles","roles","createRole","replaceIfExist","updateRole","deleteRole","roleFactory","getProfile","searchProfiles","profiles","createProfile","updateProfile","updatedContent","property","deleteProfile","profileFactory","getUser","searchUsers","createUser","updateUser","deleteUser","userFactory","isAct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QAC3C,UAGAoc,EAAAE,KAAA,SAAAC,GAA2C,sBAAAA,EAAAvc,QAC3C,cAGA,UAWAT,EAAA8C,UAAAma,cAAA,SAAAC,EAAA5c,EAAA3C,GACA,GACA2I,IAAYN,IAAAkX,GACZ9gB,EAAAZ,IAEA,KAAA0hB,GAAA,gBAAAA,GACA,SAAAle,OAAA,2DAGArB,IAAA,kBAAA2C,KACA3C,EAAA2C,EACAA,EAAA,MAGAlE,EAAAgN,OAAAvD,iBAAA,uBAAAlI,GAEAnC,KAAA4N,OAAAzM,MAAAnB,KAAA+N,eAAA,iBAAAjD,EAAAhG,EAAA3C,GAAA,SAAA+G,EAAAC,GACAhH,EAAA+G,IAAA9G,OAAA+G,EAAAK,OAAAmB,SAIAhL,EAAAD,QAAA8E","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 {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(this, function() {\nreturn \n\n\n/** WEBPACK FOOTER **\n ** webpack/universalModuleDefinition\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 {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\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 uuid = __webpack_require__(3),\n\t KuzzleDataCollection = __webpack_require__(4),\n\t KuzzleSecurity = __webpack_require__(14),\n\t KuzzleMemoryStorage = __webpack_require__(7),\n\t KuzzleUser = __webpack_require__(2),\n\t networkWrapper = __webpack_require__(9);\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 * @constructor\n\t */\n\tmodule.exports = Kuzzle = function (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\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 collections: {\n\t value: {},\n\t writable: true\n\t },\n\t connectCB: {\n\t value: cb\n\t },\n\t eventListeners: {\n\t value: {\n\t connected: {lastEmitted: null, listeners: []},\n\t error: {lastEmitted: null, listeners: []},\n\t disconnected: {lastEmitted: null, listeners: []},\n\t reconnected: {lastEmitted: null, listeners: []},\n\t jwtTokenExpired: {lastEmitted: null, listeners: []},\n\t loginAttempt: {lastEmitted: null, listeners: []},\n\t offlineQueuePush: {listeners: []},\n\t offlineQueuePop: {listeners: []}\n\t }\n\t },\n\t eventTimeout: {\n\t value: 200\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 'roomId': {\n\t kuzzleRoomID_1: kuzzleRoomInstance_1,\n\t kuzzleRoomID_2: kuzzleRoomInstance_2,\n\t kuzzleRoomID_...: 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 // read-only properties\n\t autoReconnect: {\n\t value: (options && typeof options.autoReconnect === 'boolean') ? options.autoReconnect : 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 enumerable: true\n\t },\n\t host: {\n\t value: host,\n\t enumerable: true\n\t },\n\t wsPort: {\n\t value: (options && typeof options.wsPort === 'number') ? options.wsPort : 7513,\n\t enumerable: true\n\t },\n\t ioPort: {\n\t value: (options && typeof options.ioPort === 'number') ? options.ioPort : 7512,\n\t enumerable: true\n\t },\n\t sslConnection: {\n\t value: (options && typeof options.sslConnection === 'boolean') ? options.sslConnection : false,\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 metadata: {\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: 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 (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 KuzzleSecurity(this),\n\t enumerable: true\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 Object.defineProperty(this, 'emitEvent', {\n\t value: function emitEvent(event) {\n\t var\n\t now = Date.now(),\n\t args = Array.prototype.slice.call(arguments, 1),\n\t eventProperties = this.eventListeners[event];\n\t\n\t if (eventProperties.lastEmitted && eventProperties.lastEmitted >= now - this.eventTimeout) {\n\t return false;\n\t }\n\t\n\t eventProperties.listeners.forEach(function (listener) {\n\t process.nextTick(function () {\n\t listener.fn.apply(undefined, args);\n\t });\n\t });\n\t\n\t // Events without the 'lastEmitted' property can be emitted without minimum time between emissions\n\t if (eventProperties.lastEmitted !== undefined) {\n\t eventProperties.lastEmitted = now;\n\t }\n\t }\n\t });\n\t\n\t Object.defineProperty(this, 'memoryStorage', {\n\t value: new KuzzleMemoryStorage(this),\n\t enumerable: true\n\t });\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 cleanHistory(this.requestHistory);\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', 'listIndexes', 'login', 'logout', 'now', 'query',\n\t '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\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.network = networkWrapper(self.host, self.wsPort, self.ioPort, self.sslConnection);\n\t }\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.onConnectError(function (error) {\n\t var connectionError = new Error('Unable to connect to kuzzle server at \"' + self.host + '\"');\n\t\n\t connectionError.internal = error;\n\t self.state = 'error';\n\t self.emitEvent('error', connectionError);\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('jwtTokenExpired');\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 * 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 * @returns {Kuzzle}\n\t */\n\tKuzzle.prototype.login = function (strategy) {\n\t var\n\t self = this,\n\t request = {\n\t strategy: strategy\n\t },\n\t credentials,\n\t cb = null;\n\t\n\t // Handle arguments (credentials, expiresIn, cb)\n\t if (arguments[1]) {\n\t if (typeof arguments[1] === 'object') {\n\t credentials = 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 if (typeof credentials === 'object') {\n\t Object.keys(credentials).forEach(function (key) {\n\t request[key] = credentials[key];\n\t });\n\t }\n\t\n\t this.query({controller: 'auth', action: 'login'}, {body: 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 * 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: uuid.v4(),\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 if (error === null) {\n\t self.jwtToken = undefined;\n\t cb(null, self);\n\t }\n\t else {\n\t cb(error);\n\t }\n\t });\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} callback The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t * @return {Kuzzle} The Kuzzle instance to enable chaining.\n\t */\n\tKuzzle.prototype.checkToken = function (token, callback) {\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', callback);\n\t\n\t this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, function (err, response) {\n\t if (err) {\n\t return callback(err);\n\t }\n\t\n\t callback(null, response.result);\n\t });\n\t};\n\t\n\t/**\n\t * Fetches the current user.\n\t *\n\t * @param {function} callback The callback to be called when the response is\n\t * available. The signature is `function(error, response)`.\n\t * @return {Kuzzle} The Kuzzle instance to enable chaining.\n\t */\n\tKuzzle.prototype.whoAmI = function (callback) {\n\t var self = this;\n\t\n\t self.callbackRequired('Kuzzle.whoAmI', callback);\n\t\n\t self.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, function (err, response) {\n\t if (err) {\n\t return callback(err);\n\t }\n\t\n\t callback(null, new KuzzleUser(self.security, response.result._id, response.result._source));\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 if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, 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 */\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 setTimeout(function () {\n\t cleanHistory(requestHistory);\n\t }, 1000);\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 if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n\t self.jwtToken = undefined;\n\t self.emitEvent('jwtTokenExpired', request, cb);\n\t }\n\t\n\t cb && cb(response.error, response);\n\t });\n\t }\n\t\n\t this.network.send(request);\n\t\n\t // Track requests made to allow KuzzleRoom.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 * 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 * The ID returned by this function is required to remove this listener at a later time.\n\t *\n\t * @param {string} event - name of the global event to subscribe to (see the 'eventListeners' object property)\n\t * @param {function} listener - callback to invoke each time an event is fired\n\t * @returns {string} Unique listener ID\n\t */\n\tKuzzle.prototype.addListener = function(event, listener) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t listenerType = typeof listener,\n\t listenerId;\n\t\n\t this.isValid();\n\t\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\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 listenerId = uuid.v4();\n\t this.eventListeners[event].listeners.push({id: listenerId, fn: listener});\n\t return listenerId;\n\t};\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 * @returns {object} this\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:'admin', action: 'getAllStats'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, 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 * @returns {object} this\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: 'admin', action: timestamp ? 'getStats' : 'getLastStats'}, body, options, queryCB);\n\t};\n\t\n\t/**\n\t * Create a new instance of a KuzzleDataCollection 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 {object} A KuzzleDataCollection instance\n\t */\n\tKuzzle.prototype.dataCollectionFactory = 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 KuzzleDataCollection(this, index, collection);\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 * @returns {object} this\n\t */\n\tKuzzle.prototype.listCollections = function () {\n\t var\n\t collectionType = 'all',\n\t index,\n\t options,\n\t cb,\n\t args = Array.prototype.slice.call(arguments);\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 if (options && options.type) {\n\t collectionType = options.type;\n\t }\n\t\n\t this.query({index: index, controller: 'read', action: 'listCollections'}, {body: {type: collectionType}}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, 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 * @returns {object} this\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: 'read', action: 'listIndexes'}, {}, 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 this.logout();\n\t\n\t this.state = 'disconnected';\n\t this.network.close();\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 * @returns {object} this\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: 'read', action: 'serverInfo'}, {}, options, function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t cb(null, 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: 'admin', action: 'refreshIndex'}, {}, 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 * @returns {object} this\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: 'admin', 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: 'admin', 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 * @returns {object} this\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: 'read', action: 'now'}, {}, options, function (err, res) {\n\t cb(err, res && 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 * - metadata (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 metadata: this.metadata\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.metadata) {\n\t Object.keys(options.metadata).forEach(function (meta) {\n\t object.metadata[meta] = options.metadata[meta];\n\t });\n\t }\n\t\n\t if (options.queuable === false && self.state === 'offline') {\n\t return self;\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.metadata) {\n\t Object.keys(query.metadata).forEach(function (meta) {\n\t object.metadata[meta] = query.metadata[meta];\n\t });\n\t }\n\t\n\t for (attr in query) {\n\t if (attr !== 'metadata' && 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.headers = object.headers || {};\n\t object.headers.authorization = 'Bearer ' + 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 = uuid.v4();\n\t }\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 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 } else if (self.queuing || ['initializing', 'connecting'].indexOf(self.state) !== -1) {\n\t cleanQueue.call(this, object, cb);\n\t\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 }\n\t }\n\t\n\t return self;\n\t};\n\t\n\t/**\n\t * Removes all listeners, either from a specific event or from all events\n\t *\n\t * @param {string} event - One of the event described in the Event Handling section of this documentation\n\t */\n\tKuzzle.prototype.removeAllListeners = function (event) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t self = this;\n\t\n\t if (event) {\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n\t }\n\t\n\t this.eventListeners[event].listeners = [];\n\t } else {\n\t knownEvents.forEach(function (eventName) {\n\t self.eventListeners[eventName].listeners = [];\n\t });\n\t }\n\t\n\t return this;\n\t};\n\t\n\t/**\n\t * Removes a listener from an event.\n\t *\n\t * @param {string} event - One of the event described in the Event Handling section of this documentation\n\t * @param {string} listenerId - The ID returned by addListener\n\t */\n\tKuzzle.prototype.removeListener = function (event, listenerId) {\n\t var\n\t knownEvents = Object.keys(this.eventListeners),\n\t self = this;\n\t\n\t if (knownEvents.indexOf(event) === -1) {\n\t throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n\t }\n\t\n\t this.eventListeners[event].listeners.forEach(function (listener, index) {\n\t if (listener.id === listenerId) {\n\t self.eventListeners[event].listeners.splice(index, 1);\n\t }\n\t });\n\t\n\t return this;\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\n\n/***/ },\n/* 1 */\n/***/ function(module, exports) {\n\n\tfunction KuzzleSecurityDocument(kuzzleSecurity, id, content) {\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: kuzzleSecurity.kuzzle\n\t },\n\t kuzzleSecurity: {\n\t value: kuzzleSecurity\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 });\n\t\n\t if (content) {\n\t this.setContent(content, true);\n\t }\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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 {Object} this\n\t */\n\tKuzzleSecurityDocument.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\tKuzzleSecurityDocument.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\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\tKuzzleSecurityDocument.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.kuzzleSecurity.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 */\n\tKuzzleSecurityDocument.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.kuzzleSecurity.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 = KuzzleSecurityDocument;\n\n/***/ },\n/* 2 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleUser(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 });\n\t\n\t // promisifying\n\t if (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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\tKuzzleUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleUser\n\t }\n\t});\n\t\n\t/**\n\t * Set profiles in content\n\t * @param {array} profile - an array of profiles ids string\n\t *\n\t * @returns {KuzzleUser} this\n\t */\n\tKuzzleUser.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 * Add a profile\n\t * @param {string} profile - a profile ids string\n\t *\n\t * @returns {KuzzleUser} this\n\t */\n\tKuzzleUser.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 * Saves this user into Kuzzle.\n\t *\n\t * If this is a new user, this function will create it in Kuzzle.\n\t * Otherwise, this method will replace the latest version of this user in Kuzzle by the current content\n\t * of this object.\n\t *\n\t * @param {responseCallback} [cb] - Handles the query response\n\t * @param {object} [options] - Optional parameters\n\t * @returns {*} this\n\t */\n\tKuzzleUser.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.kuzzleSecurity.buildQueryArgs('createOrReplaceUser'), 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\tKuzzleUser.prototype.serialize = function () {\n\t return {_id: this.id, body: this.content};\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\tKuzzleUser.prototype.getProfiles = function () {\n\t return this.content.profileIds;\n\t};\n\t\n\tmodule.exports = KuzzleUser;\n\n\n/***/ },\n/* 3 */\n/***/ function(module, exports) {\n\n\t// uuid.js\n\t//\n\t// Copyright (c) 2010-2012 Robert Kieffer\n\t// MIT License - http://opensource.org/licenses/mit-license.php\n\t\n\t/*global window, require, define */\n\t(function(_window) {\n\t 'use strict';\n\t\n\t // Unique ID creation requires a high quality random # generator. We feature\n\t // detect to determine the best RNG source, normalizing to a function that\n\t // returns 128-bits of randomness, since that's what's usually required\n\t var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot;\n\t\n\t function setupBrowser() {\n\t // Allow for MSIE11 msCrypto\n\t var _crypto = _window.crypto || _window.msCrypto;\n\t\n\t if (!_rng && _crypto && _crypto.getRandomValues) {\n\t // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto\n\t //\n\t // Moderately fast, high quality\n\t try {\n\t var _rnds8 = new Uint8Array(16);\n\t _whatwgRNG = _rng = function whatwgRNG() {\n\t _crypto.getRandomValues(_rnds8);\n\t return _rnds8;\n\t };\n\t _rng();\n\t } catch(e) {}\n\t }\n\t\n\t if (!_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 _mathRNG = _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 if ('undefined' !== typeof console && console.warn) {\n\t console.warn(\"[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()\");\n\t }\n\t }\n\t }\n\t\n\t function setupNode() {\n\t // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html\n\t //\n\t // Moderately fast, high quality\n\t if ('function' === typeof require) {\n\t try {\n\t var _rb = require('crypto').randomBytes;\n\t _nodeRNG = _rng = _rb && function() {return _rb(16);};\n\t _rng();\n\t } catch(e) {}\n\t }\n\t }\n\t\n\t if (_window) {\n\t setupBrowser();\n\t } else {\n\t setupNode();\n\t }\n\t\n\t // Buffer class to use\n\t var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;\n\t\n\t // Maps for number <-> hex string conversion\n\t var _byteToHex = [];\n\t var _hexToByte = {};\n\t for (var i = 0; i < 256; i++) {\n\t _byteToHex[i] = (i + 0x100).toString(16).substr(1);\n\t _hexToByte[_byteToHex[i]] = i;\n\t }\n\t\n\t // **`parse()` - Parse a UUID into it's component bytes**\n\t function parse(s, buf, offset) {\n\t var i = (buf && offset) || 0, ii = 0;\n\t\n\t buf = buf || [];\n\t s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {\n\t if (ii < 16) { // Don't overflow!\n\t buf[i + ii++] = _hexToByte[oct];\n\t }\n\t });\n\t\n\t // Zero out remaining bytes if string was short\n\t while (ii < 16) {\n\t buf[i + ii++] = 0;\n\t }\n\t\n\t return buf;\n\t }\n\t\n\t // **`unparse()` - Convert UUID byte array (ala parse()) into a string**\n\t function unparse(buf, offset) {\n\t var i = offset || 0, 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\t // **`v1()` - Generate time-based UUID**\n\t //\n\t // Inspired by https://github.com/LiosK/UUID.js\n\t // and http://docs.python.org/library/uuid.html\n\t\n\t // random #'s we need to init node and clockseq\n\t var _seedBytes = _rng();\n\t\n\t // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n\t var _nodeId = [\n\t _seedBytes[0] | 0x01,\n\t _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]\n\t ];\n\t\n\t // Per 4.2.2, randomize (14 bit) clockseq\n\t var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;\n\t\n\t // Previous uuid creation time\n\t var _lastMSecs = 0, _lastNSecs = 0;\n\t\n\t // See https://github.com/broofa/node-uuid for API details\n\t function v1(options, buf, offset) {\n\t var i = buf && offset || 0;\n\t var b = buf || [];\n\t\n\t options = options || {};\n\t\n\t var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;\n\t\n\t // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n\t // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n\t // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n\t // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\t var msecs = (options.msecs != null) ? options.msecs : new Date().getTime();\n\t\n\t // Per 4.2.1.2, use count of uuid's generated during the current clock\n\t // cycle to simulate higher resolution clock\n\t var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;\n\t\n\t // Time since last uuid creation (in msecs)\n\t var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\t\n\t // Per 4.2.1.2, Bump clockseq on clock regression\n\t if (dt < 0 && options.clockseq == null) {\n\t clockseq = clockseq + 1 & 0x3fff;\n\t }\n\t\n\t // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n\t // time interval\n\t if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {\n\t nsecs = 0;\n\t }\n\t\n\t // Per 4.2.1.2 Throw error if too many uuids are requested\n\t if (nsecs >= 10000) {\n\t throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n\t }\n\t\n\t _lastMSecs = msecs;\n\t _lastNSecs = nsecs;\n\t _clockseq = clockseq;\n\t\n\t // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\t msecs += 12219292800000;\n\t\n\t // `time_low`\n\t var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n\t b[i++] = tl >>> 24 & 0xff;\n\t b[i++] = tl >>> 16 & 0xff;\n\t b[i++] = tl >>> 8 & 0xff;\n\t b[i++] = tl & 0xff;\n\t\n\t // `time_mid`\n\t var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n\t b[i++] = tmh >>> 8 & 0xff;\n\t b[i++] = tmh & 0xff;\n\t\n\t // `time_high_and_version`\n\t b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\t b[i++] = tmh >>> 16 & 0xff;\n\t\n\t // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\t b[i++] = clockseq >>> 8 | 0x80;\n\t\n\t // `clock_seq_low`\n\t b[i++] = clockseq & 0xff;\n\t\n\t // `node`\n\t var node = options.node || _nodeId;\n\t for (var n = 0; n < 6; n++) {\n\t b[i + n] = node[n];\n\t }\n\t\n\t return buf ? buf : unparse(b);\n\t }\n\t\n\t // **`v4()` - Generate random UUID**\n\t\n\t // See https://github.com/broofa/node-uuid for API details\n\t function v4(options, buf, offset) {\n\t // Deprecated - 'format' argument, as supported in v1.2\n\t var i = buf && offset || 0;\n\t\n\t if (typeof(options) === 'string') {\n\t buf = (options === 'binary') ? new BufferClass(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 || unparse(rnds);\n\t }\n\t\n\t // Export public API\n\t var uuid = v4;\n\t uuid.v1 = v1;\n\t uuid.v4 = v4;\n\t uuid.parse = parse;\n\t uuid.unparse = unparse;\n\t uuid.BufferClass = BufferClass;\n\t uuid._rng = _rng;\n\t uuid._mathRNG = _mathRNG;\n\t uuid._nodeRNG = _nodeRNG;\n\t uuid._whatwgRNG = _whatwgRNG;\n\t\n\t if (('undefined' !== typeof module) && module.exports) {\n\t // Publish as node.js module\n\t module.exports = uuid;\n\t } else if (typeof define === 'function' && define.amd) {\n\t // Publish as AMD module\n\t define(function() {return uuid;});\n\t\n\t\n\t } else {\n\t // Publish as global (in browsers)\n\t _previousRoot = _window.uuid;\n\t\n\t // **`noConflict()` - (browser only) to reset global 'uuid' var**\n\t uuid.noConflict = function() {\n\t _window.uuid = _previousRoot;\n\t return uuid;\n\t };\n\t\n\t _window.uuid = uuid;\n\t }\n\t})('undefined' !== typeof window ? window : null);\n\n\n/***/ },\n/* 4 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleDocument = __webpack_require__(6),\n\t KuzzleDataMapping = __webpack_require__(5),\n\t KuzzleRoom = __webpack_require__(8);\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 * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @param {string} index - Index containing the data collection\n\t * @param {string} collection - name of the data collection to handle\n\t * @constructor\n\t */\n\tfunction KuzzleDataCollection(kuzzle, index, collection) {\n\t if (!index || !collection) {\n\t throw new Error('The KuzzleDataCollection object constructor needs an index and a collection arguments');\n\t }\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 * 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 * @returns {Object} this\n\t */\n\tKuzzleDataCollection.prototype.advancedSearch = 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 = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleDataCollection.advancedSearch', cb);\n\t\n\t query = self.kuzzle.addHeaders({body: filters}, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('read', '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 KuzzleDocument(self, doc._id, doc._source);\n\t\n\t newDocument.version = doc._version;\n\t\n\t documents.push(newDocument);\n\t });\n\t\n\t cb(null, { total: result.result.total, documents: documents });\n\t });\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 * @returns {Object} this\n\t */\n\tKuzzleDataCollection.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('KuzzleDataCollection.count', cb);\n\t\n\t query = this.kuzzle.addHeaders({body: filters}, this.headers);\n\t\n\t this.kuzzle.query(this.buildQueryArgs('read', 'count'), query, options, function (error, result) {\n\t cb(error, result && result.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\tKuzzleDataCollection.prototype.create = 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('write', 'createCollection'), data, options, cb);\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 * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t * - updateIfExist (boolean, default: false):\n\t * If the same document already exists: throw an error if sets to false.\n\t * Update the existing document otherwise\n\t *\n\t * @param {string} [id] - (optional) document identifier\n\t * @param {object} document - either an instance of a KuzzleDocument 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\tKuzzleDataCollection.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 KuzzleDocument) {\n\t data = document.serialize();\n\t } else {\n\t data.body = document;\n\t }\n\t\n\t if (options) {\n\t action = options.updateIfExist ? 'createOrReplace' : 'create';\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('write', 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 KuzzleDocument(self, res.result._id, res.result._source);\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 * - metadata (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 {Object} this\n\t */\n\tKuzzleDataCollection.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 = 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('write', 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 * 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 * @returns {Object} this\n\t */\n\tKuzzleDataCollection.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('KuzzleDataCollection.fetch', cb);\n\t data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('read', '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 KuzzleDocument(self, res.result._id, res.result._source);\n\t document.version = res.result._version;\n\t cb(null, document);\n\t });\n\t};\n\t\n\t/**\n\t * Retrieves all documents stored in this data collection\n\t *\n\t * @param {object} [options] - Optional parameters\n\t * @param {responseCallback} cb - Handles the query response\n\t * @returns {Object} this\n\t */\n\tKuzzleDataCollection.prototype.fetchAllDocuments = function (options, cb) {\n\t var filters = {};\n\t\n\t if (!cb && typeof options === 'function') {\n\t cb = options;\n\t options = null;\n\t }\n\t\n\t // copying pagination options to the search filter\n\t if (options) {\n\t if (options.from) {\n\t filters.from = options.from;\n\t }\n\t\n\t if (options.size) {\n\t filters.size = options.size;\n\t }\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDataCollection.fetchAll', cb);\n\t\n\t this.advancedSearch(filters, options, cb);\n\t};\n\t\n\t\n\t/**\n\t * Instantiates a KuzzleDataMapping 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 KuzzleDataMapping object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.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('KuzzleDataCollection.getMapping', cb);\n\t\n\t kuzzleMapping = new KuzzleDataMapping(this);\n\t kuzzleMapping.refresh(options, cb);\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 * - metadata (object, default: null):\n\t * Additional information passed to notifications to other users\n\t *\n\t * @param {object} document - either a KuzzleDocument 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\tKuzzleDataCollection.prototype.publishMessage = function (document, options, cb) {\n\t var data = {};\n\t\n\t if (document instanceof KuzzleDocument) {\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('write', '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 * - metadata (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 KuzzleDocument object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.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('write', '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 KuzzleDocument(self, res.result._id, res.result._source);\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 * 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 {*} KuzzleRoom object\n\t */\n\tKuzzleDataCollection.prototype.subscribe = function (filters, options, cb) {\n\t var room;\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('KuzzleDataCollection.subscribe', cb);\n\t\n\t room = new KuzzleRoom(this, options);\n\t room.renew(filters, cb);\n\t\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\tKuzzleDataCollection.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('admin', 'truncateCollection'), 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 * - metadata (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 KuzzleDocument object\n\t * @return {object} this\n\t */\n\tKuzzleDataCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n\t var\n\t 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 data = self.kuzzle.addHeaders(data, this.headers);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options, cb && function (err, res) {\n\t if (err) {\n\t return cb(err);\n\t }\n\t\n\t (new KuzzleDocument(self, res.result._id)).refresh(cb);\n\t });\n\t\n\t return self;\n\t};\n\t\n\t\n\t/**\n\t * Instantiate a new KuzzleDocument 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\tKuzzleDataCollection.prototype.documentFactory = function (id, content) {\n\t return new KuzzleDocument(this, id, content);\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleRoom 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\tKuzzleDataCollection.prototype.roomFactory = function (options) {\n\t return new KuzzleRoom(this, options);\n\t};\n\t\n\t/**\n\t * Instantiate a new KuzzleDataMapping 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 KuzzleDataMapping object with\n\t * @constructor\n\t */\n\tKuzzleDataCollection.prototype.dataMappingFactory = function (mapping) {\n\t return new KuzzleDataMapping(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\tKuzzleDataCollection.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 = KuzzleDataCollection;\n\n\n/***/ },\n/* 5 */\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 KuzzleDataMapping object allow to get the current mapping of a data collection and to modify it if needed.\n\t *\n\t * @param {object} kuzzleDataCollection - Instance of the inherited KuzzleDataCollection object\n\t * @param {object} mapping - mappings\n\t * @constructor\n\t */\n\tfunction KuzzleDataMapping(kuzzleDataCollection, mapping) {\n\t Object.defineProperties(this, {\n\t //read-only properties\n\t collection: {\n\t value: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.kuzzle,\n\t enumerable: true\n\t },\n\t // writable properties\n\t headers: {\n\t value: JSON.parse(JSON.stringify(kuzzleDataCollection.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\tKuzzleDataMapping.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('admin', '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\tKuzzleDataMapping.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('admin', '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 {KuzzleDataMapping}\n\t */\n\tKuzzleDataMapping.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\tKuzzleDataMapping.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 = KuzzleDataMapping;\n\n\n/***/ },\n/* 6 */\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 * KuzzleDocument 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 {object} kuzzleDataCollection - an instanciated KuzzleDataCollection 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 * @constructor\n\t */\n\tfunction KuzzleDocument(kuzzleDataCollection, documentId, content) {\n\t Object.defineProperties(this, {\n\t // read-only properties\n\t collection: {\n\t value: kuzzleDataCollection.collection,\n\t enumerable: true\n\t },\n\t dataCollection: {\n\t value: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.kuzzle,\n\t enumerable: true\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(kuzzleDataCollection.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 });\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\tKuzzleDocument.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._version = this.version;\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\tKuzzleDocument.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 * - metadata (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\tKuzzleDocument.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('KuzzleDocument.delete: cannot delete a document without a document ID');\n\t }\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('write', '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 * 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\tKuzzleDocument.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('KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided');\n\t }\n\t\n\t this.kuzzle.callbackRequired('KuzzleDocument.refresh', cb);\n\t\n\t self.kuzzle.query(self.dataCollection.buildQueryArgs('read', '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 KuzzleDocument(self.dataCollection, self.id, res.result._source);\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 * - metadata (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\tKuzzleDocument.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('write', '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 * - metadata (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\tKuzzleDocument.prototype.publish = function (options) {\n\t var data = this.serialize();\n\t\n\t this.kuzzle.query(this.dataCollection.buildQueryArgs('write', '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\tKuzzleDocument.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\tKuzzleDocument.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('KuzzleDocument.subscribe', cb);\n\t\n\t if (!this.id) {\n\t throw new Error('KuzzleDocument.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\tKuzzleDocument.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 = KuzzleDocument;\n\n\n/***/ },\n/* 7 */\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 * 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), excepting:\n\t * * all cluster based functions\n\t * * all script based functions\n\t * * all cursors functions\n\t *\n\t * For instance:\n\t * kuzzle.memoryStorage\n\t * .set('myKey', 'myValue')\n\t * .get('myKey', function (err, response) {\n\t * console.log(response.result);\n\t *\n\t * // { _id: 'foo', body: { value: 'myValue' }}\n\t * });\n\t *\n\t *\n\t * @param {object} kuzzle - Kuzzle instance to inherit from\n\t * @constructor\n\t */\n\tfunction KuzzleMemoryStorage(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\n\t/**\n\t * constructs the memoryStorage functions.\n\t */\n\t(function() {\n\t\n\t var\n\t keyVal = ['id', 'value'],\n\t idOrKeys = ['id', 'keys'],\n\t commands = {\n\t append: keyVal,\n\t bgrewriteaof: [],\n\t bgsave: [],\n\t bitcount: ['id', 'start', 'end'],\n\t bitop: ['operation', 'destkey', idOrKeys],\n\t bitpos: ['id', 'bit', { __opts__: ['start', 'end']}],\n\t blpop: [idOrKeys, 'timeout'],\n\t brpoplpush: ['source', 'destination'],\n\t dbsize: [],\n\t decrby: keyVal,\n\t del: [idOrKeys],\n\t discard: [],\n\t exec: [],\n\t exists: [idOrKeys],\n\t expire: ['id', 'seconds'],\n\t expireat: ['id', 'timestamp'],\n\t flushdb: [],\n\t // @todo: implement geolocation methods once available in Redis stable release\n\t getbit: ['id', 'offset'],\n\t getrange: ['id', 'start', 'end'],\n\t hdel: ['id', ['field', 'fields']],\n\t hexists: ['id', 'field'],\n\t hincrby: ['id', 'field', 'value'],\n\t hmset: ['id', 'values'],\n\t hset: ['id', 'field', 'value'],\n\t info: ['section'],\n\t keys: [ 'pattern' ],\n\t lastsave: [],\n\t lindex: ['id', 'idx'],\n\t linsert: ['id', 'position', 'pivot', 'value'],\n\t lpush: ['id', ['value', 'values']],\n\t lrange: ['id', 'start', 'stop'],\n\t lrem: ['id', 'count', 'value'],\n\t lset: ['id', 'idx', 'value'],\n\t ltrim: ['id', 'start', 'stop'],\n\t mset: ['values'],\n\t multi: [],\n\t object: ['subcommand', 'args'],\n\t pexpire: ['id', 'milliseconds'],\n\t pexpireat: ['id', 'timestamp'],\n\t pfadd: ['id', ['element', 'elements']],\n\t pfmerge: ['destkey', ['sourcekey', 'sourcekeys']],\n\t ping: [],\n\t psetex: ['id', 'milliseconds', 'value'],\n\t publish: ['channel', 'message'],\n\t randomkey: [],\n\t rename: ['id', 'newkey'],\n\t renamenx: ['id', 'newkey'],\n\t restore: ['id', 'ttl', 'content'],\n\t rpoplpush: ['source', 'destination'],\n\t sadd: ['id', ['member', 'members']],\n\t save: [],\n\t set: ['id', 'value', {__opts__:['ex', 'px', 'nx', 'xx']}],\n\t sdiffstore: ['destination', idOrKeys],\n\t setbit: ['id', 'offset', 'value'],\n\t setex: ['id', 'seconds', 'value'],\n\t setrange: ['id', 'offset', 'value'],\n\t sinterstore: ['destination', idOrKeys],\n\t sismember: ['id', 'member'],\n\t smove: ['id', 'destination', 'member'],\n\t sort: ['id', {__opts__:['by', 'offset', 'count', 'get', 'direction', 'alpha', 'store']}],\n\t spop: ['id', 'count'],\n\t srem: ['id', ['member', 'members']],\n\t sunionstore: ['destination', idOrKeys],\n\t unwatch: [],\n\t wait: ['numslaves', 'timeout'],\n\t zadd: ['id', {__opts__: ['nx', 'xx', 'ch', 'incr', 'score', 'member', 'members']}],\n\t zcount: ['id', 'min', 'max'],\n\t zincrby: ['id', 'value', 'member'],\n\t zinterstore: ['destination', idOrKeys, {__opts__: ['weight', 'weights', 'aggregate']}],\n\t zlexcount: ['id', 'min', 'max'],\n\t zrange: ['id', 'start', 'stop', {__opts__: ['withscores']}],\n\t zrangebylex: ['id', 'min', 'max', {__opts__: ['offset', 'count']}],\n\t zrangebyscore: ['id', 'min', 'max', {__opts__: ['withscores', 'offset', 'count']}],\n\t zrem: ['id', 'member'],\n\t zremrangebylex: ['id', 'min', 'max'],\n\t zremrangebyscore: ['id', 'min', 'max'],\n\t zrevrangebylex: ['id', 'max', 'min', {__opts__: ['offset', 'count']}],\n\t zrevrangebyscore: ['id', 'max', 'min', {__opts__: ['withscores', 'offset', 'count']}],\n\t zrevrank: ['id', 'member']\n\t };\n\t\n\t // unique argument key\n\t commands.decr = commands.get = commands.dump = commands.hgetall = commands.hkeys = commands.hlen = commands.hstrlen = commands.hvals = commands.incr = commands.llen = commands.lpop = commands.persist = commands.pttl = commands.rpop = commands.scard = commands.smembers = commands.strlen = commands.ttl = commands.type = commands.zcard = ['id'];\n\t\n\t // key value\n\t commands.getset = commands.lpushx = keyVal;\n\t\n\t // key key...\n\t commands.del = commands.exists = commands.mget = commands.pfcount = commands.sdiff = commands.sinter = commands.sunion = commands.watch = [idOrKeys];\n\t\n\t commands.incrby = commands.incrbyfloat = commands.decrby;\n\t commands.brpop = commands.blpop;\n\t commands.hget = commands.hexists;\n\t commands.hmget = commands.hdel;\n\t commands.hsetnx = commands.hset;\n\t commands.msetnx = commands.mset;\n\t commands.rpush = commands.lpush;\n\t commands.hincrbyfloat = commands.hincrby;\n\t commands.srandmember = commands.spop;\n\t commands.zrevrange = commands.zrange;\n\t commands.zscore = commands.zrevrank;\n\t\n\t Object.keys(commands).forEach(function (command) {\n\t KuzzleMemoryStorage.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 (typeof args[args.length - 1] === 'function') {\n\t cb = args.pop();\n\t }\n\t\n\t if (args.length && typeof args[args.length - 1] === 'object' && Object.keys(args[args.length - 1]).length === 1 && args[args.length - 1].queuable !== undefined) {\n\t options = args.pop();\n\t }\n\t\n\t commands[command].forEach(function (v, i) {\n\t if (args[i] === undefined) {\n\t return;\n\t }\n\t\n\t if (Array.isArray(v)) {\n\t v = Array.isArray(args[i]) ? v[1] : v[0];\n\t }\n\t\n\t if (v === 'id') {\n\t data._id = args[i];\n\t }\n\t else {\n\t if (!data.body) {\n\t data.body = {};\n\t }\n\t\n\t if (typeof v === 'object' && v.__opts__ !== undefined) {\n\t v.__opts__.forEach(function (arg) {\n\t if (args[i][arg] !== undefined) {\n\t data.body[arg] = args[i][arg];\n\t }\n\t });\n\t }\n\t else {\n\t data.body[v] = args[i];\n\t }\n\t }\n\t });\n\t\n\t this.kuzzle.query(query, data, options, cb);\n\t\n\t return this;\n\t\n\t };\n\t });\n\t\n\t})();\n\t\n\tmodule.exports = KuzzleMemoryStorage;\n\n\n/***/ },\n/* 8 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t uuid = __webpack_require__(3);\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} kuzzleDataCollection - an instantiated and valid kuzzle object\n\t * @param {object} [options] - subscription optional configuration\n\t * @constructor\n\t */\n\tfunction KuzzleRoom(kuzzleDataCollection, 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: uuid.v4()\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 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: kuzzleDataCollection,\n\t enumerable: true\n\t },\n\t kuzzle: {\n\t value: kuzzleDataCollection.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(kuzzleDataCollection.headers)),\n\t enumerable: true,\n\t writable: true\n\t },\n\t metadata: {\n\t value: (options && options.metadata) ? options.metadata : {},\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\tKuzzleRoom.prototype.count = function (cb) {\n\t var data;\n\t\n\t this.kuzzle.callbackRequired('KuzzleRoom.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('KuzzleRoom.count: cannot count subscriptions on an inactive room');\n\t }\n\t\n\t this.kuzzle.query(this.collection.buildQueryArgs('subscribe', '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} cb - called for each new notification\n\t */\n\tKuzzleRoom.prototype.renew = function (filters, cb) {\n\t var\n\t now = Date.now(),\n\t subscribeQuery = {\n\t scope: this.scope,\n\t state: this.state,\n\t users: this.users\n\t },\n\t self = this;\n\t\n\t if (!cb && filters && typeof filters === 'function') {\n\t cb = filters;\n\t filters = null;\n\t }\n\t\n\t self.kuzzle.callbackRequired('KuzzleRoom.renew', cb);\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;\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 = 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, 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 = 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, this.headers);\n\t\n\t self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'on'), subscribeQuery, {metadata: self.metadata}, 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 throw 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 });\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\tKuzzleRoom.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('subscribe', 'off'), {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('subscribe', 'off'), {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\tKuzzleRoom.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.error) {\n\t return this.callback(data.error);\n\t }\n\t\n\t if (data.action === 'jwtTokenExpired') {\n\t this.kuzzle.jwtToken = undefined;\n\t return this.kuzzle.emitEvent('jwtTokenExpired');\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 = KuzzleRoom;\n\n\n/***/ },\n/* 9 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/**\n\t *\n\t * @param host\n\t * @param wsPort\n\t * @param ioPort\n\t * @returns {Object} tnstantiated WebSocket/Socket.IO object\n\t */\n\t\n\tfunction network(host, wsPort, ioPort, 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__(11))(host, wsPort, sslConnection);\n\t }\n\t // otherwise fallback to socket.io, if available\n\t else if (window.io) {\n\t return new (__webpack_require__(10))(host, ioPort, 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__(!(function webpackMissingModule() { var e = new Error(\"Cannot find module \\\"./wrappers/wsnode\\\"\"); e.code = 'MODULE_NOT_FOUND'; throw e; }())))(host, wsPort, sslConnection);\n\t}\n\t\n\tmodule.exports = network;\n\n\n/***/ },\n/* 10 */\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\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 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\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.socket.on('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.socket.on('connect_error', 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.socket.on('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.socket.on('reconnect', callback);\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.socket.close();\n\t this.socket = null;\n\t };\n\t}\n\t\n\tmodule.exports = SocketIO;\n\n\n/***/ },\n/* 11 */\n/***/ function(module, exports) {\n\n\tfunction WSBrowsers(host, port, ssl) {\n\t var self = this;\n\t this.host = host;\n\t this.port = port;\n\t this.ssl = ssl;\n\t this.client = null;\n\t this.retrying = false;\n\t\n\t /*\n\t Listeners are stored using the following format:\n\t roomId: {\n\t fn: callback_function,\n\t once: boolean\n\t }\n\t */\n\t this.listeners = {\n\t error: [],\n\t connect: [],\n\t disconnect: [],\n\t reconnect: []\n\t };\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 this.client = new WebSocket((this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port);\n\t\n\t this.client.onopen = function () {\n\t if (self.retrying) {\n\t poke(self.listeners, 'reconnect');\n\t }\n\t else {\n\t poke(self.listeners, 'connect');\n\t }\n\t };\n\t\n\t this.client.onclose = function () {\n\t poke(self.listeners, 'disconnect');\n\t };\n\t\n\t this.client.onerror = function () {\n\t if (autoReconnect) {\n\t self.retrying = true;\n\t setTimeout(function () {\n\t self.connect(autoReconnect, reconnectionDelay);\n\t }, reconnectionDelay);\n\t }\n\t\n\t poke(self.listeners, 'error');\n\t };\n\t\n\t this.client.onmessage = function (payload) {\n\t var data = JSON.parse(payload.data);\n\t\n\t if (data.room && self.listeners[data.room]) {\n\t poke(self.listeners, data.room, 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.listeners.connect.push({\n\t fn: callback,\n\t keep: true\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 this.listeners.error.push({\n\t fn: callback,\n\t keep: true\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 this.listeners.disconnect.push({\n\t fn: callback,\n\t keep: true\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 this.listeners.reconnect.push({\n\t fn: callback,\n\t keep: true\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 if (!this.listeners[roomId]) {\n\t this.listeners[roomId] = [];\n\t }\n\t\n\t this.listeners[roomId].push({\n\t fn: callback,\n\t keep: false\n\t });\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 if (!this.listeners[roomId]) {\n\t this.listeners[roomId] = [];\n\t }\n\t\n\t this.listeners[roomId].push({\n\t fn: callback,\n\t keep: true\n\t });\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 var index;\n\t\n\t if (this.listeners[roomId]) {\n\t index = this.listeners[roomId].findIndex(function (listener) {\n\t return listener.fn === callback;\n\t });\n\t\n\t if (index !== -1) {\n\t if (this.listeners[roomId].length === 1 && ['error', 'connect', 'disconnect', 'reconnect'].indexOf(roomId) === -1) {\n\t delete this.listeners[roomId];\n\t }\n\t else {\n\t this.listeners[roomId].splice(index, 1);\n\t }\n\t }\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 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.listeners = {\n\t error: [],\n\t connect: [],\n\t disconnect: [],\n\t reconnect: []\n\t };\n\t\n\t this.retrying = false;\n\t this.client.close();\n\t this.client = null;\n\t };\n\t}\n\t\n\t/**\n\t * Executes all registered listeners in the provided\n\t * \"listeners\" structure.\n\t *\n\t * Listeners are of the following format:\n\t * [\n\t * { fn: callback, once: boolean },\n\t * ...\n\t * ]\n\t *\n\t * @private\n\t * @param {Object} listeners\n\t * @param {string} roomId\n\t * @param {Object} [payload]\n\t */\n\tfunction poke (listeners, roomId, payload) {\n\t var\n\t i,\n\t length = listeners[roomId].length;\n\t\n\t for (i = 0; i < length; ++i) {\n\t listeners[roomId][i].fn(payload);\n\t\n\t if (!listeners[roomId][i].keep) {\n\t if (listeners[roomId].length > 1) {\n\t listeners[roomId].splice(i, 1);\n\t --i;\n\t --length;\n\t }\n\t else {\n\t delete listeners[roomId];\n\t }\n\t }\n\t }\n\t}\n\t\n\tmodule.exports = WSBrowsers;\n\n\n/***/ },\n/* 12 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleProfile(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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\tKuzzleProfile.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleProfile\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 {Object} this\n\t */\n\tKuzzleProfile.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.kuzzleSecurity.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 {KuzzleProfile} this\n\t */\n\tKuzzleProfile.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 {KuzzleProfile} this\n\t */\n\tKuzzleProfile.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\tKuzzleProfile.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\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\tKuzzleProfile.prototype.getPolicies = function () {\n\t return this.content.policies;\n\t};\n\t\n\tmodule.exports = KuzzleProfile;\n\n\n/***/ },\n/* 13 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar KuzzleSecurityDocument = __webpack_require__(1);\n\t\n\tfunction KuzzleRole(kuzzleSecurity, id, content) {\n\t\n\t KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n\t return kuzzleSecurity.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\tKuzzleRole.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n\t constructor: {\n\t value: KuzzleRole\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 */\n\tKuzzleRole.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.kuzzleSecurity.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 = KuzzleRole;\n\n/***/ },\n/* 14 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar\n\t KuzzleRole = __webpack_require__(13),\n\t KuzzleProfile = __webpack_require__(12),\n\t KuzzleUser = __webpack_require__(2);\n\t\n\t/**\n\t * Kuzzle security constructor\n\t *\n\t * @param kuzzle\n\t * @returns {KuzzleSecurity}\n\t * @constructor\n\t */\n\tfunction KuzzleSecurity(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 = ['roleFactory', 'profileFactory', 'userFactory', '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} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getRole = 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 getRole 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('KuzzleSecurity.getRole', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n\t cb(err, err ? undefined : new KuzzleRole(self, response.result._id, response.result._source));\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} [options] - Optional parameters\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t *\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.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 KuzzleRole(self, doc._id, doc._source);\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.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 KuzzleRole(self, res.result._id, res.result._source));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.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) {\n\t cb(err, err ? undefined : new KuzzleRole(self, id, content));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleSecurity.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 KuzzleRole 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 * @constructor\n\t */\n\tKuzzleSecurity.prototype.roleFactory = function(id, content) {\n\t return new KuzzleRole(this, id, content);\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} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getProfile = 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 getProfile function');\n\t }\n\t\n\t\n\t data = {_id: id};\n\t\n\t self.kuzzle.callbackRequired('KuzzleSecurity.getProfile', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n\t cb(error, error ? undefined : new KuzzleProfile(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.searchProfiles', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n\t var documents;\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 KuzzleProfile(self, doc._id, doc._source);\n\t });\n\t\n\t cb(null, { total: response.result.total, profiles: documents });\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 {object} content - attribute `roles` in `content` must only contains an array of role id\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.createProfile = function (id, content, 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('KuzzleSecurity.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 data.body = content;\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 KuzzleProfile(self, res.result._id, res.result._source));\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 {object} content - a plain javascript object representing the profile's modification\n\t * @param {object} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.updateProfile = function (id, content, 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('KuzzleSecurity.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 data.body = content;\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 KuzzleProfile(self, res.result._id, updatedContent));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleSecurity.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 * Instantiate a new KuzzleProfile 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 * @constructor\n\t */\n\tKuzzleSecurity.prototype.profileFactory = function(id, content) {\n\t return new KuzzleProfile(this, id, content);\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} [options] - (optional) arguments\n\t * @param {responseCallback} cb - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.prototype.getUser = 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 getUser 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('KuzzleSecurity.getUser', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n\t cb(err, err ? undefined : new KuzzleUser(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - returns Kuzzle's response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.searchUsers', cb);\n\t\n\t self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n\t var documents;\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 KuzzleUser(self, doc._id, doc._source);\n\t });\n\t\n\t cb(null, { total: response.result.total, users: documents });\n\t });\n\t};\n\t\n\t/**\n\t * Create a new user 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 user already exists: throw an error if sets to false.\n\t * Replace the existing user otherwise\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.prototype.createUser = function (id, content, options, cb) {\n\t var\n\t self = this,\n\t data = {_id: id, body: content},\n\t action = 'createUser';\n\t\n\t if (!id || typeof id !== 'string') {\n\t throw new Error('KuzzleSecurity.createUser: cannot create 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 if (options) {\n\t action = options.replaceIfExist ? 'createOrReplaceUser' : 'createUser';\n\t }\n\t\n\t self.kuzzle.query(this.buildQueryArgs(action), data, null, cb && function (err, res) {\n\t cb(err, err ? undefined : new KuzzleUser(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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - (optional) Handles the query response\n\t */\n\tKuzzleSecurity.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('KuzzleSecurity.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 KuzzleUser(self, res.result._id, res.result._source));\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} [options] - (optional) arguments\n\t * @param {responseCallback} [cb] - Handles the query response\n\t */\n\tKuzzleSecurity.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 * Instantiate a new KuzzleUser 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 * @constructor\n\t */\n\tKuzzleSecurity.prototype.userFactory = function(id, content) {\n\t return new KuzzleUser(this, id, content);\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\tKuzzleSecurity.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} [options] - (optional) arguments\n\t * @param {function} cb The callback containing the normalized array of rights.\n\t */\n\tKuzzleSecurity.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\tmodule.exports = KuzzleSecurity;\n\n\n/***/ }\n/******/ ])\n});\n;\n\n\n/** WEBPACK FOOTER **\n ** kuzzle.js\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/** WEBPACK FOOTER **\n ** webpack/bootstrap 4491e1be4c84512d1594\n **/","var\n uuid = require('node-uuid'),\n KuzzleDataCollection = require('./kuzzleDataCollection'),\n KuzzleSecurity = require('./security/kuzzleSecurity'),\n KuzzleMemoryStorage = require('./kuzzleMemoryStorage'),\n KuzzleUser = require('./security/kuzzleUser'),\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 * @constructor\n */\nmodule.exports = Kuzzle = function (host, options, cb) {\n var self = this;\n\n if (!(this instanceof Kuzzle)) {\n return new Kuzzle(host, options, cb);\n }\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 collections: {\n value: {},\n writable: true\n },\n connectCB: {\n value: cb\n },\n eventListeners: {\n value: {\n connected: {lastEmitted: null, listeners: []},\n error: {lastEmitted: null, listeners: []},\n disconnected: {lastEmitted: null, listeners: []},\n reconnected: {lastEmitted: null, listeners: []},\n jwtTokenExpired: {lastEmitted: null, listeners: []},\n loginAttempt: {lastEmitted: null, listeners: []},\n offlineQueuePush: {listeners: []},\n offlineQueuePop: {listeners: []}\n }\n },\n eventTimeout: {\n value: 200\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 'roomId': {\n kuzzleRoomID_1: kuzzleRoomInstance_1,\n kuzzleRoomID_2: kuzzleRoomInstance_2,\n kuzzleRoomID_...: 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 // read-only properties\n autoReconnect: {\n value: (options && typeof options.autoReconnect === 'boolean') ? options.autoReconnect : 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 enumerable: true\n },\n host: {\n value: host,\n enumerable: true\n },\n wsPort: {\n value: (options && typeof options.wsPort === 'number') ? options.wsPort : 7513,\n enumerable: true\n },\n ioPort: {\n value: (options && typeof options.ioPort === 'number') ? options.ioPort : 7512,\n enumerable: true\n },\n sslConnection: {\n value: (options && typeof options.sslConnection === 'boolean') ? options.sslConnection : false,\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 metadata: {\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: null,\n enumerable: true,\n writable: true\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 KuzzleSecurity(this),\n enumerable: true\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 Object.defineProperty(this, 'emitEvent', {\n value: function emitEvent(event) {\n var\n now = Date.now(),\n args = Array.prototype.slice.call(arguments, 1),\n eventProperties = this.eventListeners[event];\n\n if (eventProperties.lastEmitted && eventProperties.lastEmitted >= now - this.eventTimeout) {\n return false;\n }\n\n eventProperties.listeners.forEach(function (listener) {\n process.nextTick(function () {\n listener.fn.apply(undefined, args);\n });\n });\n\n // Events without the 'lastEmitted' property can be emitted without minimum time between emissions\n if (eventProperties.lastEmitted !== undefined) {\n eventProperties.lastEmitted = now;\n }\n }\n });\n\n Object.defineProperty(this, 'memoryStorage', {\n value: new KuzzleMemoryStorage(this),\n enumerable: true\n });\n\n\n if (!options || !options.connect || options.connect === 'auto') {\n this.connect();\n } else {\n this.state = 'ready';\n }\n\n cleanHistory(this.requestHistory);\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', 'listIndexes', 'login', 'logout', 'now', 'query',\n 'checkToken', 'whoAmI', 'updateSelf', 'getMyRights',\n 'refreshIndex', 'getAutoRefresh', 'setAutoRefresh'\n ];\n\n return passes && whitelist.indexOf(name) !== -1;\n }\n });\n }\n};\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.network = networkWrapper(self.host, self.wsPort, self.ioPort, self.sslConnection);\n }\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.onConnectError(function (error) {\n var connectionError = new Error('Unable to connect to kuzzle server at \"' + self.host + '\"');\n\n connectionError.internal = error;\n self.state = 'error';\n self.emitEvent('error', connectionError);\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('jwtTokenExpired');\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 * 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 * @returns {Kuzzle}\n */\nKuzzle.prototype.login = function (strategy) {\n var\n self = this,\n request = {\n strategy: strategy\n },\n credentials,\n cb = null;\n\n // Handle arguments (credentials, expiresIn, cb)\n if (arguments[1]) {\n if (typeof arguments[1] === 'object') {\n credentials = 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 if (typeof credentials === 'object') {\n Object.keys(credentials).forEach(function (key) {\n request[key] = credentials[key];\n });\n }\n\n this.query({controller: 'auth', action: 'login'}, {body: 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 * 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: uuid.v4(),\n body: {}\n };\n\n this.query({controller: 'auth', action: 'logout'}, request, {queuable: false}, typeof cb !== 'function' ? null : function(error) {\n if (error === null) {\n self.jwtToken = undefined;\n cb(null, self);\n }\n else {\n cb(error);\n }\n });\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} callback The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n * @return {Kuzzle} The Kuzzle instance to enable chaining.\n */\nKuzzle.prototype.checkToken = function (token, callback) {\n var\n request = {\n body: {\n token: token\n }\n };\n\n this.callbackRequired('Kuzzle.checkToken', callback);\n\n this.query({controller: 'auth', action: 'checkToken'}, request, {queuable: false}, function (err, response) {\n if (err) {\n return callback(err);\n }\n\n callback(null, response.result);\n });\n};\n\n/**\n * Fetches the current user.\n *\n * @param {function} callback The callback to be called when the response is\n * available. The signature is `function(error, response)`.\n * @return {Kuzzle} The Kuzzle instance to enable chaining.\n */\nKuzzle.prototype.whoAmI = function (callback) {\n var self = this;\n\n self.callbackRequired('Kuzzle.whoAmI', callback);\n\n self.query({controller: 'auth', action: 'getCurrentUser'}, {}, {}, function (err, response) {\n if (err) {\n return callback(err);\n }\n\n callback(null, new KuzzleUser(self.security, response.result._id, response.result._source));\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 if (err) {\n return cb(err);\n }\n\n cb(null, 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 */\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 setTimeout(function () {\n cleanHistory(requestHistory);\n }, 1000);\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 if (request.action !== 'logout' && response.error && response.error.message === 'Token expired') {\n self.jwtToken = undefined;\n self.emitEvent('jwtTokenExpired', request, cb);\n }\n\n cb && cb(response.error, response);\n });\n }\n\n this.network.send(request);\n\n // Track requests made to allow KuzzleRoom.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 * 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 * The ID returned by this function is required to remove this listener at a later time.\n *\n * @param {string} event - name of the global event to subscribe to (see the 'eventListeners' object property)\n * @param {function} listener - callback to invoke each time an event is fired\n * @returns {string} Unique listener ID\n */\nKuzzle.prototype.addListener = function(event, listener) {\n var\n knownEvents = Object.keys(this.eventListeners),\n listenerType = typeof listener,\n listenerId;\n\n this.isValid();\n\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n if (listenerType !== 'function') {\n throw new Error('Invalid listener type: expected a function, got a ' + listenerType);\n }\n\n listenerId = uuid.v4();\n this.eventListeners[event].listeners.push({id: listenerId, fn: listener});\n return listenerId;\n};\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 * @returns {object} this\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:'admin', action: 'getAllStats'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, 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 * @returns {object} this\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: 'admin', action: timestamp ? 'getStats' : 'getLastStats'}, body, options, queryCB);\n};\n\n/**\n * Create a new instance of a KuzzleDataCollection 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 {object} A KuzzleDataCollection instance\n */\nKuzzle.prototype.dataCollectionFactory = 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 KuzzleDataCollection(this, index, collection);\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 * @returns {object} this\n */\nKuzzle.prototype.listCollections = function () {\n var\n collectionType = 'all',\n index,\n options,\n cb,\n args = Array.prototype.slice.call(arguments);\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 if (options && options.type) {\n collectionType = options.type;\n }\n\n this.query({index: index, controller: 'read', action: 'listCollections'}, {body: {type: collectionType}}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, 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 * @returns {object} this\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: 'read', action: 'listIndexes'}, {}, 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 this.logout();\n\n this.state = 'disconnected';\n this.network.close();\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 * @returns {object} this\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: 'read', action: 'serverInfo'}, {}, options, function (err, res) {\n if (err) {\n return cb(err);\n }\n\n cb(null, 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: 'admin', action: 'refreshIndex'}, {}, 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 * @returns {object} this\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: 'admin', 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: 'admin', 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 * @returns {object} this\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: 'read', action: 'now'}, {}, options, function (err, res) {\n cb(err, res && 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 * - metadata (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 metadata: this.metadata\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.metadata) {\n Object.keys(options.metadata).forEach(function (meta) {\n object.metadata[meta] = options.metadata[meta];\n });\n }\n\n if (options.queuable === false && self.state === 'offline') {\n return self;\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.metadata) {\n Object.keys(query.metadata).forEach(function (meta) {\n object.metadata[meta] = query.metadata[meta];\n });\n }\n\n for (attr in query) {\n if (attr !== 'metadata' && 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.headers = object.headers || {};\n object.headers.authorization = 'Bearer ' + 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 = uuid.v4();\n }\n\n if (self.state === 'connected' || (options && options.queuable === false)) {\n if (self.state === 'connected') {\n emitRequest.call(this, object, cb);\n } else if (cb) {\n cb(new Error('Unable to execute request: not connected to a Kuzzle server.\\nDiscarded request: ' + JSON.stringify(object)));\n }\n } else if (self.queuing || ['initializing', 'connecting'].indexOf(self.state) !== -1) {\n cleanQueue.call(this, object, cb);\n\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 }\n }\n\n return self;\n};\n\n/**\n * Removes all listeners, either from a specific event or from all events\n *\n * @param {string} event - One of the event described in the Event Handling section of this documentation\n */\nKuzzle.prototype.removeAllListeners = function (event) {\n var\n knownEvents = Object.keys(this.eventListeners),\n self = this;\n\n if (event) {\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n this.eventListeners[event].listeners = [];\n } else {\n knownEvents.forEach(function (eventName) {\n self.eventListeners[eventName].listeners = [];\n });\n }\n\n return this;\n};\n\n/**\n * Removes a listener from an event.\n *\n * @param {string} event - One of the event described in the Event Handling section of this documentation\n * @param {string} listenerId - The ID returned by addListener\n */\nKuzzle.prototype.removeListener = function (event, listenerId) {\n var\n knownEvents = Object.keys(this.eventListeners),\n self = this;\n\n if (knownEvents.indexOf(event) === -1) {\n throw new Error('[' + event + '] is not a known event. Known events: ' + knownEvents.toString());\n }\n\n this.eventListeners[event].listeners.forEach(function (listener, index) {\n if (listener.id === listenerId) {\n self.eventListeners[event].listeners.splice(index, 1);\n }\n });\n\n return this;\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\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzle.js\n ** module id = 0\n ** module chunks = 0\n **/","function KuzzleSecurityDocument(kuzzleSecurity, id, content) {\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: kuzzleSecurity.kuzzle\n },\n kuzzleSecurity: {\n value: kuzzleSecurity\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 });\n\n if (content) {\n this.setContent(content, true);\n }\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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 {Object} this\n */\nKuzzleSecurityDocument.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 */\nKuzzleSecurityDocument.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\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 */\nKuzzleSecurityDocument.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.kuzzleSecurity.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 */\nKuzzleSecurityDocument.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.kuzzleSecurity.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 = KuzzleSecurityDocument;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleSecurityDocument.js\n ** module id = 1\n ** module chunks = 0\n **/","var\n KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleUser(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\n\n // Define properties\n Object.defineProperties(this, {\n // private properties\n deleteActionName: {\n value: 'deleteUser'\n },\n updateActionName: {\n value: 'updateUser'\n }\n });\n\n // promisifying\n if (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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\nKuzzleUser.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleUser\n }\n});\n\n/**\n * Set profiles in content\n * @param {array} profile - an array of profiles ids string\n *\n * @returns {KuzzleUser} this\n */\nKuzzleUser.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 * Add a profile\n * @param {string} profile - a profile ids string\n *\n * @returns {KuzzleUser} this\n */\nKuzzleUser.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 * Saves this user into Kuzzle.\n *\n * If this is a new user, this function will create it in Kuzzle.\n * Otherwise, this method will replace the latest version of this user in Kuzzle by the current content\n * of this object.\n *\n * @param {responseCallback} [cb] - Handles the query response\n * @param {object} [options] - Optional parameters\n * @returns {*} this\n */\nKuzzleUser.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.kuzzleSecurity.buildQueryArgs('createOrReplaceUser'), 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 */\nKuzzleUser.prototype.serialize = function () {\n return {_id: this.id, body: this.content};\n};\n\n/**\n * Return the associated profiles IDs\n *\n * @return {array} the associated profiles IDs\n */\nKuzzleUser.prototype.getProfiles = function () {\n return this.content.profileIds;\n};\n\nmodule.exports = KuzzleUser;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleUser.js\n ** module id = 2\n ** module chunks = 0\n **/","// uuid.js\n//\n// Copyright (c) 2010-2012 Robert Kieffer\n// MIT License - http://opensource.org/licenses/mit-license.php\n\n/*global window, require, define */\n(function(_window) {\n 'use strict';\n\n // Unique ID creation requires a high quality random # generator. We feature\n // detect to determine the best RNG source, normalizing to a function that\n // returns 128-bits of randomness, since that's what's usually required\n var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot;\n\n function setupBrowser() {\n // Allow for MSIE11 msCrypto\n var _crypto = _window.crypto || _window.msCrypto;\n\n if (!_rng && _crypto && _crypto.getRandomValues) {\n // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto\n //\n // Moderately fast, high quality\n try {\n var _rnds8 = new Uint8Array(16);\n _whatwgRNG = _rng = function whatwgRNG() {\n _crypto.getRandomValues(_rnds8);\n return _rnds8;\n };\n _rng();\n } catch(e) {}\n }\n\n if (!_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 _mathRNG = _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 if ('undefined' !== typeof console && console.warn) {\n console.warn(\"[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()\");\n }\n }\n }\n\n function setupNode() {\n // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html\n //\n // Moderately fast, high quality\n if ('function' === typeof require) {\n try {\n var _rb = require('crypto').randomBytes;\n _nodeRNG = _rng = _rb && function() {return _rb(16);};\n _rng();\n } catch(e) {}\n }\n }\n\n if (_window) {\n setupBrowser();\n } else {\n setupNode();\n }\n\n // Buffer class to use\n var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;\n\n // Maps for number <-> hex string conversion\n var _byteToHex = [];\n var _hexToByte = {};\n for (var i = 0; i < 256; i++) {\n _byteToHex[i] = (i + 0x100).toString(16).substr(1);\n _hexToByte[_byteToHex[i]] = i;\n }\n\n // **`parse()` - Parse a UUID into it's component bytes**\n function parse(s, buf, offset) {\n var i = (buf && offset) || 0, ii = 0;\n\n buf = buf || [];\n s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {\n if (ii < 16) { // Don't overflow!\n buf[i + ii++] = _hexToByte[oct];\n }\n });\n\n // Zero out remaining bytes if string was short\n while (ii < 16) {\n buf[i + ii++] = 0;\n }\n\n return buf;\n }\n\n // **`unparse()` - Convert UUID byte array (ala parse()) into a string**\n function unparse(buf, offset) {\n var i = offset || 0, 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\n // **`v1()` - Generate time-based UUID**\n //\n // Inspired by https://github.com/LiosK/UUID.js\n // and http://docs.python.org/library/uuid.html\n\n // random #'s we need to init node and clockseq\n var _seedBytes = _rng();\n\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n var _nodeId = [\n _seedBytes[0] | 0x01,\n _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]\n ];\n\n // Per 4.2.2, randomize (14 bit) clockseq\n var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;\n\n // Previous uuid creation time\n var _lastMSecs = 0, _lastNSecs = 0;\n\n // See https://github.com/broofa/node-uuid for API details\n function v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || [];\n\n options = options || {};\n\n var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;\n\n // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n var msecs = (options.msecs != null) ? options.msecs : new Date().getTime();\n\n // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;\n\n // Time since last uuid creation (in msecs)\n var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\n // Per 4.2.1.2, Bump clockseq on clock regression\n if (dt < 0 && options.clockseq == null) {\n clockseq = clockseq + 1 & 0x3fff;\n }\n\n // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {\n nsecs = 0;\n }\n\n // Per 4.2.1.2 Throw error if too many uuids are requested\n if (nsecs >= 10000) {\n throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq;\n\n // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n msecs += 12219292800000;\n\n // `time_low`\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff;\n\n // `time_mid`\n var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff;\n\n // `time_high_and_version`\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n b[i++] = tmh >>> 16 & 0xff;\n\n // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n b[i++] = clockseq >>> 8 | 0x80;\n\n // `clock_seq_low`\n b[i++] = clockseq & 0xff;\n\n // `node`\n var node = options.node || _nodeId;\n for (var n = 0; n < 6; n++) {\n b[i + n] = node[n];\n }\n\n return buf ? buf : unparse(b);\n }\n\n // **`v4()` - Generate random UUID**\n\n // See https://github.com/broofa/node-uuid for API details\n function v4(options, buf, offset) {\n // Deprecated - 'format' argument, as supported in v1.2\n var i = buf && offset || 0;\n\n if (typeof(options) === 'string') {\n buf = (options === 'binary') ? new BufferClass(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 || unparse(rnds);\n }\n\n // Export public API\n var uuid = v4;\n uuid.v1 = v1;\n uuid.v4 = v4;\n uuid.parse = parse;\n uuid.unparse = unparse;\n uuid.BufferClass = BufferClass;\n uuid._rng = _rng;\n uuid._mathRNG = _mathRNG;\n uuid._nodeRNG = _nodeRNG;\n uuid._whatwgRNG = _whatwgRNG;\n\n if (('undefined' !== typeof module) && module.exports) {\n // Publish as node.js module\n module.exports = uuid;\n } else if (typeof define === 'function' && define.amd) {\n // Publish as AMD module\n define(function() {return uuid;});\n\n\n } else {\n // Publish as global (in browsers)\n _previousRoot = _window.uuid;\n\n // **`noConflict()` - (browser only) to reset global 'uuid' var**\n uuid.noConflict = function() {\n _window.uuid = _previousRoot;\n return uuid;\n };\n\n _window.uuid = uuid;\n }\n})('undefined' !== typeof window ? window : null);\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/node-uuid/uuid.js\n ** module id = 3\n ** module chunks = 0\n **/","var\n KuzzleDocument = require('./kuzzleDocument'),\n KuzzleDataMapping = require('./kuzzleDataMapping'),\n KuzzleRoom = require('./kuzzleRoom');\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 * @param {object} kuzzle - Kuzzle instance to inherit from\n * @param {string} index - Index containing the data collection\n * @param {string} collection - name of the data collection to handle\n * @constructor\n */\nfunction KuzzleDataCollection(kuzzle, index, collection) {\n if (!index || !collection) {\n throw new Error('The KuzzleDataCollection object constructor needs an index and a collection arguments');\n }\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 * 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 * @returns {Object} this\n */\nKuzzleDataCollection.prototype.advancedSearch = function (filters, options, cb) {\n var\n query,\n self = this;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleDataCollection.advancedSearch', cb);\n\n query = self.kuzzle.addHeaders({body: filters}, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('read', '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 KuzzleDocument(self, doc._id, doc._source);\n\n newDocument.version = doc._version;\n\n documents.push(newDocument);\n });\n\n cb(null, { total: result.result.total, documents: documents });\n });\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 * @returns {Object} this\n */\nKuzzleDataCollection.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('KuzzleDataCollection.count', cb);\n\n query = this.kuzzle.addHeaders({body: filters}, this.headers);\n\n this.kuzzle.query(this.buildQueryArgs('read', 'count'), query, options, function (error, result) {\n cb(error, result && result.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 */\nKuzzleDataCollection.prototype.create = 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('write', 'createCollection'), data, options, cb);\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 * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n * - updateIfExist (boolean, default: false):\n * If the same document already exists: throw an error if sets to false.\n * Update the existing document otherwise\n *\n * @param {string} [id] - (optional) document identifier\n * @param {object} document - either an instance of a KuzzleDocument object, or a document\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Handles the query response\n * @returns {Object} this\n */\nKuzzleDataCollection.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 KuzzleDocument) {\n data = document.serialize();\n } else {\n data.body = document;\n }\n\n if (options) {\n action = options.updateIfExist ? 'createOrReplace' : 'create';\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('write', action), data, options, cb && function (err, res) {\n var doc;\n\n if (err) {\n return cb(err);\n }\n\n doc = new KuzzleDocument(self, res.result._id, res.result._source);\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 * - metadata (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 {Object} this\n */\nKuzzleDataCollection.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 = 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('write', 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 * 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 * @returns {Object} this\n */\nKuzzleDataCollection.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('KuzzleDataCollection.fetch', cb);\n data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('read', 'get'), data, options, function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new KuzzleDocument(self, res.result._id, res.result._source);\n document.version = res.result._version;\n cb(null, document);\n });\n};\n\n/**\n * Retrieves all documents stored in this data collection\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Handles the query response\n * @returns {Object} this\n */\nKuzzleDataCollection.prototype.fetchAllDocuments = function (options, cb) {\n var filters = {};\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n // copying pagination options to the search filter\n if (options) {\n if (options.from) {\n filters.from = options.from;\n }\n\n if (options.size) {\n filters.size = options.size;\n }\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.fetchAll', cb);\n\n this.advancedSearch(filters, options, cb);\n};\n\n\n/**\n * Instantiates a KuzzleDataMapping object containing the current mapping of this collection.\n *\n * @param {object} [options] - Optional parameters\n * @param {responseCallback} cb - Returns an instantiated KuzzleDataMapping object\n * @return {object} this\n */\nKuzzleDataCollection.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('KuzzleDataCollection.getMapping', cb);\n\n kuzzleMapping = new KuzzleDataMapping(this);\n kuzzleMapping.refresh(options, cb);\n};\n\n/**\n * Publish a realtime message\n *\n * Takes an optional argument object with the following properties:\n * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} document - either a KuzzleDocument instance or a JSON object\n * @param {object} [options] - optional arguments\n * @param {responseCallback} [cb] - Returns a raw Kuzzle response\n * @returns {*} this\n */\nKuzzleDataCollection.prototype.publishMessage = function (document, options, cb) {\n var data = {};\n\n if (document instanceof KuzzleDocument) {\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('write', '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 * - metadata (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 KuzzleDocument object\n * @return {object} this\n */\nKuzzleDataCollection.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('write', 'createOrReplace'), data, options, cb && function (err, res) {\n var document;\n\n if (err) {\n return cb(err);\n }\n\n document = new KuzzleDocument(self, res.result._id, res.result._source);\n document.version = res.result._version;\n cb(null, document);\n });\n\n return this;\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 {*} KuzzleRoom object\n */\nKuzzleDataCollection.prototype.subscribe = function (filters, options, cb) {\n var room;\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.kuzzle.callbackRequired('KuzzleDataCollection.subscribe', cb);\n\n room = new KuzzleRoom(this, options);\n room.renew(filters, cb);\n\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 */\nKuzzleDataCollection.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('admin', 'truncateCollection'), 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 * - metadata (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 KuzzleDocument object\n * @return {object} this\n */\nKuzzleDataCollection.prototype.updateDocument = function (documentId, content, options, cb) {\n var\n 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 data = self.kuzzle.addHeaders(data, this.headers);\n\n self.kuzzle.query(this.buildQueryArgs('write', 'update'), data, options, cb && function (err, res) {\n if (err) {\n return cb(err);\n }\n\n (new KuzzleDocument(self, res.result._id)).refresh(cb);\n });\n\n return self;\n};\n\n\n/**\n * Instantiate a new KuzzleDocument 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 */\nKuzzleDataCollection.prototype.documentFactory = function (id, content) {\n return new KuzzleDocument(this, id, content);\n};\n\n/**\n * Instantiate a new KuzzleRoom 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 */\nKuzzleDataCollection.prototype.roomFactory = function (options) {\n return new KuzzleRoom(this, options);\n};\n\n/**\n * Instantiate a new KuzzleDataMapping 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 KuzzleDataMapping object with\n * @constructor\n */\nKuzzleDataCollection.prototype.dataMappingFactory = function (mapping) {\n return new KuzzleDataMapping(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 */\nKuzzleDataCollection.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\nmodule.exports = KuzzleDataCollection;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDataCollection.js\n ** module id = 4\n ** module chunks = 0\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 * 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 KuzzleDataMapping object allow to get the current mapping of a data collection and to modify it if needed.\n *\n * @param {object} kuzzleDataCollection - Instance of the inherited KuzzleDataCollection object\n * @param {object} mapping - mappings\n * @constructor\n */\nfunction KuzzleDataMapping(kuzzleDataCollection, mapping) {\n Object.defineProperties(this, {\n //read-only properties\n collection: {\n value: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.kuzzle,\n enumerable: true\n },\n // writable properties\n headers: {\n value: JSON.parse(JSON.stringify(kuzzleDataCollection.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 */\nKuzzleDataMapping.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('admin', '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 */\nKuzzleDataMapping.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('admin', '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 {KuzzleDataMapping}\n */\nKuzzleDataMapping.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 */\nKuzzleDataMapping.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\nmodule.exports = KuzzleDataMapping;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDataMapping.js\n ** module id = 5\n ** module chunks = 0\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 handles documents either as realtime messages or as stored documents.\n * KuzzleDocument 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 {object} kuzzleDataCollection - an instanciated KuzzleDataCollection object\n * @param {string} [documentId] - ID of an existing document\n * @param {object} [content] - Initializes this document with the provided content\n * @constructor\n */\nfunction KuzzleDocument(kuzzleDataCollection, documentId, content) {\n Object.defineProperties(this, {\n // read-only properties\n collection: {\n value: kuzzleDataCollection.collection,\n enumerable: true\n },\n dataCollection: {\n value: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.kuzzle,\n enumerable: true\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(kuzzleDataCollection.headers)),\n enumerable: true,\n writable: true\n },\n version: {\n value: undefined,\n enumerable: true,\n writable: true\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 */\nKuzzleDocument.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._version = this.version;\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 */\nKuzzleDocument.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 * - metadata (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 */\nKuzzleDocument.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('KuzzleDocument.delete: cannot delete a document without a document ID');\n }\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('write', 'delete'), this.serialize(), options, cb && function (err) {\n cb(err, err ? undefined : self.id);\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 */\nKuzzleDocument.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('KuzzleDocument.refresh: cannot retrieve a document if no ID has been provided');\n }\n\n this.kuzzle.callbackRequired('KuzzleDocument.refresh', cb);\n\n self.kuzzle.query(self.dataCollection.buildQueryArgs('read', 'get'), {_id: self.id}, options, function (error, res) {\n var newDocument;\n\n if (error) {\n return cb(error);\n }\n\n newDocument = new KuzzleDocument(self.dataCollection, self.id, res.result._source);\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 * - metadata (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 */\nKuzzleDocument.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('write', '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 * - metadata (object, default: null):\n * Additional information passed to notifications to other users\n *\n * @param {object} [options] - Optional parameters\n * @returns {*} this\n */\nKuzzleDocument.prototype.publish = function (options) {\n var data = this.serialize();\n\n this.kuzzle.query(this.dataCollection.buildQueryArgs('write', '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 */\nKuzzleDocument.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 */\nKuzzleDocument.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('KuzzleDocument.subscribe', cb);\n\n if (!this.id) {\n throw new Error('KuzzleDocument.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 */\nKuzzleDocument.prototype.setHeaders = function (content, replace) {\n this.kuzzle.setHeaders.call(this, content, replace);\n return this;\n};\n\n\nmodule.exports = KuzzleDocument;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleDocument.js\n ** module id = 6\n ** module chunks = 0\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), excepting:\n * * all cluster based functions\n * * all script based functions\n * * all cursors functions\n *\n * For instance:\n * kuzzle.memoryStorage\n * .set('myKey', 'myValue')\n * .get('myKey', function (err, response) {\n * console.log(response.result);\n *\n * // { _id: 'foo', body: { value: 'myValue' }}\n * });\n *\n *\n * @param {object} kuzzle - Kuzzle instance to inherit from\n * @constructor\n */\nfunction KuzzleMemoryStorage(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\n/**\n * constructs the memoryStorage functions.\n */\n(function() {\n\n var\n keyVal = ['id', 'value'],\n idOrKeys = ['id', 'keys'],\n commands = {\n append: keyVal,\n bgrewriteaof: [],\n bgsave: [],\n bitcount: ['id', 'start', 'end'],\n bitop: ['operation', 'destkey', idOrKeys],\n bitpos: ['id', 'bit', { __opts__: ['start', 'end']}],\n blpop: [idOrKeys, 'timeout'],\n brpoplpush: ['source', 'destination'],\n dbsize: [],\n decrby: keyVal,\n del: [idOrKeys],\n discard: [],\n exec: [],\n exists: [idOrKeys],\n expire: ['id', 'seconds'],\n expireat: ['id', 'timestamp'],\n flushdb: [],\n // @todo: implement geolocation methods once available in Redis stable release\n getbit: ['id', 'offset'],\n getrange: ['id', 'start', 'end'],\n hdel: ['id', ['field', 'fields']],\n hexists: ['id', 'field'],\n hincrby: ['id', 'field', 'value'],\n hmset: ['id', 'values'],\n hset: ['id', 'field', 'value'],\n info: ['section'],\n keys: [ 'pattern' ],\n lastsave: [],\n lindex: ['id', 'idx'],\n linsert: ['id', 'position', 'pivot', 'value'],\n lpush: ['id', ['value', 'values']],\n lrange: ['id', 'start', 'stop'],\n lrem: ['id', 'count', 'value'],\n lset: ['id', 'idx', 'value'],\n ltrim: ['id', 'start', 'stop'],\n mset: ['values'],\n multi: [],\n object: ['subcommand', 'args'],\n pexpire: ['id', 'milliseconds'],\n pexpireat: ['id', 'timestamp'],\n pfadd: ['id', ['element', 'elements']],\n pfmerge: ['destkey', ['sourcekey', 'sourcekeys']],\n ping: [],\n psetex: ['id', 'milliseconds', 'value'],\n publish: ['channel', 'message'],\n randomkey: [],\n rename: ['id', 'newkey'],\n renamenx: ['id', 'newkey'],\n restore: ['id', 'ttl', 'content'],\n rpoplpush: ['source', 'destination'],\n sadd: ['id', ['member', 'members']],\n save: [],\n set: ['id', 'value', {__opts__:['ex', 'px', 'nx', 'xx']}],\n sdiffstore: ['destination', idOrKeys],\n setbit: ['id', 'offset', 'value'],\n setex: ['id', 'seconds', 'value'],\n setrange: ['id', 'offset', 'value'],\n sinterstore: ['destination', idOrKeys],\n sismember: ['id', 'member'],\n smove: ['id', 'destination', 'member'],\n sort: ['id', {__opts__:['by', 'offset', 'count', 'get', 'direction', 'alpha', 'store']}],\n spop: ['id', 'count'],\n srem: ['id', ['member', 'members']],\n sunionstore: ['destination', idOrKeys],\n unwatch: [],\n wait: ['numslaves', 'timeout'],\n zadd: ['id', {__opts__: ['nx', 'xx', 'ch', 'incr', 'score', 'member', 'members']}],\n zcount: ['id', 'min', 'max'],\n zincrby: ['id', 'value', 'member'],\n zinterstore: ['destination', idOrKeys, {__opts__: ['weight', 'weights', 'aggregate']}],\n zlexcount: ['id', 'min', 'max'],\n zrange: ['id', 'start', 'stop', {__opts__: ['withscores']}],\n zrangebylex: ['id', 'min', 'max', {__opts__: ['offset', 'count']}],\n zrangebyscore: ['id', 'min', 'max', {__opts__: ['withscores', 'offset', 'count']}],\n zrem: ['id', 'member'],\n zremrangebylex: ['id', 'min', 'max'],\n zremrangebyscore: ['id', 'min', 'max'],\n zrevrangebylex: ['id', 'max', 'min', {__opts__: ['offset', 'count']}],\n zrevrangebyscore: ['id', 'max', 'min', {__opts__: ['withscores', 'offset', 'count']}],\n zrevrank: ['id', 'member']\n };\n\n // unique argument key\n commands.decr = commands.get = commands.dump = commands.hgetall = commands.hkeys = commands.hlen = commands.hstrlen = commands.hvals = commands.incr = commands.llen = commands.lpop = commands.persist = commands.pttl = commands.rpop = commands.scard = commands.smembers = commands.strlen = commands.ttl = commands.type = commands.zcard = ['id'];\n\n // key value\n commands.getset = commands.lpushx = keyVal;\n\n // key key...\n commands.del = commands.exists = commands.mget = commands.pfcount = commands.sdiff = commands.sinter = commands.sunion = commands.watch = [idOrKeys];\n\n commands.incrby = commands.incrbyfloat = commands.decrby;\n commands.brpop = commands.blpop;\n commands.hget = commands.hexists;\n commands.hmget = commands.hdel;\n commands.hsetnx = commands.hset;\n commands.msetnx = commands.mset;\n commands.rpush = commands.lpush;\n commands.hincrbyfloat = commands.hincrby;\n commands.srandmember = commands.spop;\n commands.zrevrange = commands.zrange;\n commands.zscore = commands.zrevrank;\n\n Object.keys(commands).forEach(function (command) {\n KuzzleMemoryStorage.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 (typeof args[args.length - 1] === 'function') {\n cb = args.pop();\n }\n\n if (args.length && typeof args[args.length - 1] === 'object' && Object.keys(args[args.length - 1]).length === 1 && args[args.length - 1].queuable !== undefined) {\n options = args.pop();\n }\n\n commands[command].forEach(function (v, i) {\n if (args[i] === undefined) {\n return;\n }\n\n if (Array.isArray(v)) {\n v = Array.isArray(args[i]) ? v[1] : v[0];\n }\n\n if (v === 'id') {\n data._id = args[i];\n }\n else {\n if (!data.body) {\n data.body = {};\n }\n\n if (typeof v === 'object' && v.__opts__ !== undefined) {\n v.__opts__.forEach(function (arg) {\n if (args[i][arg] !== undefined) {\n data.body[arg] = args[i][arg];\n }\n });\n }\n else {\n data.body[v] = args[i];\n }\n }\n });\n\n this.kuzzle.query(query, data, options, cb);\n\n return this;\n\n };\n });\n\n})();\n\nmodule.exports = KuzzleMemoryStorage;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleMemoryStorage.js\n ** module id = 7\n ** module chunks = 0\n **/","var\n uuid = require('node-uuid');\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} kuzzleDataCollection - an instantiated and valid kuzzle object\n * @param {object} [options] - subscription optional configuration\n * @constructor\n */\nfunction KuzzleRoom(kuzzleDataCollection, 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: uuid.v4()\n },\n lastRenewal: {\n value: null,\n writable: true\n },\n notifier: {\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: kuzzleDataCollection,\n enumerable: true\n },\n kuzzle: {\n value: kuzzleDataCollection.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(kuzzleDataCollection.headers)),\n enumerable: true,\n writable: true\n },\n metadata: {\n value: (options && options.metadata) ? options.metadata : {},\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 */\nKuzzleRoom.prototype.count = function (cb) {\n var data;\n\n this.kuzzle.callbackRequired('KuzzleRoom.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('KuzzleRoom.count: cannot count subscriptions on an inactive room');\n }\n\n this.kuzzle.query(this.collection.buildQueryArgs('subscribe', '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} cb - called for each new notification\n */\nKuzzleRoom.prototype.renew = function (filters, cb) {\n var\n now = Date.now(),\n subscribeQuery = {\n scope: this.scope,\n state: this.state,\n users: this.users\n },\n self = this;\n\n if (!cb && filters && typeof filters === 'function') {\n cb = filters;\n filters = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleRoom.renew', cb);\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;\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 = 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, cb]});\n return;\n }\n\n self.unsubscribe();\n self.roomId = null;\n self.subscribing = true;\n self.callback = cb;\n self.kuzzle.subscriptions.pending[self.id] = self;\n\n subscribeQuery.body = self.filters;\n subscribeQuery = self.kuzzle.addHeaders(subscribeQuery, this.headers);\n\n self.kuzzle.query(self.collection.buildQueryArgs('subscribe', 'on'), subscribeQuery, {metadata: self.metadata}, function (error, response) {\n delete self.kuzzle.subscriptions.pending[self.id];\n self.subscribing = false;\n\n if (error) {\n self.queue = [];\n throw 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 });\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 */\nKuzzleRoom.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('subscribe', 'off'), {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('subscribe', 'off'), {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 */\nKuzzleRoom.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.error) {\n return this.callback(data.error);\n }\n\n if (data.action === 'jwtTokenExpired') {\n this.kuzzle.jwtToken = undefined;\n return this.kuzzle.emitEvent('jwtTokenExpired');\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 = KuzzleRoom;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/kuzzleRoom.js\n ** module id = 8\n ** module chunks = 0\n **/","/**\n *\n * @param host\n * @param wsPort\n * @param ioPort\n * @returns {Object} tnstantiated WebSocket/Socket.IO object\n */\n\nfunction network(host, wsPort, ioPort, 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/wsbrowsers'))(host, wsPort, sslConnection);\n }\n // otherwise fallback to socket.io, if available\n else if (window.io) {\n return new (require('./wrappers/socketio'))(host, ioPort, 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/wsnode'))(host, wsPort, sslConnection);\n}\n\nmodule.exports = network;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/index.js\n ** module id = 9\n ** module chunks = 0\n **/","function SocketIO(host, port, ssl) {\n this.host = host;\n this.port = port;\n this.ssl = ssl;\n this.socket = null;\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 this.socket = window.io((this.ssl ? 'https://' : 'http://') + this.host + ':' + this.port, {\n reconnection: autoReconnect,\n reconnectionDelay: reconnectionDelay,\n forceNew: true\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.socket.on('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.socket.on('connect_error', 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.socket.on('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.socket.on('reconnect', callback);\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.socket.close();\n this.socket = null;\n };\n}\n\nmodule.exports = SocketIO;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/wrappers/socketio.js\n ** module id = 10\n ** module chunks = 0\n **/","function WSBrowsers(host, port, ssl) {\n var self = this;\n this.host = host;\n this.port = port;\n this.ssl = ssl;\n this.client = null;\n this.retrying = false;\n\n /*\n Listeners are stored using the following format:\n roomId: {\n fn: callback_function,\n once: boolean\n }\n */\n this.listeners = {\n error: [],\n connect: [],\n disconnect: [],\n reconnect: []\n };\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 this.client = new WebSocket((this.ssl ? 'wss://' : 'ws://') + this.host + ':' + this.port);\n\n this.client.onopen = function () {\n if (self.retrying) {\n poke(self.listeners, 'reconnect');\n }\n else {\n poke(self.listeners, 'connect');\n }\n };\n\n this.client.onclose = function () {\n poke(self.listeners, 'disconnect');\n };\n\n this.client.onerror = function () {\n if (autoReconnect) {\n self.retrying = true;\n setTimeout(function () {\n self.connect(autoReconnect, reconnectionDelay);\n }, reconnectionDelay);\n }\n\n poke(self.listeners, 'error');\n };\n\n this.client.onmessage = function (payload) {\n var data = JSON.parse(payload.data);\n\n if (data.room && self.listeners[data.room]) {\n poke(self.listeners, data.room, 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.listeners.connect.push({\n fn: callback,\n keep: true\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 this.listeners.error.push({\n fn: callback,\n keep: true\n });\n };\n\n /**\n * Fires the provided callback whenever a disconnection occurred\n * @param {function} callback\n */\n this.onDisconnect = function (callback) {\n this.listeners.disconnect.push({\n fn: callback,\n keep: true\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 this.listeners.reconnect.push({\n fn: callback,\n keep: true\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 if (!this.listeners[roomId]) {\n this.listeners[roomId] = [];\n }\n\n this.listeners[roomId].push({\n fn: callback,\n keep: false\n });\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 if (!this.listeners[roomId]) {\n this.listeners[roomId] = [];\n }\n\n this.listeners[roomId].push({\n fn: callback,\n keep: true\n });\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 var index;\n\n if (this.listeners[roomId]) {\n index = this.listeners[roomId].findIndex(function (listener) {\n return listener.fn === callback;\n });\n\n if (index !== -1) {\n if (this.listeners[roomId].length === 1 && ['error', 'connect', 'disconnect', 'reconnect'].indexOf(roomId) === -1) {\n delete this.listeners[roomId];\n }\n else {\n this.listeners[roomId].splice(index, 1);\n }\n }\n }\n };\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.listeners = {\n error: [],\n connect: [],\n disconnect: [],\n reconnect: []\n };\n\n this.retrying = false;\n this.client.close();\n this.client = null;\n };\n}\n\n/**\n * Executes all registered listeners in the provided\n * \"listeners\" structure.\n *\n * Listeners are of the following format:\n * [\n * { fn: callback, once: boolean },\n * ...\n * ]\n *\n * @private\n * @param {Object} listeners\n * @param {string} roomId\n * @param {Object} [payload]\n */\nfunction poke (listeners, roomId, payload) {\n var\n i,\n length = listeners[roomId].length;\n\n for (i = 0; i < length; ++i) {\n listeners[roomId][i].fn(payload);\n\n if (!listeners[roomId][i].keep) {\n if (listeners[roomId].length > 1) {\n listeners[roomId].splice(i, 1);\n --i;\n --length;\n }\n else {\n delete listeners[roomId];\n }\n }\n }\n}\n\nmodule.exports = WSBrowsers;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/networkWrapper/wrappers/wsbrowsers.js\n ** module id = 11\n ** module chunks = 0\n **/","var\n KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleProfile(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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\nKuzzleProfile.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleProfile\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 {Object} this\n */\nKuzzleProfile.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.kuzzleSecurity.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 {KuzzleProfile} this\n */\nKuzzleProfile.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 {KuzzleProfile} this\n */\nKuzzleProfile.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 */\nKuzzleProfile.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\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 */\nKuzzleProfile.prototype.getPolicies = function () {\n return this.content.policies;\n};\n\nmodule.exports = KuzzleProfile;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleProfile.js\n ** module id = 12\n ** module chunks = 0\n **/","var KuzzleSecurityDocument = require('./kuzzleSecurityDocument');\n\nfunction KuzzleRole(kuzzleSecurity, id, content) {\n\n KuzzleSecurityDocument.call(this, kuzzleSecurity, id, content);\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 (kuzzleSecurity.kuzzle.bluebird) {\n return kuzzleSecurity.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\nKuzzleRole.prototype = Object.create(KuzzleSecurityDocument.prototype, {\n constructor: {\n value: KuzzleRole\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 */\nKuzzleRole.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.kuzzleSecurity.buildQueryArgs('createOrReplaceRole'), data, options, cb && function (error) {\n cb(error, error ? undefined : self);\n });\n\n return this;\n};\n\nmodule.exports = KuzzleRole;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleRole.js\n ** module id = 13\n ** module chunks = 0\n **/","var\n KuzzleRole = require('./kuzzleRole'),\n KuzzleProfile = require('./kuzzleProfile'),\n KuzzleUser = require('./kuzzleUser');\n\n/**\n * Kuzzle security constructor\n *\n * @param kuzzle\n * @returns {KuzzleSecurity}\n * @constructor\n */\nfunction KuzzleSecurity(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 = ['roleFactory', 'profileFactory', 'userFactory', '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} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getRole = function (id, options, cb) {\n var\n data,\n self = this;\n\n if (!id) {\n throw new Error('Id parameter is mandatory for getRole 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('KuzzleSecurity.getRole', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getRole'), data, options, function (err, response) {\n cb(err, err ? undefined : new KuzzleRole(self, response.result._id, response.result._source));\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} [options] - Optional parameters\n * @param {responseCallback} [cb] - returns Kuzzle's response\n *\n */\nKuzzleSecurity.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('KuzzleSecurity.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 KuzzleRole(self, doc._id, doc._source);\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.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('KuzzleSecurity.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 KuzzleRole(self, res.result._id, res.result._source));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.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('KuzzleSecurity.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) {\n cb(err, err ? undefined : new KuzzleRole(self, id, content));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleSecurity.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 KuzzleRole 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 * @constructor\n */\nKuzzleSecurity.prototype.roleFactory = function(id, content) {\n return new KuzzleRole(this, id, content);\n};\n\n\n/**\n * Get a specific profile from kuzzle\n *\n *\n * @param {string} id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getProfile = 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 getProfile function');\n }\n\n\n data = {_id: id};\n\n self.kuzzle.callbackRequired('KuzzleSecurity.getProfile', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getProfile'), data, options, function (error, response) {\n cb(error, error ? undefined : new KuzzleProfile(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.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('KuzzleSecurity.searchProfiles', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchProfiles'), {body: filters}, options, function (error, response) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new KuzzleProfile(self, doc._id, doc._source);\n });\n\n cb(null, { total: response.result.total, profiles: documents });\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 {object} content - attribute `roles` in `content` must only contains an array of role id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.createProfile = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'createProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.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 data.body = content;\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 KuzzleProfile(self, res.result._id, res.result._source));\n });\n};\n\n\n/**\n * Update a profile in Kuzzle.\n *\n * @param {string} id - profile identifier\n * @param {object} content - a plain javascript object representing the profile's modification\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.updateProfile = function (id, content, options, cb) {\n var\n self = this,\n data = {},\n action = 'updateProfile';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.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 data.body = content;\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 KuzzleProfile(self, res.result._id, updatedContent));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleSecurity.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 * Instantiate a new KuzzleProfile 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 * @constructor\n */\nKuzzleSecurity.prototype.profileFactory = function(id, content) {\n return new KuzzleProfile(this, id, content);\n};\n\n/**\n * Get a specific user from kuzzle using its unique ID\n *\n * @param {string} id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} cb - returns Kuzzle's response\n */\nKuzzleSecurity.prototype.getUser = 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 getUser function');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n self.kuzzle.callbackRequired('KuzzleSecurity.getUser', cb);\n\n self.kuzzle.query(this.buildQueryArgs('getUser'), data, options, function (err, response) {\n cb(err, err ? undefined : new KuzzleUser(self, response.result._id, response.result._source));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - returns Kuzzle's response\n */\nKuzzleSecurity.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('KuzzleSecurity.searchUsers', cb);\n\n self.kuzzle.query(this.buildQueryArgs('searchUsers'), {body: filters}, options, function (error, response) {\n var documents;\n\n if (error) {\n return cb(error);\n }\n\n documents = response.result.hits.map(function (doc) {\n return new KuzzleUser(self, doc._id, doc._source);\n });\n\n cb(null, { total: response.result.total, users: documents });\n });\n};\n\n/**\n * Create a new user in Kuzzle.\n *\n * Takes an optional argument object with the following property:\n * - replaceIfExist (boolean, default: false):\n * If the same user already exists: throw an error if sets to false.\n * Replace the existing user otherwise\n *\n * @param {string} id - user identifier\n * @param {object} content - attribute `profile` in `content` must only contains the profile id\n * @param {object} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.prototype.createUser = function (id, content, options, cb) {\n var\n self = this,\n data = {_id: id, body: content},\n action = 'createUser';\n\n if (!id || typeof id !== 'string') {\n throw new Error('KuzzleSecurity.createUser: cannot create a user without a user ID');\n }\n\n if (!cb && typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n if (options) {\n action = options.replaceIfExist ? 'createOrReplaceUser' : 'createUser';\n }\n\n self.kuzzle.query(this.buildQueryArgs(action), data, null, cb && function (err, res) {\n cb(err, err ? undefined : new KuzzleUser(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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - (optional) Handles the query response\n */\nKuzzleSecurity.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('KuzzleSecurity.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 KuzzleUser(self, res.result._id, res.result._source));\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} [options] - (optional) arguments\n * @param {responseCallback} [cb] - Handles the query response\n */\nKuzzleSecurity.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 * Instantiate a new KuzzleUser 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 * @constructor\n */\nKuzzleSecurity.prototype.userFactory = function(id, content) {\n return new KuzzleUser(this, id, content);\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 */\nKuzzleSecurity.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} [options] - (optional) arguments\n * @param {function} cb The callback containing the normalized array of rights.\n */\nKuzzleSecurity.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\nmodule.exports = KuzzleSecurity;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/security/kuzzleSecurity.js\n ** module id = 14\n ** module chunks = 0\n **/"],"sourceRoot":""} \ No newline at end of file diff --git a/src/kuzzle.js b/src/kuzzle.js index 6dd5e10f5..a7b7731c5 100644 --- a/src/kuzzle.js +++ b/src/kuzzle.js @@ -447,7 +447,6 @@ Kuzzle.prototype.getJwtToken = function() { * @param credentials * @param expiresIn * @param cb - * @returns {Kuzzle} */ Kuzzle.prototype.login = function (strategy) { var @@ -535,7 +534,6 @@ Kuzzle.prototype.logout = function (cb) { * @param {string} token The jwt token to check * @param {function} callback The callback to be called when the response is * available. The signature is `function(error, response)`. - * @return {Kuzzle} The Kuzzle instance to enable chaining. */ Kuzzle.prototype.checkToken = function (token, callback) { var @@ -561,7 +559,6 @@ Kuzzle.prototype.checkToken = function (token, callback) { * * @param {function} callback The callback to be called when the response is * available. The signature is `function(error, response)`. - * @return {Kuzzle} The Kuzzle instance to enable chaining. */ Kuzzle.prototype.whoAmI = function (callback) { var self = this; @@ -608,6 +605,7 @@ Kuzzle.prototype.getMyRights = function (options, cb) { * @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 @@ -808,7 +806,6 @@ Kuzzle.prototype.addListener = function(event, listener) { * * @param {object} [options] - Optional parameters * @param {responseCallback} cb - Handles the query response - * @returns {object} this */ Kuzzle.prototype.getAllStatistics = function (options, cb) { if (!cb && typeof options === 'function') { @@ -834,7 +831,6 @@ Kuzzle.prototype.getAllStatistics = function (options, cb) { * @param {number} timestamp - Epoch time. Starting time from which the frames are to be retrieved * @param {object} [options] - Optional parameters * @param {responseCallback} cb - Handles the query response - * @returns {object} this */ Kuzzle.prototype.getStatistics = function (timestamp, options, cb) { var @@ -922,7 +918,6 @@ Kuzzle.prototype.flushQueue = function () { * @param {string} [index] - Index containing collections to be listed * @param {object} [options] - Optional parameters * @param {responseCallback} cb - Handles the query response - * @returns {object} this */ Kuzzle.prototype.listCollections = function () { var @@ -974,7 +969,6 @@ Kuzzle.prototype.listCollections = function () { * * @param {object} [options] - Optional arguments * @param {responseCallback} cb - Handles the query response - * @returns {object} this */ Kuzzle.prototype.listIndexes = function (options, cb) { if (!cb && typeof options === 'function') { @@ -1012,7 +1006,6 @@ Kuzzle.prototype.disconnect = function () { * * @param {object} [options] - Optional arguments * @param {responseCallback} cb - Handles the query response - * @returns {object} this */ Kuzzle.prototype.getServerInfo = function (options, cb) { if (!cb && typeof options === 'function') { @@ -1077,7 +1070,6 @@ Kuzzle.prototype.refreshIndex = function () { * @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 - * @returns {object} this */ Kuzzle.prototype.getAutoRefresh = function () { var @@ -1163,7 +1155,6 @@ Kuzzle.prototype.setAutoRefresh = function () { * Return the current Kuzzle's UTC Epoch time, in milliseconds * @param {object} [options] - Optional parameters * @param {responseCallback} cb - Handles the query response - * @returns {object} this */ Kuzzle.prototype.now = function (options, cb) { if (!cb && typeof options === 'function') { @@ -1281,6 +1272,7 @@ Kuzzle.prototype.query = function (queryArgs, query, options, cb) { * Removes all listeners, either from a specific event or from all events * * @param {string} event - One of the event described in the Event Handling section of this documentation + * @returns {Kuzzle} this object */ Kuzzle.prototype.removeAllListeners = function (event) { var @@ -1307,6 +1299,7 @@ Kuzzle.prototype.removeAllListeners = function (event) { * * @param {string} event - One of the event described in the Event Handling section of this documentation * @param {string} listenerId - The ID returned by addListener + * @returns {Kuzzle} this object */ Kuzzle.prototype.removeListener = function (event, listenerId) { var diff --git a/src/kuzzleDataCollection.js b/src/kuzzleDataCollection.js index 39c970775..866084879 100644 --- a/src/kuzzleDataCollection.js +++ b/src/kuzzleDataCollection.js @@ -82,7 +82,6 @@ function KuzzleDataCollection(kuzzle, index, collection) { * @param {object} filters - Filters in Elasticsearch Query DSL format * @param {object} [options] - Optional parameters * @param {responseCallback} cb - Handles the query response - * @returns {Object} this */ KuzzleDataCollection.prototype.advancedSearch = function (filters, options, cb) { var @@ -127,7 +126,6 @@ KuzzleDataCollection.prototype.advancedSearch = function (filters, options, cb) * @param {object} filters - Filters in Elasticsearch Query DSL format * @param {object} [options] - Optional parameters * @param {responseCallback} cb - Handles the query response - * @returns {Object} this */ KuzzleDataCollection.prototype.count = function (filters, options, cb) { var @@ -249,7 +247,7 @@ KuzzleDataCollection.prototype.createDocument = function (id, document, options, * @param {string|object} arg - Either a document ID (will delete only this particular document), or a set of filters * @param {object} [options] - optional arguments * @param {responseCallback} [cb] - Handles the query response - * @returns {Object} this + * @returns {KuzzleDataCollection} this */ KuzzleDataCollection.prototype.deleteDocument = function (arg, options, cb) { var @@ -289,7 +287,6 @@ KuzzleDataCollection.prototype.deleteDocument = function (arg, options, cb) { * @param {string} documentId - Unique document identifier * @param {object} [options] - Optional parameters * @param {responseCallback} cb - Handles the query response - * @returns {Object} this */ KuzzleDataCollection.prototype.fetchDocument = function (documentId, options, cb) { var @@ -322,7 +319,6 @@ KuzzleDataCollection.prototype.fetchDocument = function (documentId, options, cb * * @param {object} [options] - Optional parameters * @param {responseCallback} cb - Handles the query response - * @returns {Object} this */ KuzzleDataCollection.prototype.fetchAllDocuments = function (options, cb) { var filters = {}; @@ -354,7 +350,6 @@ KuzzleDataCollection.prototype.fetchAllDocuments = function (options, cb) { * * @param {object} [options] - Optional parameters * @param {responseCallback} cb - Returns an instantiated KuzzleDataMapping object - * @return {object} this */ KuzzleDataCollection.prototype.getMapping = function (options, cb) { var kuzzleMapping; diff --git a/src/security/kuzzleProfile.js b/src/security/kuzzleProfile.js index ed507f29f..bd75192d0 100644 --- a/src/security/kuzzleProfile.js +++ b/src/security/kuzzleProfile.js @@ -41,7 +41,7 @@ KuzzleProfile.prototype = Object.create(KuzzleSecurityDocument.prototype, { * * @param {object} [options] - Optional parameters * @param {responseCallback} [cb] - Handles the query response - * @returns {Object} this + * @returns {KuzzleProfile} this */ KuzzleProfile.prototype.save = function (options, cb) { var diff --git a/src/security/kuzzleRole.js b/src/security/kuzzleRole.js index c619b5b11..186b42942 100644 --- a/src/security/kuzzleRole.js +++ b/src/security/kuzzleRole.js @@ -44,6 +44,7 @@ KuzzleRole.prototype = Object.create(KuzzleSecurityDocument.prototype, { * * @param {object} [options] - Optional parameters * @param {responseCallback} [cb] - Handles the query response + * @returns {KuzzleRole} this object */ KuzzleRole.prototype.save = function (options, cb) { var diff --git a/src/security/kuzzleSecurity.js b/src/security/kuzzleSecurity.js index 8da9c9280..a5dcb5495 100644 --- a/src/security/kuzzleSecurity.js +++ b/src/security/kuzzleSecurity.js @@ -156,6 +156,7 @@ KuzzleSecurity.prototype.createRole = function (id, content, options, cb) { * @param {object} content - a plain javascript object representing the role's modification * @param {object} [options] - (optional) arguments * @param {responseCallback} [cb] - (optional) Handles the query response + * @returns {KuzzleSecurity} this object */ KuzzleSecurity.prototype.updateRole = function (id, content, options, cb) { var @@ -190,6 +191,7 @@ KuzzleSecurity.prototype.updateRole = function (id, content, options, cb) { * @param {string} id - Role id to delete * @param {object} [options] - (optional) arguments * @param {responseCallback} [cb] - Handles the query response + * @returns {KuzzleSecurity} this object */ KuzzleSecurity.prototype.deleteRole = function (id, options, cb) { var data = {_id: id}; @@ -337,6 +339,7 @@ KuzzleSecurity.prototype.createProfile = function (id, content, options, cb) { * @param {object} content - a plain javascript object representing the profile's modification * @param {object} [options] - (optional) arguments * @param {responseCallback} [cb] - (optional) Handles the query response + * @returns {KuzzleSecurity} this object */ KuzzleSecurity.prototype.updateProfile = function (id, content, options, cb) { var @@ -384,6 +387,7 @@ KuzzleSecurity.prototype.updateProfile = function (id, content, options, cb) { * @param {string} id - Profile id to delete * @param {object} [options] - (optional) arguments * @param {responseCallback} [cb] - Handles the query response + * @returns {KuzzleSecurity} this object */ KuzzleSecurity.prototype.deleteProfile = function (id, options, cb) { var data = {_id: id}; @@ -522,6 +526,7 @@ KuzzleSecurity.prototype.createUser = function (id, content, options, cb) { * @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 {KuzzleSecurity} this object */ KuzzleSecurity.prototype.updateUser = function (id, content, options, cb) { var @@ -559,6 +564,7 @@ KuzzleSecurity.prototype.updateUser = function (id, content, options, cb) { * @param {string} id - Profile id to delete * @param {object} [options] - (optional) arguments * @param {responseCallback} [cb] - Handles the query response + * @returns {KuzzleSecurity} this object */ KuzzleSecurity.prototype.deleteUser = function (id, options, cb) { var data = {_id: id}; diff --git a/src/security/kuzzleSecurityDocument.js b/src/security/kuzzleSecurityDocument.js index 75bc9c48d..81be39222 100644 --- a/src/security/kuzzleSecurityDocument.js +++ b/src/security/kuzzleSecurityDocument.js @@ -48,7 +48,7 @@ function KuzzleSecurityDocument(kuzzleSecurity, id, content) { * Changes made by this function won’t be applied until the save method is called. * * @param {Object} data - New securityDocument content - * @return {Object} this + * @return {KuzzleSecurityDocument} this */ KuzzleSecurityDocument.prototype.setContent = function (data) { this.content = data; @@ -105,6 +105,7 @@ KuzzleSecurityDocument.prototype.delete = function (options, cb) { * @param {object} content - Content to add to KuzzleSecurityDocument * @param {object} [options] - Optional parameters * @param {responseCallback} [cb] - Handles the query response + * @returns {KuzzleSecurityDocument} this */ KuzzleSecurityDocument.prototype.update = function (content, options, cb) { var diff --git a/src/security/kuzzleUser.js b/src/security/kuzzleUser.js index d91a8b07d..d7d49c31c 100644 --- a/src/security/kuzzleUser.js +++ b/src/security/kuzzleUser.js @@ -82,7 +82,7 @@ KuzzleUser.prototype.addProfile = function (profileId) { * * @param {responseCallback} [cb] - Handles the query response * @param {object} [options] - Optional parameters - * @returns {*} this + * @returns {KuzzleUser} this */ KuzzleUser.prototype.save = function (options, cb) { var