@dropp.cc/payment-sdk 1.0.13 โ†’ 1.0.14

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.
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).DroppPaymentSDK={})}(this,function(e){"use strict";const t={READY:"DROPP_SDK_READY",PAYMENT_SUCCESS:"PAYMENT_SUCCESS",PAYMENT_FAILED:"PAYMENT_FAILED",PAYMENT_CANCELLED:"PAYMENT_CANCELLED",ACCOUNT_STATUS:"ACCOUNT_STATUS",CLOSE_WEBVIEW:"CLOSE_WEBVIEW",AUTO_CLOSE_WEBVIEW:"AUTO_CLOSE_WEBVIEW",PAYMENT_PAGE_LOADED:"PAYMENT_PAGE_LOADED",PAGE_LOADED:"PAGE_LOADED"},s="DROPP_SDK_INIT",n="DROPP_SDK_CLOSE",i={PRODUCTION:"production",QA:"qa",SANDBOX:"sandbox"},o={[i.PRODUCTION]:"https://wv.dropp.cc",[i.QA]:"https://wv.qa.dropp.cc",[i.SANDBOX]:"https://wv.sandbox.dropp.cc"},r={[i.PRODUCTION]:["https://wv.dropp.cc"],[i.QA]:["https://wv.qa.dropp.cc"],[i.SANDBOX]:["https://wv.sandbox.dropp.cc"]},a=3e4,l=6e5,c={STANDARD:"standard",PREAUTH:"preauth",RECURRING:"recurring"},d="INIT_TIMEOUT",u="PAYMENT_TIMEOUT",p="INVALID_CONFIG",h="ALREADY_OPEN",m="UNKNOWN_ERROR",g="1.0.2";const y=new class{constructor(e,t={}){this.environment=e,this.forceEnabled=!!t.enabled,this.enabled=this._shouldEnableLogging()}_shouldEnableLogging(){return this.forceEnabled}setEnvironment(e,t={}){this.environment=e,"boolean"==typeof t.enabled&&(this.forceEnabled=t.enabled),this.enabled=this._shouldEnableLogging()}setEnabled(e){this.forceEnabled=!!e,this.enabled=this._shouldEnableLogging()}log(...e){this.enabled&&console.log(...e)}warn(...e){this.enabled&&console.warn(...e)}error(...e){this.enabled&&console.error(...e)}debug(...e){this.enabled&&console.debug(...e)}info(...e){this.enabled&&console.info(...e)}}("qa",{enabled:!1}),f=["USD","HBAR","USDC"],S=["NONE","HALF_HOURLY","HOURLY","DAILY","WEEKLY","MONTHLY","YEARLY"],D=[c.STANDARD,c.PREAUTH,c.RECURRING];function b(e,t={}){const{isProduction:s=!1,allowLocalCallbacksInNonProd:n=!1}=t;if("string"!=typeof e||!e.trim())return!1;try{const t=new URL(e.trim()),i="https:"===t.protocol;if(!("http:"===t.protocol)&&!i)return!1;return function(e){if(!e)return!1;const t=e.trim().toLowerCase();if("localhost"===t||"127.0.0.1"===t||"::1"===t||t.endsWith(".local"))return!0;if(!/^(\d{1,3}\.){3}\d{1,3}$/.test(t))return!1;const s=t.split(".").map(e=>Number(e));if(s.some(e=>Number.isNaN(e)||e<0||e>255))return!1;const[n,i]=s;return 10===n||127===n||172===n&&i>=16&&i<=31||192===n&&168===i||169===n&&254===i}(t.hostname)?!s&&n:!s||i}catch{return!1}}function w(e={},t={}){const s=[],n=e.paymentType||c.STANDARD,i="production"===(t.environment||"").toLowerCase(),o=!!t.allowLocalCallbacksInNonProd,r="string"==typeof e.currency?e.currency.trim().toUpperCase():"";if(D.includes(n)||s.push(`paymentType must be one of: ${D.join(", ")}`),void 0===e.amount||null===e.amount||""===e.amount?s.push("amount is required"):function(e){const t="number"==typeof e?e:parseFloat(e);return"number"==typeof t&&!Number.isNaN(t)&&t>0}(e.amount)||s.push("amount must be a positive number"),e.currency&&"string"==typeof e.currency&&e.currency.trim()?f.includes(r)||s.push(`currency must be one of: ${f.join(", ")}`):s.push("currency is required"),e.itemName&&"string"==typeof e.itemName&&e.itemName.trim()||s.push("itemName is required"),n===c.PREAUTH&&(r&&"USD"!==r&&s.push("currency must be USD for preauth payments"),e.callbackUrl&&String(e.callbackUrl).trim()?b(e.callbackUrl,{isProduction:i,allowLocalCallbacksInNonProd:o})||s.push(i?"callbackUrl must be HTTPS in production and cannot target loopback/private hosts":"callbackUrl must be a valid HTTP/HTTPS URL and cannot target loopback/private hosts unless explicitly enabled"):s.push("callbackUrl (signing URL) is required for preauth payments"),void 0===e.authHoldTimeInSeconds||null===e.authHoldTimeInSeconds||""===e.authHoldTimeInSeconds?s.push("authHoldTimeInSeconds is required for preauth payments"):function(e){const t="number"==typeof e?e:parseInt(e,10);return Number.isInteger(t)&&t>0}(e.authHoldTimeInSeconds)||s.push("authHoldTimeInSeconds must be a positive integer (seconds)")),n===c.RECURRING){e.callbackUrl&&String(e.callbackUrl).trim()?b(e.callbackUrl,{isProduction:i,allowLocalCallbacksInNonProd:o})||s.push(i?"callbackUrl must be HTTPS in production and cannot target loopback/private hosts":"callbackUrl must be a valid HTTP/HTTPS URL and cannot target loopback/private hosts unless explicitly enabled"):s.push("callbackUrl (signing URL) is required for recurring payments");const t=(e.frequency||e.recurringInterval||"").toString().trim().toUpperCase();t?S.includes(t)||s.push(`frequency must be one of: ${S.join(", ")}`):s.push("frequency is required for recurring payments"),e.recurringEndDate&&String(e.recurringEndDate).trim()?!function(e){if("string"!=typeof e||!e.trim())return!1;const t=new Date(e.trim());return!Number.isNaN(t.getTime())}(e.recurringEndDate)?s.push("recurringEndDate must be a valid ISO date-time string"):new Date(e.recurringEndDate.trim())<=new Date&&s.push("recurringEndDate must be in the future"):s.push("recurringEndDate (expiry) is required for recurring payments")}return{valid:0===s.length,errors:s}}function T(e,t,s={}){return{code:e,message:t,details:s,timestamp:(new Date).toISOString(),toString(){return this.message||"Dropp SDK error"}}}class v{constructor(e,t,s=null){this.environment=e,this.onMessage=t,this.sessionId=`dropp-sdk-${Date.now()}-${Math.random().toString(36).substring(2,15)}`,y.log("[MessageHandler] Session initialized"),this.iframe=null,this.allowedOrigins=s?.length>0?s:r[e]||[],this.messageListener=null,this.pendingMessages=new Map}init(e){this.iframe=e,this.messageListener=this._handleMessage.bind(this),window.addEventListener("message",this.messageListener)}destroy(){this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.iframe=null,this.pendingMessages.clear()}_handleMessage(e){if(y.log("[MessageHandler] Received postMessage event"),e.source===window)return void y.log("[MessageHandler] Ignoring message from self");if(!this._validateOrigin(e.origin))return void y.warn("[Dropp SDK] Rejected message from untrusted origin:",e.origin);if(!this.iframe||e.source!==this.iframe.contentWindow)return void y.warn("[Dropp SDK] Rejected message from unexpected source",{eventOrigin:e.origin});const t=e.data;this._validateMessageStructure(t)?t.sessionId&&t.sessionId!==this.sessionId?y.warn("[Dropp SDK] Rejected message with invalid session ID"):(y.log("[MessageHandler] Message passed validation"),this._processMessage(t)):y.warn("[Dropp SDK] Rejected message with invalid structure")}_validateOrigin(e){return!(!e.startsWith("http://localhost:")&&!e.startsWith("http://127.0.0.1:"))||this.allowedOrigins.includes(e)}_validateMessageStructure(e){if(!e||"object"!=typeof e)return!1;if(!e.type||"string"!=typeof e.type)return!1;return!!Object.values(t).includes(e.type)&&!(e.type!==t.ACCOUNT_STATUS&&!e.timestamp)}_processMessage(e){y.log("[Dropp SDK] Received message:",e.type),this.onMessage&&this.onMessage(e)}sendToPaymentApp(e,t={}){if(!this.iframe||!this.iframe.contentWindow)return y.error("[Dropp SDK] Cannot send message: iframe not ready"),!1;const s={type:e,data:t,sessionId:this.sessionId,timestamp:(new Date).toISOString(),sdkVersion:"1.0.0"},n=this.allowedOrigins[0]||"*";try{return this.iframe.contentWindow.postMessage(s,n),y.log("[Dropp SDK] Sent message:",e),!0}catch(e){return y.error("[Dropp SDK] Error sending message:",e),!1}}sendInit(e){return this.sendToPaymentApp(s,{mode:"sdk",config:e})}sendClose(){return this.sendToPaymentApp(n,{})}getSessionId(){return this.sessionId}}class E{constructor(e){this.onClose=e,this.overlay=null,this.container=null,this.iframe=null,this.closeButton=null,this.isOpen=!1,this.escapeListener=null}open(){return this.isOpen?(y.warn("[Dropp SDK] Modal is already open"),null):(this._createModal(),this._attachEventListeners(),this._show(),this.isOpen=!0,this.iframe)}close(){y.log("[ModalManager] ๐Ÿšฆ close() called, isOpen:",this.isOpen),this.isOpen?(y.log("[ModalManager] ๐Ÿšฆ Hiding modal..."),this._hide(),y.log("[ModalManager] ๐Ÿšฆ Removing event listeners..."),this._removeEventListeners(),y.log("[ModalManager] ๐Ÿšฆ Destroying modal..."),this._destroyModal(),this.isOpen=!1,y.log("[ModalManager] โœ… Modal close sequence initiated")):y.log("[ModalManager] โš ๏ธ Modal is not open, skipping close")}_createModal(){this.overlay=document.createElement("div"),this.overlay.id="dropp-payment-overlay",this._applyOverlayStyles(this.overlay),this.container=document.createElement("div"),this.container.id="dropp-payment-container",this._applyContainerStyles(this.container),this.iframe=document.createElement("iframe"),this.iframe.id="dropp-payment-iframe",this.iframe.setAttribute("allow","payment"),this.iframe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups"),this.iframe.setAttribute("referrerpolicy","no-referrer"),this.iframe.setAttribute("title","Dropp Payment"),this._applyIframeStyles(this.iframe),this.container.appendChild(this.iframe),this.overlay.appendChild(this.container),document.body.appendChild(this.overlay)}_applyOverlayStyles(e){Object.assign(e.style,{position:"fixed",inset:"0",width:"100vw",height:"100vh",margin:"0",padding:"20px",boxSizing:"border-box",backgroundColor:"rgba(0, 0, 0, 0.6)",zIndex:999999..toString(),display:"flex",alignItems:"center",justifyContent:"center",opacity:"0",transition:"opacity 0.3s ease",backdropFilter:"blur(4px)",overflow:"auto"})}_applyContainerStyles(e){const t=window.innerWidth<768;this._isMobile=t,Object.assign(e.style,{position:"relative",flex:"0 0 auto",alignSelf:"center",margin:"auto",width:"100%",maxWidth:t?"100%":"400px",height:t?"100%":"auto",minHeight:t?"100%":"800px",maxHeight:t?"100%":"min(1000px, calc(100vh - 40px))",backgroundColor:"#ffffff",borderRadius:t?"0":"16px",boxShadow:"0 20px 60px rgba(0, 0, 0, 0.3)",overflow:"hidden",transform:"scale(0.95)",transition:"transform 0.3s ease, opacity 0.3s ease",display:"flex",flexDirection:"column"})}_getContainerTransform(e){return`scale(${e})`}_applyCloseButtonStyles(e){Object.assign(e.style,{position:"absolute",top:"16px",right:"16px",zIndex:"10",width:"40px",height:"40px",border:"none",borderRadius:"50%",backgroundColor:"rgba(255, 255, 255, 0.9)",color:"#333",fontSize:"28px",lineHeight:"1",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.15)",transition:"all 0.2s ease",fontFamily:"Arial, sans-serif",padding:"0"}),e.addEventListener("mouseenter",()=>{Object.assign(e.style,{backgroundColor:"#f5f5f5",transform:"scale(1.1)"})}),e.addEventListener("mouseleave",()=>{Object.assign(e.style,{backgroundColor:"rgba(255, 255, 255, 0.9)",transform:"scale(1)"})})}_applyIframeStyles(e){const t=this._isMobile;Object.assign(e.style,{width:"100%",flex:"1 1 auto",minHeight:t?"100%":"min(520px, calc(90vh - 40px))",height:t?"100%":"min(520px, calc(90vh - 40px))",border:"none",display:"block"})}_show(){document.body.style.overflow="hidden",requestAnimationFrame(()=>{this.overlay&&(this.overlay.style.opacity="1"),this.container&&(this.container.style.transform=this._getContainerTransform(1))})}_hide(){y.log("[ModalManager] ๐ŸŽญ _hide() called"),this.overlay&&(this.overlay.style.opacity="0",y.log("[ModalManager] ๐ŸŽญ Overlay opacity set to 0")),this.container&&(this.container.style.transform=this._getContainerTransform(.95),y.log("[ModalManager] ๐ŸŽญ Container transform set to scale(0.95)")),document.body.style.overflow="",y.log("[ModalManager] ๐ŸŽญ Body scroll restored")}_destroyModal(){y.log("[ModalManager] ๐Ÿ—‘๏ธ _destroyModal() called, waiting 300ms for animation"),setTimeout(()=>{y.log("[ModalManager] ๐Ÿ—‘๏ธ Animation complete, removing from DOM"),this.overlay&&this.overlay.parentNode&&(this.overlay.parentNode.removeChild(this.overlay),y.log("[ModalManager] ๐Ÿ—‘๏ธ Overlay removed from DOM")),this.overlay=null,this.container=null,this.iframe=null,this.closeButton=null,y.log("[ModalManager] โœ… Modal destroyed")},300)}_attachEventListeners(){}_removeEventListeners(){this.escapeListener&&(document.removeEventListener("keydown",this.escapeListener),this.escapeListener=null)}_handleCloseClick(e){e.stopPropagation(),this.onClose&&this.onClose("user_closed")}_handleOverlayClick(e){e.target===this.overlay&&this.onClose&&this.onClose("user_closed")}_handleEscapeKey(e){"Escape"===e.key&&this.isOpen&&this.onClose&&this.onClose("user_closed")}getIframe(){return this.iframe}getIsOpen(){return this.isOpen}}const I=["fundnow","linkbank","linkcard","redeemnow","fundcrypto","transferusdc","usdchistory","redeemcrypto","manageaccounts","transactions","merchantlist","favorites","offers","profile","changepin","unlinkaccount","accountsettings","about"];class _{constructor(e={}){if("undefined"==typeof window||"undefined"==typeof document)throw new Error("Dropp Payment SDK can only be used in a browser environment");if(!e.merchantId||!e.apiKey||!e.packageName)throw new Error("merchantId, apiKey, and packageName are required to initialize SDK");if(this.merchantId=e.merchantId,this.apiKey=e.apiKey,this.packageName=e.packageName,this.environment=e.environment||i.QA,this.baseUrl=e.paymentAppUrl||e.baseUrl||o[this.environment],this.isInitialized=!1,this.initializationPromise=null,this.getServerAuthToken="function"==typeof e.getServerAuthToken?e.getServerAuthToken:null,this.requireServerAuthToken="boolean"==typeof e.requireServerAuthToken?e.requireServerAuthToken:this.environment===i.PRODUCTION,this.allowLocalCallbacksInNonProd=!!e.allowLocalCallbacksInNonProd,e.allowedOrigins?.length)this.allowedOrigins=e.allowedOrigins;else try{this.allowedOrigins=[new URL(this.baseUrl).origin]}catch{this.allowedOrigins=r[this.environment]||[]}this.isOpen=!1,this.currentSession=null,this.currentFlowType=null,this.statusSession=null,this.hiddenIframe=null,this.statusTimeout=null,this.initTimeout=null,this.paymentTimeout=null,this.messageHandler=null,this.modalManager=null,y.setEnvironment(this.environment,{enabled:!!e.debugLogging}),y.log(`[Dropp SDK] Initialized v${g} - Environment: ${this.environment}`)}pay(e={}){return new Promise((t,s)=>{if(this.isOpen){const e=T(h,"A payment session is already in progress",{currentSession:this.currentSession});return void s(e)}(async()=>{try{await this.initialize();const n=w(e,{environment:this.environment,allowLocalCallbacksInNonProd:this.allowLocalCallbacksInNonProd});if(!n.valid){const e=T(p,"Invalid payment configuration",{errors:n.errors});return void s(e)}this.onSuccess=e.onSuccess||null,this.onFailure=e.onFailure||null,this.onCancel=e.onCancel||null,this.onClose=e.onClose||null,this.currentSession={resolve:t,reject:s,options:e,startTime:Date.now()},await this._initializePayment(e)}catch(e){const t=e&&e.code===p?e:T(m,"Failed to initialize payment",{originalError:e?.message||String(e)});s(t),this._cleanup()}})()})}async initialize(){return this.initializationPromise||(this.initializationPromise=(async()=>(await this._validateInitializationCredentials(),this.isInitialized=!0,{status:"success",code:"INITIALIZED",message:"Dropp SDK initialized successfully"}))().catch(e=>{throw this.isInitialized=!1,this.initializationPromise=null,e})),this.initializationPromise}_getValidationUrl(){const e={[i.QA]:"https://main.qa.dropp.cc/payer/webview/validate",[i.SANDBOX]:"https://sandbox.api.dropp.cc/payer/webview/validate",[i.PRODUCTION]:"https://api.dropp.cc/payer/webview/validate"};return e[this.environment]||e[i.QA]}async _validateInitializationCredentials(){const e=this._getValidationUrl();let t,s=null;try{t=await fetch(e,{method:"POST",headers:{accept:"application/json, text/plain, */*","content-type":"application/json","x-api-key":this.apiKey,"x-app-package":this.packageName},body:JSON.stringify({id:this.merchantId})})}catch(t){throw T(p,"Unable to validate merchant credentials",{endpoint:e,originalError:t?.message||String(t)})}try{s=await t.json()}catch{s=null}if(!t.ok)throw T(p,"Merchant validation failed for merchantId/apiKey/packageName",{endpoint:e,status:t.status,response:s});const n=Number(s?.responseCode),i=s?.errors,o=!Array.isArray(i)||0===i.length;if(!(s&&0===n&&o))throw T(p,"Merchant validation returned an unsuccessful response",{endpoint:e,status:t.status,response:s});y.log("[Dropp SDK] Merchant credentials validated successfully")}closePayment(){if(this.isOpen){if("page"===this.currentFlowType)return void this._cleanup();this._handleCancel("sdk_close")}}dashboard(e={}){return this._openHostedPage("/firsttimeflow",e)}open(e,t={}){const s="string"==typeof e?e.trim():"";if(!s)throw T(p,"moduleId is required for Dropp.open(moduleId)",{moduleId:e});if(!I.includes(s))throw T(p,"Unsupported moduleId passed to Dropp.open(moduleId)",{moduleId:s,supportedModuleIds:[...I]});return this._openHostedPage("/firsttimeflow",{...t,modules:[s]})}unlinkAccount(e={}){return this._openHostedPage("/unlink",e)}transactions(e={}){return this._openHostedPage("/transactions",e)}offers(e={}){return this._openHostedPage("/offers",e)}status(){return new Promise((e,t)=>{this.isOpen||"status"===this.currentFlowType?t(T(h,"A Dropp session is already in progress",{currentSession:this.currentSession,currentFlowType:this.currentFlowType})):(async()=>{try{await this.initialize(),this.currentFlowType="status",this.currentSession=null,this.onSuccess=null,this.onFailure=null,this.onCancel=null,this.onClose=null,this.messageHandler=new v(this.environment,this._handleMessage.bind(this),this.allowedOrigins);const s=document.createElement("iframe");s.id="dropp-status-iframe",s.setAttribute("allow","payment"),s.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups"),s.setAttribute("referrerpolicy","no-referrer"),s.setAttribute("title","Dropp Account Status"),Object.assign(s.style,{position:"absolute",width:"1px",height:"1px",border:"0",opacity:"0",pointerEvents:"none",visibility:"hidden"}),document.body.appendChild(s),this.hiddenIframe=s,this.messageHandler.init(s);const n=new URLSearchParams({sdkMode:"true",sessionId:this.messageHandler.getSessionId(),sdkVersion:g,platform:"web"}),i=this.baseUrl.replace(/\/+$/,"");s.src=`${i}/#/status?${n.toString()}`,this.statusSession={resolve:e,reject:t,startTime:Date.now()},this.statusTimeout=setTimeout(()=>{const e=T(d,"Account status request timed out",{type:"status",sessionDuration:this.statusSession?Date.now()-this.statusSession.startTime:0});this.statusSession&&this.statusSession.reject(e),this._cleanup()},a)}catch(e){t(T(m,"Failed to get account status",{originalError:e?.message||String(e)})),this._cleanup()}})()})}async _initializePayment(e){y.log("[Dropp SDK] Initializing payment session"),this.currentFlowType="payment",this.messageHandler=new v(this.environment,this._handleMessage.bind(this),this.allowedOrigins),this.modalManager=new E(this._handleModalClose.bind(this));const t=this.modalManager.open();if(!t)throw new Error("Failed to create modal iframe");this.messageHandler.init(t);const s=e.paymentType||c.STANDARD;let n="/payViaUrl";s===c.PREAUTH?n="/preAuthPayment":s===c.RECURRING&&(n="/recurringPayment");const i=s===c.RECURRING?(e.frequency||e.recurringInterval||"").toString().trim().toUpperCase():"",o=s===c.RECURRING&&"NONE"===i,r=e.appUrl||("undefined"!=typeof window&&window.location?window.location.href:void 0),d={merchantAccount:this.merchantId,amount:s===c.PREAUTH?void 0:e.amount,maxAmount:s===c.PREAUTH||o?e.amount:void 0,fixAmount:s!==c.RECURRING||o?void 0:e.amount,acceptPaymentDelay:s===c.STANDARD&&!0===e.acceptPaymentDelay||void 0,currency:e.currency,itemName:e.itemName,description:e.description,invoiceId:e.invoiceId||`INV-${Date.now()}`,invoiceType:s===c.PREAUTH?"PREAUTH":void 0,apiKey:this.apiKey,packageName:this.packageName,sdkVersion:g,platform:"web",appUrl:r,sessionId:this.messageHandler.getSessionId()};if(y.log("[Dropp SDK] Including SDK session context in payment params"),e.successURL&&(d.successURL=e.successURL),e.failureURL&&(d.failureURL=e.failureURL),s===c.RECURRING){const t=e.frequency||e.recurringInterval;t&&(d.frequency=t),e.recurringEndDate&&(d.expiry=e.recurringEndDate)}s===c.PREAUTH&&e.authHoldTimeInSeconds&&(d.authHoldTimeInSeconds=e.authHoldTimeInSeconds),e.callbackUrl&&(d.url=e.callbackUrl,d.submitToCallBack="post");const u={sessionId:d.sessionId,merchantAccount:this.merchantId,amount:e.amount,paymentType:s,invoiceId:d.invoiceId,expiry:e.recurringEndDate||null,issuedAt:Date.now()};let h="string"==typeof e.serverAuthToken?e.serverAuthToken.trim():"";if(!h&&this.getServerAuthToken)try{const e=await this.getServerAuthToken(u);h="string"==typeof e?e.trim():""}catch(e){throw T(p,"Failed to obtain server auth token",{originalError:e?.message||String(e)})}if(this.requireServerAuthToken&&!h)throw T(p,"serverAuthToken is required. Provide options.serverAuthToken or config.getServerAuthToken.",{environment:this.environment,paymentType:s,invoiceId:d.invoiceId});const m=await async function(e,t,s,n,i={}){try{const{serverAuthToken:o=""}=i,r={};Object.keys(s).forEach(e=>{const t=s[e];null!=t&&(r[e]=t)}),y.log("[buildPaymentUrl] Building payment URL payload");const a=JSON.stringify(r),l=btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),c=Date.now().toString(),d=new URLSearchParams({pay:l,sdkTs:c,sdkVersion:n,platform:"web"});return o&&d.set("authToken",o),`${e}/#${t}?${d.toString()}`}catch(e){throw y.error("Error building payment URL:",e),e}}(this.baseUrl,n,d,g,{serverAuthToken:h});y.log("[Dropp SDK] Loading payment flow iframe"),t.src=m,this.isOpen=!0,this.initTimeout=setTimeout(()=>{this._handleTimeout("init")},a),this.paymentTimeout=setTimeout(()=>{this._handleTimeout("payment")},l)}async _openHostedPage(e,t={}){if(this.isOpen)throw T(h,"A Dropp session is already in progress",{currentSession:this.currentSession,route:e});await this.initialize(),this.currentFlowType="page",this.currentSession=null,this.onSuccess=null,this.onFailure=null,this.onCancel=null,this.onClose="function"==typeof t.onClose?t.onClose:null,this.messageHandler=new v(this.environment,this._handleMessage.bind(this),this.allowedOrigins),this.modalManager=new E(this._handleModalClose.bind(this));const s=this.modalManager.open();if(!s)throw new Error("Failed to create modal iframe");this.messageHandler.init(s);const n=new URLSearchParams({sdkMode:"true",sessionId:this.messageHandler.getSessionId(),sdkVersion:g,platform:"web"});if("/firsttimeflow"===e&&Array.isArray(t.modules)){const e=t.modules.map(e=>"string"==typeof e?e.trim():"").filter(Boolean);e.length>0&&n.set("modules",e.join(","))}const i=this.baseUrl.replace(/\/+$/,"");return s.src=`${i}/#${e}?${n.toString()}`,this.isOpen=!0,y.log("[Dropp SDK] Hosted page opened",{route:e}),{status:"opened",route:e}}_handleMessage(e){const{type:s,data:n}=e;switch(s){case t.READY:this._handleReady(n);break;case t.PAGE_LOADED:case t.PAYMENT_PAGE_LOADED:this._handlePageLoaded(n);break;case t.PAYMENT_SUCCESS:this._handleSuccess(n);break;case t.PAYMENT_FAILED:this._handleFailure(n);break;case t.PAYMENT_CANCELLED:this._handleCancel("user_cancelled");break;case t.ACCOUNT_STATUS:this._handleAccountStatus(n);break;case t.AUTO_CLOSE_WEBVIEW:y.log("[Dropp SDK] AUTO_CLOSE_WEBVIEW received - closing modal"),this._cleanup(),y.log("[Dropp SDK] Cleanup completed");break;case t.CLOSE_WEBVIEW:if(y.log("[Dropp SDK] CLOSE_WEBVIEW received from app - closing modal"),"status"===this.currentFlowType&&this.statusSession){const e=T(m,"Account status request was closed before response was received",{type:"status",sessionDuration:Date.now()-this.statusSession.startTime});this.statusSession.reject(e),this._cleanup();break}this._handleCancel("app_close");break;default:y.warn("[Dropp SDK] Unknown message type:",s)}}_handleReady(e){if(y.log("[Dropp SDK] Payment app ready"),this.initTimeout&&(clearTimeout(this.initTimeout),this.initTimeout=null),this.messageHandler&&this.currentSession){const e={};Object.keys(this.currentSession.options).forEach(t=>{const s=this.currentSession.options[t];"function"!=typeof s&&(e[t]=s)}),y.log("[Dropp SDK] Sending init config to payment app"),this.messageHandler.sendInit(e)}}_handlePageLoaded(e){y.log("[Dropp SDK] Payment page loaded")}_handleAccountStatus(e){y.log("[Dropp SDK] Account status received"),this.statusSession?(this.statusSession.resolve({type:t.ACCOUNT_STATUS,data:e}),this._cleanup()):y.warn("[Dropp SDK] ACCOUNT_STATUS received without active status session")}_handleSuccess(e){y.log("[Dropp SDK] Payment successful");const t={status:"success",...e,sessionDuration:Date.now()-this.currentSession.startTime};this.currentSession&&this.currentSession.resolve(t),this.onSuccess&&this.onSuccess(t)}_handleFailure(e){y.log("[Dropp SDK] Payment failed");const t={status:"failed",...e,sessionDuration:Date.now()-this.currentSession.startTime};this.currentSession&&this.currentSession.resolve(t),this.onFailure&&this.onFailure(t)}_handleCancel(e){y.log("[Dropp SDK] Payment cancelled");const t={status:"cancelled",reason:e,sessionDuration:this.currentSession?Date.now()-this.currentSession.startTime:0};this.currentSession&&this.currentSession.resolve(t),this.onCancel&&this.onCancel(t),this._cleanup()}_handleModalClose(e){y.log("[Dropp SDK] Modal closed by user"),"page"!==this.currentFlowType?this._handleCancel(e):this._cleanup()}_handleTimeout(e){y.error("[Dropp SDK] Timeout:",e);const t=T("init"===e?d:u,"init"===e?"Payment app failed to load within timeout period":"Payment session timed out",{type:e,sessionDuration:this.currentSession?Date.now()-this.currentSession.startTime:0});this.currentSession&&this.currentSession.reject(t),this.onFailure&&this.onFailure({status:"failed",error:t}),this._cleanup()}_cleanup(){y.log("[Dropp SDK] ๐Ÿงน Cleaning up session - starting cleanup"),this.initTimeout&&(clearTimeout(this.initTimeout),this.initTimeout=null),this.paymentTimeout&&(clearTimeout(this.paymentTimeout),this.paymentTimeout=null),this.statusTimeout&&(clearTimeout(this.statusTimeout),this.statusTimeout=null),this.messageHandler&&(y.log("[Dropp SDK] ๐Ÿงน Destroying message handler"),this.messageHandler.destroy(),this.messageHandler=null),this.modalManager&&(y.log("[Dropp SDK] ๐Ÿงน Closing modal manager"),this.modalManager.close(),y.log("[Dropp SDK] ๐Ÿงน Modal manager closed"),this.modalManager=null),this.hiddenIframe&&this.hiddenIframe.parentNode&&this.hiddenIframe.parentNode.removeChild(this.hiddenIframe),this.hiddenIframe=null,this.currentSession=null,this.statusSession=null,this.currentFlowType=null,this.isOpen=!1,this.onClose&&this.onClose()}static getVersion(){return g}static getEnvironments(){return{...i}}static getPaymentTypes(){return{...c}}}let A=null;async function C(e){A=new _(e);return{...await A.initialize(),sdk:A}}const N={init:e=>C(e),pay(e){if(!A){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.pay(options).");throw e.code="SDK_NOT_INITIALIZED",e}return A.pay(e)},dashboard(e){if(!A){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.dashboard(options).");throw e.code="SDK_NOT_INITIALIZED",e}return A.dashboard(e)},open(e,t){if(!A){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.open(moduleId, options).");throw e.code="SDK_NOT_INITIALIZED",e}return A.open(e,t)},unlinkAccount(e){if(!A){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.unlinkAccount(options).");throw e.code="SDK_NOT_INITIALIZED",e}return A.unlinkAccount(e)},transactions(e){if(!A){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.transactions(options).");throw e.code="SDK_NOT_INITIALIZED",e}return A.transactions(e)},offers(e){if(!A){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.offers(options).");throw e.code="SDK_NOT_INITIALIZED",e}return A.offers(e)},status(){if(!A){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.status().");throw e.code="SDK_NOT_INITIALIZED",e}return A.status()},getInstance:()=>A};var O={DroppPaymentSDK:_,createPaymentSDK:C,Dropp:N,ENVIRONMENTS:i,PAYMENT_TYPES:c};e.Dropp=N,e.DroppPaymentSDK=_,e.ENVIRONMENTS=i,e.PAYMENT_TYPES=c,e.createPaymentSDK=C,e.default=O,e.getDroppInstance=function(){return A},Object.defineProperty(e,"__esModule",{value:!0})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).DroppPaymentSDK={})}(this,function(e){"use strict";const t={READY:"DROPP_SDK_READY",PAYMENT_SUCCESS:"PAYMENT_SUCCESS",PAYMENT_FAILED:"PAYMENT_FAILED",PAYMENT_CANCELLED:"PAYMENT_CANCELLED",ACCOUNT_STATUS:"ACCOUNT_STATUS",CLOSE_WEBVIEW:"CLOSE_WEBVIEW",AUTO_CLOSE_WEBVIEW:"AUTO_CLOSE_WEBVIEW",PAYMENT_PAGE_LOADED:"PAYMENT_PAGE_LOADED",PAGE_LOADED:"PAGE_LOADED"},s="DROPP_SDK_INIT",n="DROPP_SDK_CLOSE",i={PRODUCTION:"production",QA:"qa",SANDBOX:"sandbox"},o={[i.PRODUCTION]:"https://wv.dropp.cc",[i.QA]:"https://wv.qa.dropp.cc",[i.SANDBOX]:"https://wv.sandbox.dropp.cc"},r={[i.PRODUCTION]:["https://wv.dropp.cc"],[i.QA]:["https://wv.qa.dropp.cc"],[i.SANDBOX]:["https://wv.sandbox.dropp.cc"]},a=3e4,l=6e5,c={STANDARD:"standard",PREAUTH:"preauth",RECURRING:"recurring"},d="INIT_TIMEOUT",u="PAYMENT_TIMEOUT",p="INVALID_CONFIG",h="ALREADY_OPEN",m="UNKNOWN_ERROR",g="1.0.2";const y=new class{constructor(e,t={}){this.environment=e,this.forceEnabled=!!t.enabled,this.enabled=this._shouldEnableLogging()}_shouldEnableLogging(){return this.forceEnabled}setEnvironment(e,t={}){this.environment=e,"boolean"==typeof t.enabled&&(this.forceEnabled=t.enabled),this.enabled=this._shouldEnableLogging()}setEnabled(e){this.forceEnabled=!!e,this.enabled=this._shouldEnableLogging()}log(...e){this.enabled&&console.log(...e)}warn(...e){this.enabled&&console.warn(...e)}error(...e){this.enabled&&console.error(...e)}debug(...e){this.enabled&&console.debug(...e)}info(...e){this.enabled&&console.info(...e)}}("qa",{enabled:!1}),f=["USD","HBAR","USDC"],S=["NONE","HALF_HOURLY","HOURLY","DAILY","WEEKLY","MONTHLY","YEARLY"],D=[c.STANDARD,c.PREAUTH,c.RECURRING];function b(e,t={}){const{isProduction:s=!1,allowLocalCallbacksInNonProd:n=!1}=t;if("string"!=typeof e||!e.trim())return!1;try{const t=new URL(e.trim()),i="https:"===t.protocol;if(!("http:"===t.protocol)&&!i)return!1;return function(e){if(!e)return!1;const t=e.trim().toLowerCase();if("localhost"===t||"127.0.0.1"===t||"::1"===t||t.endsWith(".local"))return!0;if(!/^(\d{1,3}\.){3}\d{1,3}$/.test(t))return!1;const s=t.split(".").map(e=>Number(e));if(s.some(e=>Number.isNaN(e)||e<0||e>255))return!1;const[n,i]=s;return 10===n||127===n||172===n&&i>=16&&i<=31||192===n&&168===i||169===n&&254===i}(t.hostname)?!s&&n:!s||i}catch{return!1}}function w(e={},t={}){const s=[],n=e.paymentType||c.STANDARD,i="production"===(t.environment||"").toLowerCase(),o=!!t.allowLocalCallbacksInNonProd,r="string"==typeof e.currency?e.currency.trim().toUpperCase():"";if(D.includes(n)||s.push(`paymentType must be one of: ${D.join(", ")}`),void 0===e.amount||null===e.amount||""===e.amount?s.push("amount is required"):function(e){const t="number"==typeof e?e:parseFloat(e);return"number"==typeof t&&!Number.isNaN(t)&&t>0}(e.amount)||s.push("amount must be a positive number"),e.currency&&"string"==typeof e.currency&&e.currency.trim()?f.includes(r)||s.push(`currency must be one of: ${f.join(", ")}`):s.push("currency is required"),e.itemName&&"string"==typeof e.itemName&&e.itemName.trim()||s.push("itemName is required"),n===c.PREAUTH&&(r&&"USD"!==r&&s.push("currency must be USD for preauth payments"),e.callbackUrl&&String(e.callbackUrl).trim()?b(e.callbackUrl,{isProduction:i,allowLocalCallbacksInNonProd:o})||s.push(i?"callbackUrl must be HTTPS in production and cannot target loopback/private hosts":"callbackUrl must be a valid HTTP/HTTPS URL and cannot target loopback/private hosts unless explicitly enabled"):s.push("callbackUrl (signing URL) is required for preauth payments"),void 0===e.authHoldTimeInSeconds||null===e.authHoldTimeInSeconds||""===e.authHoldTimeInSeconds?s.push("authHoldTimeInSeconds is required for preauth payments"):function(e){const t="number"==typeof e?e:parseInt(e,10);return Number.isInteger(t)&&t>0}(e.authHoldTimeInSeconds)||s.push("authHoldTimeInSeconds must be a positive integer (seconds)")),n===c.RECURRING){e.callbackUrl&&String(e.callbackUrl).trim()?b(e.callbackUrl,{isProduction:i,allowLocalCallbacksInNonProd:o})||s.push(i?"callbackUrl must be HTTPS in production and cannot target loopback/private hosts":"callbackUrl must be a valid HTTP/HTTPS URL and cannot target loopback/private hosts unless explicitly enabled"):s.push("callbackUrl (signing URL) is required for recurring payments");const t=(e.frequency||e.recurringInterval||"").toString().trim().toUpperCase();t?S.includes(t)||s.push(`frequency must be one of: ${S.join(", ")}`):s.push("frequency is required for recurring payments"),e.recurringEndDate&&String(e.recurringEndDate).trim()?!function(e){if("string"!=typeof e||!e.trim())return!1;const t=new Date(e.trim());return!Number.isNaN(t.getTime())}(e.recurringEndDate)?s.push("recurringEndDate must be a valid ISO date-time string"):new Date(e.recurringEndDate.trim())<=new Date&&s.push("recurringEndDate must be in the future"):s.push("recurringEndDate (expiry) is required for recurring payments")}return{valid:0===s.length,errors:s}}function T(e,t,s={}){return{code:e,message:t,details:s,timestamp:(new Date).toISOString(),toString(){return this.message||"Dropp SDK error"}}}class v{constructor(e,t,s=null){this.environment=e,this.onMessage=t,this.sessionId=`dropp-sdk-${Date.now()}-${Math.random().toString(36).substring(2,15)}`,y.log("[MessageHandler] Session initialized"),this.iframe=null,this.allowedOrigins=s?.length>0?s:r[e]||[],this.messageListener=null,this.pendingMessages=new Map}init(e){this.iframe=e,this.messageListener=this._handleMessage.bind(this),window.addEventListener("message",this.messageListener)}destroy(){this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.iframe=null,this.pendingMessages.clear()}_handleMessage(e){if(y.log("[MessageHandler] Received postMessage event"),e.source===window)return void y.log("[MessageHandler] Ignoring message from self");if(!this._validateOrigin(e.origin))return void y.warn("[Dropp SDK] Rejected message from untrusted origin:",e.origin);if(!this.iframe||e.source!==this.iframe.contentWindow)return void y.warn("[Dropp SDK] Rejected message from unexpected source",{eventOrigin:e.origin});const t=e.data;this._validateMessageStructure(t)?t.sessionId&&t.sessionId!==this.sessionId?y.warn("[Dropp SDK] Rejected message with invalid session ID"):(y.log("[MessageHandler] Message passed validation"),this._processMessage(t)):y.warn("[Dropp SDK] Rejected message with invalid structure")}_validateOrigin(e){return!(!e.startsWith("http://localhost:")&&!e.startsWith("http://127.0.0.1:"))||this.allowedOrigins.includes(e)}_validateMessageStructure(e){if(!e||"object"!=typeof e)return!1;if(!e.type||"string"!=typeof e.type)return!1;return!!Object.values(t).includes(e.type)&&!(e.type!==t.ACCOUNT_STATUS&&!e.timestamp)}_processMessage(e){y.log("[Dropp SDK] Received message:",e.type),this.onMessage&&this.onMessage(e)}sendToPaymentApp(e,t={}){if(!this.iframe||!this.iframe.contentWindow)return y.error("[Dropp SDK] Cannot send message: iframe not ready"),!1;const s={type:e,data:t,sessionId:this.sessionId,timestamp:(new Date).toISOString(),sdkVersion:"1.0.0"},n=this.allowedOrigins[0]||"*";try{return this.iframe.contentWindow.postMessage(s,n),y.log("[Dropp SDK] Sent message:",e),!0}catch(e){return y.error("[Dropp SDK] Error sending message:",e),!1}}sendInit(e){return this.sendToPaymentApp(s,{mode:"sdk",config:e})}sendClose(){return this.sendToPaymentApp(n,{})}getSessionId(){return this.sessionId}}class E{constructor(e){this.onClose=e,this.overlay=null,this.container=null,this.iframe=null,this.closeButton=null,this.isOpen=!1,this.escapeListener=null}open(){return this.isOpen?(y.warn("[Dropp SDK] Modal is already open"),null):(this._createModal(),this._attachEventListeners(),this._show(),this.isOpen=!0,this.iframe)}close(){y.log("[ModalManager] ๐Ÿšฆ close() called, isOpen:",this.isOpen),this.isOpen?(y.log("[ModalManager] ๐Ÿšฆ Hiding modal..."),this._hide(),y.log("[ModalManager] ๐Ÿšฆ Removing event listeners..."),this._removeEventListeners(),y.log("[ModalManager] ๐Ÿšฆ Destroying modal..."),this._destroyModal(),this.isOpen=!1,y.log("[ModalManager] โœ… Modal close sequence initiated")):y.log("[ModalManager] โš ๏ธ Modal is not open, skipping close")}_createModal(){this.overlay=document.createElement("div"),this.overlay.id="dropp-payment-overlay",this._applyOverlayStyles(this.overlay),this.container=document.createElement("div"),this.container.id="dropp-payment-container",this._applyContainerStyles(this.container),this.iframe=document.createElement("iframe"),this.iframe.id="dropp-payment-iframe",this.iframe.setAttribute("allow","payment"),this.iframe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups"),this.iframe.setAttribute("referrerpolicy","no-referrer"),this.iframe.setAttribute("title","Dropp Payment"),this._applyIframeStyles(this.iframe),this.container.appendChild(this.iframe),this.overlay.appendChild(this.container),document.body.appendChild(this.overlay)}_applyOverlayStyles(e){Object.assign(e.style,{position:"fixed",inset:"0",width:"100vw",height:"100vh",margin:"0",padding:"20px",boxSizing:"border-box",backgroundColor:"rgba(0, 0, 0, 0.6)",zIndex:999999..toString(),display:"flex",alignItems:"center",justifyContent:"center",opacity:"0",transition:"opacity 0.3s ease",backdropFilter:"blur(4px)",overflow:"auto"})}_applyContainerStyles(e){const t=window.innerWidth<768;this._isMobile=t,Object.assign(e.style,{position:"relative",flex:"0 0 auto",alignSelf:"center",margin:"auto",width:"100%",maxWidth:t?"100%":"400px",height:t?"100%":"auto",minHeight:t?"100%":"800px",maxHeight:t?"100%":"min(1000px, calc(100vh - 40px))",backgroundColor:"#ffffff",borderRadius:t?"0":"16px",boxShadow:"0 20px 60px rgba(0, 0, 0, 0.3)",overflow:"hidden",transform:"scale(0.95)",transition:"transform 0.3s ease, opacity 0.3s ease",display:"flex",flexDirection:"column"})}_getContainerTransform(e){return`scale(${e})`}_applyCloseButtonStyles(e){Object.assign(e.style,{position:"absolute",top:"16px",right:"16px",zIndex:"10",width:"40px",height:"40px",border:"none",borderRadius:"50%",backgroundColor:"rgba(255, 255, 255, 0.9)",color:"#333",fontSize:"28px",lineHeight:"1",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.15)",transition:"all 0.2s ease",fontFamily:"Arial, sans-serif",padding:"0"}),e.addEventListener("mouseenter",()=>{Object.assign(e.style,{backgroundColor:"#f5f5f5",transform:"scale(1.1)"})}),e.addEventListener("mouseleave",()=>{Object.assign(e.style,{backgroundColor:"rgba(255, 255, 255, 0.9)",transform:"scale(1)"})})}_applyIframeStyles(e){const t=this._isMobile;Object.assign(e.style,{width:"100%",flex:"1 1 auto",minHeight:t?"100%":"min(520px, calc(90vh - 40px))",height:t?"100%":"min(520px, calc(90vh - 40px))",border:"none",display:"block"})}_show(){document.body.style.overflow="hidden",requestAnimationFrame(()=>{this.overlay&&(this.overlay.style.opacity="1"),this.container&&(this.container.style.transform=this._getContainerTransform(1))})}_hide(){y.log("[ModalManager] ๐ŸŽญ _hide() called"),this.overlay&&(this.overlay.style.opacity="0",y.log("[ModalManager] ๐ŸŽญ Overlay opacity set to 0")),this.container&&(this.container.style.transform=this._getContainerTransform(.95),y.log("[ModalManager] ๐ŸŽญ Container transform set to scale(0.95)")),document.body.style.overflow="",y.log("[ModalManager] ๐ŸŽญ Body scroll restored")}_destroyModal(){y.log("[ModalManager] ๐Ÿ—‘๏ธ _destroyModal() called, waiting 300ms for animation"),setTimeout(()=>{y.log("[ModalManager] ๐Ÿ—‘๏ธ Animation complete, removing from DOM"),this.overlay&&this.overlay.parentNode&&(this.overlay.parentNode.removeChild(this.overlay),y.log("[ModalManager] ๐Ÿ—‘๏ธ Overlay removed from DOM")),this.overlay=null,this.container=null,this.iframe=null,this.closeButton=null,y.log("[ModalManager] โœ… Modal destroyed")},300)}_attachEventListeners(){}_removeEventListeners(){this.escapeListener&&(document.removeEventListener("keydown",this.escapeListener),this.escapeListener=null)}_handleCloseClick(e){e.stopPropagation(),this.onClose&&this.onClose("user_closed")}_handleOverlayClick(e){e.target===this.overlay&&this.onClose&&this.onClose("user_closed")}_handleEscapeKey(e){"Escape"===e.key&&this.isOpen&&this.onClose&&this.onClose("user_closed")}getIframe(){return this.iframe}getIsOpen(){return this.isOpen}}const I=["fundnow","linkbank","linkcard","redeemnow","fundcrypto","transferusdc","usdchistory","redeemcrypto","manageaccounts","transactions","merchantlist","favorites","offers","profile","changepin","unlinkaccount","accountsettings","about"];class _{constructor(e={}){if("undefined"==typeof window||"undefined"==typeof document)throw new Error("Dropp Payment SDK can only be used in a browser environment");if(!e.merchantId||!e.apiKey||!e.packageName)throw new Error("merchantId, apiKey, and packageName are required to initialize SDK");if(this.merchantId=e.merchantId,this.apiKey=e.apiKey,this.packageName=e.packageName,this.environment=e.environment||i.QA,this.baseUrl=e.paymentAppUrl||e.baseUrl||o[this.environment],this.isInitialized=!1,this.initializationPromise=null,this.getServerAuthToken="function"==typeof e.getServerAuthToken?e.getServerAuthToken:null,this.requireServerAuthToken="boolean"==typeof e.requireServerAuthToken?e.requireServerAuthToken:this.environment===i.PRODUCTION,this.allowLocalCallbacksInNonProd=!!e.allowLocalCallbacksInNonProd,e.allowedOrigins?.length)this.allowedOrigins=e.allowedOrigins;else try{this.allowedOrigins=[new URL(this.baseUrl).origin]}catch{this.allowedOrigins=r[this.environment]||[]}this.isOpen=!1,this.currentSession=null,this.currentFlowType=null,this.statusSession=null,this.hiddenIframe=null,this.statusTimeout=null,this.initTimeout=null,this.paymentTimeout=null,this.messageHandler=null,this.modalManager=null,y.setEnvironment(this.environment,{enabled:!!e.debugLogging}),y.log(`[Dropp SDK] Initialized v${g} - Environment: ${this.environment}`)}pay(e={}){return new Promise((t,s)=>{if(this.isOpen){const e=T(h,"A payment session is already in progress",{currentSession:this.currentSession});return void s(e)}(async()=>{try{await this.initialize();const n=w(e,{environment:this.environment,allowLocalCallbacksInNonProd:this.allowLocalCallbacksInNonProd});if(!n.valid){const e=T(p,"Invalid payment configuration",{errors:n.errors});return void s(e)}this.onSuccess=e.onSuccess||null,this.onFailure=e.onFailure||null,this.onCancel=e.onCancel||null,this.onClose=e.onClose||null,this.currentSession={resolve:t,reject:s,options:e,startTime:Date.now()},await this._initializePayment(e)}catch(e){const t=e&&e.code===p?e:T(m,"Failed to initialize payment",{originalError:e?.message||String(e)});s(t),this._cleanup()}})()})}async initialize(){return this.initializationPromise||(this.initializationPromise=(async()=>(await this._validateInitializationCredentials(),this.isInitialized=!0,{status:"success",code:"INITIALIZED",message:"Dropp SDK initialized successfully"}))().catch(e=>{throw this.isInitialized=!1,this.initializationPromise=null,e})),this.initializationPromise}_getValidationUrl(){const e={[i.QA]:"https://main.qa.dropp.cc/payer/webview/validate",[i.SANDBOX]:"https://sandbox.api.dropp.cc/payer/webview/validate",[i.PRODUCTION]:"https://api.dropp.cc/payer/webview/validate"};return e[this.environment]||e[i.QA]}async _validateInitializationCredentials(){const e=this._getValidationUrl();let t,s=null;try{t=await fetch(e,{method:"POST",headers:{accept:"application/json, text/plain, */*","content-type":"application/json","x-api-key":this.apiKey,"x-app-package":this.packageName},body:JSON.stringify({id:this.merchantId})})}catch(t){throw T(p,"Unable to validate merchant credentials",{endpoint:e,originalError:t?.message||String(t)})}try{s=await t.json()}catch{s=null}if(!t.ok)throw T(p,"Merchant validation failed for merchantId/apiKey/packageName",{endpoint:e,status:t.status,response:s});const n=Number(s?.responseCode),i=s?.errors,o=!Array.isArray(i)||0===i.length;if(!(s&&0===n&&o))throw T(p,"Merchant validation returned an unsuccessful response",{endpoint:e,status:t.status,response:s});y.log("[Dropp SDK] Merchant credentials validated successfully")}closePayment(){if(this.isOpen){if("page"===this.currentFlowType)return void this._cleanup();this._handleCancel("sdk_close")}}dashboard(e={}){return this._openHostedPage("/firsttimeflow",e)}open(e,t={}){const s="string"==typeof e?e.trim():"";if(!s)throw T(p,"moduleId is required for Dropp.open(moduleId)",{moduleId:e});if(!I.includes(s))throw T(p,"Unsupported moduleId passed to Dropp.open(moduleId)",{moduleId:s,supportedModuleIds:[...I]});return this._openHostedPage(`/${s}`,t)}unlinkAccount(e={}){return this._openHostedPage("/unlink",e)}transactions(e={}){return this._openHostedPage("/transactions",e)}offers(e={}){return this._openHostedPage("/offers",e)}status(){return new Promise((e,t)=>{this.isOpen||"status"===this.currentFlowType?t(T(h,"A Dropp session is already in progress",{currentSession:this.currentSession,currentFlowType:this.currentFlowType})):(async()=>{try{await this.initialize(),this.currentFlowType="status",this.currentSession=null,this.onSuccess=null,this.onFailure=null,this.onCancel=null,this.onClose=null,this.messageHandler=new v(this.environment,this._handleMessage.bind(this),this.allowedOrigins);const s=document.createElement("iframe");s.id="dropp-status-iframe",s.setAttribute("allow","payment"),s.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups"),s.setAttribute("referrerpolicy","no-referrer"),s.setAttribute("title","Dropp Account Status"),Object.assign(s.style,{position:"absolute",width:"1px",height:"1px",border:"0",opacity:"0",pointerEvents:"none",visibility:"hidden"}),document.body.appendChild(s),this.hiddenIframe=s,this.messageHandler.init(s);const n=new URLSearchParams({sdkMode:"true",sessionId:this.messageHandler.getSessionId(),sdkVersion:g,platform:"web"}),i=this.baseUrl.replace(/\/+$/,"");s.src=`${i}/#/status?${n.toString()}`,this.statusSession={resolve:e,reject:t,startTime:Date.now()},this.statusTimeout=setTimeout(()=>{const e=T(d,"Account status request timed out",{type:"status",sessionDuration:this.statusSession?Date.now()-this.statusSession.startTime:0});this.statusSession&&this.statusSession.reject(e),this._cleanup()},a)}catch(e){t(T(m,"Failed to get account status",{originalError:e?.message||String(e)})),this._cleanup()}})()})}async _initializePayment(e){y.log("[Dropp SDK] Initializing payment session"),this.currentFlowType="payment",this.messageHandler=new v(this.environment,this._handleMessage.bind(this),this.allowedOrigins),this.modalManager=new E(this._handleModalClose.bind(this));const t=this.modalManager.open();if(!t)throw new Error("Failed to create modal iframe");this.messageHandler.init(t);const s=e.paymentType||c.STANDARD;let n="/payViaUrl";s===c.PREAUTH?n="/preAuthPayment":s===c.RECURRING&&(n="/recurringPayment");const i=s===c.RECURRING?(e.frequency||e.recurringInterval||"").toString().trim().toUpperCase():"",o=s===c.RECURRING&&"NONE"===i,r=e.appUrl||("undefined"!=typeof window&&window.location?window.location.href:void 0),d={merchantAccount:this.merchantId,amount:s===c.PREAUTH?void 0:e.amount,maxAmount:s===c.PREAUTH||o?e.amount:void 0,fixAmount:s!==c.RECURRING||o?void 0:e.amount,acceptPaymentDelay:s===c.STANDARD&&!0===e.acceptPaymentDelay||void 0,currency:e.currency,itemName:e.itemName,description:e.description,invoiceId:e.invoiceId||`INV-${Date.now()}`,invoiceType:s===c.PREAUTH?"PREAUTH":void 0,apiKey:this.apiKey,packageName:this.packageName,sdkVersion:g,platform:"web",appUrl:r,sessionId:this.messageHandler.getSessionId()};if(y.log("[Dropp SDK] Including SDK session context in payment params"),e.successURL&&(d.successURL=e.successURL),e.failureURL&&(d.failureURL=e.failureURL),s===c.RECURRING){const t=e.frequency||e.recurringInterval;t&&(d.frequency=t),e.recurringEndDate&&(d.expiry=e.recurringEndDate)}s===c.PREAUTH&&e.authHoldTimeInSeconds&&(d.authHoldTimeInSeconds=e.authHoldTimeInSeconds),e.callbackUrl&&(d.url=e.callbackUrl,d.submitToCallBack="post");const u={sessionId:d.sessionId,merchantAccount:this.merchantId,amount:e.amount,paymentType:s,invoiceId:d.invoiceId,expiry:e.recurringEndDate||null,issuedAt:Date.now()};let h="string"==typeof e.serverAuthToken?e.serverAuthToken.trim():"";if(!h&&this.getServerAuthToken)try{const e=await this.getServerAuthToken(u);h="string"==typeof e?e.trim():""}catch(e){throw T(p,"Failed to obtain server auth token",{originalError:e?.message||String(e)})}if(this.requireServerAuthToken&&!h)throw T(p,"serverAuthToken is required. Provide options.serverAuthToken or config.getServerAuthToken.",{environment:this.environment,paymentType:s,invoiceId:d.invoiceId});const m=await async function(e,t,s,n,i={}){try{const{serverAuthToken:o=""}=i,r={};Object.keys(s).forEach(e=>{const t=s[e];null!=t&&(r[e]=t)}),y.log("[buildPaymentUrl] Building payment URL payload");const a=JSON.stringify(r),l=btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),c=Date.now().toString(),d=new URLSearchParams({pay:l,sdkTs:c,sdkVersion:n,platform:"web"});return o&&d.set("authToken",o),`${e}/#${t}?${d.toString()}`}catch(e){throw y.error("Error building payment URL:",e),e}}(this.baseUrl,n,d,g,{serverAuthToken:h});y.log("[Dropp SDK] Loading payment flow iframe"),t.src=m,this.isOpen=!0,this.initTimeout=setTimeout(()=>{this._handleTimeout("init")},a),this.paymentTimeout=setTimeout(()=>{this._handleTimeout("payment")},l)}async _openHostedPage(e,t={}){if(this.isOpen)throw T(h,"A Dropp session is already in progress",{currentSession:this.currentSession,route:e});await this.initialize(),this.currentFlowType="page",this.currentSession=null,this.onSuccess=null,this.onFailure=null,this.onCancel=null,this.onClose="function"==typeof t.onClose?t.onClose:null,this.messageHandler=new v(this.environment,this._handleMessage.bind(this),this.allowedOrigins),this.modalManager=new E(this._handleModalClose.bind(this));const s=this.modalManager.open();if(!s)throw new Error("Failed to create modal iframe");this.messageHandler.init(s);const n=new URLSearchParams({sdkMode:"true",sessionId:this.messageHandler.getSessionId(),sdkVersion:g,platform:"web"});if("/firsttimeflow"===e&&Array.isArray(t.modules)){const e=t.modules.map(e=>"string"==typeof e?e.trim():"").filter(Boolean);e.length>0&&n.set("modules",e.join(","))}const i=this.baseUrl.replace(/\/+$/,"");return s.src=`${i}/#${e}?${n.toString()}`,this.isOpen=!0,y.log("[Dropp SDK] Hosted page opened",{route:e}),{status:"opened",route:e}}_handleMessage(e){const{type:s,data:n}=e;switch(s){case t.READY:this._handleReady(n);break;case t.PAGE_LOADED:case t.PAYMENT_PAGE_LOADED:this._handlePageLoaded(n);break;case t.PAYMENT_SUCCESS:this._handleSuccess(n);break;case t.PAYMENT_FAILED:this._handleFailure(n);break;case t.PAYMENT_CANCELLED:this._handleCancel("user_cancelled");break;case t.ACCOUNT_STATUS:this._handleAccountStatus(n);break;case t.AUTO_CLOSE_WEBVIEW:y.log("[Dropp SDK] AUTO_CLOSE_WEBVIEW received - closing modal"),this._cleanup(),y.log("[Dropp SDK] Cleanup completed");break;case t.CLOSE_WEBVIEW:if(y.log("[Dropp SDK] CLOSE_WEBVIEW received from app - closing modal"),"status"===this.currentFlowType&&this.statusSession){const e=T(m,"Account status request was closed before response was received",{type:"status",sessionDuration:Date.now()-this.statusSession.startTime});this.statusSession.reject(e),this._cleanup();break}this._handleCancel("app_close");break;default:y.warn("[Dropp SDK] Unknown message type:",s)}}_handleReady(e){if(y.log("[Dropp SDK] Payment app ready"),this.initTimeout&&(clearTimeout(this.initTimeout),this.initTimeout=null),this.messageHandler&&this.currentSession){const e={};Object.keys(this.currentSession.options).forEach(t=>{const s=this.currentSession.options[t];"function"!=typeof s&&(e[t]=s)}),y.log("[Dropp SDK] Sending init config to payment app"),this.messageHandler.sendInit(e)}}_handlePageLoaded(e){y.log("[Dropp SDK] Payment page loaded")}_handleAccountStatus(e){y.log("[Dropp SDK] Account status received"),this.statusSession?(this.statusSession.resolve({type:t.ACCOUNT_STATUS,data:e}),this._cleanup()):y.warn("[Dropp SDK] ACCOUNT_STATUS received without active status session")}_handleSuccess(e){y.log("[Dropp SDK] Payment successful");const t={status:"success",...e,sessionDuration:Date.now()-this.currentSession.startTime};this.currentSession&&this.currentSession.resolve(t),this.onSuccess&&this.onSuccess(t)}_handleFailure(e){y.log("[Dropp SDK] Payment failed");const t={status:"failed",...e,sessionDuration:Date.now()-this.currentSession.startTime};this.currentSession&&this.currentSession.resolve(t),this.onFailure&&this.onFailure(t)}_handleCancel(e){y.log("[Dropp SDK] Payment cancelled");const t={status:"cancelled",reason:e,sessionDuration:this.currentSession?Date.now()-this.currentSession.startTime:0};this.currentSession&&this.currentSession.resolve(t),this.onCancel&&this.onCancel(t),this._cleanup()}_handleModalClose(e){y.log("[Dropp SDK] Modal closed by user"),"page"!==this.currentFlowType?this._handleCancel(e):this._cleanup()}_handleTimeout(e){y.error("[Dropp SDK] Timeout:",e);const t=T("init"===e?d:u,"init"===e?"Payment app failed to load within timeout period":"Payment session timed out",{type:e,sessionDuration:this.currentSession?Date.now()-this.currentSession.startTime:0});this.currentSession&&this.currentSession.reject(t),this.onFailure&&this.onFailure({status:"failed",error:t}),this._cleanup()}_cleanup(){y.log("[Dropp SDK] ๐Ÿงน Cleaning up session - starting cleanup"),this.initTimeout&&(clearTimeout(this.initTimeout),this.initTimeout=null),this.paymentTimeout&&(clearTimeout(this.paymentTimeout),this.paymentTimeout=null),this.statusTimeout&&(clearTimeout(this.statusTimeout),this.statusTimeout=null),this.messageHandler&&(y.log("[Dropp SDK] ๐Ÿงน Destroying message handler"),this.messageHandler.destroy(),this.messageHandler=null),this.modalManager&&(y.log("[Dropp SDK] ๐Ÿงน Closing modal manager"),this.modalManager.close(),y.log("[Dropp SDK] ๐Ÿงน Modal manager closed"),this.modalManager=null),this.hiddenIframe&&this.hiddenIframe.parentNode&&this.hiddenIframe.parentNode.removeChild(this.hiddenIframe),this.hiddenIframe=null,this.currentSession=null,this.statusSession=null,this.currentFlowType=null,this.isOpen=!1,this.onClose&&this.onClose()}static getVersion(){return g}static getEnvironments(){return{...i}}static getPaymentTypes(){return{...c}}}let A=null;async function C(e){A=new _(e);return{...await A.initialize(),sdk:A}}const N={init:e=>C(e),pay(e){if(!A){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.pay(options).");throw e.code="SDK_NOT_INITIALIZED",e}return A.pay(e)},dashboard(e){if(!A){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.dashboard(options).");throw e.code="SDK_NOT_INITIALIZED",e}return A.dashboard(e)},open(e,t){if(!A){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.open(moduleId, options).");throw e.code="SDK_NOT_INITIALIZED",e}return A.open(e,t)},unlinkAccount(e){if(!A){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.unlinkAccount(options).");throw e.code="SDK_NOT_INITIALIZED",e}return A.unlinkAccount(e)},transactions(e){if(!A){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.transactions(options).");throw e.code="SDK_NOT_INITIALIZED",e}return A.transactions(e)},offers(e){if(!A){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.offers(options).");throw e.code="SDK_NOT_INITIALIZED",e}return A.offers(e)},status(){if(!A){const e=new Error("Dropp SDK is not initialized. Call Dropp.init(config) before Dropp.status().");throw e.code="SDK_NOT_INITIALIZED",e}return A.status()},getInstance:()=>A};var O={DroppPaymentSDK:_,createPaymentSDK:C,Dropp:N,ENVIRONMENTS:i,PAYMENT_TYPES:c};e.Dropp=N,e.DroppPaymentSDK=_,e.ENVIRONMENTS=i,e.PAYMENT_TYPES=c,e.createPaymentSDK=C,e.default=O,e.getDroppInstance=function(){return A},Object.defineProperty(e,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=dropp-payment-sdk.js.map