diff --git a/rakam.js b/rakam.js index b5b8cdb..04d1e8c 100644 --- a/rakam.js +++ b/rakam.js @@ -248,7 +248,6 @@ Rakam.prototype.init = function (apiKey, opt_userId, opt_config, callback) { _saveCookieData(this); log('initialized with apiKey=' + apiKey); - this.setUserId(opt_userId); if (this.options.saveEvents) { var savedUnsentEventsString = localStorage.getItem(this.options.unsentKey); @@ -293,11 +292,12 @@ Rakam.prototype.init = function (apiKey, opt_userId, opt_config, callback) { } this._lastEventTime = now; localStorage.setItem(LocalStorageKeys.LAST_EVENT_TIME, this._lastEventTime); - } catch (e) { log(e); } + this.setUserId(opt_userId); + if (callback && typeof(callback) === 'function') { setTimeout(function () { callback(); diff --git a/rakam.min.js b/rakam.min.js index bf5aca2..1010451 100644 --- a/rakam.min.js +++ b/rakam.min.js @@ -1,2 +1,2 @@ -(function umd(require){if("object"==typeof exports){module.exports=require("1")}else if("function"==typeof define&&define.amd){define(function(){return require("1")})}else{this["rakam"]=require("1")}})(function outer(modules,cache,entries){var global=function(){return this}();function require(name,jumped){if(cache[name])return cache[name].exports;if(modules[name])return call(name,require);throw new Error('cannot find module "'+name+'"')}function call(id,require){var m=cache[id]={exports:{}};var mod=modules[id];var name=mod[2];var fn=mod[0];fn.call(m.exports,function(req){var dep=modules[id][1][req];return require(dep?dep:req)},m,m.exports,outer,modules,cache,entries);if(name)cache[name]=cache[id];return cache[id].exports}for(var id in entries){if(entries[id]){global[entries[id]]=require(id)}else{require(id)}}require.duo=true;require.cache=cache;require.modules=modules;return require}({1:[function(require,module,exports){var Rakam=require("./rakam");var old=window.rakam||{};var instance=new Rakam;instance._q=old._q||[];module.exports=instance},{"./rakam":2}],2:[function(require,module,exports){var Cookie=require("./cookie");var JSON=require("json");var language=require("./language");var localStorage=require("./localstorage");var object=require("object");var Request=require("./xhr");var UUID=require("./uuid");var version=require("./version");var User=require("./user");var ifvisible=require("../node_modules/ifvisible.js/src/ifvisible.min.js");var type=require("./type");var log=function(s){console.log("[Rakam] "+s)};var indexOf;if(!Array.prototype.indexOf){indexOf=function(obj,start){for(var i=start||0,j=this.length;i0?idleTime:(new Date).getTime())-startTime-gapMillis)/1e3};Rakam.prototype.getTimeOnPreviousPage=function(){return Cookie.get("_rakam_time")};Rakam.prototype.nextEventId=function(){this._eventId++;return this._eventId};Rakam.prototype._sendEventsIfReady=function(callback){if(this._unsentEvents.length===0){return false}if(!this.options.batchEvents){this.sendEvents(callback);return true}if(this._unsentEvents.length>=this.options.eventUploadThreshold){this.sendEvents(callback);return true}setTimeout(this.sendEvents.bind(this),this.options.eventUploadPeriodMillis);return false};var _loadCookieData=function(scope){var cookieData=Cookie.get(scope.options.cookieName);if(cookieData){if(cookieData.deviceId){scope.options.deviceId=cookieData.deviceId}if(cookieData.userId){scope.options.userId=cookieData.userId}if(cookieData.superProps){scope.options.superProperties=cookieData.superProps}if(cookieData.optOut!==undefined){scope.options.optOut=cookieData.optOut}if(cookieData.deviceIdCreatedAt!==undefined){scope.deviceIdCreatedAt=new Date(parseInt(cookieData.deviceIdCreatedAt))}}};var _saveCookieData=function(scope){Cookie.set(scope.options.cookieName,{deviceId:scope.options.deviceId,deviceIdCreatedAt:scope.deviceIdCreatedAt?scope.deviceIdCreatedAt.getTime():undefined,userId:scope.options.userId,superProps:scope.options.superProperties,optOut:scope.options.optOut})};Rakam._getUtmParam=function(name,query){name=name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var regex=new RegExp("[\\?&]"+name+"=([^&#]*)");var results=regex.exec(query);return results===null?undefined:decodeURIComponent(results[1].replace(/\+/g," "))};Rakam._getUtmData=function(rawCookie,query){var cookie=rawCookie?"?"+rawCookie.split(".").slice(-1)[0].replace(/\|/g,"&"):"";var fetchParam=function(queryName,query,cookieName,cookie){return Rakam._getUtmParam(queryName,query)||Rakam._getUtmParam(cookieName,cookie)};return{utm_source:fetchParam("utm_source",query,"utmcsr",cookie),utm_medium:fetchParam("utm_medium",query,"utmcmd",cookie),utm_campaign:fetchParam("utm_campaign",query,"utmccn",cookie),utm_term:fetchParam("utm_term",query,"utmctr",cookie),utm_content:fetchParam("utm_content",query,"utmcct",cookie)}};Rakam.prototype._initUtmData=function(queryParams,cookieParams){queryParams=queryParams||location.search;cookieParams=cookieParams||Cookie.get("__utmz");this._utmProperties=Rakam._getUtmData(cookieParams,queryParams)};Rakam.prototype._initTrackForms=function(){document.addEventListener("submit",function(event){var targetElement=event.target||event.srcElement;var collection=targetElement.getAttribute("rakam-event-form");if(targetElement.tagName==="FORM"&&collection){var properties={};var extraAttributes=targetElement.getAttribute("rakam-event-extra");if(extraAttributes!==null){for(var key in JSON.parse(extraAttributes)){if(extraAttributes.hasOwnProperty(key)){properties[key]=extraAttributes[key]}}}for(var i=0;i0&&previousUserId===null||previousUserId!==null&&this.deviceIdCreatedAt!==undefined)){var _this=this;this.User()._merge(previousUserId,this.deviceIdCreatedAt,function(){_this.deviceIdCreatedAt=undefined;_saveCookieData(_this)})}_saveCookieData(this);log("set userId="+userId)}catch(e){log(e)}};Rakam.prototype.setUserProperties=function(parameters){try{return(new this.User).set(parameters)}catch(e){log(e)}};Rakam.prototype.getUserId=function(){return this.options.userId};Rakam.prototype.getDeviceId=function(){return this._eventId>0?this.options.deviceId:null};Rakam.prototype.setOptOut=function(enable){try{this.options.optOut=enable;_saveCookieData(this);log("set optOut="+enable)}catch(e){log(e)}};Rakam.prototype.setDeviceId=function(deviceId){try{if(deviceId){this.options.deviceId=""+deviceId;console.log(this.options,deviceId);_saveCookieData(this)}}catch(e){log(e)}};Rakam.prototype.setSuperProperties=function(eventProps,opt_replace){try{this.options.superProperties=this.options.superProperties||{};for(var property in eventProps){if(eventProps.hasOwnProperty(property)){if(opt_replace===false&&this.options.superProperties[property]!==undefined){continue}this.options.superProperties[property]=eventProps[property]}}_saveCookieData(this);log("set super properties="+JSON.stringify(eventProps))}catch(e){log(e)}};Rakam.prototype.setVersionName=function(versionName){try{this.options.versionName=versionName;log("set versionName="+versionName)}catch(e){log(e)}};Rakam.prototype._logEvent=function(eventType,eventProperties,apiProperties,callback){if(typeof callback!=="function"){callback=null}if(!eventType||this.options.optOut){if(callback){callback(0,"No request sent")}return}try{var eventTime=(new Date).getTime();var eventId=this.nextEventId();if(!this._sessionId||!this._lastEventTime||eventTime-this._lastEventTime>this.options.sessionTimeout){this._sessionId=eventTime;localStorage.setItem(LocalStorageKeys.SESSION_ID,this._sessionId)}this._lastEventTime=eventTime;localStorage.setItem(LocalStorageKeys.LAST_EVENT_TIME,this._lastEventTime);localStorage.setItem(LocalStorageKeys.LAST_ID,eventId);apiProperties=apiProperties||{};eventProperties=eventProperties||{};object.merge(eventProperties,this._utmProperties);var event={collection:eventType,properties:{_device_id:this.options.deviceId,_user:this.options.userId,_time:parseInt(eventTime/1e3)*1e3,_session_id:this._sessionId||-1,_platform:this.options.platform,_language:this.options.language}};object.merge(event.properties,this.options.superProperties);object.merge(event.properties,apiProperties);object.merge(event.properties,eventProperties);log("logged eventType="+eventType+", properties="+JSON.stringify(eventProperties));this._unsentEvents.push({id:eventId,event:event});if(this._unsentEvents.length>this.options.savedMaxCount){this._unsentEvents.splice(0,this._unsentEvents.length-this.options.savedMaxCount)}if(this.options.saveEvents){this.saveEvents()}if(!this._sendEventsIfReady(callback)&&callback){callback(0,"No request sent")}return eventId}catch(e){log(e)}};Rakam.prototype.logEvent=function(eventType,eventProperties,callback){return this._logEvent(eventType,eventProperties,null,callback)};Rakam.prototype.removeEvents=function(maxEventId,errors){var filteredEvents=[];var errorList=errors||[];for(var i=0;i-1||id>maxEventId){filteredEvents.push(this._unsentEvents[i])}}this._unsentEvents=filteredEvents};Rakam.prototype.sendEvents=function(callback){if(!this._sending&&!this.options.optOut&&this._unsentEvents.length>0){this._sending=true;var url=("https:"===window.location.protocol?"https":"http")+"://"+this.options.apiEndpoint+this.options.eventEndpointPath;var numEvents=Math.min(this._unsentEvents.length,this.options.uploadBatchSize);var maxEventId=this._unsentEvents[numEvents-1].id;this._unsentEvents.slice(0,numEvents);var events=this._unsentEvents.slice(0,numEvents).map(function(e){return e.event});var upload_time=(new Date).getTime();var api={upload_time:upload_time,api_version:API_VERSION,api_key:this.options.apiKey};var scope=this;new Request(url,{api:api,events:events}).send(function(status,response,headers){scope._sending=false;try{if(status===200||status===409){log("successful upload");scope.removeEvents(maxEventId,status===409?JSON.parse(response):null);if(scope.options.saveEvents){scope.saveEvents()}if(!scope._sendEventsIfReady(callback)&&callback){callback(status,response)}}else if(status===413){log("request too large");if(scope.options.uploadBatchSize===1){scope.removeEvents(maxEventId)}scope.options.uploadBatchSize=Math.ceil(numEvents/2);scope.sendEvents(callback)}else if(callback){callback(status,response)}}catch(e){log("failed upload")}if(scope.options.eventCallbacks){try{for(var i=0;i>2;enc2=(chr1&3)<<4|chr2>>4;enc3=(chr2&15)<<2|chr3>>6;enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64}else if(isNaN(chr3)){enc4=64}output=output+Base64._keyStr.charAt(enc1)+Base64._keyStr.charAt(enc2)+Base64._keyStr.charAt(enc3)+Base64._keyStr.charAt(enc4)}return output},decode:function(input){try{if(window.btoa&&window.atob){return decodeURIComponent(escape(window.atob(input)))}}catch(e){}return Base64._decode(input)},_decode:function(input){var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(i>4;chr2=(enc2&15)<<4|enc3>>2;chr3=(enc3&3)<<6|enc4;output=output+String.fromCharCode(chr1);if(enc3!==64){output=output+String.fromCharCode(chr2)}if(enc4!==64){output=output+String.fromCharCode(chr3)}}output=UTF8.decode(output);return output}};module.exports=Base64},{"./utf8":16}],16:[function(require,module,exports){var UTF8={encode:function(s){var utftext="";for(var n=0;n127&&c<2048){utftext+=String.fromCharCode(c>>6|192);utftext+=String.fromCharCode(c&63|128)}else{utftext+=String.fromCharCode(c>>12|224);utftext+=String.fromCharCode(c>>6&63|128);utftext+=String.fromCharCode(c&63|128)}}return utftext},decode:function(utftext){var s="";var i=0;var c=0,c1=0,c2=0;while(i191&&c<224){c1=utftext.charCodeAt(i+1);s+=String.fromCharCode((c&31)<<6|c1&63);i+=2}else{c1=utftext.charCodeAt(i+1);c2=utftext.charCodeAt(i+2);s+=String.fromCharCode((c&15)<<12|(c1&63)<<6|c2&63);i+=3}}return s}};module.exports=UTF8},{}],4:[function(require,module,exports){var json=window.JSON||{};var stringify=json.stringify;var parse=json.parse;module.exports=parse&&stringify?JSON:require("json-fallback")},{"json-fallback":17}],17:[function(require,module,exports){(function(){"use strict";var JSON=module.exports={};function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}}var cx,escapable,gap,indent,meta,rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i0){var key=headerPair.substring(0,index);var val=headerPair.substring(index+2);headers[key]=val}}return headers}Request.prototype.send=function(callback){var isIE=window.XDomainRequest?true:false;if(isIE){var xdr=new window.XDomainRequest;xdr.open("POST",this.url,true);xdr.onload=function(){callback(xdr.responseText)};xdr.send(JSON.stringify(this.data))}else{var xhr=new XMLHttpRequest;xhr.withCredentials="true";xhr.open("POST",this.url,true);xhr.onreadystatechange=function(){if(xhr.readyState===4){callback(xhr.status,xhr.responseText,parseResponseHeaders(xhr.getAllResponseHeaders()))}};xhr.setRequestHeader("Content-Type","text/plain");for(var key in this.headers){if(this.headers.hasOwnProperty(key)){xhr.setRequestHeader(key,this.headers[key])}}xhr.send(JSON.stringify(this.data))}};module.exports=Request},{json:4}],9:[function(require,module,exports){var uuid=function(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,uuid); +(function umd(require){if("object"==typeof exports){module.exports=require("1")}else if("function"==typeof define&&define.amd){define(function(){return require("1")})}else{this["rakam"]=require("1")}})(function outer(modules,cache,entries){var global=function(){return this}();function require(name,jumped){if(cache[name])return cache[name].exports;if(modules[name])return call(name,require);throw new Error('cannot find module "'+name+'"')}function call(id,require){var m=cache[id]={exports:{}};var mod=modules[id];var name=mod[2];var fn=mod[0];fn.call(m.exports,function(req){var dep=modules[id][1][req];return require(dep?dep:req)},m,m.exports,outer,modules,cache,entries);if(name)cache[name]=cache[id];return cache[id].exports}for(var id in entries){if(entries[id]){global[entries[id]]=require(id)}else{require(id)}}require.duo=true;require.cache=cache;require.modules=modules;return require}({1:[function(require,module,exports){var Rakam=require("./rakam");var old=window.rakam||{};var instance=new Rakam;instance._q=old._q||[];module.exports=instance},{"./rakam":2}],2:[function(require,module,exports){var Cookie=require("./cookie");var JSON=require("json");var language=require("./language");var localStorage=require("./localstorage");var object=require("object");var Request=require("./xhr");var UUID=require("./uuid");var version=require("./version");var User=require("./user");var ifvisible=require("../node_modules/ifvisible.js/src/ifvisible.min.js");var type=require("./type");var log=function(s){console.log("[Rakam] "+s)};var indexOf;if(!Array.prototype.indexOf){indexOf=function(obj,start){for(var i=start||0,j=this.length;i0?idleTime:(new Date).getTime())-startTime-gapMillis)/1e3};Rakam.prototype.getTimeOnPreviousPage=function(){return Cookie.get("_rakam_time")};Rakam.prototype.nextEventId=function(){this._eventId++;return this._eventId};Rakam.prototype._sendEventsIfReady=function(callback){if(this._unsentEvents.length===0){return false}if(!this.options.batchEvents){this.sendEvents(callback);return true}if(this._unsentEvents.length>=this.options.eventUploadThreshold){this.sendEvents(callback);return true}setTimeout(this.sendEvents.bind(this),this.options.eventUploadPeriodMillis);return false};var _loadCookieData=function(scope){var cookieData=Cookie.get(scope.options.cookieName);if(cookieData){if(cookieData.deviceId){scope.options.deviceId=cookieData.deviceId}if(cookieData.userId){scope.options.userId=cookieData.userId}if(cookieData.superProps){scope.options.superProperties=cookieData.superProps}if(cookieData.optOut!==undefined){scope.options.optOut=cookieData.optOut}if(cookieData.deviceIdCreatedAt!==undefined){scope.deviceIdCreatedAt=new Date(parseInt(cookieData.deviceIdCreatedAt))}}};var _saveCookieData=function(scope){Cookie.set(scope.options.cookieName,{deviceId:scope.options.deviceId,deviceIdCreatedAt:scope.deviceIdCreatedAt?scope.deviceIdCreatedAt.getTime():undefined,userId:scope.options.userId,superProps:scope.options.superProperties,optOut:scope.options.optOut})};Rakam._getUtmParam=function(name,query){name=name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var regex=new RegExp("[\\?&]"+name+"=([^&#]*)");var results=regex.exec(query);return results===null?undefined:decodeURIComponent(results[1].replace(/\+/g," "))};Rakam._getUtmData=function(rawCookie,query){var cookie=rawCookie?"?"+rawCookie.split(".").slice(-1)[0].replace(/\|/g,"&"):"";var fetchParam=function(queryName,query,cookieName,cookie){return Rakam._getUtmParam(queryName,query)||Rakam._getUtmParam(cookieName,cookie)};return{utm_source:fetchParam("utm_source",query,"utmcsr",cookie),utm_medium:fetchParam("utm_medium",query,"utmcmd",cookie),utm_campaign:fetchParam("utm_campaign",query,"utmccn",cookie),utm_term:fetchParam("utm_term",query,"utmctr",cookie),utm_content:fetchParam("utm_content",query,"utmcct",cookie)}};Rakam.prototype._initUtmData=function(queryParams,cookieParams){queryParams=queryParams||location.search;cookieParams=cookieParams||Cookie.get("__utmz");this._utmProperties=Rakam._getUtmData(cookieParams,queryParams)};Rakam.prototype._initTrackForms=function(){document.addEventListener("submit",function(event){var targetElement=event.target||event.srcElement;var collection=targetElement.getAttribute("rakam-event-form");if(targetElement.tagName==="FORM"&&collection){var properties={};var extraAttributes=targetElement.getAttribute("rakam-event-extra");if(extraAttributes!==null){for(var key in JSON.parse(extraAttributes)){if(extraAttributes.hasOwnProperty(key)){properties[key]=extraAttributes[key]}}}for(var i=0;i0&&previousUserId===null||previousUserId!==null&&this.deviceIdCreatedAt!==undefined)){var _this=this;this.User()._merge(previousUserId,this.deviceIdCreatedAt,function(){_this.deviceIdCreatedAt=undefined;_saveCookieData(_this)})}_saveCookieData(this);log("set userId="+userId)}catch(e){log(e)}};Rakam.prototype.setUserProperties=function(parameters){try{return(new this.User).set(parameters)}catch(e){log(e)}};Rakam.prototype.getUserId=function(){return this.options.userId};Rakam.prototype.getDeviceId=function(){return this._eventId>0?this.options.deviceId:null};Rakam.prototype.setOptOut=function(enable){try{this.options.optOut=enable;_saveCookieData(this);log("set optOut="+enable)}catch(e){log(e)}};Rakam.prototype.setDeviceId=function(deviceId){try{if(deviceId){this.options.deviceId=""+deviceId;console.log(this.options,deviceId);_saveCookieData(this)}}catch(e){log(e)}};Rakam.prototype.setSuperProperties=function(eventProps,opt_replace){try{this.options.superProperties=this.options.superProperties||{};for(var property in eventProps){if(eventProps.hasOwnProperty(property)){if(opt_replace===false&&this.options.superProperties[property]!==undefined){continue}this.options.superProperties[property]=eventProps[property]}}_saveCookieData(this);log("set super properties="+JSON.stringify(eventProps))}catch(e){log(e)}};Rakam.prototype.setVersionName=function(versionName){try{this.options.versionName=versionName;log("set versionName="+versionName)}catch(e){log(e)}};Rakam.prototype._logEvent=function(eventType,eventProperties,apiProperties,callback){if(typeof callback!=="function"){callback=null}if(!eventType||this.options.optOut){if(callback){callback(0,"No request sent")}return}try{var eventTime=(new Date).getTime();var eventId=this.nextEventId();if(!this._sessionId||!this._lastEventTime||eventTime-this._lastEventTime>this.options.sessionTimeout){this._sessionId=eventTime;localStorage.setItem(LocalStorageKeys.SESSION_ID,this._sessionId)}this._lastEventTime=eventTime;localStorage.setItem(LocalStorageKeys.LAST_EVENT_TIME,this._lastEventTime);localStorage.setItem(LocalStorageKeys.LAST_ID,eventId);apiProperties=apiProperties||{};eventProperties=eventProperties||{};object.merge(eventProperties,this._utmProperties);var event={collection:eventType,properties:{_device_id:this.options.deviceId,_user:this.options.userId,_time:parseInt(eventTime/1e3)*1e3,_session_id:this._sessionId||-1,_platform:this.options.platform,_language:this.options.language}};object.merge(event.properties,this.options.superProperties);object.merge(event.properties,apiProperties);object.merge(event.properties,eventProperties);log("logged eventType="+eventType+", properties="+JSON.stringify(eventProperties));this._unsentEvents.push({id:eventId,event:event});if(this._unsentEvents.length>this.options.savedMaxCount){this._unsentEvents.splice(0,this._unsentEvents.length-this.options.savedMaxCount)}if(this.options.saveEvents){this.saveEvents()}if(!this._sendEventsIfReady(callback)&&callback){callback(0,"No request sent")}return eventId}catch(e){log(e)}};Rakam.prototype.logEvent=function(eventType,eventProperties,callback){return this._logEvent(eventType,eventProperties,null,callback)};Rakam.prototype.removeEvents=function(maxEventId,errors){var filteredEvents=[];var errorList=errors||[];for(var i=0;i-1||id>maxEventId){filteredEvents.push(this._unsentEvents[i])}}this._unsentEvents=filteredEvents};Rakam.prototype.sendEvents=function(callback){if(!this._sending&&!this.options.optOut&&this._unsentEvents.length>0){this._sending=true;var url=("https:"===window.location.protocol?"https":"http")+"://"+this.options.apiEndpoint+this.options.eventEndpointPath;var numEvents=Math.min(this._unsentEvents.length,this.options.uploadBatchSize);var maxEventId=this._unsentEvents[numEvents-1].id;this._unsentEvents.slice(0,numEvents);var events=this._unsentEvents.slice(0,numEvents).map(function(e){return e.event});var upload_time=(new Date).getTime();var api={upload_time:upload_time,api_version:API_VERSION,api_key:this.options.apiKey};var scope=this;new Request(url,{api:api,events:events}).send(function(status,response,headers){scope._sending=false;try{if(status===200||status===409){log("successful upload");scope.removeEvents(maxEventId,status===409?JSON.parse(response):null);if(scope.options.saveEvents){scope.saveEvents()}if(!scope._sendEventsIfReady(callback)&&callback){callback(status,response)}}else if(status===413){log("request too large");if(scope.options.uploadBatchSize===1){scope.removeEvents(maxEventId)}scope.options.uploadBatchSize=Math.ceil(numEvents/2);scope.sendEvents(callback)}else if(callback){callback(status,response)}}catch(e){log("failed upload")}if(scope.options.eventCallbacks){try{for(var i=0;i>2;enc2=(chr1&3)<<4|chr2>>4;enc3=(chr2&15)<<2|chr3>>6;enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64}else if(isNaN(chr3)){enc4=64}output=output+Base64._keyStr.charAt(enc1)+Base64._keyStr.charAt(enc2)+Base64._keyStr.charAt(enc3)+Base64._keyStr.charAt(enc4)}return output},decode:function(input){try{if(window.btoa&&window.atob){return decodeURIComponent(escape(window.atob(input)))}}catch(e){}return Base64._decode(input)},_decode:function(input){var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(i>4;chr2=(enc2&15)<<4|enc3>>2;chr3=(enc3&3)<<6|enc4;output=output+String.fromCharCode(chr1);if(enc3!==64){output=output+String.fromCharCode(chr2)}if(enc4!==64){output=output+String.fromCharCode(chr3)}}output=UTF8.decode(output);return output}};module.exports=Base64},{"./utf8":16}],16:[function(require,module,exports){var UTF8={encode:function(s){var utftext="";for(var n=0;n127&&c<2048){utftext+=String.fromCharCode(c>>6|192);utftext+=String.fromCharCode(c&63|128)}else{utftext+=String.fromCharCode(c>>12|224);utftext+=String.fromCharCode(c>>6&63|128);utftext+=String.fromCharCode(c&63|128)}}return utftext},decode:function(utftext){var s="";var i=0;var c=0,c1=0,c2=0;while(i191&&c<224){c1=utftext.charCodeAt(i+1);s+=String.fromCharCode((c&31)<<6|c1&63);i+=2}else{c1=utftext.charCodeAt(i+1);c2=utftext.charCodeAt(i+2);s+=String.fromCharCode((c&15)<<12|(c1&63)<<6|c2&63);i+=3}}return s}};module.exports=UTF8},{}],4:[function(require,module,exports){var json=window.JSON||{};var stringify=json.stringify;var parse=json.parse;module.exports=parse&&stringify?JSON:require("json-fallback")},{"json-fallback":17}],17:[function(require,module,exports){(function(){"use strict";var JSON=module.exports={};function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}}var cx,escapable,gap,indent,meta,rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i0){var key=headerPair.substring(0,index);var val=headerPair.substring(index+2);headers[key]=val}}return headers}Request.prototype.send=function(callback){var isIE=window.XDomainRequest?true:false;if(isIE){var xdr=new window.XDomainRequest;xdr.open("POST",this.url,true);xdr.onload=function(){callback(xdr.responseText)};xdr.send(JSON.stringify(this.data))}else{var xhr=new XMLHttpRequest;xhr.withCredentials="true";xhr.open("POST",this.url,true);xhr.onreadystatechange=function(){if(xhr.readyState===4){callback(xhr.status,xhr.responseText,parseResponseHeaders(xhr.getAllResponseHeaders()))}};xhr.setRequestHeader("Content-Type","text/plain");for(var key in this.headers){if(this.headers.hasOwnProperty(key)){xhr.setRequestHeader(key,this.headers[key])}}xhr.send(JSON.stringify(this.data))}};module.exports=Request},{json:4}],9:[function(require,module,exports){var uuid=function(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,uuid); };module.exports=uuid},{}],10:[function(require,module,exports){module.exports="undefined"},{}],11:[function(require,module,exports){var type=require("./type");var Request=require("./xhr");var API_VERSION=1;var log=function(s,opts){console.log("[Rakam] "+s,opts)};var wrapCallback=function(operation,props,callback){return function(status,response,headers){log("Successfully sent "+operation,props);if(callback!==undefined){callback(status,response,headers)}}};var getUrl=function(options){return("https:"===window.location.protocol?"https":"http")+"://"+options.apiEndpoint+"/user"};var User=function(){};User.prototype.init=function(options){this.options=options};User.prototype.set=function(properties,callback){new Request(getUrl(this.options)+"/set_properties",{api:{api_version:API_VERSION,api_key:this.options.apiKey},id:this.options.userId,properties:properties}).send(wrapCallback("set_properties",properties,callback));return this};User.prototype._merge=function(previousUserId,createdAt,callback){new Request(getUrl(this.options)+"/merge",{api:{api_version:API_VERSION,api_key:this.options.apiKey,upload_time:(new Date).getTime()},anonymous_id:previousUserId,id:this.options.userId,created_at:createdAt.getTime(),merged_at:(new Date).getTime()}).send(wrapCallback("merge",null,callback));return this};User.prototype.setOnce=function(properties,callback){new Request(getUrl(this.options)+"/set_properties_once",{api:{api_version:API_VERSION,api_key:this.options.apiKey},id:this.options.userId,properties:properties}).send(wrapCallback("set_properties_once",properties,callback));return this};User.prototype.increment=function(property,value,callback){new Request(getUrl(this.options)+"/increment_property",{api:{api_version:API_VERSION,api_key:this.options.apiKey},id:this.options.userId,property:property,value:value}).send(wrapCallback("increment_property",property+" by "+value,callback));return this};User.prototype.unset=function(properties,callback){new Request(getUrl(this.options)+"/unset_properties",{api:{api_version:API_VERSION,api_key:this.options.apiKey},id:this.options.userId,properties:type(properties)==="array"?properties:[properties]}).send(wrapCallback("unset_properties",properties,callback));return this};module.exports=User},{"./type":13,"./xhr":8}],13:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object Error]":return"error"}if(val===null){return"null"}if(val===undefined){return"undefined"}if(val!==val){return"nan"}if(val&&val.nodeType===1){return"element"}if(typeof Buffer!=="undefined"&&Buffer.isBuffer(val)){return"buffer"}val=val.valueOf?val.valueOf():Object.prototype.valueOf.apply(val);return typeof val}},{}],12:[function(require,module,exports){(function(){!function(a,b){return"function"==typeof define&&define.amd?define(function(){return b()}):"object"==typeof exports?module.exports=b():a.ifvisible=b()}(this,function(){var a,b,c,d,e,f,g,h,i,j,k,l,m,n;return i={},c=document,k=!1,l="active",g=6e4,f=!1,b=function(){var a,b,c,d,e,f,g;return a=function(){return(65536*(1+Math.random())|0).toString(16).substring(1)},e=function(){return a()+a()+"-"+a()+"-"+a()+"-"+a()+"-"+a()+a()+a()},f={},c="__ceGUID",b=function(a,b,d){return a[c]=void 0,a[c]||(a[c]="ifvisible.object.event.identifier"),f[a[c]]||(f[a[c]]={}),f[a[c]][b]||(f[a[c]][b]=[]),f[a[c]][b].push(d)},d=function(a,b,d){var e,g,h,i,j;if(a[c]&&f[a[c]]&&f[a[c]][b]){for(i=f[a[c]][b],j=[],g=0,h=i.length;h>g;g++)e=i[g],j.push(e(d||{}));return j}},g=function(a,b,d){var e,g,h,i,j;if(d){if(a[c]&&f[a[c]]&&f[a[c]][b])for(j=f[a[c]][b],g=h=0,i=j.length;i>h;g=++h)if(e=j[g],e===d)return f[a[c]][b].splice(g,1),e}else if(a[c]&&f[a[c]]&&f[a[c]][b])return delete f[a[c]][b]},{add:b,remove:g,fire:d}}(),a=function(){var a;return a=!1,function(b,c,d){return a||(a=b.addEventListener?function(a,b,c){return a.addEventListener(b,c,!1)}:b.attachEvent?function(a,b,c){return a.attachEvent("on"+b,c,!1)}:function(a,b,c){return a["on"+b]=c}),a(b,c,d)}}(),d=function(a,b){var d;return c.createEventObject?a.fireEvent("on"+b,d):(d=c.createEvent("HTMLEvents"),d.initEvent(b,!0,!0),!a.dispatchEvent(d))},h=function(){var a,b,d,e,f;for(e=void 0,f=3,d=c.createElement("div"),a=d.getElementsByTagName("i"),b=function(){return d.innerHTML="",a[0]};b(););return f>4?f:e}(),e=!1,n=void 0,"undefined"!=typeof c.hidden?(e="hidden",n="visibilitychange"):"undefined"!=typeof c.mozHidden?(e="mozHidden",n="mozvisibilitychange"):"undefined"!=typeof c.msHidden?(e="msHidden",n="msvisibilitychange"):"undefined"!=typeof c.webkitHidden&&(e="webkitHidden",n="webkitvisibilitychange"),m=function(){var b,d;return b=!1,d=function(){return clearTimeout(b),"active"!==l&&i.wakeup(),f=+new Date,b=setTimeout(function(){return"active"===l?i.idle():void 0},g)},d(),a(c,"mousemove",d),a(c,"keyup",d),a(window,"scroll",d),i.focus(d),i.wakeup(d)},j=function(){var b;return k?!0:(e===!1?(b="blur",9>h&&(b="focusout"),a(window,b,function(){return i.blur()}),a(window,"focus",function(){return i.focus()})):a(c,n,function(){return c[e]?i.blur():i.focus()},!1),k=!0,m())},i={setIdleDuration:function(a){return g=1e3*a},getIdleDuration:function(){return g},getIdleInfo:function(){var a,b;return a=+new Date,b={},"idle"===l?(b.isIdle=!0,b.idleFor=a-f,b.timeLeft=0,b.timeLeftPer=100):(b.isIdle=!1,b.idleFor=a-f,b.timeLeft=f+g-a,b.timeLeftPer=(100-100*b.timeLeft/g).toFixed(2)),b},focus:function(a){return"function"==typeof a?this.on("focus",a):(l="active",b.fire(this,"focus"),b.fire(this,"wakeup"),b.fire(this,"statusChanged",{status:l}))},blur:function(a){return"function"==typeof a?this.on("blur",a):(l="hidden",b.fire(this,"blur"),b.fire(this,"idle"),b.fire(this,"statusChanged",{status:l}))},idle:function(a){return"function"==typeof a?this.on("idle",a):(l="idle",b.fire(this,"idle"),b.fire(this,"statusChanged",{status:l}))},wakeup:function(a){return"function"==typeof a?this.on("wakeup",a):(l="active",b.fire(this,"wakeup"),b.fire(this,"statusChanged",{status:l}))},on:function(a,c){return j(),b.add(this,a,c)},off:function(a,c){return j(),b.remove(this,a,c)},onEvery:function(a,b){var c,d;return j(),c=!1,b&&(d=setInterval(function(){return"active"===l&&c===!1?b():void 0},1e3*a)),{stop:function(){return clearInterval(d)},pause:function(){return c=!0},resume:function(){return c=!1},code:d,callback:b}},now:function(a){return j(),l===(a||"active")}}})}).call(this)},{}]},{},{1:""})); \ No newline at end of file diff --git a/src/rakam.js b/src/rakam.js index 4c44b0b..ba03151 100644 --- a/src/rakam.js +++ b/src/rakam.js @@ -143,7 +143,6 @@ Rakam.prototype.init = function (apiKey, opt_userId, opt_config, callback) { _saveCookieData(this); log('initialized with apiKey=' + apiKey); - this.setUserId(opt_userId); if (this.options.saveEvents) { var savedUnsentEventsString = localStorage.getItem(this.options.unsentKey); @@ -188,11 +187,12 @@ Rakam.prototype.init = function (apiKey, opt_userId, opt_config, callback) { } this._lastEventTime = now; localStorage.setItem(LocalStorageKeys.LAST_EVENT_TIME, this._lastEventTime); - } catch (e) { log(e); } + this.setUserId(opt_userId); + if (callback && typeof(callback) === 'function') { setTimeout(function () { callback(); diff --git a/src/version.js b/src/version.js index 686309e..6fb5b34 100644 --- a/src/version.js +++ b/src/version.js @@ -1 +1 @@ -module.exports = '2.5.1'; \ No newline at end of file +module.exports = 'undefined'; \ No newline at end of file