181,6,152,30,67002,8,149,41,1487,48,349,30,391,32,126,27,1173,16,2043,18,2484,15,817,19,8927,20,4995,17,74,17,3242,26,2582,24,2149,10,3343,13,18,24,1188,15,754,15,993,27,487,37,843 _info {"project":"logger01","branch":"master","version":133,"versionDate":"2022-05-16T08:57:33.000Z","fromVersion":0,"reset":true,"checksumDocs":"23-106099"} external/socketcluster.min.js /** * SocketCluster JavaScript client v14.2.2 */ !function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).socketCluster=t()}}(function(){return function i(s,a,c){function u(e,t){if(!a[e]){if(!s[e]){var r="function"==typeof require&&require;if(!t&&r)return r(e,!0);if(h)return h(e,!0);var n=new Error("Cannot find module '"+e+"'");throw n.code="MODULE_NOT_FOUND",n}var o=a[e]={exports:{}};s[e][0].call(o.exports,function(t){return u(s[e][1][t]||t)},o,o.exports,i,s,a,c)}return a[e].exports}for(var h="function"==typeof require&&require,t=0;tr)throw new f("The "+t+" value provided exceeded the maximum amount allowed")};if(n("connectTimeout"),n("ackTimeout"),this._localEvents={connect:1,connectAbort:1,close:1,disconnect:1,message:1,error:1,raw:1,kickOut:1,subscribe:1,unsubscribe:1,subscribeStateChange:1,authStateChange:1,authenticate:1,deauthenticate:1,removeAuthToken:1,subscribeRequest:1},this.connectAttempts=0,this._emitBuffer=new p,this.channels={},this.options=t,this._cid=1,this.options.callIdGenerator=function(){return e._cid++},this.options.autoReconnect){null==this.options.autoReconnectOptions&&(this.options.autoReconnectOptions={});var o=this.options.autoReconnectOptions;null==o.initialDelay&&(o.initialDelay=1e4),null==o.randomness&&(o.randomness=1e4),null==o.multiplier&&(o.multiplier=1.5),null==o.maxDelay&&(o.maxDelay=6e4)}if(null==this.options.subscriptionRetryOptions&&(this.options.subscriptionRetryOptions={}),this.options.authEngine?this.auth=this.options.authEngine:this.auth=new c,this.options.codecEngine?this.codec=this.options.codecEngine:this.codec=u,this.options.protocol){var i=new f('The "protocol" option does not affect socketcluster-client. If you want to utilize SSL/TLS - use "secure" option instead');this._onSCError(i)}this.options.path=this.options.path.replace(/\/$/,"")+"/",this.options.query=t.query||{},"string"==typeof this.options.query&&(this.options.query=h.parse(this.options.query)),this._channelEmitter=new a,this._unloadHandler=function(){e.disconnect()},g&&this.disconnectOnUnload&&s.addEventListener&&s.addEventListener("beforeunload",this._unloadHandler,!1),(this._clientMap[this.clientId]=this).options.autoConnect&&this.connect()};b.prototype=Object.create(a.prototype),b.CONNECTING=b.prototype.CONNECTING=e.prototype.CONNECTING,b.OPEN=b.prototype.OPEN=e.prototype.OPEN,b.CLOSED=b.prototype.CLOSED=e.prototype.CLOSED,b.AUTHENTICATED=b.prototype.AUTHENTICATED="authenticated",b.UNAUTHENTICATED=b.prototype.UNAUTHENTICATED="unauthenticated",b.PENDING=b.prototype.PENDING="pending",b.ignoreStatuses=i.socketProtocolIgnoreStatuses,b.errorStatuses=i.socketProtocolErrorStatuses,b.prototype._privateEventHandlerMap={"#publish":function(t){var e=this._undecorateChannelName(t.channel);this.isSubscribed(e,!0)&&this._channelEmitter.emit(e,t.data)},"#kickOut":function(t){var e=this._undecorateChannelName(t.channel),r=this.channels[e];r&&(a.prototype.emit.call(this,"kickOut",t.message,e),r.emit("kickOut",t.message,e),this._triggerChannelUnsubscribe(r))},"#setAuthToken":function(e,r){var n=this;if(e){this.auth.saveToken(this.authTokenName,e.token,{},function(t){t?(r.error(t),n._onSCError(t)):(n._changeToAuthenticatedState(e.token),r.end())})}else r.error(new t("No token data provided by #setAuthToken event"))},"#removeAuthToken":function(t,r){var n=this;this.auth.removeToken(this.authTokenName,function(t,e){t?(r.error(t),n._onSCError(t)):(a.prototype.emit.call(n,"removeAuthToken",e),n._changeToUnauthenticatedStateAndClearTokens(),r.end())})},"#disconnect":function(t){this.transport.close(t.code,t.data)}},b.prototype.getState=function(){return this.state},b.prototype.getBytesReceived=function(){return this.transport.getBytesReceived()},b.prototype.deauthenticate=function(r){var n=this;this.auth.removeToken(this.authTokenName,function(t,e){t?n._onSCError(t):(a.prototype.emit.call(n,"removeAuthToken",e),n.state!==n.CLOSED&&n.emit("#removeAuthToken"),n._changeToUnauthenticatedStateAndClearTokens()),r&&r(t)})},b.prototype.connect=b.prototype.open=function(){var n=this;if(this.active)this.state===this.CLOSED&&(this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this.state=this.CONNECTING,a.prototype.emit.call(this,"connecting"),this.transport&&this.transport.off(),this.transport=new e(this.auth,this.codec,this.options),this.transport.on("open",function(t){n.state=n.OPEN,n._onSCOpen(t)}),this.transport.on("error",function(t){n._onSCError(t)}),this.transport.on("close",function(t,e){n.state=n.CLOSED,n._onSCClose(t,e)}),this.transport.on("openAbort",function(t,e){n.state=n.CLOSED,n._onSCClose(t,e,!0)}),this.transport.on("event",function(t,e,r){n._onSCEvent(t,e,r)}));else{var t=new o("Cannot connect a destroyed client");this._onSCError(t)}},b.prototype.reconnect=function(t,e){this.disconnect(t,e),this.connect()},b.prototype.disconnect=function(t,e){if("number"!=typeof(t=t||1e3))throw new f("If specified, the code argument must be a number");this.state===this.OPEN||this.state===this.CONNECTING?this.transport.close(t,e):(this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef))},b.prototype.destroy=function(t,e){g&&s.removeEventListener&&s.removeEventListener("beforeunload",this._unloadHandler,!1),this.active=!1,this.disconnect(t,e),delete this._clientMap[this.clientId]},b.prototype._changeToUnauthenticatedStateAndClearTokens=function(){if(this.authState!==this.UNAUTHENTICATED){var t=this.authState,e=this.signedAuthToken;this.authState=this.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null;var r={oldState:t,newState:this.authState};a.prototype.emit.call(this,"authStateChange",r),a.prototype.emit.call(this,"deauthenticate",e)}},b.prototype._changeToAuthenticatedState=function(t){if(this.signedAuthToken=t,this.authToken=this._extractAuthTokenData(t),this.authState!==this.AUTHENTICATED){var e=this.authState;this.authState=this.AUTHENTICATED;var r={oldState:e,newState:this.authState,signedAuthToken:t,authToken:this.authToken};this.preparingPendingSubscriptions||this.processPendingSubscriptions(),a.prototype.emit.call(this,"authStateChange",r)}a.prototype.emit.call(this,"authenticate",t)},b.prototype.decodeBase64=function(t){return r.from(t,"base64").toString("utf8")},b.prototype.encodeBase64=function(t){return r.from(t,"utf8").toString("base64")},b.prototype._extractAuthTokenData=function(t){var e=(t||"").split(".")[1];if(null!=e){var r=e;try{return r=this.decodeBase64(r),JSON.parse(r)}catch(t){return r}}return null},b.prototype.getAuthToken=function(){return this.authToken},b.prototype.getSignedAuthToken=function(){return this.signedAuthToken},b.prototype.authenticate=function(r,n){var o=this;this.emit("#authenticate",r,function(t,e){e&&null!=e.isAuthenticated?e.authError&&(e.authError=i.hydrateError(e.authError)):e={isAuthenticated:o.authState,authError:null},t?("BadConnectionError"!==t.name&&"TimeoutError"!==t.name&&o._changeToUnauthenticatedStateAndClearTokens(),n&&n(t,e)):o.auth.saveToken(o.authTokenName,r,{},function(t){t&&o._onSCError(t),e.isAuthenticated?o._changeToAuthenticatedState(r):o._changeToUnauthenticatedStateAndClearTokens(),n&&n(t,e)})})},b.prototype._tryReconnect=function(t){var e,r=this,n=this.connectAttempts++,o=this.options.autoReconnectOptions;if(null==t||0o.maxDelay&&(e=o.maxDelay),clearTimeout(this._reconnectTimeoutRef),this.pendingReconnect=!0,this.pendingReconnectTimeout=e,this._reconnectTimeoutRef=setTimeout(function(){r.connect()},e)},b.prototype._onSCOpen=function(t){var e=this;this.preparingPendingSubscriptions=!0,t?(this.id=t.id,this.pingTimeout=t.pingTimeout,this.transport.pingTimeout=this.pingTimeout,t.isAuthenticated?this._changeToAuthenticatedState(t.authToken):this._changeToUnauthenticatedStateAndClearTokens()):this._changeToUnauthenticatedStateAndClearTokens(),this.connectAttempts=0,this.options.autoSubscribeOnConnect&&this.processPendingSubscriptions(),a.prototype.emit.call(this,"connect",t,function(){e.processPendingSubscriptions()}),this.state===this.OPEN&&this._flushEmitBuffer()},b.prototype._onSCError=function(t){var e=this;setTimeout(function(){if(e.listeners("error").length<1)throw t;a.prototype.emit.call(e,"error",t)},0)},b.prototype._suspendSubscriptions=function(){var t,e;for(var r in this.channels)this.channels.hasOwnProperty(r)&&(e=(t=this.channels[r]).state===t.SUBSCRIBED||t.state===t.PENDING?t.PENDING:t.UNSUBSCRIBED,this._triggerChannelUnsubscribe(t,e))},b.prototype._abortAllPendingEventsDueToBadConnection=function(t){for(var e,r=this._emitBuffer.head;r;){e=r.next;var n=r.data;clearTimeout(n.timeout),delete n.timeout,r.detach(),r=e;var o=n.callback;if(o){delete n.callback;var i="Event '"+n.event+"' was aborted due to a bad connection",s=new m(i,t);o.call(n,s,n)}n.cid&&this.transport.cancelPendingResponse(n.cid)}},b.prototype._onSCClose=function(t,e,r){if(this.id=null,this.transport&&this.transport.off(),this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this._suspendSubscriptions(),this._abortAllPendingEventsDueToBadConnection(r?"connectAbort":"disconnect"),this.options.autoReconnect&&(4e3===t||4001===t||1005===t?this._tryReconnect(0):1e3!==t&&t<4500&&this._tryReconnect()),r?a.prototype.emit.call(this,"connectAbort",t,e):a.prototype.emit.call(this,"disconnect",t,e),a.prototype.emit.call(this,"close",t,e),!b.ignoreStatuses[t]){var n;n=e?"Socket connection closed with status code "+t+" and reason: "+e:"Socket connection closed with status code "+t;var o=new d(b.errorStatuses[t]||n,t);this._onSCError(o)}},b.prototype._onSCEvent=function(t,e,r){var n=this._privateEventHandlerMap[t];n?n.call(this,e,r):a.prototype.emit.call(this,t,e,function(){r&&r.callback.apply(r,arguments)})},b.prototype.decode=function(t){return this.transport.decode(t)},b.prototype.encode=function(t){return this.transport.encode(t)},b.prototype._flushEmitBuffer=function(){for(var t,e=this._emitBuffer.head;e;){t=e.next;var r=e.data;e.detach(),this.transport.emitObject(r),e=t}},b.prototype._handleEventAckTimeout=function(t,e){e&&e.detach(),delete t.timeout;var r=t.callback;if(r){delete t.callback;var n=new y("Event response for '"+t.event+"' timed out");r.call(t,n,t)}t.cid&&this.transport.cancelPendingResponse(t.cid)},b.prototype._emit=function(t,e,r){var n=this;this.state===this.CLOSED&&this.connect();var o={event:t,callback:r},i=new p.Item;this.options.cloneData?o.data=l(e):o.data=e,(i.data=o).timeout=setTimeout(function(){n._handleEventAckTimeout(o,i)},this.ackTimeout),this._emitBuffer.append(i),this.state===this.OPEN&&this._flushEmitBuffer()},b.prototype.send=function(t){this.transport.send(t)},b.prototype.emit=function(t,e,r){if(null==this._localEvents[t])this._emit(t,e,r);else if("error"===t)a.prototype.emit.call(this,t,e);else{var n=new o('The "'+t+'" event is reserved and cannot be emitted on a client socket');this._onSCError(n)}},b.prototype.publish=function(t,e,r){var n={channel:this._decorateChannelName(t),data:e};this.emit("#publish",n,r)},b.prototype._triggerChannelSubscribe=function(t,e){var r=t.name;if(t.state!==t.SUBSCRIBED){var n=t.state;t.state=t.SUBSCRIBED;var o={channel:r,oldState:n,newState:t.state,subscriptionOptions:e};t.emit("subscribeStateChange",o),t.emit("subscribe",r,e),a.prototype.emit.call(this,"subscribeStateChange",o),a.prototype.emit.call(this,"subscribe",r,e)}},b.prototype._triggerChannelSubscribeFail=function(t,e,r){var n=e.name,o=!e.waitForAuth||this.authState===this.AUTHENTICATED;e.state!==e.UNSUBSCRIBED&&o&&(e.state=e.UNSUBSCRIBED,e.emit("subscribeFail",t,n,r),a.prototype.emit.call(this,"subscribeFail",t,n,r))},b.prototype._cancelPendingSubscribeCallback=function(t){null!=t._pendingSubscriptionCid&&(this.transport.cancelPendingResponse(t._pendingSubscriptionCid),delete t._pendingSubscriptionCid)},b.prototype._decorateChannelName=function(t){return this.channelPrefix&&(t=this.channelPrefix+t),t},b.prototype._undecorateChannelName=function(t){return this.channelPrefix&&0===t.indexOf(this.channelPrefix)?t.replace(this.channelPrefix,""):t},b.prototype._trySubscribe=function(e){var r=this,t=!e.waitForAuth||this.authState===this.AUTHENTICATED;if(this.state===this.OPEN&&!this.preparingPendingSubscriptions&&null==e._pendingSubscriptionCid&&t){var n={noTimeout:!0},o={channel:this._decorateChannelName(e.name)};e.waitForAuth&&(n.waitForAuth=!0,o.waitForAuth=n.waitForAuth),e.data&&(o.data=e.data),e.batch&&(n.batch=!0,o.batch=!0),e._pendingSubscriptionCid=this.transport.emit("#subscribe",o,n,function(t){delete e._pendingSubscriptionCid,t?r._triggerChannelSubscribeFail(t,e,o):r._triggerChannelSubscribe(e,o)}),a.prototype.emit.call(this,"subscribeRequest",e.name,o)}},b.prototype.subscribe=function(t,e){var r=this.channels[t];return r?e&&r.setOptions(e):(r=new n(t,this,e),this.channels[t]=r),r.state===r.UNSUBSCRIBED&&(r.state=r.PENDING,this._trySubscribe(r)),r},b.prototype._triggerChannelUnsubscribe=function(t,e){var r=t.name,n=t.state;if(t.state=e||t.UNSUBSCRIBED,this._cancelPendingSubscribeCallback(t),n===t.SUBSCRIBED){var o={channel:r,oldState:n,newState:t.state};t.emit("subscribeStateChange",o),t.emit("unsubscribe",r),a.prototype.emit.call(this,"subscribeStateChange",o),a.prototype.emit.call(this,"unsubscribe",r)}},b.prototype._tryUnsubscribe=function(t){if(this.state===this.OPEN){var e={noTimeout:!0};t.batch&&(e.batch=!0),this._cancelPendingSubscribeCallback(t);var r=this._decorateChannelName(t.name);this.transport.emit("#unsubscribe",r,e)}},b.prototype.unsubscribe=function(t){var e=this.channels[t];e&&e.state!==e.UNSUBSCRIBED&&(this._triggerChannelUnsubscribe(e),this._tryUnsubscribe(e))},b.prototype.channel=function(t,e){var r=this.channels[t];return r||(r=new n(t,this,e),this.channels[t]=r),r},b.prototype.destroyChannel=function(t){var e=this.channels[t];e&&(e.unwatch(),e.unsubscribe(),delete this.channels[t])},b.prototype.subscriptions=function(t){var e,r=[];for(var n in this.channels)this.channels.hasOwnProperty(n)&&(e=this.channels[n],(t?e&&(e.state===e.SUBSCRIBED||e.state===e.PENDING):e&&e.state===e.SUBSCRIBED)&&r.push(n));return r},b.prototype.isSubscribed=function(t,e){var r=this.channels[t];return e?!!r&&(r.state===r.SUBSCRIBED||r.state===r.PENDING):!!r&&r.state===r.SUBSCRIBED},b.prototype.processPendingSubscriptions=function(){var e=this;this.preparingPendingSubscriptions=!1;var t=[];for(var r in this.channels)if(this.channels.hasOwnProperty(r)){var n=this.channels[r];n.state===n.PENDING&&t.push(n)}t.sort(function(t,e){var r=t.priority||0,n=e.priority||0;return n>16&255,i[s++]=e>>8&255,i[s++]=255&e;var u,h;2===o&&(e=p[t.charCodeAt(c)]<<2|p[t.charCodeAt(c+1)]>>4,i[s++]=255&e);1===o&&(e=p[t.charCodeAt(c)]<<10|p[t.charCodeAt(c+1)]<<4|p[t.charCodeAt(c+2)]>>2,i[s++]=e>>8&255,i[s++]=255&e);return i},r.fromByteArray=function(t){for(var e,r=t.length,n=r%3,o=[],i=0,s=r-n;i>2]+a[e<<4&63]+"==")):2===n&&(e=(t[r-2]<<8)+t[r-1],o.push(a[e>>10]+a[e>>4&63]+a[e<<2&63]+"="));return o.join("")};for(var a=[],p=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,i=n.length;o>18&63]+a[o>>12&63]+a[o>>6&63]+a[63&o]);return i.join("")}p["-".charCodeAt(0)]=62,p["_".charCodeAt(0)]=63},{}],9:[function(t,e,D){(function(p){"use strict";var n=t("base64-js"),i=t("ieee754");D.Buffer=p,D.SlowBuffer=function(t){+t!=t&&(t=0);return p.alloc(+t)},D.INSPECT_MAX_BYTES=50;var r=2147483647;function s(t){if(r>>1;case"base64":return U(t).length;default:if(o)return n?-1:N(t).length;e=(""+e).toLowerCase(),o=!0}}function f(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function d(t,e,r,n,o){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):2147483647=t.length){if(o)return-1;r=t.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof e&&(e=p.from(e,n)),p.isBuffer(e))return 0===e.length?-1:y(t,e,r,n,o);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):y(t,[e],r,n,o);throw new TypeError("val must be string, number or Buffer")}function y(t,e,r,n,o){var i,s=1,a=t.length,c=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;a/=s=2,c/=2,r/=2}function u(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(o){var h=-1;for(i=r;i>>10&1023|55296),h=56320|1023&h),n.push(h),o+=p}return function(t){var e=t.length;if(e<=E)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return S(this,e,r);case"utf8":case"utf-8":return v(this,e,r);case"ascii":return w(this,e,r);case"latin1":case"binary":return T(this,e,r);case"base64":return b(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},p.prototype.equals=function(t){if(!p.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===p.compare(this,t)},p.prototype.inspect=function(){var t="",e=D.INSPECT_MAX_BYTES;return t=this.toString("hex",0,e).replace(/(.{2})/g,"$1 ").trim(),this.length>e&&(t+=" ... "),""},p.prototype.compare=function(t,e,r,n,o){if(R(t,Uint8Array)&&(t=p.from(t,t.offset,t.byteLength)),!p.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),e<0||r>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(o<=n&&r<=e)return 0;if(o<=n)return-1;if(r<=e)return 1;if(this===t)return 0;for(var i=(o>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0),a=Math.min(i,s),c=this.slice(n,o),u=t.slice(e,r),h=0;h>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var o=this.length-e;if((void 0===r||othis.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i,s,a,c,u,h,p,l,f,d=!1;;)switch(n){case"hex":return m(this,t,e,r);case"utf8":case"utf-8":return l=e,f=r,x(N(t,(p=this).length-l),p,l,f);case"ascii":return g(this,t,e,r);case"latin1":case"binary":return g(this,t,e,r);case"base64":return c=this,u=e,h=r,x(U(t),c,u,h);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return s=e,a=r,x(function(t,e){for(var r,n,o,i=[],s=0;s>8,o=r%256,i.push(o),i.push(n);return i}(t,(i=this).length-s),i,s,a);default:if(d)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),d=!0}},p.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var E=4096;function w(t,e,r){var n="";r=Math.min(t.length,r);for(var o=e;ot.length)throw new RangeError("Index out of range")}function A(t,e,r,n){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function O(t,e,r,n,o){return e=+e,r>>>=0,o||A(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function B(t,e,r,n,o){return e=+e,r>>>=0,o||A(t,0,r,8),i.write(t,e,r,n,52,8),r+8}p.prototype.slice=function(t,e){var r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):r>>=0,e>>>=0,r||_(t,e,this.length);for(var n=this[t],o=1,i=0;++i>>=0,e>>>=0,r||_(t,e,this.length);for(var n=this[t+--e],o=1;0>>=0,e||_(t,1,this.length),this[t]},p.prototype.readUInt16LE=function(t,e){return t>>>=0,e||_(t,2,this.length),this[t]|this[t+1]<<8},p.prototype.readUInt16BE=function(t,e){return t>>>=0,e||_(t,2,this.length),this[t]<<8|this[t+1]},p.prototype.readUInt32LE=function(t,e){return t>>>=0,e||_(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},p.prototype.readUInt32BE=function(t,e){return t>>>=0,e||_(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},p.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||_(t,e,this.length);for(var n=this[t],o=1,i=0;++i>>=0,e>>>=0,r||_(t,e,this.length);for(var n=e,o=1,i=this[t+--n];0>>=0,e||_(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},p.prototype.readInt16LE=function(t,e){t>>>=0,e||_(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},p.prototype.readInt16BE=function(t,e){t>>>=0,e||_(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},p.prototype.readInt32LE=function(t,e){return t>>>=0,e||_(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},p.prototype.readInt32BE=function(t,e){return t>>>=0,e||_(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},p.prototype.readFloatLE=function(t,e){return t>>>=0,e||_(t,4,this.length),i.read(this,t,!0,23,4)},p.prototype.readFloatBE=function(t,e){return t>>>=0,e||_(t,4,this.length),i.read(this,t,!1,23,4)},p.prototype.readDoubleLE=function(t,e){return t>>>=0,e||_(t,8,this.length),i.read(this,t,!0,52,8)},p.prototype.readDoubleBE=function(t,e){return t>>>=0,e||_(t,8,this.length),i.read(this,t,!1,52,8)},p.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||C(this,t,e,r,Math.pow(2,8*r)-1,0);var o=1,i=0;for(this[e]=255&t;++i>>=0,r>>>=0,n)||C(this,t,e,r,Math.pow(2,8*r)-1,0);var o=r-1,i=1;for(this[e+o]=255&t;0<=--o&&(i*=256);)this[e+o]=t/i&255;return e+r},p.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||C(this,t,e,1,255,0),this[e]=255&t,e+1},p.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||C(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},p.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||C(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},p.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||C(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},p.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||C(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},p.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var o=Math.pow(2,8*r-1);C(this,t,e,r,o-1,-o)}var i=0,s=1,a=0;for(this[e]=255&t;++i>0)-a&255;return e+r},p.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var o=Math.pow(2,8*r-1);C(this,t,e,r,o-1,-o)}var i=r-1,s=1,a=0;for(this[e+i]=255&t;0<=--i&&(s*=256);)t<0&&0===a&&0!==this[e+i+1]&&(a=1),this[e+i]=(t/s>>0)-a&255;return e+r},p.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||C(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},p.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||C(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},p.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||C(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},p.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||C(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},p.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||C(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},p.prototype.writeFloatLE=function(t,e,r){return O(this,t,e,!0,r)},p.prototype.writeFloatBE=function(t,e,r){return O(this,t,e,!1,r)},p.prototype.writeDoubleLE=function(t,e,r){return B(this,t,e,!0,r)},p.prototype.writeDoubleBE=function(t,e,r){return B(this,t,e,!1,r)},p.prototype.copy=function(t,e,r,n){if(!p.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),0=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function U(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(e,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function x(t,e,r,n){for(var o=0;o=e.length||o>=t.length);++o)e[o+r]=t[o];return o}function R(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function P(t){return t!=t}}).call(this,t("buffer").Buffer)},{"base64-js":8,buffer:9,ieee754:12}],10:[function(t,e){(function(k){var t=function(){"use strict";function b(t,e){return null!=e&&t instanceof e}var v,E,w;try{v=Map}catch(t){v=function(){}}try{E=Set}catch(t){E=function(){}}try{w=Promise}catch(t){w=function(){}}function T(t,f,e,d,y){"object"==typeof f&&(e=f.depth,d=f.prototype,y=f.includeNonEnumerable,f=f.circular);var m=[],g=[];return void 0===f&&(f=!0),void 0===e&&(e=1/0),function o(t,i){if(null===t)return null;if(0===i)return t;var s,e;if("object"!=typeof t)return t;if(b(t,v))s=new v;else if(b(t,E))s=new E;else if(b(t,w))s=new w(function(e,r){t.then(function(t){e(o(t,i-1))},function(t){r(o(t,i-1))})});else if(T.__isArray(t))s=[];else if(T.__isRegExp(t))s=new RegExp(t.source,S(t)),t.lastIndex&&(s.lastIndex=t.lastIndex);else if(T.__isDate(t))s=new Date(t.getTime());else{if(void 0!==k&&k.isBuffer(t))return s=new k(t.length),t.copy(s),s;b(t,Error)?s=Object.create(t):void 0===d?(e=Object.getPrototypeOf(t),s=Object.create(e)):(s=Object.create(d),e=d)}if(f){var r=m.indexOf(t);if(-1!=r)return g[r];m.push(t),g.push(s)}for(var n in b(t,v)&&t.forEach(function(t,e){var r=o(e,i-1),n=o(t,i-1);s.set(r,n)}),b(t,E)&&t.forEach(function(t){var e=o(t,i-1);s.add(e)}),t){var a;e&&(a=Object.getOwnPropertyDescriptor(e,n)),a&&null==a.set||(s[n]=o(t[n],i-1))}if(Object.getOwnPropertySymbols){var c=Object.getOwnPropertySymbols(t);for(n=0;n>1,h=-7,p=r?o-1:0,l=r?-1:1,f=t[e+p];for(p+=l,i=f&(1<<-h)-1,f>>=-h,h+=a;0>=-h,h+=n;0>1,l=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:i-1,d=n?1:-1,y=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=h):(s=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-s))<1&&(s--,c*=2),2<=(e+=1<=s+p?l/c:l*Math.pow(2,1-p))*c&&(s++,c/=2),h<=s+p?(a=0,s=h):1<=s+p?(a=(e*c-1)*Math.pow(2,o),s+=p):(a=e*Math.pow(2,p-1)*Math.pow(2,o),s=0));8<=o;t[r+f]=255&a,f+=d,a/=256,o-=8);for(s=s<>2],n+=i[(3&e[o])<<4|e[o+1]>>4],n+=i[(15&e[o+1])<<2|e[o+2]>>6],n+=i[63&e[o+2]];return r%3==2?n=n.substring(0,n.length-1)+"=":r%3==1&&(n=n.substring(0,n.length-2)+"=="),n}(e)};if(r.Buffer){if(e instanceof r.Buffer)return{base64:!0,data:e.toString("base64")};if(e&&"Buffer"===e.type&&Array.isArray(e.data))return{base64:!0,data:(r.Buffer.from?r.Buffer.from(e.data):new r.Buffer(e.data)).toString("base64")}}return e};o.exports.decode=function(t){if(null==t)return null;if("#1"===t||"#2"===t)return t;var e=t.toString();if(!n.test(e))return e;try{return JSON.parse(e)}catch(t){}return e},o.exports.encode=function(t){return"#1"===t||"#2"===t?t:JSON.stringify(t,e)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],22:[function(t,e){var r=t("./v1"),n=t("./v4"),o=n;o.v1=r,o.v4=n,e.exports=o},{"./v1":25,"./v4":26}],23:[function(t,e){for(var o=[],r=0;r<256;++r)o[r]=(r+256).toString(16).substr(1);e.exports=function(t,e){var r=e||0,n=o;return n[t[r++]]+n[t[r++]]+n[t[r++]]+n[t[r++]]+"-"+n[t[r++]]+n[t[r++]]+"-"+n[t[r++]]+n[t[r++]]+"-"+n[t[r++]]+n[t[r++]]+"-"+n[t[r++]]+n[t[r++]]+n[t[r++]]+n[t[r++]]+n[t[r++]]+n[t[r++]]}},{}],24:[function(t,e){var r="undefined"!=typeof crypto&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&msCrypto.getRandomValues.bind(msCrypto);if(r){var n=new Uint8Array(16);e.exports=function(){return r(n),n}}else{var o=new Array(16);e.exports=function(){for(var t,e=0;e<16;e++)0==(3&e)&&(t=4294967296*Math.random()),o[e]=t>>>((3&e)<<3)&255;return o}}},{}],25:[function(t,e){var d,y,m=t("./lib/rng"),g=t("./lib/bytesToUuid"),b=0,v=0;e.exports=function(t,e,r){var n=e&&r||0,o=e||[],i=(t=t||{}).node||d,s=void 0!==t.clockseq?t.clockseq:y;if(null==i||null==s){var a=m();null==i&&(i=d=[1|a[0],a[1],a[2],a[3],a[4],a[5]]),null==s&&(s=y=16383&(a[6]<<8|a[7]))}var c=void 0!==t.msecs?t.msecs:(new Date).getTime(),u=void 0!==t.nsecs?t.nsecs:v+1,h=c-b+(u-v)/1e4;if(h<0&&void 0===t.clockseq&&(s=s+1&16383),(h<0||b>>24&255,o[n++]=p>>>16&255,o[n++]=p>>>8&255,o[n++]=255&p;var l=c/4294967296*1e4&268435455;o[n++]=l>>>8&255,o[n++]=255&l,o[n++]=l>>>24&15|16,o[n++]=l>>>16&255,o[n++]=s>>>8|128,o[n++]=255&s;for(var f=0;f<6;++f)o[n+f]=i[f];return e||g(o)}},{"./lib/bytesToUuid":23,"./lib/rng":24}],26:[function(t,e){var s=t("./lib/rng"),a=t("./lib/bytesToUuid");e.exports=function(t,e,r){var n=e&&r||0;"string"==typeof t&&(e="binary"===t?new Array(16):null,t=null);var o=(t=t||{}).random||(t.rng||s)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,e)for(var i=0;i<16;++i)e[n+i]=o[i];return e||a(o)}},{"./lib/bytesToUuid":23,"./lib/rng":24}]},{},[1])(1)}); init.ls (function(){ return function(){ if (!window.Logger) { include("external/socketcluster.min.js"); return window.Logger = include('logger'); } }; })(); lib/functions/changeEvent/changeEvent.ls (function(){ return function(logger){ return function(o){ var fromEvent, toEvent, isDelete, ref$, reason, logChangeEvent, eventName; fromEvent = _.cloneDeep(o.from); toEvent = _.cloneDeep(o.to); isDelete = (ref$ = o['delete']) != null ? ref$ : !(toEvent != null && toEvent.event) && (toEvent != null ? toEvent['delete'] : void 8); reason = o.reason; logChangeEvent = (ref$ = o.logChangeEvent) != null ? ref$ : true; eventName = _.isString(fromEvent) ? fromEvent : fromEvent != null ? fromEvent.event : void 8; eventName == null && (eventName = toEvent != null ? toEvent.event : void 8); if (!eventName) { throw new Error("eventName missing"); } if ((fromEvent != null && fromEvent.event) && fromEvent.event !== eventName) { throw new Error("eventName not matching from.event"); } if ((toEvent != null && toEvent.event) && toEvent.event !== eventName) { throw new Error("eventName not matching to.event"); } if (!fromEvent || _.isString(fromEvent)) { fromEvent = {}; } fromEvent.event == null && (fromEvent.event = eventName); fromEvent = logger.channel.findLast(fromEvent); if (isDelete && fromEvent == null) { return; } if (!isDelete) { if (!toEvent) { throw new Error("to event missing"); } toEvent.event == null && (toEvent.event = eventName); } if (logChangeEvent) { include("logChangeEvent/log")(logger, fromEvent, toEvent, eventName, isDelete, reason); } if (!isDelete) { logger.channel.log(toEvent); } if (fromEvent != null) { logger.channel.deleteEvent(fromEvent); } }; }; })(); lib/functions/changeEvent/logChangeEvent/log.ls (function(){ return function(logger, oldEvent, newEvent, eventName, isDelete, reason){ var changeEvent; eventName = "change" + (eventName.charAt(0).toUpperCase() + eventName.substr(1)); changeEvent = { event: eventName, from: oldEvent, to: isDelete ? { 'delete': true } : newEvent, reason: reason }; return logger.channel.log(changeEvent); }; })(); lib/getEvents/calcUrl/calc.ls (function(){ return function(triedUrls){ var that, urls, untriedUrls, url; if (that = app.loggerSubscribeUrl) { return that; } urls = ["https://apis-db-logger-s-lb-1.anton.app/apisLogger/subscribe/", "https://apis-db-logger-s-lb-2.anton.app/apisLogger/subscribe/"]; untriedUrls = _.difference(urls, triedUrls); url = _.sample(untriedUrls); app.loggerSubscribeUrl = url; return url; }; })(); lib/getEvents/clearUrl/clear.ls (function(){ return function(){ var ref$; return ref$ = app.loggerSubscribeUrl, delete app.loggerSubscribeUrl, ref$; }; })(); lib/getEvents/getEvents.ls (function(){ var doGet, onError; doGet = function(o){ var url, p, that; url = include("calcUrl/calc")(o.triedUrls); if (!url) { o.reject(o.error); return; } p = { path: "subscribe", params: { logId: o.options.log, filter: o.options.filter, inserted: o.options.inserted, readOnly: o.options.readOnly } }; if (that = o.options.deviceLogId) { p.deviceLogId = that; } if (that = o.options.authToken) { p.params.authToken = that; } return helpers.httpRequest.get(url, p, function(error, result){ var that; if (that = result != null ? result.authToken : void 8) { o.options.logger.authTokenReceived = that; } if (_.includes(result != null ? result.message : void 8, "invalid authToken")) { o.options.logger.authTokenError = result.message; o.reject(Error("invalid authToken")); return; } if (error) { o.error = error; return onError(o); } else { return o.resolve(result); } }); }; onError = function(o){ o.triedUrls.push(app.loggerSubscribeUrl); include("clearUrl/clear")(); return doGet(o); }; return function(options){ return new Promise(function(resolve, reject){ var o; o = { options: options, resolve: resolve, reject: reject, triedUrls: [] }; return doGet(o); }); }; })(); lib/logCache.ls (function(){ return function(){ var insert, remove, cache, keyCache, indexCache, getKey, logFind, uncacheEvent, cacheEvent; insert = include('/util/insert'); remove = include('/util/remove'); cache = []; keyCache = {}; indexCache = {}; getKey = function(event){ var e; try { return event.src + new Date(event.created).toISOString(); } catch (e$) { e = e$; return event.src + event.created; } }; logFind = function(func, filter){ var events; if (_.isString(filter)) { filter = { event: filter }; } events = filter != null && filter.event ? indexCache[filter.event] : cache; return func(events, filter); }; uncacheEvent = function(event){ var key$, ref$; if ((event != null ? event.event : void 8) == null) { return; } remove(indexCache[event.event], event); remove(cache, event); return ref$ = keyCache[key$ = getKey(event)], delete keyCache[key$], ref$; }; cacheEvent = function(event){ var key, ref$; key = getKey(event); if (keyCache[key]) { return; } try { event.created = new Date((typeof (ref$ = event.created).getTime == 'function' ? ref$.getTime() : void 8) || event.created); } catch (e$) {} try { event.inserted = event.inserted ? new Date((typeof (ref$ = event.inserted).getTime == 'function' ? ref$.getTime() : void 8) || event.inserted) : void 8; } catch (e$) {} insert(cache, event); if (!indexCache[event.event]) { indexCache[event.event] = []; } insert(indexCache[event.event], event); return keyCache[key] = event; }; return { updateEvent: function(event){ uncacheEvent(event); return cacheEvent(event); }, cacheEvent: cacheEvent, uncacheEvent: uncacheEvent, getCache: function(){ return cache; }, getKeyCache: function(){ return keyCache; }, clearCache: function(){ indexCache = {}; cache = []; return keyCache = {}; }, cacheEvents: function(events){ var t; t = this; return _.each(events, t.cacheEvent); }, findLast: logFind.bind(this, _.findLast), findFirst: logFind.bind(this, _.find), list: logFind.bind(this, _.filter), hasEvent: function(event){ var key; key = getKey(event); return keyCache[key] != null; } }; }; })(); lib/logChannel.ls (function(){ return function(logger){ var logChannel; logChannel = { sync: function(callback){ callback = callback || _.noop; return logger.routines.syncEventsExternal().then(function(){ return setTimeout(callback); })['catch'](callback); }, log: function(event){ var ref$; if (event.inserted != null) { throw new Error("logging events with key 'inserted' is not allowed"); } if (event.created != null) { throw new Error("logging events with key 'created' is not allowed"); } event.src = Store('sourceId'); if (event.src == null) { event.src = include("/util/repairLocalStorageSrc/repair")(logger.logId, event); } event.created = helpers.secureEventCreated(); if (event.event === 'deleteEvent') { if (((ref$ = event.target) != null ? ref$.event : void 8) === 'deleteEvent') { return; } logger.routines.deleteTargetEvent(event); } logger.cache.cacheEvent(event); logger.stores.saveUnsentEvent(event).then(logger.routines.sendUnsent); return logger.routines.triggerEvents(event); }, changeEvent: include("functions/changeEvent/changeEvent")(logger), deleteEvent: logger.routines.deleteEvent, findLast: logger.cache.findLast, findFirst: logger.cache.findFirst, list: logger.cache.list, id: function(){ return logger.logId; }, getDetails: function(callback){ var unsent, details; unsent = _.filter(logger.cache.getCache(), function(l){ return l.inserted == null; }); details = { id: logger.logId, state: logger.serverApi.socketState(), totalUnsentEvents: unsent.length, totalLocalEvents: logger.cache.getCache().length - unsent.length, lastInserted: logger.lastInserted, logInfo: logger.info.getCache(logger.logId) }; return callback(details); }, unsubscribe: function(callback){ logger.state = logger.states.CLOSED; logger.subscribeHandler.removeOpenChannel(logger.logId); logger.subscribeHandler.removeInitChannel(logger.logId); return logger.serverApi.unsubscribe(logger.logId, callback); }, clear: function(callback){ logger.cache.clearCache(); return logger.stores.removeAllEvents().then(function(){ return logger.stores.removeAllUnsentEvents(); }).then(function(){ logger.lastInserted = null; return logger.info.update(logger.logId, null); }).then(function(){ return typeof callback == 'function' ? callback() : void 8; }); } }; Object.defineProperty(logChannel, "authToken", { configurable: true, enumerable: true, get: function(){ var ref$; return (ref$ = logger.authTokenReceived) != null ? ref$ : (ref$ = logger.authToken) != null ? ref$ : ""; } }); return logChannel; }; })(); lib/logInfo.ls (function(){ return function(){ var logInfoStore, logInfoCache; logInfoStore = null; logInfoCache = {}; return { init: function(logOptions){ return new Promise(function(resolve){ return Lawnchair({ adapter: logOptions.memoryOnly ? 'memory' : void 8, name: 'info', prefix: 'logger' }, function(db){ logInfoStore = db; return logInfoStore.all(function(logInfos){ _.each(logInfos, function(logInfo){ return logInfoCache[logInfo.key] = logInfo; }); return typeof resolve == 'function' ? resolve() : void 8; }); }); }); }, save: function(){}, getCache: function(log){ return logInfoCache[log] || {}; }, update: function(log, lastInserted){ return new Promise(function(resolve){ var info; info = { key: log, lastInserted: lastInserted }; logInfoCache[log] = info; return logInfoStore.save(info, resolve); }); } }; }; })(); lib/logRoutines.ls (function(){ return function(logger){ var ackUnsentEvent, batchAckUnsentEvents, removeUnsentEvent, batchRemoveUnsentEvents, updateLastInserted, tryUpdateLastInserted, sendEventsBatch, lastSentCache, getDueForSending, updateDueEvents, sendUnsentUnthrottled, sendUnsent, cacheEventsFromDb, cacheUnsentEventsFromDb, loadEventsFromServer, insertEvents, filterTriggerEvents, syncEventsOrig, syncEvents, fetchOffline, deleteTargetEvent, deleteEvent, triggerEvents; ackUnsentEvent = function(event){ return logger.stores.transferUnsent(event).then(function(){ return logger.cache.updateEvent(event); }); }; batchAckUnsentEvents = function(events){ return logger.stores.batchTransferUnsent(events).then(function(){ if (events.length >= 1000) { logger.cache.clearCache(); return fetchOffline(); } else { return _.map(events, logger.cache.updateEvent); } }); }; removeUnsentEvent = function(event){ logger.channel.log({ event: 'debugRemoveUnsentEvent', eventToRemove: event }); return; return logger.stores.removeUnsentEvent(event).then(function(){ return logger.cache.uncacheEvent(event); }); }; batchRemoveUnsentEvents = function(events){ if (events.length) { logger.channel.log({ event: 'debugBatchRemoveUnsentEvents', eventsToRemove: events }); } return; return logger.stores.batchRemoveUnsentEvents(events).then(function(){ return _.map(events, logger.cache.uncacheEvent); }); }; updateLastInserted = function(newLastInserted){ logger.curLastInserted = newLastInserted; return logger.info.update(logger.logId, newLastInserted); }; tryUpdateLastInserted = function(newLastInserted){ if (newLastInserted > logger.lastInserted) { return updateLastInserted(newLastInserted); } }; sendEventsBatch = function(events){ return logger.serverApi.sendEvents(logger, _.map(events, 'data')).then(function(result){ var ackBatch, removeBatch; ackBatch = []; removeBatch = []; _.map(result, function(data){ var ref$; if (data.event != null) { try { data.event.created = new Date((typeof (ref$ = data.event.created).getTime == 'function' ? ref$.getTime() : void 8) || data.event.created); } catch (e$) {} return ackBatch.push(data.event); } else if (data.error) { try { data.error.created = new Date((typeof (ref$ = data.error.created).getTime == 'function' ? ref$.getTime() : void 8) || data.error.created); } catch (e$) {} return removeBatch.push(data.error); } }); return batchAckUnsentEvents(ackBatch).then(function(){ return _.map(ackBatch, function(data){ return tryUpdateLastInserted(data.event.inserted); }); }).then(function(){ return batchRemoveUnsentEvents(removeBatch); }); }); }; lastSentCache = {}; getDueForSending = function(events){ var now, filteredEvents; now = Date.now(); filteredEvents = _.filter(events, function(d, i){ var event, key, ref$, lastSentDate; event = d.data; key = (((ref$ = event.created) != null ? typeof ref$.getTime == 'function' ? ref$.getTime() : void 8 : void 8) || event.created) + event.src; lastSentDate = lastSentCache[key] || 0; if (now - lastSentDate < logger.retryMinDuration) { return false; } return true; }); return filteredEvents; }; updateDueEvents = function(events){ var now, i$, len$, d, event, key, ref$, results$ = []; now = Date.now(); for (i$ = 0, len$ = events.length; i$ < len$; ++i$) { d = events[i$]; event = d.data; key = (((ref$ = event.created) != null ? typeof ref$.getTime == 'function' ? ref$.getTime() : void 8 : void 8) || event.created) + event.src; results$.push(lastSentCache[key] = now); } return results$; }; sendUnsentUnthrottled = function(){ var ref$; if ((ref$ = logger.options) != null && ref$.readOnly) { return; } return logger.stores.getUnsentEvents().then(function(events){ var nonScoreEvents, batch; events = getDueForSending(events); if (events.length < 10) { nonScoreEvents = _.filter(events, function(event){ var isNonScore, ref$, isOld, ref1$; isNonScore = ((ref$ = event.data) != null ? ref$.event : void 8) !== 'score'; isOld = new Date((ref1$ = event.data) != null ? ref1$.created : void 8) < new Date(Date.now() - logger.retryMinDuration); return isNonScore || isOld; }); if (nonScoreEvents.length === 0) { return Promise.resolve(); } } if (events.length > logger.maxBatchSize) { batch = events.slice(0, logger.maxBatchSize); updateDueEvents(batch); return sendEventsBatch(batch).then(function(){ return setTimeout(sendUnsentUnthrottled); }); } else if (events.length < 5) { updateDueEvents(events); return _.each(events, function(event){ return logger.serverApi.log(logger, event.data); }); } else { updateDueEvents(events); return sendEventsBatch(events); } }); }; sendUnsent = _.throttle(sendUnsentUnthrottled, 5000, { leading: true, trailing: true }); cacheEventsFromDb = function(){ return logger.stores.getEvents().then(function(events){ return logger.cache.cacheEvents(_.map(events, 'data')); }); }; cacheUnsentEventsFromDb = function(){ return logger.stores.getUnsentEvents().then(function(events){ return logger.cache.cacheEvents(_.map(events, 'data')); }); }; loadEventsFromServer = function(firstFetch){ var ref$, fetchInserted, options; logger.lastInserted = (ref$ = logger.info.getCache(logger.logId)) != null ? ref$.lastInserted : void 8; fetchInserted = logger.lastInserted; if (firstFetch) { fetchInserted = logger.params.fromInserted; } fetchInserted == null && (fetchInserted = "1970-01-01"); options = { logger: logger, log: logger.logId, authToken: logger.authToken, deviceLogId: logger.deviceLogId, readOnly: logger.options.readOnly, inserted: fetchInserted, filter: { name: logger.params.filter } }; return logger.serverApi.getEvents(options); }; insertEvents = function(data){ return logger.stores.saveEvents(data.events).then(function(){ return updateLastInserted(data.maxInserted); }); }; filterTriggerEvents = function(events){ return _.filter(events, function(event){ return !logger.cache.hasEvent(event); }); }; syncEventsOrig = function(firstSync){ return loadEventsFromServer(firstSync).then(function(data){ var p; p = Promise.resolve(); if (logger.params.removeOldEvents && firstSync) { p = logger.stores.removeAllEvents(); } return Promise.all([data, p]); }).then(function(arg$){ var data; data = arg$[0]; if (!firstSync) { triggerEvents(filterTriggerEvents(data.events)); } if (logger.params.removeOldEvents && firstSync) { logger.cache.clearCache(); } logger.cache.cacheEvents(data.events); return Promise.all([data, insertEvents(data)]); }).then(function(arg$){ var data; data = arg$[0]; return Promise.all(_.concat(data, _.map(data.events, function(event){ if (event.event === 'deleteEvent') { return deleteTargetEvent(event); } }))); }).then(function(arg$){ var data; data = arg$[0]; return Promise.all([data, cacheUnsentEventsFromDb()]); }).then(function(arg$){ var data; data = arg$[0]; return Promise.all([data, sendUnsent()]); }).then(function(arg$){ var data; data = arg$[0]; logger.state = logger.states.SYNC; return data; })['catch'](function(err){ logger.lastSync = null; console.error("error loading events logId: " + logger.logId, err); sendUnsent(); throw err; }); }; syncEvents = function(firstSync){ if (Date.now() - logger.lastSync < 10000) { return logger.lastSyncRes; } logger.lastSync = Date.now(); return logger.lastSyncRes = syncEventsOrig(firstSync); }; fetchOffline = function(){ return cacheEventsFromDb().then(cacheUnsentEventsFromDb); }; deleteTargetEvent = function(event){ var target, ref$, ref1$, ref2$, ref3$; target = logger.cache.findFirst({ src: (ref$ = event.target) != null ? ref$.src : void 8, created: new Date(((ref1$ = event.target) != null ? typeof (ref2$ = ref1$.created).getTime == 'function' ? ref2$.getTime() : void 8 : void 8) || ((ref2$ = event.target) != null ? ref2$.created : void 8)), event: (ref3$ = event.target) != null ? ref3$.event : void 8 }); if (!target) { return Promise.resolve(); } logger.cache.uncacheEvent(target); return Promise.all([logger.stores.removeUnsentEvent(target), logger.stores.removeEvents(target)]); }; deleteEvent = function(event){ if ((event != null ? event.event : void 8) === 'deleteEvent') { return; } return logger.channel.log({ event: 'deleteEvent', target: event }); }; triggerEvents = function(events){ var newEvents; if (events == null || events.length === 0) { return; } if (!_.isArray(events)) { events = [events]; } newEvents = _.cloneDeep(events); _.each(newEvents, function(event){ return event.logId = logger.logId; }); if (typeof body != 'undefined' && body !== null) { if (typeof body.triggerCustomEvent == 'function') { body.triggerCustomEvent({ event: "onNewLogEvents", detail: { events: newEvents } }); } } return Promise.resolve(); }; return { ackUnsentEvent: ackUnsentEvent, removeUnsentEvent: removeUnsentEvent, updateLastInserted: updateLastInserted, tryUpdateLastInserted: tryUpdateLastInserted, sendUnsent: sendUnsent, syncEvents: syncEvents, syncEventsExternal: syncEventsOrig, fetchOffline: fetchOffline, deleteTargetEvent: deleteTargetEvent, triggerEvents: triggerEvents, deleteEvent: deleteEvent }; }; })(); lib/logServerApi.ls (function(){ var STATE_NONE, STATE_CONNECTING, STATE_CONNECTED, STATE_ERRORED, MIN_DISCONNECT_TIME_FOR_RESUBSCRIBE, connected, socket, state, disconnectAt, secure, r, url, host, socketOptions, connect, destroy, getEvents, sendEvents, _handler, _channel; STATE_NONE = "none"; STATE_CONNECTING = "connecting"; STATE_CONNECTED = "connected"; STATE_ERRORED = "errored"; MIN_DISCONNECT_TIME_FOR_RESUBSCRIBE = 60000; connected = Promise.defer(); socket = null; state = STATE_NONE; disconnectAt = 0; secure = true; r = _.random(3) + 2; url = "https://logger-lb-" + r + ".anton.app"; host = url.replace("https://", ""); socketOptions = { hostname: host, port: secure ? 443 : 80, secure: secure, ackTimeout: 6000, pingTimeout: 6000 }; connect = function(){ state = STATE_CONNECTING; socket = socketCluster.connect(socketOptions); socket.on("error", function(error){ if (state !== STATE_ERRORED) { disconnectAt = Date.now(); } state = STATE_ERRORED; if (error) { console.error("socket error", error); } return _.each(_handler, function(handler){ return typeof handler.onError == 'function' ? handler.onError(error) : void 8; }); }); socket.on("err", function(error){ if (error) { return console.error("socket error", error); } }); socket.on("connect", function(){ state = STATE_CONNECTED; return connected.resolve(); }); socket.on("ack", function(data){ var log, ref$; log = data != null ? data.log : void 8; delete data.log; return (ref$ = _handler[log]) != null ? typeof ref$.onAck == 'function' ? ref$.onAck(data) : void 8 : void 8; }); return socket.on("writeError", function(data){ var log, ref$; log = data != null ? data.log : void 8; delete data.log; return (ref$ = _handler[log]) != null ? typeof ref$.onWriteError == 'function' ? ref$.onWriteError(data) : void 8 : void 8; }); }; destroy = function(){ state = STATE_NONE; socket.disconnect(); return socketCluster.destroy(socket); }; getEvents = function(options){ options.queryTime = new Date().toISOString(); return include("getEvents/getEvents")(options); }; sendEvents = function(logger, events){ return new Promise(function(resolve, reject){ var server, data, i$, ref$, len$, e, src; server = url; if (server.slice(-1) !== "/") { server += "/"; } data = { events: events, log: logger.logId, credentials: { authToken: logger.authToken, deviceLogId: logger.deviceLogId } }; for (i$ = 0, len$ = (ref$ = events).length; i$ < len$; ++i$) { e = ref$[i$]; if (!e.src) { src == null && (src = include("/util/repairLocalStorageSrc/repair")(log, e)); e.src = src; } } return helpers.httpRequest.post(server + "events", data, function(err, body){ if (err) { return reject(err); } return resolve(body); }); }); }; _handler = {}; _channel = {}; return { socketState: function(){ return socket.state; }, subscribe: function(logger, handler){ var log, ref$; log = logger.logId; _handler[log] = handler; if (state === STATE_NONE) { connect(); } if ((ref$ = _handler[log]) != null) { if (typeof ref$.onCreate == 'function') { ref$.onCreate(); } } return connected.promise.then(function(){ var credentials, channel; credentials = { deviceLogId: logger.deviceLogId, authToken: logger.authToken }; channel = socket.subscribe(log, { data: credentials }); _channel[log] = channel; channel.on("subscribe", function(){ var ref$, ref1$; if (!channel.wasSubscribed) { channel.wasSubscribed = true; return (ref$ = _handler[log]) != null ? typeof ref$.onSubscribe == 'function' ? ref$.onSubscribe(null, channel) : void 8 : void 8; } else { if (Date.now() - disconnectAt > MIN_DISCONNECT_TIME_FOR_RESUBSCRIBE) { return (ref1$ = _handler[log]) != null ? typeof ref1$.onSubscribe == 'function' ? ref1$.onSubscribe(null, channel) : void 8 : void 8; } } }); channel.on("subscribeFail", function(log, data){ var ref$; channel.wasSubscribed = false; console.error("subscribe failed", log, data); return (ref$ = _handler[log]) != null ? typeof ref$.onSubscribe == 'function' ? ref$.onSubscribe(data) : void 8 : void 8; }); return channel.watch(function(data){ var ref$; return (ref$ = _handler[log]) != null ? typeof ref$.onEvent == 'function' ? ref$.onEvent(data) : void 8 : void 8; }); }); }, unsubscribe: function(log, callback){ if (state === STATE_ERRORED) { return typeof callback == 'function' ? callback() : void 8; } else { return connected.promise.then(function(){ var channel; channel = _channel[log]; if (channel.isSubscribed(channel.id)) { channel.unsubscribe(); } channel.unwatch(); channel.destroy(); delete _channel[log]; delete _handler[log]; return typeof callback == 'function' ? callback() : void 8; }); } }, log: function(logger, _data){ var log, credentials, channel; log = logger.logId; credentials = { authToken: logger.authToken, deviceLogId: logger.deviceLogId }; if (!_data.src) { _data.src = include("/util/repairLocalStorageSrc/repair")(log, _data); } channel = _channel[log]; return channel != null ? channel.publish({ event: _data, credentials: credentials }) : void 8; }, sendEvents: sendEvents, getEvents: getEvents, destroy: destroy }; })(); lib/logStates.ls (function(){ return { NONE: 0, SUBSCRIBED: 1, SYNC: 2, CLOSED: 3 }; })(); lib/logStores.ls (function(){ return function(){ var logStore, unsentStore, logOptions, getKey; logStore = null; unsentStore = null; logOptions = {}; getKey = function(event){ return event.src + new Date(event.created).toISOString(); }; return { init: function(log, options, logInfo){ var initStore, initUnsent; logOptions = options; initStore = new Promise(function(resolve){ return Lawnchair({ adapter: logOptions.memoryOnly ? 'memory' : void 8, name: "events_" + log, prefix: 'logger' }, function(db){ if (db.error && db.error.message !== 'empty file') { logInfo.update(log, -1); console.error("error loading events file logId: " + log, db.error); } logStore = db; return resolve(); }); }); initUnsent = new Promise(function(resolve){ return Lawnchair({ adapter: logOptions.memoryOnly ? 'memory' : void 8, name: "events_" + log + "_unsent", prefix: 'logger' }, function(db){ if (db.error && db.error.message !== 'empty file') { console.error("error loading unsent events file logId: " + log, db.error); } unsentStore = db; return resolve(); }); }); return Promise.all([initStore, initUnsent]); }, getEvents: function(){ return new Promise(function(resolve){ return logStore.all(resolve); }); }, getUnsentEvents: function(limit){ return new Promise(function(resolve){ return unsentStore.all(function(events){ if (limit != null && events.length > limit) { events = _.sortBy(events, 'created'); return resolve(events.slice(0, limit)); } else { return resolve(events); } }); }); }, removeAllEvents: function(){ return new Promise(function(resolve){ return logStore.nuke(resolve); }); }, removeAllUnsentEvents: function(){ return new Promise(function(resolve){ return unsentStore.nuke(resolve); }); }, removeEvents: function(events){ if (!_.isArray(events)) { events = [events]; } return new Promise(function(resolve){ return logStore.remove(_.map(events, getKey), resolve); }); }, saveEvents: function(events){ return new Promise(function(resolve){ var data; if (!_.isArray(events)) { events = [events]; } data = _.map(events, function(e){ return { data: e, key: getKey(e) }; }); return logStore.batch(data, resolve); }); }, saveUnsentEvent: function(event){ return new Promise(function(resolve){ var data; if (logOptions != null && logOptions.readOnly) { return resolve(); } data = { key: getKey(event), data: event }; return unsentStore.save(data, resolve); }); }, transferUnsent: function(event){ return new Promise(function(resolve){ var data; data = { key: getKey(event), data: event }; return logStore.save(data, function(){ return unsentStore.remove(getKey(event), resolve); }); }); }, batchTransferUnsent: function(events){ var data, writeP, removeP; data = _.map(events, function(event){ return { key: getKey(event), data: event }; }); writeP = new Promise(function(resolve){ return logStore.batch(data, resolve); }); removeP = new Promise(function(resolve){ return unsentStore.remove(_.map(data, 'key'), resolve); }); return Promise.all([writeP, removeP]); }, removeUnsentEvent: function(event){ return new Promise(function(resolve){ return unsentStore.remove(getKey(event), resolve); }); }, batchRemoveUnsentEvents: function(events){ return new Promise(function(resolve){ return unsentStore.remove(_.map(events, getKey), resolve); }); } }; }; })(); lib/serverEventHandler.ls (function(){ return function(logger){ return { onSubscribe: function(){ var firstSync; firstSync = logger.state === logger.states.NONE; logger.state = logger.states.SUBSCRIBED; return logger.routines.syncEvents(firstSync)['finally'](function(token){ logger.subscribeHandler.addOpenChannel(logger.logId, logger.channel); return logger.subscribeHandler.notifySubscribeWaiting(logger.logId, logger.channel, token); }); }, onCreate: function(){ var firstSync; firstSync = logger.state === logger.states.NONE; return logger.routines.syncEvents(firstSync)['finally'](function(token){ logger.subscribeHandler.addOpenChannel(logger.logId, logger.channel); return logger.subscribeHandler.notifySubscribeWaiting(logger.logId, logger.channel, token); }); }, onEvent: function(data){ var wasCached; if ((data != null ? data.event : void 8) == null) { return; } wasCached = logger.cache.hasEvent(data.event); logger.cache.cacheEvent(data.event); if (data.event.event === 'deleteEvent') { logger.routines.deleteTargetEvent(data.event); } logger.stores.saveEvents(data.event).then(function(){ return logger.routines.tryUpdateLastInserted(data.event.inserted); }); if (!wasCached) { return logger.routines.triggerEvents(data.event); } }, onAck: function(data){ var ref$; if (data.event) { data.event.created = new Date((typeof (ref$ = data.event.created).getTime == 'function' ? ref$.getTime() : void 8) || data.event.created); data.event.inserted = data.event.inserted ? new Date((typeof (ref$ = data.event.inserted).getTime == 'function' ? ref$.getTime() : void 8) || data.event.inserted) : void 8; return logger.routines.ackUnsentEvent(data.event).then(function(){ return logger.routines.tryUpdateLastInserted(data.event.inserted); }); } else if (data.error) { data.error.created = new Date((typeof (ref$ = data.error.created).getTime == 'function' ? ref$.getTime() : void 8) || data.error.created); data.error.inserted = data.event.inserted ? new Date((typeof (ref$ = data.error.inserted).getTime == 'function' ? ref$.getTime() : void 8) || data.error.inserted) : void 8; return logger.routines.removeUnsentEvent(data.error); } }, onWriteError: function(data){ console.error('log write error', data); return logger.routines.removeUnsentEvent(data.event); }, onError: function(data){ console.error('log error', data); if (logger.state === logger.states.NONE) { return logger.routines.syncEvents()['finally'](function(){ logger.subscribeHandler.addOpenChannel(logger.logId, logger.channel); return logger.subscribeHandler.notifySubscribeWaiting(logger.logId, logger.channel); }); } } }; }; })(); lib/subscribeHandler.ls (function(){ return function(){ var openChannels, initChannels, waitingInitChannels, waitingSubscribeChannels; openChannels = {}; initChannels = {}; waitingInitChannels = {}; waitingSubscribeChannels = {}; return { addInitWaiting: function(log, onInit){ if (onInit == null) { return; } if (!_.isFunction(onInit)) { throw new Error('logger onInitDone expects function'); } if (waitingInitChannels[log] == null) { waitingInitChannels[log] = []; } return waitingInitChannels[log].push(onInit); }, addSubscribeWaiting: function(log, onSubscribe){ if (onSubscribe == null) { return; } if (!_.isFunction(onSubscribe)) { throw new Error('logger onSubscribe expects function'); } if (waitingSubscribeChannels[log] == null) { waitingSubscribeChannels[log] = []; } return waitingSubscribeChannels[log].push(onSubscribe); }, notifyInitWaiting: function(log, channel){ var ref$; _.each(waitingInitChannels[log], function(cb){ return setTimeout(function(){ return typeof cb == 'function' ? cb(channel) : void 8; }); }); return ref$ = waitingInitChannels[log], delete waitingInitChannels[log], ref$; }, notifySubscribeWaiting: function(log, channel){ var ref$; _.each(waitingSubscribeChannels[log], function(cb){ return setTimeout(function(){ return typeof cb == 'function' ? cb(channel) : void 8; }); }); return ref$ = waitingSubscribeChannels[log], delete waitingSubscribeChannels[log], ref$; }, hasWaiting: function(log){ return waitingInitChannels[log] != null || waitingSubscribeChannels[log] != null; }, hasInitWaiting: function(log){ return waitingInitChannels[log] != null; }, getAllOpenChannels: function(){ return openChannels; }, getOpenChannel: function(log){ return openChannels[log]; }, addOpenChannel: function(log, channel){ return openChannels[log] = channel; }, removeOpenChannel: function(log){ var ref$; return ref$ = openChannels[log], delete openChannels[log], ref$; }, getInitChannel: function(log){ return initChannels[log]; }, addInitChannel: function(log, channel){ return initChannels[log] = channel; }, removeInitChannel: function(log, channel){ var ref$; return ref$ = initChannels[log], delete initChannels[log], ref$; } }; }; })(); logger.ls (function(){ var logServerApi, logInfo, logOptions, MAX_BATCH_SIZE, RETRY_MIN_DURATION, ref$, subscribeHandler; logServerApi = include('/lib/logServerApi'); logInfo = null; logOptions = {}; MAX_BATCH_SIZE = 2000; RETRY_MIN_DURATION = 60000; window.loggerInstances = (ref$ = window.loggerInstances) != null ? ref$ : {}; subscribeHandler = include('/lib/subscribeHandler')(); return { init: function(options, callback){ if (!callback && _.isFunction(options)) { callback = options; logOptions = {}; } else { logOptions = options || {}; } logInfo = include('/lib/logInfo')(); return logInfo.init(logOptions).then(function(){ return setTimeout(function(){ return typeof callback == 'function' ? callback() : void 8; }); }); }, info: function(){ return _.clone(subscribeHandler.getAllOpenChannels()); }, removeAllIndexedDbs: include('/util/removeAllndexedDbs'), destroy: function(callback){ return Promise.all(_.map(_.values(subscribeHandler.getAllOpenChannels()), function(channel){ return new Promise(function(resolve){ return channel.unsubscribe(resolve); }); })).then(function(){ logServerApi.destroy(); delete window.Logger; return typeof callback == 'function' ? callback() : void 8; }); }, subscribe: function(params, callback){ var logId, hasWaiting, logger, logStores; if (!_.isObject(params)) { params = { logId: params }; } if (callback) { params.onSubscribe = callback; } if (params.onInitDone == null && params.onSubscribe == null) { throw new Error('logger.subscribe needs initDone or subscribe callback'); } logId = params.logId; if (subscribeHandler.getOpenChannel(logId) != null) { if (typeof params.onInitDone == 'function') { params.onInitDone(subscribeHandler.getOpenChannel(logId)); } if (typeof params.onSubscribe == 'function') { params.onSubscribe(subscribeHandler.getOpenChannel(logId)); } delete params.onInitDone; delete params.onSubscribe; return; } if (subscribeHandler.getInitChannel(logId) != null) { if (typeof params.onInitDone == 'function') { params.onInitDone(subscribeHandler.getInitChannel(logId)); } delete params.onInitDone; } hasWaiting = subscribeHandler.hasWaiting(logId); subscribeHandler.addInitWaiting(logId, params.onInitDone); subscribeHandler.addSubscribeWaiting(logId, params.onSubscribe); delete params.onInitDone; delete params.onSubscribe; if (hasWaiting) { return; } logger = { cache: include('/lib/logCache')(), subscribeHandler: subscribeHandler, lastInserted: null, state: include('/lib/logStates').NONE, states: include('/lib/logStates'), info: logInfo, serverApi: logServerApi, logId: logId, authToken: params.authToken, deviceLogId: params.deviceLogId, params: params, options: logOptions, maxBatchSize: MAX_BATCH_SIZE, retryMinDuration: RETRY_MIN_DURATION }; window.loggerInstances[logId] = logger; logStores = include('/lib/logStores')(); return logStores.init(logId, logOptions, logInfo).then(function(){ logger.stores = logStores; logger.routines = include('/lib/logRoutines')(logger); logger.channel = include('/lib/logChannel')(logger); logger.serverEventHandler = include('/lib/serverEventHandler')(logger); return logger.routines.fetchOffline(); }).then(function(){ logger.subscribeHandler.addInitChannel(logId, logger.channel); logger.subscribeHandler.notifyInitWaiting(logId, logger.channel); return logger.serverApi.subscribe(logger, logger.serverEventHandler); }); } }; })(); testcases.ls (function(){})(); util/indexedDbHelper.ls (function(){ var openDb, readDb; openDb = function(dbName){ return new Promise(function(resolve, reject){ var req; req = typeof indexedDB != 'undefined' && indexedDB !== null ? indexedDB.open(dbName) : void 8; req.onsuccess = function(e){ return resolve(e.target.result); }; return req.onerror = reject; }); }; readDb = function(db){ return new Promise(function(resolve, reject){ var objectStore, r, toReturn, req; objectStore = db.transaction('record').objectStore('record'); if (store.getAll != null) { r = objectStore.getAll(); r.onsuccess = function(){ return resolve(r.result); }; return r.onerror = reject; } else { toReturn = []; req = objectStore.openCursor(); req.onsuccess = function(event){ var cursor; cursor = event.target.result; if (cursor) { toReturn.push(cursor.value); return cursor['continue'](); } else { return resolve(toReturn); } }; return req.onerror = reject; } }); }; return { readDb: function(dbName){ return openDb(dbName).then(function(db){ return readDb(db); }); }, deleteDb: function(dbName){ return new Promise(function(resolve, reject){ var req; req = indexedDB.deleteDatabase(dbName); req.onsuccess = resolve; return req.onerror = reject; }); } }; })(); util/insert.ls (function(){ return function(arr, obj){ var comp, min, max, curr, pos; comp = function(a, b){ var ref$, ref1$; return (((ref$ = a.created) != null ? typeof ref$.getTime == 'function' ? ref$.getTime() : void 8 : void 8) || a.created) < (((ref1$ = b.created) != null ? typeof ref1$.getTime == 'function' ? ref1$.getTime() : void 8 : void 8) || b.created); }; if (!obj) { return; } if (arr.length === 0 || comp(arr[arr.length - 1], obj)) { arr.push(obj); return arr.length - 1; } min = 0; max = arr.length; curr = undefined; while (max - min > 1) { curr = min + Math.floor((max - min) / 2); if (comp(arr[curr], obj)) { min = curr; } else { max = curr; } } pos = min; if (comp(arr[min], obj)) { pos = min + 1; } arr.splice(pos, 0, obj); return pos; }; })(); util/remove.ls (function(){ return function(arr, obj){ var getKey, getKey2, comp, last, min, max, curr, pos; getKey = function(a){ var ref$; return ((ref$ = a.created) != null ? typeof ref$.getTime == 'function' ? ref$.getTime() : void 8 : void 8) || a.created; }; getKey2 = function(a){ var ref$; return (((ref$ = a.created) != null ? typeof ref$.getTime == 'function' ? ref$.getTime() : void 8 : void 8) || a.created) + a.src; }; comp = function(a, b){ return getKey(a) < getKey(b); }; if (!obj) { return; } if (!arr) { return; } last = arr[arr.length - 1]; if (arr.length === 0 || getKey2(arr[arr.length - 1]) === getKey2(obj)) { arr.pop(); return arr.length; } min = 0; max = arr.length; curr = undefined; while (max - min > 1) { curr = min + Math.floor((max - min) / 2); if (comp(arr[curr], obj)) { min = curr; } else { max = curr; } } pos = min; if (getKey2(arr[pos]) !== getKey2(obj)) { pos = min + 1; } if (arr[pos] && getKey2(arr[pos]) === getKey2(obj)) { arr.splice(pos, 1); } return pos; }; })(); util/removeAllndexedDbs.ls (function(){ return function(){ var indexedDbHelper; indexedDbHelper = include('indexedDbHelper'); return indexedDbHelper.readDb('logger_info').then(function(logs){ return Promise.all(_.map(logs, function(info){ var del1, del2; del1 = indexedDbHelper.deleteDb("logger_events_" + info.key); del2 = indexedDbHelper.deleteDb("logger_events_" + info.key + "_unsent"); return Promise.all([del1, del2]); })); }).then(function(res){ return indexedDbHelper.deleteDb('logger_info'); }); }; })(); util/repairLocalStorageSrc/repair.ls (function(){ return function(logId, event){ var deviceLogId, newSrc, debugEvent, data; deviceLogId = typeof deviceLog != 'undefined' && deviceLog !== null ? deviceLog.id() : void 8; newSrc = deviceLogId != null ? deviceLogId.split("-")[1] : void 8; if (newSrc) { Store("sourceId", newSrc); Store("deviceLogId", deviceLogId); } debugEvent = { src: newSrc != null ? newSrc : "debugSrc", event: 'debugRepairLocalStorageSrc', description: 'empty local storage', newSrc: newSrc, store: Store(), localStorage: localStorage, created: helpers.secureEventCreated(), deviceLogId: deviceLogId, userAgent: typeof navigator != 'undefined' && navigator !== null ? navigator.userAgent : void 8, originalEvent: event }; data = { events: [debugEvent], log: logId }; helpers.httpRequest.post("https://logger.solocode.com/events", data); return newSrc; }; })();