UNPKG

@tiun/sdk

Version:

tiun SDK for payments and subscriptions

2 lines (1 loc) • 10.8 kB
(function(o,a){typeof exports=="object"&&typeof module<"u"?a(exports):typeof define=="function"&&define.amd?define(["exports"],a):(o=typeof globalThis<"u"?globalThis:o||self,a(o.tiun={}))})(this,function(o){"use strict";var H=Object.defineProperty;var j=(o,a,c)=>a in o?H(o,a,{enumerable:!0,configurable:!0,writable:!0,value:c}):o[a]=c;var u=(o,a,c)=>(j(o,typeof a!="symbol"?a+"":a,c),c);const a=["en","de","fr"],c=new Set;function y(i){if(i==null||i==="")return"en";const e=i.trim().toLowerCase();return a.includes(e)?e:(c.has(e)||(c.add(e),console.warn(`[tiun] Unsupported language "${i}" passed to tiun.init(). Falling back to "en". Supported languages: ${a.join(", ")}.`)),"en")}const m=["formal","informal"],T=new Set;function P(i){if(i==null||i==="")return;const e=i.trim().toLowerCase();if(m.includes(e))return e;T.has(e)||(T.add(e),console.warn(`[tiun] Unsupported tone "${i}" passed to tiun.init(). Falling back to the snippet default ("informal"). Supported tones: ${m.join(", ")}.`))}const _=["light","dark","auto"],w=new Set;function I(i){if(i==null||i==="")return;const e=i.trim().toLowerCase();if(_.includes(e))return e;w.has(e)||(w.add(e),console.warn(`[tiun] Unsupported appearance "${i}". Supported appearances: ${_.join(", ")}.`))}const v="https://api.tiun.live/live_api",A="https://api-sandbox.tiun.live/live_api";function S(i,e){return e||(i?A:v)}function N(i){typeof window<"u"&&(window.__TIUN_CONFIG__=i)}function b(){typeof window<"u"&&delete window.__TIUN_CONFIG__}const L=1e4;class O{constructor(e){u(this,"pending",new Map);this.send=e}request(e,t={},{timeoutMs:n=L,whenReady:s}={}){const r=`req_${Math.random().toString(36).slice(2)}_${Date.now()}`;return new Promise((d,h)=>{const l={resolve:d,reject:h};this.pending.set(r,l);const g=()=>{this.pending.get(r)===l&&(l.timer=setTimeout(()=>{this.pending.delete(r),h({code:"timeout",message:`${e} timed out`})},n),this.send(e,{...t,requestId:r}))};s?s.then(g):g()})}settle(e,t,n){const s=e?this.pending.get(e):void 0;s&&(clearTimeout(s.timer),this.pending.delete(e),n?s.reject(n):s.resolve(t))}rejectAll(e){this.pending.forEach(({reject:t,timer:n})=>{clearTimeout(n),t(e)}),this.pending.clear()}}const z=5e3;class q{constructor(){u(this,"config",{});u(this,"initialized",!1);u(this,"ready",!1);u(this,"readyPromise",null);u(this,"readyResolve",null);u(this,"readyReplayTimer",null);u(this,"eventListeners",new Map);u(this,"boundMessageHandler",null);u(this,"requests",new O((e,t)=>this.emit(e,t)));u(this,"_isAuthenticated",!1);u(this,"_user",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),e.appearance!==void 0&&this.setAppearance(e.appearance),this):(this.config={...e,appearance:e.appearance??this.config.appearance},e=this.config,this.initialized=!0,this.readyPromise||(this.readyPromise=new Promise(t=>{this.readyResolve=t})),this.boundMessageHandler=this.handleMessage.bind(this),window.addEventListener("message",this.boundMessageHandler),this.ready&&(this.readyReplayTimer=setTimeout(()=>{var t,n;this.readyReplayTimer=null,this.triggerEvent("ready",void 0),(n=(t=this.config).onReady)==null||n.call(t),this.log("Snippet ready (re-initialized)")},0)),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:S(e.sandbox,t),language:y(e.language),tone:P(e.tone),appearance:I(e.appearance),debug:e.debug};N(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,referenceId:e.referenceId||void 0}),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)}setAppearance(e){const t=I(e);if(!t||(this.config.appearance=t,!this.initialized||typeof window>"u"))return;const n=window.__TIUN_CONFIG__;n&&(n.appearance=t),this.emit("TIUN_SET_APPEARANCE",{appearance:t}),this.log("Appearance set",t)}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.requests.request("TIUN_GET_VERIFICATION_TOKEN",{},{timeoutMs:z}).catch(()=>null):null}listProducts(){return this.requestProductFromSnippet("TIUN_LIST_PRODUCTS")}getProduct(e){return e?this.requestProductFromSnippet("TIUN_GET_PRODUCT",{productId:e}):this.rejectInvalidProductId()}listProductAccess(){return this.requestProductFromSnippet("TIUN_LIST_PRODUCT_ACCESS")}checkProductAccess(e,t={}){return e?this.requestProductFromSnippet("TIUN_CHECK_PRODUCT_ACCESS",{productId:e,referenceId:t.referenceId||void 0}):this.rejectInvalidProductId()}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,s=>{n(),t(s)});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.requests.rejectAll({code:"destroyed",message:"tiun SDK was destroyed"}),this.readyReplayTimer&&(clearTimeout(this.readyReplayTimer),this.readyReplayTimer=null),this.initialized=!1,this.ready||(this.readyPromise=null,this.readyResolve=null),this.config={},this._isAuthenticated=!1,this._user=null,this.log("SDK destroyed"))}get version(){return"0.12.0"}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}async requestProductFromSnippet(e,t={}){if(typeof window>"u")throw{code:"ssr",message:"tiun is not available during SSR"};return this.ensureInitialized(),this.log("Product request",e,t),this.requests.request(e,t,{whenReady:this.waitForReady()})}rejectInvalidProductId(){return Promise.reject({code:"invalid_argument",message:"productId is required"})}ensureInitialized(){this.initialized||this.init()}handleMessage(e){var n,s,r,d,h,l;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}),(s=(n=this.config).onPaywallShow)==null||s.call(n,{isConnected:t.isConnected??!1});break;case"TIUN_HIDE_PAYWALL":this.triggerEvent("paywallHide",{sessionId:t.sessionId??"",isConnected:t.isConnected??!0}),(d=(r=this.config).onPaywallHide)==null||d.call(r,{sessionId:t.sessionId??"",isConnected:t.isConnected??!0});break;case"TIUN_ERROR":t.error&&(this.triggerEvent("error",t.error),(l=(h=this.config).onError)==null||l.call(h,t.error));break;case"TIUN_USER_CHANGE":this.handleUserChange(t);break;case"TIUN_VERIFICATION_TOKEN":this.requests.settle(t.requestId,t.token??null);break;case"TIUN_PRODUCT_RESULT":this.requests.settle(t.requestId,t.result,t.error);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(s=>{try{s(t)}catch(r){console.error(`[Tiun] Error in ${e} listener:`,r)}})}handleUserChange(e){var s,r,d,h,l,g;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),(r=(s=this.config).onUserChange)==null||r.call(s,n),t==="login"&&this._user){const R={user:this._user};this.triggerEvent("login",R),(h=(d=this.config).onLogin)==null||h.call(d,R)}t==="logout"&&(this.triggerEvent("logout",void 0),(g=(l=this.config).onLogout)==null||g.call(l))}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 p=new q,E="script[data-tiun-snippet][data-snippet-id]",U="link[data-tiun-snippet][data-snippet-id]";function F(i){const e=new URLSearchParams;i.language!=null&&i.language!==""&&e.set("language",y(i.language)),i.tone==="formal"&&e.set("formal","true");const t=e.toString();return t?`?${t}`:""}function $(i,e,t){const n=i.replace(/\/$/,""),s=F(t);return{scriptUrl:`${n}/v2/snippets/${e}/background_js${s}`,cssUrl:`${n}/v2/snippets/${e}/background_css${s}`}}function C(i){if(typeof document>"u")return!1;const e=document.querySelector(`${E}[data-snippet-id="${i}"]`),t=document.querySelector(`${U}[data-snippet-id="${i}"]`);return!!e||!!t}function k(){return typeof document>"u"?!1:!!document.querySelector(`${E}, ${U}`)}let f=!1;function M(i,e,t){if(!(typeof document>"u")&&!C(e)&&!f){f=!0;try{const{scriptUrl:n,cssUrl:s}=$(i,e,t),r=document.createElement("link");r.rel="stylesheet",r.href=s,r.setAttribute("data-tiun-snippet",""),r.setAttribute("data-snippet-id",e),document.head.appendChild(r);const d=document.createElement("script");d.src=n,d.async=!0,d.setAttribute("data-tiun-snippet",""),d.setAttribute("data-snippet-id",e),document.head.appendChild(d)}finally{f=!1}}}const D=p.init.bind(p);p.init=function(i={}){const e=D(i);if(typeof window<"u")if(i.snippetId){if(!C(i.snippetId)){const t=i.baseUrl,n=S(i.sandbox,t);M(n,i.snippetId,{language:i.language,tone:i.tone})}}else k()||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=p),o.default=p,o.tiun=p,Object.defineProperties(o,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});