@tiun/sdk
Version:
tiun SDK for payments and subscriptions
2 lines (1 loc) • 8.58 kB
JavaScript
(function(o,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(o=typeof globalThis<"u"?globalThis:o||self,s(o.tiun={}))})(this,function(o){"use strict";var O=Object.defineProperty;var $=(o,s,l)=>s in o?O(o,s,{enumerable:!0,configurable:!0,writable:!0,value:l}):o[s]=l;var d=(o,s,l)=>($(o,typeof s!="symbol"?s+"":s,l),l);const s=["en","de","fr"],l=new Set;function p(i){if(i==null||i==="")return"en";const e=i.trim().toLowerCase();return s.includes(e)?e:(l.has(e)||(l.add(e),console.warn(`[tiun] Unsupported language "${i}" passed to tiun.init(). Falling back to "en". Supported languages: ${s.join(", ")}.`)),"en")}const y=["formal","informal"],T=new Set;function v(i){if(i==null||i==="")return;const e=i.trim().toLowerCase();if(y.includes(e))return e;T.has(e)||(T.add(e),console.warn(`[tiun] Unsupported tone "${i}" passed to tiun.init(). Falling back to the default ("formal"). Supported tones: ${y.join(", ")}.`))}const S="https://api.tiun.live/live_api",U="https://api-sandbox.tiun.live/live_api";function w(i,e){return e||(i?U:S)}function C(i){typeof window<"u"&&(window.__TIUN_CONFIG__=i)}function b(){typeof window<"u"&&delete window.__TIUN_CONFIG__}class N{constructor(){d(this,"config",{});d(this,"initialized",!1);d(this,"ready",!1);d(this,"readyPromise",null);d(this,"readyResolve",null);d(this,"eventListeners",new Map);d(this,"boundMessageHandler",null);d(this,"_isAuthenticated",!1);d(this,"_user",null);d(this,"pendingTokenResolve",null);d(this,"pendingTokenTimeout",null)}init(e={}){return typeof window>"u"?(this.log("SSR detected, skipping initialization"),this):this.initialized?(this.log("Already initialized, updating config"),this.config={...this.config,...e},this.setRuntimeConfigFromTiunConfig(e),this):(this.config=e,this.initialized=!0,this.readyPromise=new Promise(t=>{this.readyResolve=t}),this.boundMessageHandler=this.handleMessage.bind(this),window.addEventListener("message",this.boundMessageHandler),this.setRuntimeConfigFromTiunConfig(e),this.log("SDK initialized",e.snippetId?"(NPM mode)":"(legacy mode)"),e.snippetId&&window.dispatchEvent(new CustomEvent("tiun:config-ready",{detail:e})),this)}setRuntimeConfigFromTiunConfig(e){const t=e.baseUrl,n={snippetId:e.snippetId,baseUrl:w(e.sandbox,t),language:p(e.language),tone:v(e.tone),debug:e.debug};C(n)}async start(){this.ensureInitialized(),await this.waitForReady(),this.emit("TIUN_START"),this.log("Start triggered")}async checkout(e={}){this.ensureInitialized(),await this.waitForReady(),this.emit("TIUN_CHECKOUT",{productId:e.productId}),this.log("Checkout triggered",e)}async setContent(e){this.ensureInitialized(),await this.waitForReady(),this.emit("TIUN_UPDATE_CONTENT",{contentId:e.contentId,contentType:e.type,mediaType:e.mediaType||"text"}),this.log("Content updated",e)}async login(){this.ensureInitialized(),await this.waitForReady(),this.emit("TIUN_LOGIN"),this.log("Login triggered")}logout(){this.ensureInitialized(),this.emit("TIUN_LOGOUT"),this.log("Logout triggered")}getUser(){return{isAuthenticated:this._isAuthenticated,user:this._user}}async getUserVerificationToken(){return this._isAuthenticated?this.requestTokenFromSnippet():null}on(e,t){return this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t),()=>{var n;(n=this.eventListeners.get(e))==null||n.delete(t)}}once(e,t){const n=this.on(e,r=>{n(),t(r)});return n}off(e){e?this.eventListeners.delete(e):this.eventListeners.clear()}async waitForReady(){if(!this.ready)return this.readyPromise||(this.readyPromise=new Promise(e=>{this.readyResolve=e})),this.readyPromise}destroy(){typeof window>"u"||(this.boundMessageHandler&&(window.removeEventListener("message",this.boundMessageHandler),this.boundMessageHandler=null),this.eventListeners.clear(),b(),this.handleVerificationTokenResponse(null),this.initialized=!1,this.ready=!1,this.readyPromise=null,this.readyResolve=null,this.config={},this._isAuthenticated=!1,this._user=null,this.log("SDK destroyed"))}get version(){return"0.9.1"}get isInitialized(){return this.initialized}get isReady(){return this.ready}get isBrowser(){return typeof window<"u"}get isAuthenticated(){return this._isAuthenticated}get user(){return this._user}requestTokenFromSnippet(){return typeof window>"u"?Promise.resolve(null):(this.handleVerificationTokenResponse(null),new Promise(e=>{this.pendingTokenResolve=e,this.pendingTokenTimeout=setTimeout(()=>{this.pendingTokenResolve=null,e(null)},5e3),this.emit("TIUN_GET_VERIFICATION_TOKEN")}))}handleVerificationTokenResponse(e){this.pendingTokenResolve&&(this.pendingTokenTimeout&&(clearTimeout(this.pendingTokenTimeout),this.pendingTokenTimeout=null),this.pendingTokenResolve(e),this.pendingTokenResolve=null)}ensureInitialized(){this.initialized||this.init()}handleMessage(e){var n,r,a,u,c,g;if(typeof window<"u"&&e.origin!==window.location.origin)return;const t=e.data;if((t==null?void 0:t.type)==="TIUN_EVENT")switch(this.log("Received event",t.content,t),t.content){case"TIUN_SNIPPET_INITIALIZED":this.handleReady();break;case"TIUN_SHOW_PAYWALL":this.triggerEvent("paywallShow",{isConnected:t.isConnected??!1}),(r=(n=this.config).onPaywallShow)==null||r.call(n,{isConnected:t.isConnected??!1});break;case"TIUN_HIDE_PAYWALL":this.triggerEvent("paywallHide",{sessionId:t.sessionId??"",isConnected:t.isConnected??!0}),(u=(a=this.config).onPaywallHide)==null||u.call(a,{sessionId:t.sessionId??"",isConnected:t.isConnected??!0});break;case"TIUN_ERROR":t.error&&(this.triggerEvent("error",t.error),(g=(c=this.config).onError)==null||g.call(c,t.error));break;case"TIUN_USER_CHANGE":this.handleUserChange(t);break;case"TIUN_VERIFICATION_TOKEN":this.handleVerificationTokenResponse(t.token??null);break}}handleReady(){var e,t,n;this.ready||(this.ready=!0,(e=this.readyResolve)==null||e.call(this),this.triggerEvent("ready",void 0),(n=(t=this.config).onReady)==null||n.call(t),this.log("Snippet ready"))}triggerEvent(e,t){const n=this.eventListeners.get(e);n&&n.forEach(r=>{try{r(t)}catch(a){console.error(`[Tiun] Error in ${e} listener:`,a)}})}handleUserChange(e){var r,a,u,c,g,E;const t=e.userEvent??"update";this._isAuthenticated=e.isAuthenticated??!1,this._user=e.user??null;const n={event:t,isAuthenticated:this._isAuthenticated,user:this._user};if(this.triggerEvent("userChange",n),(a=(r=this.config).onUserChange)==null||a.call(r,n),t==="login"&&this._user){const R={user:this._user};this.triggerEvent("login",R),(c=(u=this.config).onLogin)==null||c.call(u,R)}t==="logout"&&(this.triggerEvent("logout",void 0),(E=(g=this.config).onLogout)==null||E.call(g))}emit(e,t={}){if(typeof window>"u"){this.log("Cannot emit in SSR");return}window.postMessage({type:"TIUN_EVENT",content:e,...t},window.location.origin)}log(...e){this.config.debug&&console.log("[tiun]",...e)}}const h=new N,m="script[data-tiun-snippet][data-snippet-id]",_="link[data-tiun-snippet][data-snippet-id]";function k(i){const e=new URLSearchParams;i.language!=null&&i.language!==""&&e.set("language",p(i.language)),i.tone==="formal"&&e.set("formal","true");const t=e.toString();return t?`?${t}`:""}function L(i,e,t){const n=i.replace(/\/$/,""),r=k(t);return{scriptUrl:`${n}/v2/snippets/${e}/background_js${r}`,cssUrl:`${n}/v2/snippets/${e}/background_css${r}`}}function I(i){if(typeof document>"u")return!1;const e=document.querySelector(`${m}[data-snippet-id="${i}"]`),t=document.querySelector(`${_}[data-snippet-id="${i}"]`);return!!e||!!t}function A(){return typeof document>"u"?!1:!!document.querySelector(`${m}, ${_}`)}let f=!1;function P(i,e,t){if(!(typeof document>"u")&&!I(e)&&!f){f=!0;try{const{scriptUrl:n,cssUrl:r}=L(i,e,t),a=document.createElement("link");a.rel="stylesheet",a.href=r,a.setAttribute("data-tiun-snippet",""),a.setAttribute("data-snippet-id",e),document.head.appendChild(a);const u=document.createElement("script");u.src=n,u.async=!0,u.setAttribute("data-tiun-snippet",""),u.setAttribute("data-snippet-id",e),document.head.appendChild(u)}finally{f=!1}}}const z=h.init.bind(h);h.init=function(i={}){const e=z(i);if(typeof window<"u")if(i.snippetId){if(!I(i.snippetId)){const t=i.baseUrl,n=w(i.sandbox,t);P(n,i.snippetId,{language:i.language,tone:i.tone})}}else A()||console.warn(`[tiun] No "snippetId" was provided to tiun.init(), so the snippet cannot load. Pass it as tiun.init({ snippetId: 'your-id' }). (If you use the legacy script-tag integration, you can ignore this.)`);return e},typeof window<"u"&&(window.tiun=h),o.default=h,o.tiun=h,Object.defineProperties(o,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});