@looplay/sdk 0.8.9 → 0.8.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/looplay-sdk.cjs.js +58 -54
- package/dist/looplay-sdk.cjs.js.map +1 -1
- package/dist/looplay-sdk.esm.js +58 -54
- package/dist/looplay-sdk.esm.js.map +1 -1
- package/dist/looplay-sdk.min.js +4 -4
- package/dist/looplay-sdk.min.js.map +1 -1
- package/dist/types/apps/api-client.d.ts +1 -1
- package/dist/types/apps/http.d.ts +2 -2
- package/dist/types/iframe/iframe-auth.d.ts +1 -1
- package/dist/types/version.d.ts +1 -1
- package/package.json +1 -1
package/dist/looplay-sdk.min.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var LooplaySDK=(function(exports){'use strict';var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;var u=class extends Error{constructor(e){super(e),this.name="LooplaySDKError";}},c=class extends u{constructor(){super("LooplaySDK not initialized. Call init({ gameId }) first."),this.name="NotInitializedError";}},l=class extends u{constructor(){super("Missing baseUrl. Provide `baseUrl` to enable HTTP integration."),this.name="MissingBaseUrlError";}},x=class extends u{constructor(){super("Missing auth. Provide `auth` options to enable user login/session."),this.name="MissingAuthError";}},m=class extends u{constructor(){super("Not authenticated. Login is required for this operation."),this.name="NotAuthenticatedError";}};var y=class{map=new Map;async getItem(e){return this.map.has(e)?this.map.get(e):null}async setItem(e,t){this.map.set(e,t);}async removeItem(e){this.map.delete(e);}},b=class{async getItem(e){return typeof window>"u"||!window.localStorage?null:window.localStorage.getItem(e)}async setItem(e,t){typeof window>"u"||!window.localStorage||window.localStorage.setItem(e,t);}async removeItem(e){typeof window>"u"||!window.localStorage||window.localStorage.removeItem(e);}};var w=class extends u{constructor(){super("Invalid session returned by auth provider"),this.name="InvalidSessionError";}},f=class{provider;storage;key;session=null;listeners=new Set;constructor(e){this.provider=e.provider,this.storage=e.storage??new y,this.key=`${e.storageKeyPrefix??"looplay"}:auth:session`;}async init(){await this.provider.init?.(),await this.restoreFromStorage(),await this.provider.onSessionChanged?.(this.session);}getSession(){return this.session}async login(e){let t=await this.provider.login(e);if(!t?.session?.user?.id)throw new w;return await this.setSession(t.session,"login"),t.session}async logout(){await this.provider.logout(),await this.setSession(null,"logout");}async getAccessToken(){if(!this.session)return;let e=Date.now();if(!(typeof this.session.expiresAt=="number"&&this.session.expiresAt<=e))return this.session.accessToken;if(!this.provider.refresh)return this.session.accessToken;let s=await this.provider.refresh(),n={...this.session,...s};return await this.setSession(n,"sessionChanged"),n.accessToken}on(e,t){return this.listeners.add(t),()=>this.listeners.delete(t)}async restoreFromStorage(){let e=await this.storage.getItem(this.key);if(e)try{let t=JSON.parse(e);t?.user?.id&&(this.session=t);}catch{await this.storage.removeItem(this.key);}}async setSession(e,t){this.session=e,await this.provider.onSessionChanged?.(this.session),e?await this.storage.setItem(this.key,JSON.stringify(e)):await this.storage.removeItem(this.key);for(let s of this.listeners)s(this.session);}};var R="0.8.5";function U(i){return i?typeof window<"u"&&i===window.fetch?window.fetch.bind(window):i:globalThis.fetch.bind(globalThis)}var v=class extends Error{status;bodyText;constructor(e,t,s){super(e),this.name="HttpError",this.status=t,this.bodyText=s;}},k=class{baseUrl;fetchFn;defaultHeaders;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.fetchFn=U(e.fetch),this.defaultHeaders={"x-looplay-sdk-version":R,...e.defaultHeaders??{}};}async request(e,t,s){let n=this.buildUrl(t,s?.query),r=this.mergeHeaders(this.defaultHeaders,s?.headers);s?.bearerToken?r.Authorization=`Bearer ${s.bearerToken}`:s?.anonId&&(r["x-looplay-anon-id"]=s.anonId);let o;s?.body!==void 0&&(r["Content-Type"]=r["Content-Type"]??"application/json",o=JSON.stringify(s.body));let a=await this.fetchFn(n,{method:e,headers:r,body:o});if(!a.ok){let G=await this.safeText(a);throw new v(`HTTP ${a.status} ${a.statusText}`,a.status,G)}let d=await this.safeText(a);if(d)return JSON.parse(d)}mergeHeaders(...e){let t={};for(let s of e)if(s)for(let[n,r]of Object.entries(s))r!==void 0&&(t[n]=r);return t}buildUrl(e,t){let s=e.startsWith("/")?e:`/${e}`,n=new URL(`${this.baseUrl}${s}`);if(t)for(let[r,o]of Object.entries(t))o!==void 0&&n.searchParams.set(r,String(o));return n.toString()}async safeText(e){try{return await e.text()}catch{return ""}}};var h=class{http;constructor(e){this.http=new k(e);}async telegramLogin(e){let t={telegramInitData:e};return this.http.request("POST","/account/telegram-login",{body:t})}async refresh(e){let t={refreshToken:e};return this.http.request("POST","/account/refresh",{body:t})}async logout(e){let t={refreshToken:e};return this.http.request("POST","/account/logout",{body:t})}async recordGameView(e,t={}){return await this.http.request("POST","/sdk/games/views/record",{...t,headers:{"x-game-key":e,...this.trackingHeaders(t)}}),true}async startPlaySession(e,t={},s={}){return this.http.request("POST","/sdk/games/play-sessions/start",{...t,headers:{"x-game-key":e,...this.trackingHeaders(t)},body:s})}async renewPlaySession(e,t={},s){return this.http.request("POST","/sdk/games/play-sessions/renew",{...t,headers:{"x-game-key":e,...this.trackingHeaders(t)},body:s})}async completePlaySession(e,t,s){return await this.http.request("POST","/sdk/games/play-sessions/complete",{...t,headers:{"x-game-key":e,...this.trackingHeaders(t)},body:s}),true}async completeGameplayMatch(e,t,s){return await this.http.request("POST","/sdk/games/matches/complete",{...t,headers:{"x-game-key":e,...this.trackingHeaders(t)},body:s}),true}async recordGameplayAction(e,t,s){return this.http.request("POST","/sdk/games/actions/record",{...t,headers:{"x-game-key":e,...this.trackingHeaders(t)},body:s})}async bootstrapTrackingSession(e){return this.http.request("POST","/sdk/games/tracking/bootstrap",{headers:{"x-looplay-anon-id":e}})}async detectGameIntegration(e){return await this.http.request("POST","/sdk/games/integration/detect",{headers:{"x-game-key":e}}),true}trackingHeaders(e){return {"x-game-tracking-session-id":e.trackingSessionId,"x-looplay-anon-token":e.anonTrackingToken}}async getStore(e){return this.http.request("GET","/sdk/games/store/current",{headers:{"x-game-key":e}})}async listGameAssets(e){return this.http.request("GET","/sdk/games/store/assets",{headers:{"x-game-key":e}})}async listMyGameAssets(e,t){return this.http.request("GET","/sdk/games/store/assets/me",{bearerToken:e,headers:{"x-game-key":t}})}async listMyStorePurchases(e,t){return this.http.request("GET","/sdk/games/store/purchases/me",{bearerToken:e,headers:{"x-game-key":t}})}async createMyStoreCheckoutIntent(e,t,s,n){return this.http.request("POST","/sdk/games/store/checkout-intent/me",{bearerToken:t,headers:{"x-game-key":e,"x-game-tracking-session-id":n},body:s})}async purchaseMyStoreOffer(e,t,s,n){return this.http.request("POST","/sdk/games/store/purchase/me",{bearerToken:t,headers:{"x-game-key":e,"x-game-tracking-session-id":n},body:s})}async createGameStoreCheckoutIntent(e,t){return this.http.request("POST","/sdk/games/store/checkout-intent",{bearerToken:e.bearerToken,headers:{"x-creator-key":e.creatorKey,"x-game-secret":e.gameSecret,"x-game-tracking-session-id":e.trackingSessionId},body:t})}async purchaseGameStoreOffer(e,t){return this.http.request("POST","/sdk/games/store/purchase",{bearerToken:e.bearerToken,headers:{"x-creator-key":e.creatorKey,"x-game-secret":e.gameSecret,"x-game-tracking-session-id":e.trackingSessionId},body:t})}async getBalances(e,t){return this.http.request("GET","/sdk/balance",{bearerToken:e,query:t})}async getBalanceHistory(e,t){return this.http.request("GET","/sdk/balance/history",{bearerToken:e,query:t})}async getMyProfile(e){return this.http.request("GET","/sdk/user/profile",{bearerToken:e})}async getMyBalance(e){return this.http.request("GET","/sdk/user/balance",{bearerToken:e})}};function D(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let e=Math.random()*16|0;return (i==="x"?e:e&3|8).toString(16)})}var g=class{raw;getAccessToken;getAnonymousId;trackingSession;trackingSessionPromiseKey;trackingSessionPromise;currentPlaySessionId;playSession;playSessionPromiseKey;playSessionPromise;constructor(e){if(!e.baseUrl)throw new l;this.raw=new h({baseUrl:e.baseUrl,fetch:e.fetch,defaultHeaders:e.defaultHeaders}),this.getAccessToken=e.getAccessToken,this.getAnonymousId=e.getAnonymousId;}unsafeRaw(){return this.raw}async detectIntegration(e){return this.raw.detectGameIntegration(e)}async requireToken(){let e=await this.getAccessToken?.();if(!e)throw new m;return e}async resolveTrackingAuth(){let e=await this.getAccessToken?.(),t=e?void 0:this.getAnonymousId?.();if(!e&&!t)throw new m;let s=await this.ensureTrackingSession(e?`bearer:${e}`:`anon:${t}`,t);return {bearerToken:e,anonId:t,trackingSessionId:s?.trackingSessionId,anonTrackingToken:s?.anonTrackingToken}}async ensureTrackingSession(e,t){let s=Date.now();return this.trackingSession&&this.trackingSession.cacheKey===e&&this.trackingSession.expiresAtMs>s+3e4?this.trackingSession:((!this.trackingSessionPromise||this.trackingSessionPromiseKey!==e)&&(this.trackingSessionPromiseKey=e,this.trackingSessionPromise=this.raw.bootstrapTrackingSession(t).then(n=>(this.trackingSession={cacheKey:e,trackingSessionId:n.trackingSessionId,anonTrackingToken:n.trackingToken,expiresAtMs:new Date(n.expiresAt).getTime()},this.trackingSession)).catch(()=>{}).finally(()=>{this.trackingSessionPromise=void 0,this.trackingSessionPromiseKey=void 0;})),this.trackingSessionPromise)}getTrackingAuthKey(e){return [e.bearerToken?`bearer:${e.bearerToken}`:`anon:${e.anonId??""}`,e.trackingSessionId??"",e.anonTrackingToken??""].join(`
|
|
1
|
+
var LooplaySDK=(function(exports){'use strict';var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;var l=class extends Error{constructor(e){super(e),this.name="LooplaySDKError";}},c=class extends l{constructor(){super("LooplaySDK not initialized. Call init({ gameId }) first."),this.name="NotInitializedError";}},u=class extends l{constructor(){super("Missing baseUrl. Provide `baseUrl` to enable HTTP integration."),this.name="MissingBaseUrlError";}},x=class extends l{constructor(){super("Missing auth. Provide `auth` options to enable user login/session."),this.name="MissingAuthError";}},f=class extends l{constructor(){super("Not authenticated. Login is required for this operation."),this.name="NotAuthenticatedError";}};var k=class{map=new Map;async getItem(e){return this.map.has(e)?this.map.get(e):null}async setItem(e,t){this.map.set(e,t);}async removeItem(e){this.map.delete(e);}},b=class{async getItem(e){return typeof window>"u"||!window.localStorage?null:window.localStorage.getItem(e)}async setItem(e,t){typeof window>"u"||!window.localStorage||window.localStorage.setItem(e,t);}async removeItem(e){typeof window>"u"||!window.localStorage||window.localStorage.removeItem(e);}};var w=class extends l{constructor(){super("Invalid session returned by auth provider"),this.name="InvalidSessionError";}},S=class{provider;storage;key;session=null;listeners=new Set;constructor(e){this.provider=e.provider,this.storage=e.storage??new k,this.key=`${e.storageKeyPrefix??"looplay"}:auth:session`;}async init(){await this.provider.init?.(),await this.restoreFromStorage(),await this.provider.onSessionChanged?.(this.session);}getSession(){return this.session}async login(e){let t=await this.provider.login(e);if(!t?.session?.user?.id)throw new w;return await this.setSession(t.session,"login"),t.session}async logout(){await this.provider.logout(),await this.setSession(null,"logout");}async getAccessToken(){if(!this.session)return;let e=Date.now();if(!(typeof this.session.expiresAt=="number"&&this.session.expiresAt<=e))return this.session.accessToken;if(!this.provider.refresh)return this.session.accessToken;let s=await this.provider.refresh(),n={...this.session,...s};return await this.setSession(n,"sessionChanged"),n.accessToken}on(e,t){return this.listeners.add(t),()=>this.listeners.delete(t)}async restoreFromStorage(){let e=await this.storage.getItem(this.key);if(e)try{let t=JSON.parse(e);t?.user?.id&&(this.session=t);}catch{await this.storage.removeItem(this.key);}}async setSession(e,t){this.session=e,await this.provider.onSessionChanged?.(this.session),e?await this.storage.setItem(this.key,JSON.stringify(e)):await this.storage.removeItem(this.key);for(let s of this.listeners)s(this.session);}};var d="https://miniapp-api.looplay.gg";function R(){try{if(typeof ({ url: (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('looplay-sdk.min.js', document.baseURI).href) })<"u"&&undefined?.VITE_PARENT_ORIGIN){let i=undefined.VITE_PARENT_ORIGIN;if(typeof i=="string"&&i.trim().length>0)return i.trim()}}catch{}try{if(typeof process<"u"&&process.env?.VITE_PARENT_ORIGIN){let i=process.env.VITE_PARENT_ORIGIN;if(typeof i=="string"&&i.trim().length>0)return i.trim()}}catch{}}function h(){try{if(typeof ({ url: (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('looplay-sdk.min.js', document.baseURI).href) })<"u"&&undefined){let i=undefined.VITE_API_URL??undefined.VITE_LOOPLAY_API_URL;if(typeof i=="string"&&i.trim().length>0)return i.trim()}}catch{}try{if(typeof process<"u"&&process.env){let i=process.env.VITE_API_URL??process.env.VITE_LOOPLAY_API_URL;if(typeof i=="string"&&i.trim().length>0)return i.trim()}}catch{}}var L="0.8.10";function G(i){return i?typeof window<"u"&&i===window.fetch?window.fetch.bind(window):i:globalThis.fetch.bind(globalThis)}var v=class extends Error{status;bodyText;constructor(e,t,s){super(e),this.name="HttpError",this.status=t,this.bodyText=s;}},A=class{baseUrl;fetchFn;defaultHeaders;constructor(e={}){let t=typeof e.baseUrl=="string"&&e.baseUrl.trim().length>0?e.baseUrl.trim():h()??d;this.baseUrl=t.replace(/\/$/,""),this.fetchFn=G(e.fetch),this.defaultHeaders={"x-looplay-sdk-version":L,...e.defaultHeaders??{}};}async request(e,t,s){let n=this.buildUrl(t,s?.query),r=this.mergeHeaders(this.defaultHeaders,s?.headers);s?.bearerToken?r.Authorization=`Bearer ${s.bearerToken}`:s?.anonId&&(r["x-looplay-anon-id"]=s.anonId);let o;s?.body!==void 0&&(r["Content-Type"]=r["Content-Type"]??"application/json",o=JSON.stringify(s.body));let a=await this.fetchFn(n,{method:e,headers:r,body:o});if(!a.ok){let U=await this.safeText(a);throw new v(`HTTP ${a.status} ${a.statusText}`,a.status,U)}let m=await this.safeText(a);if(m)return JSON.parse(m)}mergeHeaders(...e){let t={};for(let s of e)if(s)for(let[n,r]of Object.entries(s))r!==void 0&&(t[n]=r);return t}buildUrl(e,t){let s=e.startsWith("/")?e:`/${e}`,n=new URL(`${this.baseUrl}${s}`);if(t)for(let[r,o]of Object.entries(t))o!==void 0&&n.searchParams.set(r,String(o));return n.toString()}async safeText(e){try{return await e.text()}catch{return ""}}};var p=class{http;constructor(e){this.http=new A(e);}async telegramLogin(e){let t={telegramInitData:e};return this.http.request("POST","/account/telegram-login",{body:t})}async refresh(e){let t={refreshToken:e};return this.http.request("POST","/account/refresh",{body:t})}async logout(e){let t={refreshToken:e};return this.http.request("POST","/account/logout",{body:t})}async recordGameView(e,t={}){return await this.http.request("POST","/sdk/games/views/record",{...t,headers:{"x-game-key":e,...this.trackingHeaders(t)}}),true}async startPlaySession(e,t={},s={}){return this.http.request("POST","/sdk/games/play-sessions/start",{...t,headers:{"x-game-key":e,...this.trackingHeaders(t)},body:s})}async renewPlaySession(e,t={},s){return this.http.request("POST","/sdk/games/play-sessions/renew",{...t,headers:{"x-game-key":e,...this.trackingHeaders(t)},body:s})}async completePlaySession(e,t,s){return await this.http.request("POST","/sdk/games/play-sessions/complete",{...t,headers:{"x-game-key":e,...this.trackingHeaders(t)},body:s}),true}async completeGameplayMatch(e,t,s){return await this.http.request("POST","/sdk/games/matches/complete",{...t,headers:{"x-game-key":e,...this.trackingHeaders(t)},body:s}),true}async recordGameplayAction(e,t,s){return this.http.request("POST","/sdk/games/actions/record",{...t,headers:{"x-game-key":e,...this.trackingHeaders(t)},body:s})}async bootstrapTrackingSession(e){return this.http.request("POST","/sdk/games/tracking/bootstrap",{headers:{"x-looplay-anon-id":e}})}async detectGameIntegration(e){return await this.http.request("POST","/sdk/games/integration/detect",{headers:{"x-game-key":e}}),true}trackingHeaders(e){return {"x-game-tracking-session-id":e.trackingSessionId,"x-looplay-anon-token":e.anonTrackingToken}}async getStore(e){return this.http.request("GET","/sdk/games/store/current",{headers:{"x-game-key":e}})}async listGameAssets(e){return this.http.request("GET","/sdk/games/store/assets",{headers:{"x-game-key":e}})}async listMyGameAssets(e,t){return this.http.request("GET","/sdk/games/store/assets/me",{bearerToken:e,headers:{"x-game-key":t}})}async listMyStorePurchases(e,t){return this.http.request("GET","/sdk/games/store/purchases/me",{bearerToken:e,headers:{"x-game-key":t}})}async createMyStoreCheckoutIntent(e,t,s,n){return this.http.request("POST","/sdk/games/store/checkout-intent/me",{bearerToken:t,headers:{"x-game-key":e,"x-game-tracking-session-id":n},body:s})}async purchaseMyStoreOffer(e,t,s,n){return this.http.request("POST","/sdk/games/store/purchase/me",{bearerToken:t,headers:{"x-game-key":e,"x-game-tracking-session-id":n},body:s})}async createGameStoreCheckoutIntent(e,t){return this.http.request("POST","/sdk/games/store/checkout-intent",{bearerToken:e.bearerToken,headers:{"x-creator-key":e.creatorKey,"x-game-secret":e.gameSecret,"x-game-tracking-session-id":e.trackingSessionId},body:t})}async purchaseGameStoreOffer(e,t){return this.http.request("POST","/sdk/games/store/purchase",{bearerToken:e.bearerToken,headers:{"x-creator-key":e.creatorKey,"x-game-secret":e.gameSecret,"x-game-tracking-session-id":e.trackingSessionId},body:t})}async getBalances(e,t){return this.http.request("GET","/sdk/balance",{bearerToken:e,query:t})}async getBalanceHistory(e,t){return this.http.request("GET","/sdk/balance/history",{bearerToken:e,query:t})}async getMyProfile(e){return this.http.request("GET","/sdk/user/profile",{bearerToken:e})}async getMyBalance(e){return this.http.request("GET","/sdk/user/balance",{bearerToken:e})}};function D(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let e=Math.random()*16|0;return (i==="x"?e:e&3|8).toString(16)})}var y=class{raw;getAccessToken;getAnonymousId;trackingSession;trackingSessionPromiseKey;trackingSessionPromise;currentPlaySessionId;playSession;playSessionPromiseKey;playSessionPromise;constructor(e={}){let t=typeof e.baseUrl=="string"&&e.baseUrl.trim().length>0?e.baseUrl.trim():h()??d;if(!t)throw new u;this.raw=new p({baseUrl:t,fetch:e.fetch,defaultHeaders:e.defaultHeaders}),this.getAccessToken=e.getAccessToken,this.getAnonymousId=e.getAnonymousId;}unsafeRaw(){return this.raw}async detectIntegration(e){return this.raw.detectGameIntegration(e)}async requireToken(){let e=await this.getAccessToken?.();if(!e)throw new f;return e}async resolveTrackingAuth(){let e=await this.getAccessToken?.(),t=e?void 0:this.getAnonymousId?.();if(!e&&!t)throw new f;let s=await this.ensureTrackingSession(e?`bearer:${e}`:`anon:${t}`,t);return {bearerToken:e,anonId:t,trackingSessionId:s?.trackingSessionId,anonTrackingToken:s?.anonTrackingToken}}async ensureTrackingSession(e,t){let s=Date.now();return this.trackingSession&&this.trackingSession.cacheKey===e&&this.trackingSession.expiresAtMs>s+3e4?this.trackingSession:((!this.trackingSessionPromise||this.trackingSessionPromiseKey!==e)&&(this.trackingSessionPromiseKey=e,this.trackingSessionPromise=this.raw.bootstrapTrackingSession(t).then(n=>(this.trackingSession={cacheKey:e,trackingSessionId:n.trackingSessionId,anonTrackingToken:n.trackingToken,expiresAtMs:new Date(n.expiresAt).getTime()},this.trackingSession)).catch(()=>{}).finally(()=>{this.trackingSessionPromise=void 0,this.trackingSessionPromiseKey=void 0;})),this.trackingSessionPromise)}getTrackingAuthKey(e){return [e.bearerToken?`bearer:${e.bearerToken}`:`anon:${e.anonId??""}`,e.trackingSessionId??"",e.anonTrackingToken??""].join(`
|
|
2
2
|
`)}async ensurePlaySession(e,t,s){let n=Date.now(),r=[e,s,this.getTrackingAuthKey(t)].join(`
|
|
3
|
-
`);if(this.playSession&&this.playSession.cacheKey===r&&this.playSession.gameKey===e&&this.playSession.playSessionId===s&&this.playSession.expiresAtMs>n+1e4)return this.playSession;let o=this.playSession&&this.playSession.cacheKey===r&&this.playSession.gameKey===e&&this.playSession.playSessionId===s?this.playSession:void 0;if(!this.playSessionPromise||this.playSessionPromiseKey!==r){this.playSessionPromiseKey=r;let a=o?this.raw.renewPlaySession(e,t,{playSessionId:s,playSessionToken:o.playSessionToken}).catch(()=>this.raw.startPlaySession(e,t,{playSessionId:s})):this.raw.startPlaySession(e,t,{playSessionId:s});this.playSessionPromise=a.then(d=>(this.playSession={cacheKey:r,gameKey:e,playSessionId:d.playSessionId,playSessionToken:d.playSessionToken,expiresAtMs:new Date(d.expiresAt).getTime()},this.playSession)).finally(()=>{this.playSessionPromise=void 0,this.playSessionPromiseKey=void 0;});}return this.playSessionPromise}async trackView(e){let t=await this.resolveTrackingAuth();return this.raw.recordGameView(e,t)}startPlaySession(){return this.currentPlaySessionId=D(),this.playSession=void 0,this.currentPlaySessionId}async trackPlay(e,t){let s=await this.resolveTrackingAuth(),n=this.currentPlaySessionId??this.startPlaySession(),{playSessionToken:r}=await this.ensurePlaySession(e,s,n);return this.raw.completePlaySession(e,s,{playTimeSeconds:t,playSessionId:n,playSessionToken:r})}async trackMatch(e,t){let s=await this.resolveTrackingAuth(),n=this.currentPlaySessionId??this.startPlaySession(),{playSessionToken:r}=await this.ensurePlaySession(e,s,n);return this.raw.completeGameplayMatch(e,s,{...t,playSessionId:n,playSessionToken:r})}async emit(e,t,s){let n=await this.resolveTrackingAuth(),r=this.currentPlaySessionId??this.startPlaySession(),{playSessionToken:o}=await this.ensurePlaySession(e,n,r),a={playSessionId:r,playSessionToken:o,actionCode:t,value:s?.value,refId:s?.refId,payload:s?.payload};return this.raw.recordGameplayAction(e,n,a)}async getStore(e){return this.raw.getStore(e)}async listGameAssets(e){return this.raw.listGameAssets(e)}async listMyGameAssets(e){let t=await this.requireToken();return this.raw.listMyGameAssets(t,e)}async listMyStorePurchases(e){let t=await this.requireToken();return this.raw.listMyStorePurchases(t,e)}async purchaseStoreOffer(e,t,s){let n=await this.requireToken(),r=await this.raw.createMyStoreCheckoutIntent(e,n,{offerCode:t,requestId:s?.requestId,quantity:s?.quantity});return this.raw.purchaseMyStoreOffer(e,n,{offerCode:r.offerCode,requestId:r.requestId,quantity:r.quantity,checkoutToken:r.checkoutToken})}async getMyProfile(){let e=await this.requireToken();return this.raw.getMyProfile(e)}async getMyBalance(){let e=await this.requireToken();return this.raw.getMyBalance(e)}async getBalances(e){let t=await this.requireToken();return this.raw.getBalances(t,e)}async getBalanceHistory(e){let t=await this.requireToken();return this.raw.getBalanceHistory(t,e)}};var S="https://miniapp-api.looplay.gg";function L(){try{if(typeof ({ url: (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('looplay-sdk.min.js', document.baseURI).href) })<"u"&&undefined?.VITE_PARENT_ORIGIN){let i=undefined.VITE_PARENT_ORIGIN;if(typeof i=="string"&&i.trim().length>0)return i.trim()}}catch{}try{if(typeof process<"u"&&process.env?.VITE_PARENT_ORIGIN){let i=process.env.VITE_PARENT_ORIGIN;if(typeof i=="string"&&i.trim().length>0)return i.trim()}}catch{}}function A(){try{if(typeof ({ url: (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('looplay-sdk.min.js', document.baseURI).href) })<"u"&&undefined){let i=undefined.VITE_API_URL??undefined.VITE_LOOPLAY_API_URL;if(typeof i=="string"&&i.trim().length>0)return i.trim()}}catch{}try{if(typeof process<"u"&&process.env){let i=process.env.VITE_API_URL??process.env.VITE_LOOPLAY_API_URL;if(typeof i=="string"&&i.trim().length>0)return i.trim()}}catch{}}var O=class{auth;api;gameId;initialized=false;constructor(e={}){let{auth:t,baseUrl:s=A()??S,fetch:n,defaultHeaders:r}=e;t&&(this.auth=new f(t)),s&&(this.api=new g({baseUrl:s,fetch:n,defaultHeaders:r,getAccessToken:async()=>this.auth?.getAccessToken()}));}async init(e){this.gameId=e.gameId,await this.auth?.init(),await this.detectIntegration(e),await this.verifyGameId(e),this.initialized=true;}async getAccessToken(){return this.auth?.getAccessToken()}getGameId(){return this.gameId}async getMyProfile(){if(this.assertInitialized(),!this.api)throw new l;return this.api.getMyProfile()}async trackView(){if(this.assertInitialized(),!this.api)throw new l;if(!this.gameId)throw new c;return this.api.trackView(this.gameId)}startPlaySession(){if(this.assertInitialized(),!this.api)throw new l;return this.api.startPlaySession()}async trackPlay(e){if(this.assertInitialized(),!this.api)throw new l;if(!this.gameId)throw new c;return this.api.trackPlay(this.gameId,e)}async trackMatch(e,t){if(this.assertInitialized(),!this.api)throw new l;if(!this.gameId)throw new c;return this.api.trackMatch(this.gameId,{matchId:e,matchDurationSeconds:t.durationSeconds,isCompleted:t.isCompleted,isWin:t.isWin})}async emit(e,t){if(this.assertInitialized(),!this.api)throw new l;if(!this.gameId)throw new c;return this.api.emit(this.gameId,e,t)}assertInitialized(){if(!this.initialized)throw new c}async verifyGameId(e){if((e.verifyMode??"none")!=="none"){if(!this.api)throw new l;await this.api.listGameAssets(e.gameId);}}async detectIntegration(e){if(this.api)try{await this.api.detectIntegration(e.gameId);}catch(t){console.warn("[LooplaySDK] detectIntegration failed (SDK will still initialize) \u2014 check that this game has a whitelisted origin/domain configured:",t);}}};function M(i){if(!i)return;let e=i.split(".");if(!(e.length<2))try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),s=t+"===".slice((t.length+3)%4);if(typeof globalThis.atob!="function")return;let n=globalThis.atob(s);return JSON.parse(n)}catch{return}}function P(i){let e=M(i)?.exp;return typeof e=="number"?e*1e3:void 0}var I=class extends u{constructor(){super("Missing Telegram init data"),this.name="MissingTelegramInitDataError";}},T=class extends u{constructor(){super("Missing refresh token"),this.name="MissingRefreshTokenError";}},q=class{id="telegram";client;getTelegramInitData;mapUser;session=null;constructor(e){this.client=new h(e),this.getTelegramInitData=e.getTelegramInitData,this.mapUser=e.mapUser;}onSessionChanged=e=>{this.session=e;};async login(e){let t=e?.telegramInitData??this.getTelegramInitData?.()??globalThis?.Telegram?.WebApp?.initData;if(!t)throw new I;let s=await this.client.telegramLogin(t),n=s.user??{},o={user:this.mapUser?this.mapUser(n):this.defaultMapUser(n),accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:P(s.accessToken)};return this.session=o,{session:o}}async refresh(){let e=this.session,t=e?.refreshToken;if(!e||!t)throw new T;let s=await this.client.refresh(t),n={accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:P(s.accessToken)};return this.session={...e,...n},n}async logout(){let e=this.session?.refreshToken;if(e)try{await this.client.logout(e);}catch{}this.session=null;}defaultMapUser(e){let t=e.id??e._id??e.userId??e.telegramId;if(t==null||String(t).trim()==="")throw new u("Missing user id from auth response");return {id:String(t),displayName:e.displayName??e.username??e.name,avatarUrl:e.avatarUrl??e.photoUrl??e.avatar}}};var C="looplay:anon-id",_=4e3,K=5e3,F={jwt:null,gameId:null,apiUrl:null,anonymousId:null,origin:null,receivedAt:null},H=i=>typeof i=="object"&&i!==null,p=i=>{if(typeof i!="string")return null;let e=i.trim();return e||null};function N(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let e=Math.random()*16|0;return (i==="x"?e:e&3|8).toString(16)})}function z(i){if(typeof window>"u"||!window.localStorage)return null;try{return window.localStorage.getItem(i)}catch{return null}}function V(i,e){if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(i,e);}catch{}}var E=class{state=F;initialized=false;lifecycleTrackingInitialized=false;lastGameStartedKey=null;integrationDetectionKeys=new Set;client=null;listeners=new Set;options;messageListener=null;anonymousFallbackTimer=null;pendingAdsRequests=new Map;requestAdsSequence=0;adsRequestInFlight=false;adsRequestsSent=0;lastAdsRequestAt=0;autoAdsActionCount=0;constructor(e={}){this.options=e;}getState(){return this.state}getJwt(){return this.state.jwt}getApiUrl(){return this.state.apiUrl??this.options.apiUrl??A()??S}getGameId(){return this.state.gameId??this.options.appId??null}getAnonymousId(){return this.state.anonymousId}canTrack(){return !this.getApiUrl()||!this.getGameId()?false:!!(this.state.jwt||this.state.anonymousId)}subscribe(e){return this.listeners.add(e),e(this.state),()=>this.listeners.delete(e)}requestAuth(){if(typeof window>"u"||window.parent===window){this.debug("standalone mode detected; auth request skipped");return}this.debug("requesting auth from parent",{targetOrigin:this.resolveParentOrigin()??"*"}),window.parent.postMessage({type:"LOOPLAY_AUTH_REQUEST"},this.resolveParentOrigin()??"*");}requestAds(e={}){if(typeof window>"u"||window.parent===window)return this.debug("requestAds skipped; standalone mode detected"),Promise.resolve(false);if(this.adsRequestInFlight)return this.debug("requestAds skipped; another ad request is already in flight"),Promise.resolve(false);let t=this.resolveParentOrigin()??"*",s=`ads-${Date.now()}-${++this.requestAdsSequence}`,n=e.timeoutMs??K;return this.adsRequestInFlight=true,this.adsRequestsSent+=1,this.lastAdsRequestAt=Date.now(),this.debug("requesting rewarded ad from parent",{requestId:s,targetOrigin:t,gameId:this.getGameId()}),new Promise(r=>{let o=setTimeout(()=>{this.pendingAdsRequests.delete(s),this.adsRequestInFlight=false,this.debug("requestAds timed out",{requestId:s,timeoutMs:n}),r(false);},n);this.pendingAdsRequests.set(s,{resolve:r,timer:o}),window.parent.postMessage({type:"LOOPLAY_REQUEST_ADS",requestId:s,gameId:this.getGameId()},t);})}init(){if(this.initialized||typeof window>"u")return;this.initialized=true,this.detectIntegrationOnce();let e=window.parent!==window;if(this.debug("auth listener initialized",{isIframe:e,parentOrigin:this.resolveParentOrigin()}),!e){this.activateAnonymousMode();return}let t=this.resolveParentOrigin();t||console.warn("[LooplaySDK] LooplayIframeAuth could not resolve a parent origin to verify postMessage against (document.referrer is empty). Auth messages from window.parent will be accepted regardless of origin. Pass `parentOrigin` explicitly to harden this."),this.messageListener=s=>{if(s.source===window.parent){if(t&&s.origin!==t){this.debug("ignored message from unexpected origin",{expectedOrigin:t,receivedOrigin:s.origin});return}this.handleIncomingMessage(s.data,s.origin);}},window.addEventListener("message",this.messageListener),this.anonymousFallbackTimer=setTimeout(()=>{this.state.jwt||this.activateAnonymousMode();},this.options.anonymousFallbackTimeoutMs??_),this.requestAuth();}dispose(){typeof window<"u"&&this.messageListener&&window.removeEventListener("message",this.messageListener),this.anonymousFallbackTimer!==null&&clearTimeout(this.anonymousFallbackTimer);for(let e of this.pendingAdsRequests.values())e.timer!==null&&clearTimeout(e.timer),e.resolve(false);this.pendingAdsRequests.clear(),this.messageListener=null,this.anonymousFallbackTimer=null,this.initialized=false,this.lifecycleTrackingInitialized=false,this.integrationDetectionKeys.clear(),this.listeners.clear();}getClient(){if(this.client)return this.client;let e=this.getApiUrl();return this.debug("creating sdk ApiClient",{baseUrl:e}),this.client=new g({baseUrl:e??void 0,getAccessToken:async()=>this.getJwt()??void 0,getAnonymousId:()=>this.getAnonymousId()??void 0}),this.client}trackView(){let e=this.getGameId();return !this.canTrack()||!e?(this.debug("trackView skipped; auth is not ready",{hasGameId:!!e}),Promise.resolve(false)):(this.debug("trackView dispatched",{gameId:e}),this.getClient().trackView(e))}startPlaySession(){return this.getClient().startPlaySession()}trackPlay(e){let t=this.getGameId();return !this.canTrack()||!t?(this.debug("trackPlay skipped; auth is not ready",{hasGameId:!!t}),Promise.resolve(false)):(this.debug("trackPlay dispatched",{gameId:t,playTimeSeconds:e}),this.getClient().trackPlay(t,e))}trackMatch(e,t){let s=this.getGameId();if(!this.canTrack()||!s)return this.debug("trackMatch skipped; auth is not ready",{matchId:e}),Promise.resolve(false);this.debug("trackMatch dispatched",{gameId:s,matchId:e,...t});let n=this.getClient().trackMatch(s,{matchId:e,matchDurationSeconds:t.durationSeconds,isCompleted:t.isCompleted,isWin:t.isWin});return n.then(r=>{r&&this.recordAutoRequestAdsActivity();}).catch(()=>{}),n}emitGameEvent(e,t){let s=this.getGameId();return !this.canTrack()||!s?(this.debug("emitGameEvent skipped; auth is not ready",{actionCode:e}),Promise.resolve(null)):(this.debug("emitGameEvent dispatched",{gameId:s,actionCode:e,...t}),this.getClient().emit(s,e,t))}initLifecycleTracking(){this.lifecycleTrackingInitialized||typeof window>"u"||(this.lifecycleTrackingInitialized=true,this.debug("lifecycle tracking initialized"),this.subscribe(()=>{let e=this.getTrackingKey();!e||this.lastGameStartedKey===e||(this.lastGameStartedKey=e,this.debug("auto GAME_STARTED dispatch"),this.emitGameEvent("GAME_STARTED"));}));}getTrackingKey(){let e=this.getGameId(),t=this.getApiUrl(),s=this.state.jwt??this.state.anonymousId;return !e||!t||!s?null:`${t}
|
|
3
|
+
`);if(this.playSession&&this.playSession.cacheKey===r&&this.playSession.gameKey===e&&this.playSession.playSessionId===s&&this.playSession.expiresAtMs>n+1e4)return this.playSession;let o=this.playSession&&this.playSession.cacheKey===r&&this.playSession.gameKey===e&&this.playSession.playSessionId===s?this.playSession:void 0;if(!this.playSessionPromise||this.playSessionPromiseKey!==r){this.playSessionPromiseKey=r;let a=o?this.raw.renewPlaySession(e,t,{playSessionId:s,playSessionToken:o.playSessionToken}).catch(()=>this.raw.startPlaySession(e,t,{playSessionId:s})):this.raw.startPlaySession(e,t,{playSessionId:s});this.playSessionPromise=a.then(m=>(this.playSession={cacheKey:r,gameKey:e,playSessionId:m.playSessionId,playSessionToken:m.playSessionToken,expiresAtMs:new Date(m.expiresAt).getTime()},this.playSession)).finally(()=>{this.playSessionPromise=void 0,this.playSessionPromiseKey=void 0;});}return this.playSessionPromise}async trackView(e){let t=await this.resolveTrackingAuth();return this.raw.recordGameView(e,t)}startPlaySession(){return this.currentPlaySessionId=D(),this.playSession=void 0,this.currentPlaySessionId}async trackPlay(e,t){let s=await this.resolveTrackingAuth(),n=this.currentPlaySessionId??this.startPlaySession(),{playSessionToken:r}=await this.ensurePlaySession(e,s,n);return this.raw.completePlaySession(e,s,{playTimeSeconds:t,playSessionId:n,playSessionToken:r})}async trackMatch(e,t){let s=await this.resolveTrackingAuth(),n=this.currentPlaySessionId??this.startPlaySession(),{playSessionToken:r}=await this.ensurePlaySession(e,s,n);return this.raw.completeGameplayMatch(e,s,{...t,playSessionId:n,playSessionToken:r})}async emit(e,t,s){let n=await this.resolveTrackingAuth(),r=this.currentPlaySessionId??this.startPlaySession(),{playSessionToken:o}=await this.ensurePlaySession(e,n,r),a={playSessionId:r,playSessionToken:o,actionCode:t,value:s?.value,refId:s?.refId,payload:s?.payload};return this.raw.recordGameplayAction(e,n,a)}async getStore(e){return this.raw.getStore(e)}async listGameAssets(e){return this.raw.listGameAssets(e)}async listMyGameAssets(e){let t=await this.requireToken();return this.raw.listMyGameAssets(t,e)}async listMyStorePurchases(e){let t=await this.requireToken();return this.raw.listMyStorePurchases(t,e)}async purchaseStoreOffer(e,t,s){let n=await this.requireToken(),r=await this.raw.createMyStoreCheckoutIntent(e,n,{offerCode:t,requestId:s?.requestId,quantity:s?.quantity});return this.raw.purchaseMyStoreOffer(e,n,{offerCode:r.offerCode,requestId:r.requestId,quantity:r.quantity,checkoutToken:r.checkoutToken})}async getMyProfile(){let e=await this.requireToken();return this.raw.getMyProfile(e)}async getMyBalance(){let e=await this.requireToken();return this.raw.getMyBalance(e)}async getBalances(e){let t=await this.requireToken();return this.raw.getBalances(t,e)}async getBalanceHistory(e){let t=await this.requireToken();return this.raw.getBalanceHistory(t,e)}};var O=class{auth;api;gameId;initialized=false;constructor(e={}){let{auth:t,fetch:s,defaultHeaders:n}=e,r=typeof e.baseUrl=="string"&&e.baseUrl.trim().length>0?e.baseUrl.trim():h()??d;t&&(this.auth=new S(t)),this.api=new y({baseUrl:r,fetch:s,defaultHeaders:n,getAccessToken:async()=>this.auth?.getAccessToken()});}async init(e){this.gameId=e.gameId,await this.auth?.init(),await this.detectIntegration(e),await this.verifyGameId(e),this.initialized=true;}async getAccessToken(){return this.auth?.getAccessToken()}getGameId(){return this.gameId}async getMyProfile(){if(this.assertInitialized(),!this.api)throw new u;return this.api.getMyProfile()}async trackView(){if(this.assertInitialized(),!this.api)throw new u;if(!this.gameId)throw new c;return this.api.trackView(this.gameId)}startPlaySession(){if(this.assertInitialized(),!this.api)throw new u;return this.api.startPlaySession()}async trackPlay(e){if(this.assertInitialized(),!this.api)throw new u;if(!this.gameId)throw new c;return this.api.trackPlay(this.gameId,e)}async trackMatch(e,t){if(this.assertInitialized(),!this.api)throw new u;if(!this.gameId)throw new c;return this.api.trackMatch(this.gameId,{matchId:e,matchDurationSeconds:t.durationSeconds,isCompleted:t.isCompleted,isWin:t.isWin})}async emit(e,t){if(this.assertInitialized(),!this.api)throw new u;if(!this.gameId)throw new c;return this.api.emit(this.gameId,e,t)}assertInitialized(){if(!this.initialized)throw new c}async verifyGameId(e){if((e.verifyMode??"none")!=="none"){if(!this.api)throw new u;await this.api.listGameAssets(e.gameId);}}async detectIntegration(e){if(this.api)try{await this.api.detectIntegration(e.gameId);}catch(t){console.warn("[LooplaySDK] detectIntegration failed (SDK will still initialize) \u2014 check that this game has a whitelisted origin/domain configured:",t);}}};function M(i){if(!i)return;let e=i.split(".");if(!(e.length<2))try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),s=t+"===".slice((t.length+3)%4);if(typeof globalThis.atob!="function")return;let n=globalThis.atob(s);return JSON.parse(n)}catch{return}}function P(i){let e=M(i)?.exp;return typeof e=="number"?e*1e3:void 0}var I=class extends l{constructor(){super("Missing Telegram init data"),this.name="MissingTelegramInitDataError";}},T=class extends l{constructor(){super("Missing refresh token"),this.name="MissingRefreshTokenError";}},q=class{id="telegram";client;getTelegramInitData;mapUser;session=null;constructor(e){this.client=new p(e),this.getTelegramInitData=e.getTelegramInitData,this.mapUser=e.mapUser;}onSessionChanged=e=>{this.session=e;};async login(e){let t=e?.telegramInitData??this.getTelegramInitData?.()??globalThis?.Telegram?.WebApp?.initData;if(!t)throw new I;let s=await this.client.telegramLogin(t),n=s.user??{},o={user:this.mapUser?this.mapUser(n):this.defaultMapUser(n),accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:P(s.accessToken)};return this.session=o,{session:o}}async refresh(){let e=this.session,t=e?.refreshToken;if(!e||!t)throw new T;let s=await this.client.refresh(t),n={accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:P(s.accessToken)};return this.session={...e,...n},n}async logout(){let e=this.session?.refreshToken;if(e)try{await this.client.logout(e);}catch{}this.session=null;}defaultMapUser(e){let t=e.id??e._id??e.userId??e.telegramId;if(t==null||String(t).trim()==="")throw new l("Missing user id from auth response");return {id:String(t),displayName:e.displayName??e.username??e.name,avatarUrl:e.avatarUrl??e.photoUrl??e.avatar}}};var C="looplay:anon-id",_=4e3,K=5e3,F={jwt:null,gameId:null,apiUrl:null,anonymousId:null,origin:null,receivedAt:null},H=i=>typeof i=="object"&&i!==null,g=i=>{if(typeof i!="string")return null;let e=i.trim();return e||null};function N(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let e=Math.random()*16|0;return (i==="x"?e:e&3|8).toString(16)})}function z(i){if(typeof window>"u"||!window.localStorage)return null;try{return window.localStorage.getItem(i)}catch{return null}}function V(i,e){if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(i,e);}catch{}}var E=class{state=F;initialized=false;lifecycleTrackingInitialized=false;lastGameStartedKey=null;integrationDetectionKeys=new Set;client=null;listeners=new Set;options;messageListener=null;anonymousFallbackTimer=null;pendingAdsRequests=new Map;requestAdsSequence=0;adsRequestInFlight=false;adsRequestsSent=0;lastAdsRequestAt=0;autoAdsActionCount=0;constructor(e={}){this.options=e;}getState(){return this.state}getJwt(){return this.state.jwt}getApiUrl(){return (g(this.state.apiUrl)??g(this.options.apiUrl)??h()??d).trim()}getGameId(){return this.state.gameId??this.options.appId??null}getAnonymousId(){return this.state.anonymousId}canTrack(){return !this.getApiUrl()||!this.getGameId()?false:!!(this.state.jwt||this.state.anonymousId)}subscribe(e){return this.listeners.add(e),e(this.state),()=>this.listeners.delete(e)}requestAuth(){if(typeof window>"u"||window.parent===window){this.debug("standalone mode detected; auth request skipped");return}this.debug("requesting auth from parent",{targetOrigin:this.resolveParentOrigin()??"*"}),window.parent.postMessage({type:"LOOPLAY_AUTH_REQUEST"},this.resolveParentOrigin()??"*");}requestAds(e={}){if(typeof window>"u"||window.parent===window)return this.debug("requestAds skipped; standalone mode detected"),Promise.resolve(false);if(this.adsRequestInFlight)return this.debug("requestAds skipped; another ad request is already in flight"),Promise.resolve(false);let t=this.resolveParentOrigin()??"*",s=`ads-${Date.now()}-${++this.requestAdsSequence}`,n=e.timeoutMs??K;return this.adsRequestInFlight=true,this.adsRequestsSent+=1,this.lastAdsRequestAt=Date.now(),this.debug("requesting rewarded ad from parent",{requestId:s,targetOrigin:t,gameId:this.getGameId()}),new Promise(r=>{let o=setTimeout(()=>{this.pendingAdsRequests.delete(s),this.adsRequestInFlight=false,this.debug("requestAds timed out",{requestId:s,timeoutMs:n}),r(false);},n);this.pendingAdsRequests.set(s,{resolve:r,timer:o}),window.parent.postMessage({type:"LOOPLAY_REQUEST_ADS",requestId:s,gameId:this.getGameId()},t);})}init(){if(this.initialized||typeof window>"u")return;this.initialized=true,this.detectIntegrationOnce();let e=window.parent!==window;if(this.debug("auth listener initialized",{isIframe:e,parentOrigin:this.resolveParentOrigin()}),!e){this.activateAnonymousMode();return}let t=this.resolveParentOrigin();t||console.warn("[LooplaySDK] LooplayIframeAuth could not resolve a parent origin to verify postMessage against (document.referrer is empty). Auth messages from window.parent will be accepted regardless of origin. Pass `parentOrigin` explicitly to harden this."),this.messageListener=s=>{if(s.source===window.parent){if(t&&s.origin!==t){this.debug("ignored message from unexpected origin",{expectedOrigin:t,receivedOrigin:s.origin});return}this.handleIncomingMessage(s.data,s.origin);}},window.addEventListener("message",this.messageListener),this.anonymousFallbackTimer=setTimeout(()=>{this.state.jwt||this.activateAnonymousMode();},this.options.anonymousFallbackTimeoutMs??_),this.requestAuth();}dispose(){typeof window<"u"&&this.messageListener&&window.removeEventListener("message",this.messageListener),this.anonymousFallbackTimer!==null&&clearTimeout(this.anonymousFallbackTimer);for(let e of this.pendingAdsRequests.values())e.timer!==null&&clearTimeout(e.timer),e.resolve(false);this.pendingAdsRequests.clear(),this.messageListener=null,this.anonymousFallbackTimer=null,this.initialized=false,this.lifecycleTrackingInitialized=false,this.integrationDetectionKeys.clear(),this.listeners.clear();}getClient(){if(this.client)return this.client;let e=this.getApiUrl();return this.debug("creating sdk ApiClient",{baseUrl:e}),this.client=new y({baseUrl:e??void 0,getAccessToken:async()=>this.getJwt()??void 0,getAnonymousId:()=>this.getAnonymousId()??void 0}),this.client}trackView(){let e=this.getGameId();return !this.canTrack()||!e?(this.debug("trackView skipped; auth is not ready",{hasGameId:!!e}),Promise.resolve(false)):(this.debug("trackView dispatched",{gameId:e}),this.getClient().trackView(e))}startPlaySession(){return this.getClient().startPlaySession()}trackPlay(e){let t=this.getGameId();return !this.canTrack()||!t?(this.debug("trackPlay skipped; auth is not ready",{hasGameId:!!t}),Promise.resolve(false)):(this.debug("trackPlay dispatched",{gameId:t,playTimeSeconds:e}),this.getClient().trackPlay(t,e))}trackMatch(e,t){let s=this.getGameId();if(!this.canTrack()||!s)return this.debug("trackMatch skipped; auth is not ready",{matchId:e}),Promise.resolve(false);this.debug("trackMatch dispatched",{gameId:s,matchId:e,...t});let n=this.getClient().trackMatch(s,{matchId:e,matchDurationSeconds:t.durationSeconds,isCompleted:t.isCompleted,isWin:t.isWin});return n.then(r=>{r&&this.recordAutoRequestAdsActivity();}).catch(()=>{}),n}emitGameEvent(e,t){let s=this.getGameId();return !this.canTrack()||!s?(this.debug("emitGameEvent skipped; auth is not ready",{actionCode:e}),Promise.resolve(null)):(this.debug("emitGameEvent dispatched",{gameId:s,actionCode:e,...t}),this.getClient().emit(s,e,t))}initLifecycleTracking(){this.lifecycleTrackingInitialized||typeof window>"u"||(this.lifecycleTrackingInitialized=true,this.debug("lifecycle tracking initialized"),this.subscribe(()=>{let e=this.getTrackingKey();!e||this.lastGameStartedKey===e||(this.lastGameStartedKey=e,this.debug("auto GAME_STARTED dispatch"),this.emitGameEvent("GAME_STARTED"));}));}getTrackingKey(){let e=this.getGameId(),t=this.getApiUrl(),s=this.state.jwt??this.state.anonymousId;return !e||!t||!s?null:`${t}
|
|
4
4
|
${e}
|
|
5
|
-
${s}`}activateAnonymousMode(){if(this.state.anonymousId)return;let e=this.options.anonymousIdStorageKey??C,t=z(e)??N();V(e,t),this.lastGameStartedKey=null,this.setState({...this.state,anonymousId:t,receivedAt:Date.now()}),this.debug("anonymous tracking mode active",{anonymousId:t});}handleAuthMessage(e,t){this.anonymousFallbackTimer!==null&&(clearTimeout(this.anonymousFallbackTimer),this.anonymousFallbackTimer=null);let s=
|
|
6
|
-
${e}`;if(!this.integrationDetectionKeys.has(s)){this.integrationDetectionKeys.add(s);try{await this.getClient().detectIntegration(e),this.debug("integration detected",{gameId:e,apiUrl:t});}catch(n){this.integrationDetectionKeys.delete(s),this.debug("integration detection failed",{gameId:e,apiUrl:t,error:n instanceof Error?n.message:String(n)});}}}resolveParentOrigin(){if(this.options.parentOrigin)
|
|
5
|
+
${s}`}activateAnonymousMode(){if(this.state.anonymousId)return;let e=this.options.anonymousIdStorageKey??C,t=z(e)??N();V(e,t),this.lastGameStartedKey=null,this.setState({...this.state,anonymousId:t,receivedAt:Date.now()}),this.debug("anonymous tracking mode active",{anonymousId:t});}handleAuthMessage(e,t){this.anonymousFallbackTimer!==null&&(clearTimeout(this.anonymousFallbackTimer),this.anonymousFallbackTimer=null);let s=g(e.jwt),n=g(e.gameId),r=g(e.apiUrl),o=n??this.getGameId(),a=r??this.getApiUrl();if(!o||!a){this.lastGameStartedKey=null,this.setState({...this.state,jwt:null,gameId:null,apiUrl:null,origin:t,receivedAt:Date.now()}),this.debug("auth message missing game identity; falling back to anonymous tracking"),this.activateAnonymousMode();return}if(!s){this.lastGameStartedKey=null,this.setState({...this.state,jwt:null,gameId:o,apiUrl:a,origin:t,receivedAt:Date.now()}),this.debug("auth message missing jwt; falling back to anonymous tracking",{gameId:o,apiUrl:a}),this.activateAnonymousMode();return}this.lastGameStartedKey=null,this.setState({jwt:s,gameId:n,apiUrl:r,anonymousId:null,origin:t,receivedAt:Date.now()});}handleRequestAdsResult(e){if(e.type!=="LOOPLAY_ADS_WATCHED")return;let t=g(e.requestId);if(!t)return;let s=this.pendingAdsRequests.get(t);s&&(this.pendingAdsRequests.delete(t),s.timer!==null&&clearTimeout(s.timer),this.adsRequestInFlight=false,this.debug("requestAds watched message received",{requestId:t}),s.resolve(true));}handleRequestAdsUnavailable(e){if(e.type!=="LOOPLAY_ADS_UNAVAILABLE")return;let t=g(e.requestId);if(!t)return;let s=this.pendingAdsRequests.get(t);s&&(this.pendingAdsRequests.delete(t),s.timer!==null&&clearTimeout(s.timer),this.adsRequestInFlight=false,this.debug("requestAds unavailable message received",{requestId:t}),s.resolve(false));}handleIncomingMessage(e,t){if(H(e)){if(e.type==="LOOPLAY_AUTH"){this.handleAuthMessage(e,t);return}if(e.type==="LOOPLAY_ADS_WATCHED"){this.handleRequestAdsResult(e);return}if(e.type==="LOOPLAY_ADS_UNAVAILABLE"){this.handleRequestAdsUnavailable(e);return}}}setState(e){let t=this.getApiUrl();this.state=e,this.getApiUrl()!==t&&(this.client=null),this.debug("auth state updated",{gameId:this.getGameId(),apiUrl:this.getApiUrl(),origin:e.origin,hasJwt:!!e.jwt,hasAnonymousId:!!e.anonymousId}),this.listeners.forEach(s=>s(e)),this.detectIntegrationOnce();}async detectIntegrationOnce(){let e=this.getGameId(),t=this.getApiUrl();if(!e||!t)return;let s=`${t}
|
|
6
|
+
${e}`;if(!this.integrationDetectionKeys.has(s)){this.integrationDetectionKeys.add(s);try{await this.getClient().detectIntegration(e),this.debug("integration detected",{gameId:e,apiUrl:t});}catch(n){this.integrationDetectionKeys.delete(s),this.debug("integration detection failed",{gameId:e,apiUrl:t,error:n instanceof Error?n.message:String(n)});}}}resolveParentOrigin(){if(this.options.parentOrigin){let t=g(this.options.parentOrigin);if(t)return t}let e=R();if(e)return e;if(typeof document>"u"||!document.referrer)return null;try{return new URL(document.referrer).origin}catch{return null}}debug(e,t){this.options.onDebug?.(e,t);}recordAutoRequestAdsActivity(){this.autoAdsActionCount+=1;let e=this.options.autoRequestAds;if(!e?.enabled||this.adsRequestInFlight||!this.canTrack())return;let t=Date.now();if(e.cooldownMs&&t-this.lastAdsRequestAt<e.cooldownMs||e.maxRequestsPerSession&&this.adsRequestsSent>=e.maxRequestsPerSession)return;let s=e.afterActionCount??0;if(!(s>0&&this.autoAdsActionCount%s===0))return;let r=e.chance??1;if(r<=0||Math.random()>r){this.debug("auto requestAds skipped by chance",{actionCount:this.autoAdsActionCount,chance:r});return}this.debug("auto requestAds triggered",{actionCount:this.autoAdsActionCount}),this.requestAds();}};exports.ApiClient=y;exports.BrowserLocalStorageAuthStorage=b;exports.DEFAULT_API_URL=d;exports.HttpClient=A;exports.HttpError=v;exports.LOOPLAY_SDK_VERSION=L;exports.LooplayAuth=S;exports.LooplayIframeAuth=E;exports.LooplaySDK=O;exports.LooplaySDKError=l;exports.MemoryAuthStorage=k;exports.MissingAuthError=x;exports.MissingBaseUrlError=u;exports.NotAuthenticatedError=f;exports.NotInitializedError=c;exports.ServiceClient=p;exports.TelegramAuthProvider=q;exports.resolveEnvApiUrl=h;exports.resolveEnvParentOrigin=R;return exports;})({});//# sourceMappingURL=looplay-sdk.min.js.map
|
|
7
7
|
//# sourceMappingURL=looplay-sdk.min.js.map
|