@telazer/zilana_client_sdk
Advanced tools
Comparing version 0.9.6 to 0.9.7
@@ -357,3 +357,3 @@ "use strict"; | ||
return session; | ||
}); | ||
}).filter((session) => session.isActive); | ||
response.data.sessions.forEach((syncedSession) => { | ||
@@ -360,0 +360,0 @@ var _a; |
@@ -1,2 +0,2 @@ | ||
"use strict";(()=>{var c=(f,t,e)=>new Promise((s,r)=>{var n=o=>{try{a(e.next(o))}catch(d){r(d)}},i=o=>{try{a(e.throw(o))}catch(d){r(d)}},a=o=>o.done?s(o.value):Promise.resolve(o.value).then(n,i);a((e=e.apply(f,t)).next())});var h={dataKey:"com.telazer.zilana.dev-data",apiBase:"https://api.dev.zilana.io",AFK_THRESHOLD_SEC:60},l=class{static initialize(r){return c(this,arguments,function*({config:t,eventMap:e,debug:s=!1}){var n;try{if(this.initialized){this.log("SDK is already initialized.","warn");return}this.debug=s,this.eventMap=e,this.log("Initializing SDK...","info"),this.config=t,this.data=this.getLocalData()||{},this.sanitizeSessions(),(n=this.data.sessions)!=null&&n.length?this.data.sessions.forEach(i=>{i.isActive&&(i.isActive=!1)}):this.data.sessions=[],this.data.playerId?(!this.data.playerCustomId&&this.config.playerCustomId&&(yield this.refreshPlayer(this.config.playerCustomId)),this.data.playerCustomId&&!this.config.playerCustomId&&(yield this.refreshPlayer(null)),this.data.playerCustomId&&this.config.playerCustomId&&this.data.playerCustomId!==this.config.playerCustomId&&(yield this.refreshPlayer(this.config.playerCustomId))):yield this.assignPlayerId(),this.setLocalData(),this.startHealthChecker(),this.initialized=!0,this.startSession(),this.monitorActivity(),this.log("SDK initialized successfully.","info")}catch(i){this.log("SDK initialized failed. Contact support!","error"),console.error(i),this.config=null,this.data=null,this.initialized=!1}})}static sanitizeSessions(){this.data&&(this.data.sessions||(this.data.sessions=[]),this.data.sessions.forEach(t=>{t.afk?(t.afk.afkStartedAt||(t.afk.afkStartedAt=null),typeof t.afk.totalAfkSec!="number"&&(t.afk.totalAfkSec=0)):t.afk={afkStartedAt:null,totalAfkSec:0}}),this.setLocalData())}static recordEvent(t){var e,s,r,n;try{this.ensureInitialized();let i=(e=this.eventMap)==null?void 0:e[t];if(!i){this.log(`Event "${t}" is not registered.`,"warn");return}this.log(`Recording event: ${t} -> ${i}`,"info");let a=(r=(s=this.data)==null?void 0:s.sessions)==null?void 0:r.find(o=>o.isActive);if(!a){this.log("No active session found. Event not recorded.","warn");return}a.gameEventFires=a.gameEventFires||[],a.gameEventFires.push({gameEventId:i,createdAt:new Date}),(n=this.setLocalData)==null||n.call(this),this.log(`Event "${t}" recorded successfully.`,"info")}catch(i){let a=i;this.log(`Error recording event: ${a.message}`,"error")}}static refreshPlayer(t){return c(this,null,function*(){var e,s,r,n;try{this.ensureInitialized(!0);try{this.log("Try sync existing sessions","info"),yield(e=this.syncSessions)==null?void 0:e.call(this,!0)}catch(i){let a=i;this.log(`Error syncing sessions: ${a.message}`,"error")}try{this.log(`Refreshing player with customId: ${t}`,"info"),this.config&&(this.config.playerCustomId=t),yield(s=this.assignPlayerId)==null?void 0:s.call(this),this.log(`Player refreshed successfully with customId: ${t}`,"info")}catch(i){let a=i;this.log(`Error refreshing player: ${a.message}`,"error")}(r=this.setLocalData)==null||r.call(this),(n=this.startSession)==null||n.call(this)}catch(i){let a=i;this.log(`Critical error in refreshPlayer: ${a.message}`,"error")}})}static log(t,e="info"){let s="[Zilana SDK]";e==="info"&&this.debug?console.log(`${s} ${t}`):e==="warn"?console.warn(`${s} ${t}`):e==="error"&&console.error(`${s} ${t}`)}static getLocalData(){try{let t=localStorage.getItem(h.dataKey);return t?JSON.parse(t):null}catch(t){return this.log(`Failed to retrieve data: ${t}`,"error"),null}}static setLocalData(){try{localStorage.setItem(h.dataKey,JSON.stringify(this.data))}catch(t){this.log(`Failed to save data: ${t}`,"error")}}static assignPlayerId(){return c(this,null,function*(){this.ensureInitialized(!0),this.log("Assigning player ID...","info");let t={userId:this.config.userId,gameId:this.config.gameId,customId:this.config.playerCustomId},e=yield this.apiPost("/api/sdk/players",t);this.data.playerId=e.data.playerId,this.data.playerCustomId=this.config.playerCustomId,this.setLocalData(),this.log("Player ID assigned successfully.","info")})}static apiPost(t,e){return c(this,null,function*(){if(!this.config)throw this.log("SDK config is not set. Call initialize() first.","error"),new Error("Zilana SDK config not set. Call initialize() first.");let s=yield fetch(`${h.apiBase}${t}`,{method:"POST",headers:{"Content-Type":"application/json","zilana-user-id":this.config.userId,"zilana-game-id":this.config.gameId},body:JSON.stringify(e)});if(!s.ok){let r=yield s.json();throw this.log(`API Error ${s.status}: ${r.message}`,"error"),new Error(`API Error ${s.status}: ${r.message}`)}return this.log(`API call to ${t} successful.`,"info"),s.json()})}static startSession(){var t,e;this.ensureInitialized(),this.log("Starting new session...","info"),(t=this.data.sessions)==null||t.forEach(s=>s.isActive=!1),(e=this.data.sessions)==null||e.push({tempId:`${Date.now()}`,isActive:!0,createdAt:new Date,updatedAt:new Date,afk:{afkStartedAt:null,totalAfkSec:0},gameEventFires:[]}),this.setLocalData(),this.scheduleSync(),this.log("Session started successfully.","info")}static ensureInitialized(t=!1){if(!t&&!this.initialized||!this.data||!this.config)throw this.log("SDK is not properly initialized. Call initialize() first.","error"),new Error("Zilana SDK not properly initialized. Call initialize() first.")}static syncSessions(t){return c(this,null,function*(){var e;try{if(!this.data.playerId||!((e=this.data.sessions)!=null&&e.length))return;let s=new Date;this.log("Syncing sessions with server...","info");let r={userId:this.config.userId,gameId:this.config.gameId,playerId:this.data.playerId,sessions:this.data.sessions.filter(i=>!i.afk.afkStartedAt||t).map(i=>{var a;return{id:i.id,tempId:i.id?void 0:i.tempId,durationSec:this.adjustSessionDuration(i,s),isActive:i.isActive,gameEventFires:(a=i.gameEventFires)==null?void 0:a.map(o=>({gameEventId:o.gameEventId}))}})};if(!r.sessions.length){this.log("No sessions to sync. Skipping...","info");return}let n=yield this.apiPost("/api/sdk/sessions",r);this.data.sessions=this.data.sessions.map(i=>(i.isActive&&(i.updatedAt=s,i.gameEventFires&&(i.gameEventFires=i.gameEventFires.filter(a=>new Date(a.createdAt)>s))),i)),n.data.sessions.forEach(i=>{var o;let a=(o=this.data.sessions)==null?void 0:o.find(d=>d.tempId===i.tempId);a&&(a.id=i.id,delete a.tempId)}),this.setLocalData(),this.log("Sessions synced successfully.","info")}catch(s){throw s}finally{t||this.scheduleSync()}})}static scheduleSync(){this.syncTimeout&&clearTimeout(this.syncTimeout),this.syncTimeout=setTimeout(()=>this.syncSessions(),9e3),this.log("Sync scheduled in 9 seconds.","info")}static startHealthChecker(){setInterval(()=>c(this,null,function*(){var t;try{this.log("Running health check...","info"),(t=this.data)!=null&&t.playerId||(yield this.assignPlayerId()),this.syncTimeout||this.scheduleSync(),this.log("Health check passed.","info")}catch(e){this.log(`Health check failed: ${e}`,"error")}}),3e4)}static monitorActivity(){let t=()=>{let e=Date.now();e-this.lastActivityTime>=h.AFK_THRESHOLD_SEC*1e3&&this.resumeFromAFK(),this.lastActivityTime=e,this.afkTimeout&&clearTimeout(this.afkTimeout),this.afkTimeout=setTimeout(()=>{this.markAFK()},h.AFK_THRESHOLD_SEC*1e3)};window.addEventListener("mousemove",t),window.addEventListener("keydown",t),t()}static markAFK(){var e,s;this.log("Marking session as AFK...","info");let t=(s=(e=this.data)==null?void 0:e.sessions)==null?void 0:s.find(r=>r.isActive);t&&!t.afk.afkStartedAt&&(t.afk.afkStartedAt=new Date,this.setLocalData(),this.log("Session marked as AFK. Skipping updates...","info"))}static resumeFromAFK(){var e,s;let t=(s=(e=this.data)==null?void 0:e.sessions)==null?void 0:s.find(r=>r.isActive);if(t&&t.afk.afkStartedAt){let r=new Date(t.afk.afkStartedAt).getTime(),n=Date.now(),i=Math.round((n-r)/1e3);t.afk.totalAfkSec+=i,t.afk.afkStartedAt=null,this.setLocalData(),this.log(`Resumed from AFK. Total AFK time: ${t.afk.totalAfkSec}s`,"info"),this.scheduleSync()}}static adjustSessionDuration(t,e){let s=new Date(t.createdAt).getTime(),r=t.isActive?e.getTime():new Date(t.updatedAt).getTime(),n=Math.round((r-s)/1e3);return Math.max(0,n-(t.afk.totalAfkSec||0))}};l.initialized=!1,l.config=null,l.data=null,l.syncTimeout=null,l.debug=!1,l.eventMap={},l.afkTimeout=null,l.lastActivityTime=Date.now();typeof window!="undefined"&&(window.Zilana=l);})(); | ||
"use strict";(()=>{var c=(f,t,e)=>new Promise((s,r)=>{var n=o=>{try{a(e.next(o))}catch(d){r(d)}},i=o=>{try{a(e.throw(o))}catch(d){r(d)}},a=o=>o.done?s(o.value):Promise.resolve(o.value).then(n,i);a((e=e.apply(f,t)).next())});var h={dataKey:"com.telazer.zilana.dev-data",apiBase:"https://api.dev.zilana.io",AFK_THRESHOLD_SEC:60},l=class{static initialize(r){return c(this,arguments,function*({config:t,eventMap:e,debug:s=!1}){var n;try{if(this.initialized){this.log("SDK is already initialized.","warn");return}this.debug=s,this.eventMap=e,this.log("Initializing SDK...","info"),this.config=t,this.data=this.getLocalData()||{},this.sanitizeSessions(),(n=this.data.sessions)!=null&&n.length?this.data.sessions.forEach(i=>{i.isActive&&(i.isActive=!1)}):this.data.sessions=[],this.data.playerId?(!this.data.playerCustomId&&this.config.playerCustomId&&(yield this.refreshPlayer(this.config.playerCustomId)),this.data.playerCustomId&&!this.config.playerCustomId&&(yield this.refreshPlayer(null)),this.data.playerCustomId&&this.config.playerCustomId&&this.data.playerCustomId!==this.config.playerCustomId&&(yield this.refreshPlayer(this.config.playerCustomId))):yield this.assignPlayerId(),this.setLocalData(),this.startHealthChecker(),this.initialized=!0,this.startSession(),this.monitorActivity(),this.log("SDK initialized successfully.","info")}catch(i){this.log("SDK initialized failed. Contact support!","error"),console.error(i),this.config=null,this.data=null,this.initialized=!1}})}static sanitizeSessions(){this.data&&(this.data.sessions||(this.data.sessions=[]),this.data.sessions.forEach(t=>{t.afk?(t.afk.afkStartedAt||(t.afk.afkStartedAt=null),typeof t.afk.totalAfkSec!="number"&&(t.afk.totalAfkSec=0)):t.afk={afkStartedAt:null,totalAfkSec:0}}),this.setLocalData())}static recordEvent(t){var e,s,r,n;try{this.ensureInitialized();let i=(e=this.eventMap)==null?void 0:e[t];if(!i){this.log(`Event "${t}" is not registered.`,"warn");return}this.log(`Recording event: ${t} -> ${i}`,"info");let a=(r=(s=this.data)==null?void 0:s.sessions)==null?void 0:r.find(o=>o.isActive);if(!a){this.log("No active session found. Event not recorded.","warn");return}a.gameEventFires=a.gameEventFires||[],a.gameEventFires.push({gameEventId:i,createdAt:new Date}),(n=this.setLocalData)==null||n.call(this),this.log(`Event "${t}" recorded successfully.`,"info")}catch(i){let a=i;this.log(`Error recording event: ${a.message}`,"error")}}static refreshPlayer(t){return c(this,null,function*(){var e,s,r,n;try{this.ensureInitialized(!0);try{this.log("Try sync existing sessions","info"),yield(e=this.syncSessions)==null?void 0:e.call(this,!0)}catch(i){let a=i;this.log(`Error syncing sessions: ${a.message}`,"error")}try{this.log(`Refreshing player with customId: ${t}`,"info"),this.config&&(this.config.playerCustomId=t),yield(s=this.assignPlayerId)==null?void 0:s.call(this),this.log(`Player refreshed successfully with customId: ${t}`,"info")}catch(i){let a=i;this.log(`Error refreshing player: ${a.message}`,"error")}(r=this.setLocalData)==null||r.call(this),(n=this.startSession)==null||n.call(this)}catch(i){let a=i;this.log(`Critical error in refreshPlayer: ${a.message}`,"error")}})}static log(t,e="info"){let s="[Zilana SDK]";e==="info"&&this.debug?console.log(`${s} ${t}`):e==="warn"?console.warn(`${s} ${t}`):e==="error"&&console.error(`${s} ${t}`)}static getLocalData(){try{let t=localStorage.getItem(h.dataKey);return t?JSON.parse(t):null}catch(t){return this.log(`Failed to retrieve data: ${t}`,"error"),null}}static setLocalData(){try{localStorage.setItem(h.dataKey,JSON.stringify(this.data))}catch(t){this.log(`Failed to save data: ${t}`,"error")}}static assignPlayerId(){return c(this,null,function*(){this.ensureInitialized(!0),this.log("Assigning player ID...","info");let t={userId:this.config.userId,gameId:this.config.gameId,customId:this.config.playerCustomId},e=yield this.apiPost("/api/sdk/players",t);this.data.playerId=e.data.playerId,this.data.playerCustomId=this.config.playerCustomId,this.setLocalData(),this.log("Player ID assigned successfully.","info")})}static apiPost(t,e){return c(this,null,function*(){if(!this.config)throw this.log("SDK config is not set. Call initialize() first.","error"),new Error("Zilana SDK config not set. Call initialize() first.");let s=yield fetch(`${h.apiBase}${t}`,{method:"POST",headers:{"Content-Type":"application/json","zilana-user-id":this.config.userId,"zilana-game-id":this.config.gameId},body:JSON.stringify(e)});if(!s.ok){let r=yield s.json();throw this.log(`API Error ${s.status}: ${r.message}`,"error"),new Error(`API Error ${s.status}: ${r.message}`)}return this.log(`API call to ${t} successful.`,"info"),s.json()})}static startSession(){var t,e;this.ensureInitialized(),this.log("Starting new session...","info"),(t=this.data.sessions)==null||t.forEach(s=>s.isActive=!1),(e=this.data.sessions)==null||e.push({tempId:`${Date.now()}`,isActive:!0,createdAt:new Date,updatedAt:new Date,afk:{afkStartedAt:null,totalAfkSec:0},gameEventFires:[]}),this.setLocalData(),this.scheduleSync(),this.log("Session started successfully.","info")}static ensureInitialized(t=!1){if(!t&&!this.initialized||!this.data||!this.config)throw this.log("SDK is not properly initialized. Call initialize() first.","error"),new Error("Zilana SDK not properly initialized. Call initialize() first.")}static syncSessions(t){return c(this,null,function*(){var e;try{if(!this.data.playerId||!((e=this.data.sessions)!=null&&e.length))return;let s=new Date;this.log("Syncing sessions with server...","info");let r={userId:this.config.userId,gameId:this.config.gameId,playerId:this.data.playerId,sessions:this.data.sessions.filter(i=>!i.afk.afkStartedAt||t).map(i=>{var a;return{id:i.id,tempId:i.id?void 0:i.tempId,durationSec:this.adjustSessionDuration(i,s),isActive:i.isActive,gameEventFires:(a=i.gameEventFires)==null?void 0:a.map(o=>({gameEventId:o.gameEventId}))}})};if(!r.sessions.length){this.log("No sessions to sync. Skipping...","info");return}let n=yield this.apiPost("/api/sdk/sessions",r);this.data.sessions=this.data.sessions.map(i=>(i.isActive&&(i.updatedAt=s,i.gameEventFires&&(i.gameEventFires=i.gameEventFires.filter(a=>new Date(a.createdAt)>s))),i)).filter(i=>i.isActive),n.data.sessions.forEach(i=>{var o;let a=(o=this.data.sessions)==null?void 0:o.find(d=>d.tempId===i.tempId);a&&(a.id=i.id,delete a.tempId)}),this.setLocalData(),this.log("Sessions synced successfully.","info")}catch(s){throw s}finally{t||this.scheduleSync()}})}static scheduleSync(){this.syncTimeout&&clearTimeout(this.syncTimeout),this.syncTimeout=setTimeout(()=>this.syncSessions(),9e3),this.log("Sync scheduled in 9 seconds.","info")}static startHealthChecker(){setInterval(()=>c(this,null,function*(){var t;try{this.log("Running health check...","info"),(t=this.data)!=null&&t.playerId||(yield this.assignPlayerId()),this.syncTimeout||this.scheduleSync(),this.log("Health check passed.","info")}catch(e){this.log(`Health check failed: ${e}`,"error")}}),3e4)}static monitorActivity(){let t=()=>{let e=Date.now();e-this.lastActivityTime>=h.AFK_THRESHOLD_SEC*1e3&&this.resumeFromAFK(),this.lastActivityTime=e,this.afkTimeout&&clearTimeout(this.afkTimeout),this.afkTimeout=setTimeout(()=>{this.markAFK()},h.AFK_THRESHOLD_SEC*1e3)};window.addEventListener("mousemove",t),window.addEventListener("keydown",t),t()}static markAFK(){var e,s;this.log("Marking session as AFK...","info");let t=(s=(e=this.data)==null?void 0:e.sessions)==null?void 0:s.find(r=>r.isActive);t&&!t.afk.afkStartedAt&&(t.afk.afkStartedAt=new Date,this.setLocalData(),this.log("Session marked as AFK. Skipping updates...","info"))}static resumeFromAFK(){var e,s;let t=(s=(e=this.data)==null?void 0:e.sessions)==null?void 0:s.find(r=>r.isActive);if(t&&t.afk.afkStartedAt){let r=new Date(t.afk.afkStartedAt).getTime(),n=Date.now(),i=Math.round((n-r)/1e3);t.afk.totalAfkSec+=i,t.afk.afkStartedAt=null,this.setLocalData(),this.log(`Resumed from AFK. Total AFK time: ${t.afk.totalAfkSec}s`,"info"),this.scheduleSync()}}static adjustSessionDuration(t,e){let s=new Date(t.createdAt).getTime(),r=t.isActive?e.getTime():new Date(t.updatedAt).getTime(),n=Math.round((r-s)/1e3);return Math.max(0,n-(t.afk.totalAfkSec||0))}};l.initialized=!1,l.config=null,l.data=null,l.syncTimeout=null,l.debug=!1,l.eventMap={},l.afkTimeout=null,l.lastActivityTime=Date.now();typeof window!="undefined"&&(window.Zilana=l);})(); | ||
//# sourceMappingURL=sdk.min.js.map |
{ | ||
"name": "@telazer/zilana_client_sdk", | ||
"version": "0.9.6", | ||
"version": "0.9.7", | ||
"description": "", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
76634