kuzzle-sdk
Version:
Official Javascript SDK for Kuzzle
2 lines • 94.3 kB
JavaScript
(function(a,_){typeof exports=="object"&&typeof module!="undefined"?_(exports):typeof define=="function"&&define.amd?define(["exports"],_):(a=typeof globalThis!="undefined"?globalThis:a||self,_(a.KuzzleSDK={}))})(this,(function(a){"use strict";var et=Object.defineProperty,tt=Object.defineProperties;var rt=Object.getOwnPropertyDescriptors;var Se=Object.getOwnPropertySymbols;var st=Object.prototype.hasOwnProperty,it=Object.prototype.propertyIsEnumerable;var xe=(a,_,b)=>_ in a?et(a,_,{enumerable:!0,configurable:!0,writable:!0,value:b}):a[_]=b,v=(a,_)=>{for(var b in _||(_={}))st.call(_,b)&&xe(a,b,_[b]);if(Se)for(var b of Se(_))it.call(_,b)&&xe(a,b,_[b]);return a},M=(a,_)=>tt(a,rt(_));var m=(a,_,b)=>new Promise(($,D)=>{var G=q=>{try{g(b.next(q))}catch(I){D(I)}},T=q=>{try{g(b.throw(q))}catch(I){D(I)}},g=q=>q.done?$(q.value):Promise.resolve(q.value).then(G,T);g((b=b.apply(a,_)).next())});class _{constructor(e,t=!1){this.fn=e,this.once=t}}class b{constructor(){this._events=new Map}_exists(e,t){return!!e.find(r=>r.fn===t)}listeners(e){return this._events.has(e)?this._events.get(e).map(t=>t.fn):[]}addListener(e,t,r=!1){if(!e||!t)return this;const s=typeof t;if(s!=="function")throw new Error(`Invalid listener type: expected a function, got a ${s}`);return this._events.has(e)||this._events.set(e,[]),this._exists(this._events.get(e),t)||this._events.get(e).push(new _(t,r)),this}on(e,t){return this.addListener(e,t)}prependListener(e,t,r=!1){if(!e||!t)return this;if(this._events.has(e)||this._events.set(e,[]),!this._exists(this._events.get(e),t)){const s=[new _(t,r)].concat(this._events.get(e));this._events.set(e,s)}return this}addOnceListener(e,t){return this.addListener(e,t,!0)}once(e,t){return this.addOnceListener(e,t)}prependOnceListener(e,t){return this.prependListener(e,t,!0)}removeListener(e,t){const r=this._events.get(e);if(!r||!r.length)return this;const s=r.findIndex(i=>i.fn===t);return s!==-1&&r.splice(s,1),r.length===0&&this._events.delete(e),this}removeAllListeners(e){return e?this._events.delete(e):this._events=new Map,this}emit(e,...t){const r=this._events.get(e);if(r===void 0)return!1;const s=[];for(const i of r)i.fn(...t),i.once&&s.push(i.fn);for(const i of s)this.removeListener(e,i);return!0}eventNames(){return Array.from(this._events.keys())}listenerCount(e){return this._events.has(e)&&this._events.get(e).length||0}}const $="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",D=o=>{const e=o.replace(/=+$/,"");let t="";if(e.length%4===1)throw new Error("Malformed base64 string.");for(let r=0,s=0,i,n=0;i=e.charAt(n++);~i&&(s=r%4?s*64+i:i,r++%4)?t+=String.fromCharCode(255&s>>(-2*r&6)):0)i=$.indexOf(i);return t};class G{constructor(e){this._encodedJwt=e,this._userId=null,this._expiresAt=null,this._decode()}get encodedJwt(){return this._encodedJwt}get userId(){return this._userId}get expiresAt(){return this._expiresAt}get expired(){const e=this._expiresAt;return e===null?!0:Math.round(Date.now()/1e3)>e}_decode(){var r,s;const e=this._encodedJwt.split(".")[1];if(!e)throw new Error("Invalid JWT format");let t;try{t=JSON.parse(D(e))}catch(i){throw new Error("Invalid JSON payload for JWT")}this._userId=(r=t._id)!=null?r:null,this._expiresAt=(s=t.exp)!=null?s:null}}class T{constructor(e,t){Reflect.defineProperty(this,"_kuzzle",{value:e}),this._name=t}get kuzzle(){return this._kuzzle}get name(){return this._name}query(e,t={}){return e.controller=e.controller||this.name,this._kuzzle.query(e,t)}}class g{constructor(e,t=null,r={}){Reflect.defineProperty(this,"_kuzzle",{value:e}),Reflect.defineProperty(this,"content",{enumerable:!0,get(){return this._source}}),this._id=t,this._source=r}get kuzzle(){return this._kuzzle}get profileIds(){return this._source.profileIds||[]}getProfiles(){return!this.profileIds||this.profileIds.length===0?Promise.resolve([]):this.kuzzle.security.mGetProfiles(this.profileIds)}serialize(){return{_id:this._id,_source:this._source}}}class q extends T{constructor(e){super(e,"auth"),this._authenticationToken=null,this.kuzzle.on("tokenExpired",()=>{this._authenticationToken=null})}get authenticationToken(){return this._authenticationToken}set authenticationToken(e){if(e==null)this._authenticationToken=null;else if(typeof e=="string")this._authenticationToken=new G(e);else throw new Error(`Invalid token argument: ${e}`)}authenticateRequest(e){this.kuzzle.cookieAuthentication||!this.authenticationToken||e.controller==="auth"&&(e.action==="checkToken"||e.action==="login")||(e.jwt=this.authenticationToken.encodedJwt)}createApiKey(e,t={}){const r={_id:t._id,action:"createApiKey",body:{description:e},expiresIn:t.expiresIn,refresh:t.refresh};return this.query(r,t).then(s=>s.result)}checkRights(e,t={}){const r={action:"checkRights",body:e};return this.query(r,t).then(s=>s.result.allowed)}deleteApiKey(e,t={}){const r={_id:e,action:"deleteApiKey",refresh:t.refresh};return this.query(r,t).then(()=>null)}searchApiKeys(e={},t={}){const r={action:"searchApiKeys",body:e,from:t.from,lang:t.lang,size:t.size};return this.query(r,t).then(s=>s.result)}checkToken(e,t={}){let r=!1;return e===void 0&&(r=this.kuzzle.cookieAuthentication,!r&&this.authenticationToken&&(e=this.authenticationToken.encodedJwt)),this.query({action:"checkToken",body:{token:e},cookieAuth:r},v({queuable:!1},t)).then(s=>s.result)}createMyCredentials(e,t,r={}){return this.query({action:"createMyCredentials",body:t,strategy:e},r).then(s=>s.result)}credentialsExist(e,t={}){return this.query({action:"credentialsExist",strategy:e},t).then(r=>r.result)}deleteMyCredentials(e,t={}){return this.query({action:"deleteMyCredentials",strategy:e},t).then(r=>r.result.acknowledged)}getCurrentUser(e={}){return this.query({action:"getCurrentUser"},e).then(t=>new g(this.kuzzle,t.result._id,t.result._source))}getMyCredentials(e,t={}){return this.query({action:"getMyCredentials",strategy:e},t).then(r=>r.result)}getMyRights(e={}){return this.query({action:"getMyRights"},e).then(t=>t.result.hits)}getStrategies(e={}){return this.query({action:"getStrategies"},e).then(t=>t.result)}login(e,t,r,s={}){const i={action:"login",body:t,cookieAuth:this.kuzzle.cookieAuthentication,expiresIn:r,strategy:e};return this.kuzzle.emit("beforeLogin"),this.query(i,v({queuable:!1,timeout:-1,verb:"POST"},s)).then(n=>{if(this.kuzzle.cookieAuthentication){if(n.result.jwt){const u=new Error("Kuzzle support for cookie authentication is disabled or not supported");throw this.kuzzle.emit("loginAttempt",{error:u.message,success:!1}),this.kuzzle.emit("afterLogin",{error:u.message,success:!1}),u}this.kuzzle.emit("loginAttempt",{success:!0}),this.kuzzle.emit("afterLogin",{success:!0});return}return this._authenticationToken=new G(n.result.jwt),this.kuzzle.emit("loginAttempt",{success:!0}),this.kuzzle.emit("afterLogin",{success:!0}),n.result.jwt}).catch(n=>{throw this.kuzzle.emit("loginAttempt",{error:n.message,success:!1}),this.kuzzle.emit("afterLogin",{error:n.message,success:!1}),n})}logout(){return m(this,arguments,function*(e={}){this.kuzzle.emit("beforeLogout");try{yield this.query({action:"logout",cookieAuth:this.kuzzle.cookieAuthentication},v({queuable:!1,timeout:-1},e)),this._authenticationToken=null,this.kuzzle.emit("logoutAttempt",{success:!0}),this.kuzzle.emit("afterLogout",{success:!0})}catch(t){throw this.kuzzle.emit("logoutAttempt",{error:t.message,success:!1}),this.kuzzle.emit("afterLogout",{error:t.message,success:!1}),t}})}updateMyCredentials(e,t,r={}){return this.query({action:"updateMyCredentials",body:t,strategy:e},r).then(s=>s.result)}updateSelf(e,t={}){return this.query({action:"updateSelf",body:e},t).then(r=>new g(this.kuzzle,r.result._id,r.result._source))}validateMyCredentials(e,t,r={}){return this.query({action:"validateMyCredentials",body:t,strategy:e},r).then(s=>s.result)}refreshToken(e={}){const t={action:"refreshToken",cookieAuth:this.kuzzle.cookieAuthentication,expiresIn:e.expiresIn};return this.query(t,e).then(r=>(this.kuzzle.cookieAuthentication||(this._authenticationToken=new G(r.result.jwt)),r.result))}}class I extends T{constructor(e){super(e,"bulk")}deleteByQuery(e,t,r={},s={}){const i={action:"deleteByQuery",body:r,collection:t,index:e};return this.query(i,s).then(n=>n.result.deleted)}import(e,t,r,s={}){return this.query({action:"import",body:{bulkData:r},collection:t,index:e},s).then(i=>i.result)}updateByQuery(e,t,r,s,i={}){const n={action:"updateByQuery",body:{changes:s,query:r},collection:t,index:e};return this.query(n,i).then(u=>u.result.updated)}write(e,t,r,s,i={}){return this.query({_id:s,action:"write",body:r,collection:t,index:e,notify:i.notify},i).then(n=>n.result)}mWrite(e,t,r,s={}){return this.query({action:"mWrite",body:{documents:r},collection:t,index:e,notify:s.notify},s).then(i=>i.result)}}class x{constructor(e,t,r={},s={}){Reflect.defineProperty(this,"_kuzzle",{value:e}),Reflect.defineProperty(this,"_request",{value:t}),Reflect.defineProperty(this,"_options",{value:r}),Reflect.defineProperty(this,"_result",{value:s}),Reflect.defineProperty(this,"_controller",{value:t.controller,writable:!0}),Reflect.defineProperty(this,"_searchAction",{value:"search",writable:!0}),Reflect.defineProperty(this,"_scrollAction",{value:"scroll",writable:!0}),this.aggregations=s.aggregations,this.hits=s.hits||[],this.fetched=this.hits.length,this.total=s.total||0,this.suggest=s.suggest}next(){if(this.fetched>=this.total)return Promise.resolve(null);if(this._request.scroll)return this._kuzzle.query({action:this._scrollAction,controller:this._request.controller,scroll:this._request.scroll,scrollId:this._result.scrollId}).then(({result:e})=>this._buildNextSearchResult(e));if(this._request.size&&this._request.body.sort){const e=M(v({},this._request),{action:this._searchAction}),t=this._result.hits[this._result.hits.length-1];if(!t)return Promise.reject(new Error('Unable to retrieve all results from search: the sort combination must identify one item only. Add document "_id" to the sort.'));e.body.search_after=[];let r;if(typeof this._request.body.sort=="string"?r=[this._request.body.sort]:Array.isArray(this._request.body.sort)?r=this._request.body.sort:r=Object.keys(this._request.body.sort),r.length===0)return Promise.reject(new Error("Unable to retrieve next results from search: sort param is empty"));for(const s of r){const i=typeof s=="string"?s:Object.keys(s)[0],n=i==="_id"?t._id:this._get(t._source,i.split("."));e.body.search_after.push(n)}return this._kuzzle.query(e,this._options).then(({result:s})=>this._buildNextSearchResult(s))}else if(this._request.size)return this._request.from>=this._result.total?Promise.resolve(null):this._kuzzle.query(M(v({},this._request),{action:this._searchAction,from:this.fetched})).then(({result:e})=>this._buildNextSearchResult(e));return Promise.reject(new Error("Unable to retrieve next results from search: missing scrollId, from/sort, or from/size params"))}_get(e,t){if(!e)return e;if(t.length===1)return e[t[0]];const r=t.shift();return this._get(e[r],t)}_buildNextSearchResult(e){const t=this.constructor,r=new t(this._kuzzle,this._request,this._options,e);return r.fetched+=this.fetched,r}}class X extends x{constructor(e,t,r,s){super(e,t,r,s),this._controller="collection",this._searchAction="searchSpecifications",this._scrollAction="scrollSpecifications"}}class Z extends T{constructor(e){super(e,"collection")}create(e,t,r,s={}){const i={action:"create",body:r,collection:t,index:e};return this.query(i,s).then(()=>{})}deleteSpecifications(e,t,r={}){const s={action:"deleteSpecifications",collection:t,index:e};return this.query(s,r).then(()=>{})}exists(e,t,r={}){return this.query({action:"exists",collection:t,index:e},r).then(s=>s.result)}refresh(e,t,r={}){return this.query({action:"refresh",collection:t,index:e},r).then(()=>{})}getMapping(e,t,r={}){const s={action:"getMapping",collection:t,includeKuzzleMeta:r.includeKuzzleMeta||!1,index:e};return this.query(s,r).then(i=>i.result)}getSpecifications(e,t,r={}){return this.query({action:"getSpecifications",collection:t,index:e},r).then(s=>s.result)}list(e,t={}){const r={action:"list",from:t.from,index:e,size:t.size||0};return this.query(r,t).then(s=>s.result)}searchSpecifications(e={},t={}){const r={action:"searchSpecifications",body:e};for(const s of["from","size","scroll"])r[s]=t[s];return this.query(r,t).then(s=>new X(this.kuzzle,r,t,s.result))}truncate(e,t,r={}){const s={action:"truncate",collection:t,index:e};return this.query(s,r).then(()=>{})}update(e,t,r,s={}){return this.query({action:"update",body:r,collection:t,index:e},s).then(()=>{})}updateMapping(e,t,r,s={}){return this.query({action:"updateMapping",body:r,collection:t,index:e},s).then(i=>i.result)}updateSpecifications(e,t,r,s={}){return this.query({action:"updateSpecifications",body:r,collection:t,index:e},s).then(i=>i.result)}validateSpecifications(e,t,r,s={}){return this.query({action:"validateSpecifications",body:r,collection:t,index:e},s).then(i=>i.result)}delete(e,t,r={}){const s={action:"delete",collection:t,index:e};return this.query(s,r).then(()=>{})}}class Y extends x{constructor(e,t,r,s){super(e,t,r,s),this._searchAction="search",this._scrollAction="scroll"}}class j extends T{constructor(e){super(e,"document")}count(e,t,r,s={}){const i={action:"count",body:r,collection:t,index:e};return this.query(i,s).then(n=>n.result.count)}create(e,t,r,s=null,i={}){const n={_id:s,action:"create",body:r,collection:t,index:e,silent:i.silent};return this.query(n,i).then(u=>u.result)}createOrReplace(e,t,r,s,i={}){const n={_id:r,action:"createOrReplace",body:s,collection:t,index:e,silent:i.silent};return this.query(n,i).then(u=>u.result)}delete(e,t,r,s={}){const i={_id:r,action:"delete",collection:t,index:e,silent:s.silent};return this.query(i,s).then(n=>n.result._id)}deleteByQuery(e,t,r={},s={}){const i={action:"deleteByQuery",body:r,collection:t,index:e,lang:s.lang,silent:s.silent};return this.query(i,s).then(n=>n.result.ids)}deleteFields(e,t,r,s,i={}){const n={_id:r,action:"deleteFields",body:{fields:s},collection:t,index:e,silent:i.silent,source:i.source};return this.query(n,i).then(u=>u.result)}exists(e,t,r,s={}){const i={_id:r,action:"exists",collection:t,index:e};return this.query(i,s).then(n=>n.result)}get(e,t,r,s={}){const i={_id:r,action:"get",collection:t,index:e};return this.query(i,s).then(n=>n.result)}mCreate(e,t,r,s={}){const i={action:"mCreate",body:{documents:r},collection:t,index:e,silent:s.silent,strict:s.strict};return this.query(i,s).then(n=>n.result)}mCreateOrReplace(e,t,r,s={}){const i={action:"mCreateOrReplace",body:{documents:r},collection:t,index:e,silent:s.silent,strict:s.strict};return this.query(i,s).then(n=>n.result)}mDelete(e,t,r,s={}){const i={action:"mDelete",body:{ids:r},collection:t,index:e,silent:s.silent,strict:s.strict};return this.query(i,s).then(n=>n.result)}mGet(e,t,r,s={}){const i={action:"mGet",body:{ids:r},collection:t,index:e};return this.query(i,s).then(n=>n.result)}mReplace(e,t,r,s={}){const i={action:"mReplace",body:{documents:r},collection:t,index:e,silent:s.silent,strict:s.strict};return this.query(i,s).then(n=>n.result)}mUpdate(e,t,r,s={}){const i={action:"mUpdate",body:{documents:r},collection:t,index:e,silent:s.silent,strict:s.strict};return this.query(i,s).then(n=>n.result)}mUpsert(e,t,r,s={}){const i={action:"mUpsert",body:{documents:r},collection:t,index:e,silent:s.silent,strict:s.strict};return this.query(i,s).then(n=>n.result)}replace(e,t,r,s,i={}){const n={_id:r,action:"replace",body:s,collection:t,index:e,silent:i.silent};return this.query(n,i).then(u=>u.result)}search(e,t,r={},s={}){return this._search(e,t,r,s).then(({response:i,request:n,opts:u})=>new Y(this.kuzzle,n,u,i.result))}_search(e,t,r={},s={}){const i={action:"search",body:null,collection:t,index:e};this.kuzzle.protocol.name==="http"&&s.verb&&s.verb.toLowerCase()==="get"?i.searchBody=r:i.body=r;for(const u of["from","size","scroll","lang"])i[u]=s[u];const n=v({verb:s.verb||"POST"},s);return this.query(i,n).then(u=>({opts:n,request:i,response:u}))}update(e,t,r,s,i={}){const n={_id:r,action:"update",body:s,collection:t,index:e,retryOnConflict:i.retryOnConflict,silent:i.silent,source:i.source};return this.query(n,i).then(u=>u.result)}updateByQuery(e,t,r,s,i={}){const n={action:"updateByQuery",body:{changes:s,query:r},collection:t,index:e,lang:i.lang,silent:i.silent,source:i.source};return this.query(n,i).then(u=>u.result)}upsert(e,t,r,s,i={}){const n={_id:r,action:"upsert",body:{changes:s,default:i.default},collection:t,index:e,silent:i.silent,source:i.source};return this.query(n,i).then(u=>u.result)}validate(e,t,r,s={}){return this.query({action:"validate",body:r,collection:t,index:e},s).then(i=>i.result)}}class ee extends T{constructor(e){super(e,"index")}create(e,t={}){const r={action:"create",index:e};return this.query(r,t).then(()=>{})}delete(e,t={}){const r={action:"delete",index:e};return this.query(r,t).then(()=>{})}exists(e,t={}){return this.query({action:"exists",index:e},t).then(r=>r.result)}list(e={}){return this.query({action:"list"},e).then(t=>t.result.indexes)}mDelete(e,t={}){const r={action:"mDelete",body:{indexes:e}};return this.query(r,t).then(s=>s.result.deleted)}stats(e={}){return this.query({action:"stats"},e).then(t=>t.result)}}class Re{constructor(e,t,r,s,i,n={}){this.id=null,this.channel=null,Reflect.defineProperty(this,"_kuzzle",{value:e.kuzzle}),this.controller=e,this.index=t,this.collection=r,this.callback=i,this.options=n,this.id=null,this.channel=null,this.request={action:"subscribe",body:s,collection:r,controller:"realtime",index:t,scope:this.options.scope,state:this.options.state,users:this.options.users,volatile:this.options.volatile},this.autoResubscribe=typeof n.autoResubscribe=="boolean"?n.autoResubscribe:this.kuzzle.autoResubscribe,this.subscribeToSelf=typeof n.subscribeToSelf=="boolean"?n.subscribeToSelf:!0,this._channelListener=this._channelListener.bind(this)}get kuzzle(){return this._kuzzle}subscribe(){return this.kuzzle.query(this.request,this.options).then(e=>(this.id=e.result.roomId,this.channel=e.result.channel,this.kuzzle.protocol.on(this.channel,this._channelListener),e))}removeListeners(){this.channel&&this.kuzzle.protocol.removeListener(this.channel,this._channelListener)}_channelListener(e){if(e.type==="TokenExpired")return this.kuzzle.tokenExpired();const t=e.volatile&&e.volatile.sdkInstanceId===this.kuzzle.protocol.id;if(this.subscribeToSelf||!t)try{const r=this.callback(e);r!==null&&typeof r=="object"&&typeof r.then=="function"&&typeof r.catch=="function"&&r.catch(s=>{this.kuzzle.emit("callbackError",{error:s,notification:e})})}catch(r){this.kuzzle.emit("callbackError",{error:r,notification:e})}}}var te=(o=>(o.all="all",o.in="in",o.out="out",o.none="none",o))(te||{}),re=(o=>(o.all="all",o.in="in",o.out="out",o.none="none",o))(re||{});class se extends T{constructor(e){super(e,"realtime"),this._subscriptions=new Map,this._subscriptionsOff=new Map,this.kuzzle.on("tokenExpired",()=>this.removeSubscriptions()),this.kuzzle.on("disconnected",()=>this.saveSubscriptions()),this.kuzzle.on("networkError",()=>this.saveSubscriptions()),this.kuzzle.on("reconnected",()=>this.resubscribe()),this.kuzzle.on("reAuthenticated",()=>{this.saveSubscriptions(),this.resubscribe()})}count(e,t={}){return this.query({action:"count",body:{roomId:e}},t).then(r=>r.result.count)}publish(e,t,r,s={}){const i={_id:s._id,action:"publish",body:r,collection:t,index:e};return this.query(i,s).then(n=>n.result.published)}subscribe(e,t,r,s,i={}){const n=new Re(this,e,t,r,s,i);return n.subscribe().then(()=>(this._subscriptions.has(n.id)||this._subscriptions.set(n.id,[]),this._subscriptions.get(n.id).push(n),n.id))}unsubscribe(e,t={}){const r={action:"unsubscribe",body:{roomId:e}};return this.query(r,t).then(()=>{const s=this._subscriptions.get(e);if(s){for(const i of s)i.removeListeners();this._subscriptions.delete(e)}})}saveSubscriptions(){this._subscriptions.forEach((e,t)=>{for(const r of e)r.removeListeners(),r.autoResubscribe&&(this._subscriptionsOff.has(t)||this._subscriptionsOff.set(t,[]),this._subscriptionsOff.get(t).push(r));this._subscriptions.delete(t)})}resubscribe(){this._subscriptionsOff.forEach((e,t)=>{for(const r of e)this._subscriptions.has(t)||this._subscriptions.set(t,[]),this._subscriptions.get(t).push(r),r.subscribe().catch(()=>this.kuzzle.emit("discarded",{request:r.request}));this._subscriptionsOff.delete(t)})}removeSubscriptions(){this._subscriptions.forEach(e=>{for(const t of e)t.removeListeners()}),this._subscriptions=new Map,this._subscriptionsOff=new Map}}class ie extends T{constructor(e){super(e,"server")}adminExists(e){return this.query({action:"adminExists"},e).then(t=>t.result.exists)}capabilities(e){return this.query({action:"capabilities"},e).then(t=>t.result)}getAllStats(e){return this.query({action:"getAllStats"},e).then(t=>t.result)}getConfig(e){return this.query({action:"getConfig"},e).then(t=>t.result)}getLastStats(e){return this.query({action:"getLastStats"},e).then(t=>t.result)}getStats(e,t,r){return this.query({action:"getStats",startTime:e,stopTime:t},r).then(s=>s.result)}info(e){return this.query({action:"info"},e).then(t=>t.result)}now(e){return this.query({action:"now"},e).then(t=>t.result.now)}}class k{constructor(e,t=null,r={}){Reflect.defineProperty(this,"_kuzzle",{value:e}),this._id=t,this.controllers=r}get kuzzle(){return this._kuzzle}serialize(){return{_id:this._id,controllers:this.controllers}}}class ne extends x{constructor(e,t,r,s){super(e,t,r,s),this._searchAction="searchRoles",this._scrollAction=null,this.hits=this._result.hits.map(i=>new k(this._kuzzle,i._id,i._source.controllers))}next(){return this._request.scroll||this._request.sort?Promise.reject(new Error("only from/size params are allowed for role search")):super.next().then(e=>e?(e.hits=e._result.hits.map(t=>new k(e._kuzzle,t._id,t._source.controllers)),e):null)}}class P{constructor(e,t=null,r={}){Reflect.defineProperty(this,"_kuzzle",{value:e}),this._id=t,this.rateLimit=r&&r.rateLimit?r.rateLimit:0,this.policies=r&&r.policies?r.policies:[];for(const[s,i]of Object.entries(r))this[s]||(this[s]=i)}get kuzzle(){return this._kuzzle}getRoles(e={}){return!this.policies||this.policies.length===0?Promise.resolve([]):this.kuzzle.security.mGetRoles(this.policies.map(t=>t.roleId),e)}serialize(){return{_id:this._id,policies:this.policies,rateLimit:this.rateLimit}}}class oe extends x{constructor(e,t,r,s){super(e,t,r,s),this._searchAction="searchProfiles",this._scrollAction="scrollProfiles",this.hits=s.hits.map(i=>new P(this._kuzzle,i._id,i._source))}next(){return super.next().then(e=>e?(e.hits=e._result.hits.map(t=>new P(e._kuzzle,t._id,t._source)),e):null)}}class ue extends x{constructor(e,t,r,s){super(e,t,r,s),this._searchAction="searchUsers",this._scrollAction="scrollUsers",this.hits=this._result.hits.map(i=>new g(this._kuzzle,i._id,i._source))}next(){return super.next().then(e=>e?(e.hits=e._result.hits.map(t=>new g(e._kuzzle,t._id,t._source)),e):null)}}class Oe extends T{constructor(e){super(e,"security")}createApiKey(e,t,r={}){const s={_id:r._id,action:"createApiKey",body:{description:t},expiresIn:r.expiresIn,refresh:r.refresh,userId:e};return this.query(s,r).then(i=>i.result)}checkRights(e,t,r={}){const s={action:"checkRights",body:t,userId:e};return this.query(s,r).then(i=>i.result.allowed)}deleteApiKey(e,t,r={}){const s={_id:t,action:"deleteApiKey",refresh:r.refresh,userId:e};return this.query(s,r)}searchApiKeys(e,t={},r={}){const s={action:"searchApiKeys",body:t,from:r.from,lang:r.lang,size:r.size,userId:e};return this.query(s,r).then(i=>i.result)}createCredentials(e,t,r,s={}){return this.query({_id:t,action:"createCredentials",body:r,strategy:e},s).then(i=>i.result)}createFirstAdmin(e,t,r={}){const s={_id:e,action:"createFirstAdmin",body:t,reset:r.reset};return this.query(s,r).then(i=>new g(this.kuzzle,i.result._id,i.result._source))}createOrReplaceProfile(e,t,r={}){const s={_id:e,action:"createOrReplaceProfile",body:t};return this.query(s,r).then(i=>new P(this.kuzzle,i.result._id,i.result._source))}createOrReplaceRole(e,t,r={}){const s={_id:e,action:"createOrReplaceRole",body:t,force:r.force?!0:null};return this.query(s,r).then(i=>new k(this.kuzzle,i.result._id,i.result._source.controllers))}createProfile(e,t,r={}){const s={_id:e,action:"createProfile",body:t};return this.query(s,r).then(i=>new P(this.kuzzle,i.result._id,i.result._source))}createRestrictedUser(e,t=null,r={}){e.content||(e.content={});const s={_id:t,action:"createRestrictedUser",body:e};return this.query(s,r).then(i=>new g(this.kuzzle,i.result._id,i.result._source))}createRole(e,t,r={}){const s={_id:e,action:"createRole",body:t,force:r.force?!0:null};return this.query(s,r).then(i=>new k(this.kuzzle,i.result._id,i.result._source.controllers))}createUser(e,t,r={}){const s={_id:e,action:"createUser",body:t};return this.query(s,r).then(i=>new g(this.kuzzle,i.result._id,i.result._source))}deleteCredentials(e,t,r={}){const s={_id:t,action:"deleteCredentials",strategy:e};return this.query(s,r).then(i=>i.result)}deleteProfile(e,t={}){const r={_id:e,action:"deleteProfile"};return this.query(r,t).then(s=>s.result)}deleteRole(e,t={}){const r={_id:e,action:"deleteRole"};return this.query(r,t).then(s=>s.result)}deleteUser(e,t={}){const r={_id:e,action:"deleteUser"};return this.query(r,t).then(s=>s.result)}getAllCredentialFields(e={}){return this.query({action:"getAllCredentialFields"},e).then(t=>t.result)}getCredentialFields(e,t={}){return this.query({action:"getCredentialFields",strategy:e},t).then(r=>r.result)}getCredentials(e,t,r={}){return this.query({_id:t,action:"getCredentials",strategy:e},r).then(s=>s.result)}getCredentialsById(e,t,r={}){return this.query({_id:t,action:"getCredentialsById",strategy:e},r).then(s=>s.result)}getProfile(e,t={}){return this.query({_id:e,action:"getProfile"},t).then(r=>new P(this.kuzzle,r.result._id,r.result._source))}getProfileMapping(e={}){return this.query({action:"getProfileMapping"},e).then(t=>t.result)}getProfileRights(e,t={}){return this.query({_id:e,action:"getProfileRights"},t).then(r=>r.result.hits)}getRole(e,t={}){return this.query({_id:e,action:"getRole"},t).then(r=>new k(this.kuzzle,r.result._id,r.result._source.controllers))}getRoleMapping(e={}){return this.query({action:"getRoleMapping"},e).then(t=>t.result)}getUser(e,t={}){return this.query({_id:e,action:"getUser"},t).then(r=>new g(this.kuzzle,r.result._id,r.result._source))}getUserMapping(e={}){return this.query({action:"getUserMapping"},e).then(t=>t.result)}getUserRights(e,t={}){return this.query({_id:e,action:"getUserRights"},t).then(r=>r.result.hits)}getUserStrategies(e,t={}){return this.query({_id:e,action:"getUserStrategies"},t).then(r=>r.result.strategies)}hasCredentials(e,t,r={}){return this.query({_id:t,action:"hasCredentials",strategy:e},r).then(s=>s.result)}mDeleteProfiles(e,t={}){const r={action:"mDeleteProfiles",body:{ids:e}};return this.query(r,t).then(s=>s.result)}mDeleteRoles(e,t={}){const r={action:"mDeleteRoles",body:{ids:e}};return this.query(r,t).then(s=>s.result)}mDeleteUsers(e,t={}){const r={action:"mDeleteUsers",body:{ids:e}};return this.query(r,t).then(s=>s.result)}mGetProfiles(e,t={}){return this.query({action:"mGetProfiles",body:{ids:e}},t).then(r=>r.result.hits.map(s=>new P(this.kuzzle,s._id,s._source)))}mGetUsers(e,t={}){const r={action:"mGetUsers",body:{ids:e}};return this.query(r,t).then(s=>s.result.hits.map(i=>new g(this.kuzzle,i._id,i._source)))}mGetRoles(e,t={}){return this.query({action:"mGetRoles",body:{ids:e}},t).then(r=>r.result.hits.map(s=>new k(this.kuzzle,s._id,s._source.controllers)))}refresh(e,t={}){return this.query({action:"refresh",collection:e},t)}replaceUser(e,t,r={}){const s={_id:e,action:"replaceUser",body:t};return this.query(s,r).then(i=>new g(this.kuzzle,i.result._id,i.result._source))}searchProfiles(e,t={}){const r={action:"searchProfiles",body:e};for(const[s,i]of Object.entries(t))r[s]=i;return this.query(r,t).then(s=>new oe(this.kuzzle,r,t,s.result))}searchRoles(e,t={}){const r={action:"searchRoles",body:e};for(const[s,i]of Object.entries(t))r[s]=i;return this.query(r,t).then(s=>new ne(this.kuzzle,r,t,s.result))}searchUsers(e,t={}){const r={action:"searchUsers",body:e};for(const s of["from","size","scroll","lang"])r[s]=t[s];return this.query(r,t).then(s=>new ue(this.kuzzle,r,t,s.result))}updateCredentials(e,t,r,s={}){return this.query({_id:t,action:"updateCredentials",body:r,strategy:e},s).then(i=>i.result)}updateProfile(e,t,r={}){const s={_id:e,action:"updateProfile",body:t};return this.query(s,r).then(i=>new P(this.kuzzle,i.result._id,i.result._source))}updateProfileMapping(e,t={}){return this.query({action:"updateProfileMapping",body:e},t).then(r=>r.result)}updateRole(e,t,r={}){const s={_id:e,action:"updateRole",body:t,force:r.force?!0:null};return this.query(s,r).then(i=>new k(this.kuzzle,i.result._id,i.result._source.controllers))}updateRoleMapping(e,t={}){return this.query({action:"updateRoleMapping",body:e},t).then(r=>r.result)}updateUser(e,t,r={}){const s={_id:e,action:"updateUser",body:t};return this.query(s,r).then(i=>new g(this.kuzzle,i.result._id,i.result._source))}updateUserMapping(e,t={}){return this.query({action:"updateUserMapping",body:e},t).then(r=>r.result)}validateCredentials(e,t,r,s={}){return this.query({_id:t,action:"validateCredentials",body:r,strategy:e},s).then(i=>i.result)}}const E={getter:!0,required:["_id"]},le={getter:!0,required:["_id","field"]},A={getter:!0,required:["keys"]},ce={getter:!0,required:["_id","member"]},Q={getter:!0,required:["_id","cursor"],opts:["match","count"],mapResults:ve},ae={getter:!0,required:["_id","start","stop"],opts:pe,mapResults:ge},he={getter:!0,required:["_id","min","max"],opts:pe,mapResults:ge},U={required:["_id"]},O={required:["_id","value"]},de={append:O,bitcount:{getter:!0,required:["_id"],opts:["start","end"]},bitop:{required:["_id","operation","keys"]},bitpos:{getter:!0,required:["_id","bit"],opts:["start","end"]},dbsize:{getter:!0},decr:U,decrby:O,del:{required:["keys"]},exists:A,expire:{required:["_id","seconds"],mapResults:Boolean},expireat:{required:["_id","timestamp"],mapResults:Boolean},flushdb:{mapResults:w},geoadd:{required:["_id","points"]},geodist:{getter:!0,required:["_id","member1","member2"],opts:["unit"],mapResults:parseFloat},geohash:{getter:!0,required:["_id","members"]},geopos:{getter:!0,required:["_id","members"],mapResults:Ce},georadius:{getter:!0,required:["_id","lon","lat","distance","unit"],opts:_e,mapResults:be},georadiusbymember:{getter:!0,required:["_id","member","distance","unit"],opts:_e,mapResults:be},get:E,getbit:{getter:!0,required:["_id","offset"]},getrange:{getter:!0,required:["_id","start","end"]},getset:O,hdel:{required:["_id","fields"]},hexists:{getter:!0,required:["_id","field"],mapResults:Boolean},hget:le,hgetall:{getter:!0,required:["_id"]},hincrby:{required:["_id","field","value"]},hincrbyfloat:{required:["_id","field","value"],mapResults:parseFloat},hkeys:E,hlen:E,hmget:{getter:!0,required:["_id","fields"]},hmset:{required:["_id","entries"],mapResults:w},hscan:Q,hset:{required:["_id","field","value"],mapResults:Boolean},hsetnx:{required:["_id","field","value"],mapResults:Boolean},hstrlen:le,hvals:E,incr:U,incrby:O,incrbyfloat:{required:["_id","value"],mapResults:parseFloat},keys:{getter:!0,required:["pattern"]},lindex:{getter:!0,required:["_id","idx"]},linsert:{required:["_id","position","pivot","value"]},llen:E,lpop:U,lpush:{required:["_id","values"]},lpushx:O,lrange:{getter:!0,required:["_id","start","stop"]},lrem:{required:["_id","count","value"]},lset:{required:["_id","index","value"],mapResults:w},ltrim:{required:["_id","start","stop"],mapResults:w},mexecute:{required:["actions"]},mget:A,mset:{required:["entries"],mapResults:w},msetnx:{required:["entries"],mapResults:Boolean},object:{getter:!0,required:["_id","subcommand"]},persist:{required:["_id"],mapResults:Boolean},pexpire:{required:["_id","milliseconds"],mapResults:Boolean},pexpireat:{required:["_id","timestamp"],mapResults:Boolean},pfadd:{required:["_id","elements"],mapResults:Boolean},pfcount:A,pfmerge:{required:["_id","sources"],mapResults:w},ping:{getter:!0},psetex:{required:["_id","value","milliseconds"],mapResults:w},pttl:E,randomkey:{getter:!0},rename:{required:["_id","newkey"],mapResults:w},renamenx:{required:["_id","newkey"],mapResults:Boolean},rpop:U,rpoplpush:{required:["source","destination"]},rpush:{required:["_id","values"]},rpushx:O,sadd:{required:["_id","members"]},scan:{getter:!0,required:["cursor"],opts:["match","count"],mapResults:ve},scard:E,sdiff:{getter:!0,required:["_id","keys"]},sdiffstore:{required:["_id","keys","destination"]},set:{required:["_id","value"],opts:["ex","px","nx","xx"],mapResults:w},setex:{required:["_id","value","seconds"],mapResults:w},setnx:{required:["_id","value"],mapResults:Boolean},sinter:A,sinterstore:{required:["destination","keys"]},sismember:{getter:!0,required:["_id","member"],mapResults:Boolean},smembers:E,smove:{required:["_id","destination","member"],mapResults:Boolean},sort:{required:["_id"],opts:["alpha","by","direction","get","limit"]},spop:{required:["_id"],opts:["count"],mapResults:ye},srandmember:{getter:!0,required:["_id"],opts:["count"],mapResults:ye},srem:{required:["_id","members"]},sscan:Q,strlen:E,sunion:A,sunionstore:{required:["destination","keys"]},time:{getter:!0,mapResults:Ge},touch:{required:["keys"]},ttl:E,type:E,zadd:{required:["_id","elements"],opts:["nx","xx","ch","incr"]},zcard:E,zcount:{getter:!0,required:["_id","min","max"]},zincrby:{required:["_id","member","value"]},zinterstore:{required:["_id","keys"],opts:["weights","aggregate"]},zlexcount:{getter:!0,required:["_id","min","max"]},zrange:ae,zrangebylex:{getter:!0,required:["_id","min","max"],opts:["limit"]},zrevrangebylex:{getter:!0,required:["_id","min","max"],opts:["limit"]},zrangebyscore:he,zrank:ce,zrem:{required:["_id","members"]},zremrangebylex:{required:["_id","min","max"]},zremrangebyrank:{required:["_id","start","stop"]},zremrangebyscore:{required:["_id","min","max"]},zrevrange:ae,zrevrangebyscore:he,zrevrank:ce,zscan:Q,zscore:{getter:!0,required:["_id","member"],mapResults:parseFloat},zunionstore:{required:["_id","keys"],opts:["weights","aggregate"]}};class fe extends T{constructor(e){super(e,"ms")}}for(const o of Object.keys(de))fe.prototype[o]=function(...e){const t=de[o],r={action:o},s={};t.getter||(r.body={});for(const i of t.required||[]){const n=e.shift();if(n===void 0)throw new Error(`ms.${o}: missing parameter ${i}`);me(r,t.getter,i,n)}if(e.length>1)throw new Error(`ms.${o}: too many parameters provided`);if(e.length){if(typeof e[0]!="object"||Array.isArray(e[0]))throw new Error(`ms.${o}: invalid optional paramater (expected an object`);if(Object.assign(s,e[0]),Array.isArray(t.opts))for(const i of t.opts)s[i]!==null&&s[i]!==void 0&&me(r,t.getter,i,s[i])}return typeof t.opts=="function"&&t.opts(r,s),this.query(r,s).then(i=>t.mapResults?t.mapResults(i.result):i.result)};function me(o,e,t,r){e||t==="_id"?o[t]=r:o.body[t]=r}function _e(o,e){const t=[];Object.keys(e).filter(function(r){return e[r]&&["withcoord","withdist","count","sort"].indexOf(r)!==-1}).forEach(function(r){r==="withcoord"||r==="withdist"?t.push(r):(r==="count"||r==="sort")&&(r==="count"&&t.push("count"),t.push(e[r]))}),t.length>0&&(o.options=t)}function pe(o,e){o.options=["withscores"],e.limit&&(o.limit=e.limit)}function Ce(o){return o.map(e=>e.map(parseFloat))}function be(o){return Array.isArray(o[0])?o.map(function(e){const t={name:e.shift()};for(const r of e)Array.isArray(r)?t.coordinates=r.map(parseFloat):t.distance=parseFloat(r);return t}):o.map(function(e){return{name:e}})}function ye(o){return Array.isArray(o)?o:[o]}function Ge(o){return o.map(e=>parseInt(e))}function w(){}function ge(o){const e=[];for(let t=0;t<o.length;t+=2)e.push({member:o[t],score:parseFloat(o[t+1])});return e}function ve(o){return{cursor:o[0],values:o[1]}}class Ie{constructor(e){this.deprecationWarning=process.env.NODE_ENV!=="production"?e:!1}logDeprecation(e){if(this.deprecationWarning&&e.deprecations&&e.deprecations.length)for(const t of e.deprecations)console.warn(t.message);return e}}const y=new Array(256);for(let o=0;o<256;o++)y[o]=(o+256).toString(16).substring(1);const p=new Uint8Array(16),C=typeof globalThis!="undefined"?globalThis.crypto:void 0,Ae=o=>{if(C&&typeof C.getRandomValues=="function"){C.getRandomValues(o);return}for(let e=0;e<o.length;e++)o[e]=Math.random()*256|0},Te=()=>C&&typeof C.randomUUID=="function"?C.randomUUID():(Ae(p),p[6]=p[6]&15|64,p[8]=p[8]&63|128,y[p[0]]+y[p[1]]+y[p[2]]+y[p[3]]+"-"+y[p[4]]+y[p[5]]+"-"+y[p[6]]+y[p[7]]+"-"+y[p[8]]+y[p[9]]+"-"+y[p[10]]+y[p[11]]+y[p[12]]+y[p[13]]+y[p[14]]+y[p[15]]),Le=o=>Object.assign({},{apiNamespace:"__proxy__",name:"object",deprecated:[],exposeApi:!1,seal:!0,sealGet:!1,warnDeprecationOnce:!0},o),Ee=o=>{if(!o)return[];const e=Object.getOwnPropertyNames(o.prototype||o),t=Object.getPrototypeOf(o);return De([...e,...Ee(t)])},De=o=>[...new Set(o)],Ue=(o,e={})=>{if(!o||typeof o!="object"&&typeof o!="function")throw Error("proxify only applies on non-null object");const t=Le(e),r=new Set(["inspect"]),s=new Set(t.deprecated),i=new Set,n=l=>{const c=`${t.name}.${l}`;t.warnDeprecationOnce&&i.has(c)||(i.add(c),console.warn(`Warning: ${c} is deprecated`))};t.exposeApi&&(o[t.apiNamespace]={registerProp:l=>r.add(l),unregisterProp:l=>r.delete(l),hasProp:l=>r.has(l)}),[...Object.getOwnPropertyNames(o),...Ee(o)].forEach(l=>r.add(l));const u={get:(l,c)=>{if(t.sealGet&&!r.has(c))throw new Error(`${t.name}.${c} is not defined`);return s.has(c)&&n(c),l[c]},set:(l,c,f)=>{if(t.seal&&!r.has(c))throw new Error(`Cannot set a value to the undefined '${c}' property in '${t.name}'`);return s.has(c)&&n(c),l[c]=f,!0}};return new Proxy(o,u)};function N(){let o;try{if(o||(o=globalThis.window),o)return o}catch(e){}try{if(o||(o=global.window),o)return o}catch(e){}try{if(o||(o=window),o)return o}catch(e){}}function K(){const o=N();return o!=null&&typeof o=="object"}let F;function Be(){var o,e;try{if(!K())return F===void 0&&(F=((o=process.env.DEBUG)!=null?o:"").includes("kuzzle-sdk")),F;const t=N();if(!t)return!1;if(t.debugKuzzleSdk)return!0;const r=t.location;if(!r)return!1;const s=typeof r=="string"?r:(e=r.href)!=null?e:String(r);return new URL(s).searchParams.get("debugKuzzleSdk")!==null}catch(t){return!1}}function qe(o,e){if(Be()&&(console.log(o),e)){const t=K()?e:JSON.stringify(e);console.log(t)}}class Me extends Error{constructor(e,t){super(`Request timed out after ${t} ms`),this.request=e,this.delay=t}}class $e extends b{constructor(e,t={}){if(super(),this.authenticator=null,this.events=["callbackError","connected","discarded","disconnected","loginAttempt","beforeLogin","afterLogin","logoutAttempt","beforeLogout","afterLogout","networkError","offlineQueuePush","offlineQueuePop","queryError","reAuthenticated","reconnected","reconnectionError","tokenExpired"],e==null)throw new Error('"protocol" argument missing');for(const r of["addListener","isReady","query"])if(typeof e[r]!="function")throw new Error(`Protocol instance must implement a "${r}" method`);if(this.protocol=e,this._protectedEvents={afterLogin:{},connected:{},disconnected:{},error:{},loginAttempt:{},reconnected:{},tokenExpired:{}},this.autoResubscribe=typeof t.autoResubscribe=="boolean"?t.autoResubscribe:!0,this.eventTimeout=typeof t.eventTimeout=="number"?t.eventTimeout:200,this.sdkVersion="7.17.1",this.sdkName=`js@${this.sdkVersion}`,this.volatile=typeof t.volatile=="object"?t.volatile:{},this._cookieAuthentication=typeof t.cookieAuth=="boolean"?t.cookieAuth:!1,this._cookieAuthentication){this.protocol.enableCookieSupport();let r,s,i;this.protocol.addListener("websocketRenewalStart",()=>{r=this.autoQueue,s=this.autoReplay,i=this.autoResubscribe,this.autoQueue=!0,this.autoReplay=!0,this.autoResubscribe=!0}),this.protocol.addListener("websocketRenewalDone",()=>{this.autoQueue=r,this.autoReplay=s,this.autoResubscribe=i})}if(this.deprecationHandler=new Ie(typeof t.deprecationWarning=="boolean"?t.deprecationWarning:!0),this._cookieAuthentication&&typeof XMLHttpRequest=="undefined")throw new Error("Support for cookie authentication with cookieAuth option is not supported outside a browser");return this.useController(q,"auth"),this.useController(I,"bulk"),this.useController(Z,"collection"),this.useController(j,"document"),this.useController(ee,"index"),this.useController(fe,"ms"),this.useController(se,"realtime"),this.useController(Oe,"security"),this.useController(ie,"server"),this._offlineQueue=[],this._autoQueue=typeof t.autoQueue=="boolean"?t.autoQueue:!1,this._autoReplay=typeof t.autoReplay=="boolean"?t.autoReplay:!1,this._offlineQueueLoader=typeof t.offlineQueueLoader=="function"?t.offlineQueueLoader:null,this._queueFilter=typeof t.queueFilter=="function"?t.queueFilter:null,this._queueMaxSize=typeof t.queueMaxSize=="number"?t.queueMaxSize:500,this._queueTTL=typeof t.queueTTL=="number"?t.queueTTL:12e4,this._replayInterval=typeof t.replayInterval=="number"?t.replayInterval:10,this._requestTimeout=typeof t.requestTimeout=="number"?t.requestTimeout:-1,this._tokenExpiredInterval=typeof t.tokenExpiredInterval=="number"?t.tokenExpiredInterval:1e3,t.offlineMode==="auto"&&(this._autoQueue=!0,this._autoReplay=!0),this._queuing=!1,this._lastTokenExpired=null,this._reconnectInProgress=!1,this._loggedIn=!1,this.on("afterLogin",r=>m(this,null,function*(){if(r.success){this._loggedIn=!0;return}try{this._loggedIn=yield this.isAuthenticated()}catch(s){this._loggedIn=!1}})),this.on("afterLogout",r=>{r.success&&(this._loggedIn=!1)}),this.on("connected",()=>m(this,null,function*(){try{this._loggedIn=yield this.isAuthenticated()}catch(r){this._loggedIn=!1}})),Ue(this,{exposeApi:!0,name:"kuzzle",seal:!0})}get authenticated(){return!!(this.auth.authenticationToken&&!this.auth.authenticationToken.expired)}get autoQueue(){return this._autoQueue}set autoQueue(e){this._checkPropertyType("_autoQueue","boolean",e),this._autoQueue=e}get autoReconnect(){return this.protocol.autoReconnect}set autoReconnect(e){this._checkPropertyType("autoReconnect","boolean",e);const t=this.protocol;t.autoReconnect=e}get autoReplay(){return this._autoReplay}set autoReplay(e){this._checkPropertyType("_autoReplay","boolean",e),this._autoReplay=e}get cookieAuthentication(){return this._cookieAuthentication}get connected(){return this.protocol.connected}get host(){return this.protocol.host}get jwt(){return this.auth.authenticationToken?this.auth.authenticationToken.encodedJwt:null}set jwt(e){this.auth.authenticationToken=e,this._loggedIn=!!e}get offlineQueue(){return this._offlineQueue}get offlineQueueLoader(){return this._offlineQueueLoader}set offlineQueueLoader(e){this._checkPropertyType("_offlineQueueLoader","function",e),this._offlineQueueLoader=e}get port(){return this.protocol.port}get queueFilter(){return this._queueFilter}set queueFilter(e){this._checkPropertyType("_queueFilter","function",e),this._queueFilter=e}get queueMaxSize(){return this._queueMaxSize}set queueMaxSize(e){this._checkPropertyType("_queueMaxSize","number",e),this._queueMaxSize=e}get queueTTL(){return this._queueTTL}set queueTTL(e){this._checkPropertyType("_queueTTL","number",e),this._queueTTL=e}get reconnectionDelay(){return this.protocol.reconnectionDelay}get replayInterval(){return this._replayInterval}set replayInterval(e){this._checkPropertyType("_replayInterval","number",e),this._replayInterval=e}get requestTimeout(){return this._requestTimeout}set requestTimeout(e){this._checkPropertyType("_requestTimeout","number",e),this._requestTimeout=e}get sslConnection(){return this.protocol.sslConnection}get tokenExpiredInterval(){return this._tokenExpiredInterval}set tokenExpiredInterval(e){this._checkPropertyType("_tokenExpiredInterval","number",e),this._tokenExpiredInterval=e}emit(e,...t){const r=Date.now(),s=this._protectedEvents[e];if(s){if(s.lastEmitted&&s.lastEmitted>r-this.eventTimeout)return!1;s.lastEmitted=r}return this._superEmit(e,...t)}_superEmit(e,...t){return super.emit(e,...t)}on(e,t){return super.on(e,t)}connect(){return this.protocol.isReady()?Promise.resolve():(this.autoQueue&&this.startQueuing(),this.protocol.addListener("queryError",({error:e,request:t})=>{this.emit("queryError",{error:e,request:t})}),this.protocol.addListener("tokenExpired",()=>this.tokenExpired()),this.protocol.addListener("connect",()=>{this.autoQueue&&this.stopQueuing(),this.autoReplay&&this.playQueue(),this.emit("connected")}),this.protocol.addListener("networkError",e=>{this.autoQueue&&this.startQueuing(),this.emit("networkError",e)}),this.protocol.addListener("disconnect",e=>{this.emit("disconnected",e)}),this.protocol.addListener("reconnect",this._reconnect.bind(this)),this.protocol.addListener("discarded",e=>this.emit("discarded",e)),this.protocol.addListener("websocketRenewalStart",()=>{this._reconnectInProgress=!0}),this.protocol.addListener("websocketRenewalDone",()=>{this._reconnectInProgress=!1}),this.protocol.connect())}setAPIKey(e){if(e.match(/^kapikey-/)===null)throw new Error("Invalid API key. Missing the `kapikey-` prefix.");this.jwt=e}_reconnect(){return m(this,null,function*(){if(!this._reconnectInProgress){if(this.autoQueue&&this.stopQueuing(),this._loggedIn&&!(yield this.tryReAuthenticate())){this._loggedIn=!1,this.disconnect();return}this.autoReplay&&this.playQueue(),this.emit("reconnected")}})}tryReAuthenticate(){return m(this,null,function*(){this._reconnectInProgress=!0;try{return(yield this.isAuthenticated())?!0:this.authenticator?(yield this.authenticate(),!0):(this.emit("reconnectionError",{error:new Error('Could not re-authenticate: "authenticator" property is not set.')}),!1)}catch(e){return this.emit("reconnectionError",{error:new Error(`Failed to authenticate the SDK after reconnection: ${e}`)}),!1}finally{this._reconnectInProgress=!1}})}authenticate(){return m(this,null,function*(){if(typeof this.authenticator!="function")throw new Error('The "authenticator" property must be a function.');yield this.authenticator();const e=yield this.isAuthenticated();if(this._loggedIn=e,!e)throw new Error('The "authenticator" function failed to authenticate the SDK.')})}isAuthenticated(){return m(this,null,function*(){const{valid:e,kuid:t}=yield this.auth.checkToken();return e&&t!=="-1"})}addListener(e,t){if(this.events.indexOf(e)===-1)throw new Error(`[${e}] is not a known event. Known events: ${this.events.join(", ")}`);return this._superAddListener(e,t)}_superAddListener(e,t){return super.addListener(e,t)}flushQueue(){return this._offlineQueue=[],this}disconnect(){this._loggedIn=!1,this.protocol.close()}query(e,t={}){if(typeof e!="object"||Array.isArray(e))throw new Error(`Kuzzle.query: Invalid request: ${JSON.stringify(e)}`);if(typeof t!="object"||Array.isArray(t))throw new Error(`Kuzzle.query: Invalid "options" argument: ${JSON.stringify(t)}`);const r=JSON.parse(JSON.stringify(e)),s=JSON.parse(JSON.stringify(t));r.requestId||(r.requestId=Te());let i=!0;s&&s.queuable===!1&&(i=!1),this.queueFilter&&(i=i&&this.queueFilter(r));const n=typeof s.timeout=="number"?s.timeout:this._requestTimeout;for(const[u,l]of Object.entries(s))["queuable","timeout"].includes(u)||(r[u]=l);if(r.refresh===void 0&&s.refresh!==void 0&&(r.refresh=s.refresh),r.retryOnConflict===void 0&&s.retryOnConflict!==void 0&&(r.retryOnConflict=s.retryOnConflict),!r.volatile)r.volatile=this.volatile;else if(typeof r.volatile!="object"||Array.isArray(r.volatile))throw new Error(`Kuzzle.query: Invalid volatile argument received: ${JSON.stringify(r.volatile)}`);for(const u of Object.keys(this.volatile))r.volatile[u]===void 0&&(r.volatile[u]=this.volatile[u]);return r.volatile.sdkInstanceId=r.volatile.sdkInstanceId||this.protocol.id,r.volatile.sdkName=r.volatile.sdkName||this.sdkName,this.auth.authenticateRequest(r),this._queuing?i?(this._cleanQueue(),this.emit("offlineQueuePush",{request:r}),new Promise((u,l)=>{this.offlineQueue.push({reject:l,request:r,resolve:u,timeout:n,ts:Date.now()})})):(this.emit("discarded",{request:r}),Promise.reject(new Error(`Unable to execute request: not connected to a Kuzzle server.
Discarded request: ${JSON.stringify(r)}`))):this._timeoutRequest(n,r,s).then(u=>(qe("RESPONSE",u),this.deprecationHandler.logDeprecation(u)))}startQueuing(){return this._queuing=!0,this}stopQueuing(){return this._queuing=!1,this}playQueue(){return this.protocol.isReady()&&(this._cleanQueue(),this._dequeue()),this}tokenExpired(){return m(this,null,function*(){if(this._reconnectInProgress)return;if(this._loggedIn&&(yield this.tryReAuthenticate())){this.emit("reAuthenticated");return}const e=Date.now();e-this._lastTokenExpired<this.tokenExpiredInterval||(this._lastTokenExpired=e,this.jwt=null,this.emit("tokenExpired"))})}useController(e,t){if(!(t&&t.length>0))throw new Error("You must provide a valid accessor.");if(this.__proxy__?this.__proxy__.hasProp(t):this[t])throw new Error(`There is already a controller with the accessor '${t}'. Please use another one.`);const r=new e(this);if(!(r.name&&r.name.length>0))throw new Error("Controllers must have a name.");if(r.kuzzle!==this)throw new Error("You must pass the Kuzzle SDK instance to the parent constructor.");return this.__proxy__&&this.__proxy__.registerProp(t),this[t]=r,this}_checkPropertyType(e,t,r){if(t==="array"?!Array.isArray(r):typeof r!==t)throw new Error(`Expected ${e} to be a ${t}, ${typeof r} received`)}_cleanQueue(){const e=Date.now();let t=-1;this.queueTTL>0&&(this.offlineQueue.forEach((r,s)=>{r.ts<e-this.queueTTL&&(t=s)}),t!==-1&&this.offlineQueue.splice(0,t+1).forEach(r=>{this.emit("offlineQueuePop",r.request),r.reject(new Error("Query aborted: queued time exceeded the queueTTL option value"))})),this.queueMaxSize>0&&this.offlineQueue.length>this.queueMaxSize&&this.offlineQueue.splice(0,this.offlineQueue.length-this.queueMaxSize).forEach(r=>{this.emit("offlineQueuePop",r.request),r.reject(new Error("Query aborted: too many queued requests (see the queueMaxSize option)"))})}_dequeue(){const e={},t=()=>{this.offlineQueue.length>0&&(this.offlineQueue[0].request.jwt=this.jwt,this._timeoutReques