@frak-labs/core-sdk 0.1.0 → 0.1.1-beta.1e44255d

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.
Files changed (131) hide show
  1. package/README.md +58 -0
  2. package/cdn/bundle.js +3 -8
  3. package/dist/actions.cjs +1 -1
  4. package/dist/actions.d.cts +3 -1400
  5. package/dist/actions.d.ts +3 -1400
  6. package/dist/actions.js +1 -1
  7. package/dist/bundle.cjs +1 -13
  8. package/dist/bundle.d.cts +4 -1927
  9. package/dist/bundle.d.ts +4 -1927
  10. package/dist/bundle.js +1 -13
  11. package/dist/computeLegacyProductId-BkyJ4rEY.d.ts +538 -0
  12. package/dist/computeLegacyProductId-Raks6FXg.d.cts +538 -0
  13. package/dist/index.cjs +1 -13
  14. package/dist/index.d.cts +3 -1269
  15. package/dist/index.d.ts +3 -1269
  16. package/dist/index.js +1 -13
  17. package/dist/openSso-BCJGchIb.d.cts +1022 -0
  18. package/dist/openSso-DG-_9CED.d.ts +1022 -0
  19. package/dist/setupClient-Cfwpu08d.js +13 -0
  20. package/dist/setupClient-Dh8ljuhV.cjs +13 -0
  21. package/dist/siweAuthenticate-BH7Dn7nZ.d.cts +536 -0
  22. package/dist/siweAuthenticate-BJHbtty4.js +1 -0
  23. package/dist/siweAuthenticate-Btem4QHs.d.ts +536 -0
  24. package/dist/siweAuthenticate-Cwj3HP0m.cjs +1 -0
  25. package/dist/trackEvent-M2RLTQ2p.js +1 -0
  26. package/dist/trackEvent-T_R9ER2S.cjs +1 -0
  27. package/package.json +25 -31
  28. package/src/actions/displayEmbeddedWallet.test.ts +194 -0
  29. package/src/actions/displayEmbeddedWallet.ts +21 -0
  30. package/src/actions/displayModal.test.ts +388 -0
  31. package/src/actions/displayModal.ts +120 -0
  32. package/src/actions/ensureIdentity.ts +68 -0
  33. package/src/actions/getMerchantInformation.test.ts +116 -0
  34. package/src/actions/getMerchantInformation.ts +16 -0
  35. package/src/actions/index.ts +30 -0
  36. package/src/actions/openSso.ts +118 -0
  37. package/src/actions/prepareSso.test.ts +223 -0
  38. package/src/actions/prepareSso.ts +48 -0
  39. package/src/actions/referral/processReferral.test.ts +248 -0
  40. package/src/actions/referral/processReferral.ts +232 -0
  41. package/src/actions/referral/referralInteraction.test.ts +147 -0
  42. package/src/actions/referral/referralInteraction.ts +52 -0
  43. package/src/actions/sendInteraction.ts +56 -0
  44. package/src/actions/trackPurchaseStatus.test.ts +500 -0
  45. package/src/actions/trackPurchaseStatus.ts +90 -0
  46. package/src/actions/watchWalletStatus.test.ts +372 -0
  47. package/src/actions/watchWalletStatus.ts +93 -0
  48. package/src/actions/wrapper/modalBuilder.test.ts +239 -0
  49. package/src/actions/wrapper/modalBuilder.ts +203 -0
  50. package/src/actions/wrapper/sendTransaction.test.ts +164 -0
  51. package/src/actions/wrapper/sendTransaction.ts +62 -0
  52. package/src/actions/wrapper/siweAuthenticate.test.ts +290 -0
  53. package/src/actions/wrapper/siweAuthenticate.ts +94 -0
  54. package/src/bundle.ts +2 -0
  55. package/src/clients/DebugInfo.test.ts +418 -0
  56. package/src/clients/DebugInfo.ts +182 -0
  57. package/src/clients/createIFrameFrakClient.ts +292 -0
  58. package/src/clients/index.ts +3 -0
  59. package/src/clients/setupClient.test.ts +343 -0
  60. package/src/clients/setupClient.ts +73 -0
  61. package/src/clients/transports/iframeLifecycleManager.test.ts +558 -0
  62. package/src/clients/transports/iframeLifecycleManager.ts +229 -0
  63. package/src/constants/interactionTypes.ts +15 -0
  64. package/src/constants/locales.ts +14 -0
  65. package/src/index.ts +109 -0
  66. package/src/types/client.ts +14 -0
  67. package/src/types/compression.ts +22 -0
  68. package/src/types/config.ts +117 -0
  69. package/src/types/context.ts +13 -0
  70. package/src/types/index.ts +74 -0
  71. package/src/types/lifecycle/client.ts +69 -0
  72. package/src/types/lifecycle/iframe.ts +41 -0
  73. package/src/types/lifecycle/index.ts +2 -0
  74. package/src/types/rpc/displayModal.ts +82 -0
  75. package/src/types/rpc/embedded/index.ts +68 -0
  76. package/src/types/rpc/embedded/loggedIn.ts +55 -0
  77. package/src/types/rpc/embedded/loggedOut.ts +28 -0
  78. package/src/types/rpc/interaction.ts +30 -0
  79. package/src/types/rpc/merchantInformation.ts +77 -0
  80. package/src/types/rpc/modal/final.ts +46 -0
  81. package/src/types/rpc/modal/generic.ts +46 -0
  82. package/src/types/rpc/modal/index.ts +16 -0
  83. package/src/types/rpc/modal/login.ts +36 -0
  84. package/src/types/rpc/modal/siweAuthenticate.ts +37 -0
  85. package/src/types/rpc/modal/transaction.ts +33 -0
  86. package/src/types/rpc/sso.ts +80 -0
  87. package/src/types/rpc/walletStatus.ts +29 -0
  88. package/src/types/rpc.ts +150 -0
  89. package/src/types/tracking.ts +60 -0
  90. package/src/types/transport.ts +34 -0
  91. package/src/utils/FrakContext.test.ts +407 -0
  92. package/src/utils/FrakContext.ts +158 -0
  93. package/src/utils/backendUrl.test.ts +83 -0
  94. package/src/utils/backendUrl.ts +62 -0
  95. package/src/utils/clientId.test.ts +41 -0
  96. package/src/utils/clientId.ts +43 -0
  97. package/src/utils/compression/b64.test.ts +181 -0
  98. package/src/utils/compression/b64.ts +29 -0
  99. package/src/utils/compression/compress.test.ts +123 -0
  100. package/src/utils/compression/compress.ts +11 -0
  101. package/src/utils/compression/decompress.test.ts +149 -0
  102. package/src/utils/compression/decompress.ts +11 -0
  103. package/src/utils/compression/index.ts +3 -0
  104. package/src/utils/computeLegacyProductId.ts +11 -0
  105. package/src/utils/constants.test.ts +23 -0
  106. package/src/utils/constants.ts +9 -0
  107. package/src/utils/deepLinkWithFallback.test.ts +243 -0
  108. package/src/utils/deepLinkWithFallback.ts +103 -0
  109. package/src/utils/formatAmount.test.ts +113 -0
  110. package/src/utils/formatAmount.ts +24 -0
  111. package/src/utils/getCurrencyAmountKey.test.ts +44 -0
  112. package/src/utils/getCurrencyAmountKey.ts +15 -0
  113. package/src/utils/getSupportedCurrency.test.ts +51 -0
  114. package/src/utils/getSupportedCurrency.ts +14 -0
  115. package/src/utils/getSupportedLocale.test.ts +64 -0
  116. package/src/utils/getSupportedLocale.ts +16 -0
  117. package/src/utils/iframeHelper.test.ts +463 -0
  118. package/src/utils/iframeHelper.ts +150 -0
  119. package/src/utils/index.ts +36 -0
  120. package/src/utils/merchantId.test.ts +653 -0
  121. package/src/utils/merchantId.ts +143 -0
  122. package/src/utils/sso.ts +126 -0
  123. package/src/utils/ssoUrlListener.test.ts +252 -0
  124. package/src/utils/ssoUrlListener.ts +60 -0
  125. package/src/utils/trackEvent.test.ts +180 -0
  126. package/src/utils/trackEvent.ts +41 -0
  127. package/cdn/bundle.js.LICENSE.txt +0 -10
  128. package/dist/interactions.cjs +0 -1
  129. package/dist/interactions.d.cts +0 -182
  130. package/dist/interactions.d.ts +0 -182
  131. package/dist/interactions.js +0 -1
@@ -0,0 +1,13 @@
1
+ import{f as e,h as t}from"./trackEvent-M2RLTQ2p.js";import{Deferred as n,FrakRpcError as r,RpcErrorCodes as i,createRpcClient as a,jsonDecode as o}from"@frak-labs/frame-connector";import{OpenPanel as s}from"@openpanel/web";function c(t){return o(e(t))}const l=`nexus-wallet-backup`,u=`frakwallet://`;function d(){let e=navigator.userAgent;return/Android/i.test(e)&&/Chrome\/\d+/i.test(e)}function f(e){return`intent://${e.slice(13)}#Intent;scheme=frakwallet;end`}function p(e,t){let n=t?.timeout??2500,r=!1,i=()=>{document.hidden&&(r=!0)};document.addEventListener(`visibilitychange`,i);let a=d()&&m(e)?f(e):e;window.location.href=a,setTimeout(()=>{document.removeEventListener(`visibilitychange`,i),r||t?.onFallback?.()},n)}function m(e){return e.startsWith(u)}const h={eur:`fr-FR`,usd:`en-US`,gbp:`en-GB`};function g(e){return e&&e in h?e:`eur`}function _(e){return e?h[e]??h.eur:h.eur}function v(e,t){let n=_(t),r=g(t);return e.toLocaleString(n,{style:`currency`,currency:r,minimumFractionDigits:0,maximumFractionDigits:2})}function y(e){return e?`${e}Amount`:`eurAmount`}const b={id:`frak-wallet`,name:`frak-wallet`,title:`Frak Wallet`,allow:`publickey-credentials-get *; clipboard-write; web-share *`,style:{width:`0`,height:`0`,border:`0`,position:`absolute`,zIndex:2000001,top:`-1000px`,left:`-1000px`,colorScheme:`auto`}};function x({walletBaseUrl:e,config:n}){let r=document.querySelector(`#frak-wallet`);r&&r.remove();let i=document.createElement(`iframe`);i.id=b.id,i.name=b.name,i.allow=b.allow,i.style.zIndex=b.style.zIndex.toString(),S({iframe:i,isVisible:!1});let a=n?.walletUrl??e??`https://wallet.frak.id`,o=t();return i.src=`${a}/listener?clientId=${encodeURIComponent(o)}`,new Promise(e=>{i.addEventListener(`load`,()=>e(i)),document.body.appendChild(i)})}function S({iframe:e,isVisible:t}){if(!t){e.style.width=`0`,e.style.height=`0`,e.style.border=`0`,e.style.position=`fixed`,e.style.top=`-1000px`,e.style.left=`-1000px`;return}e.style.position=`fixed`,e.style.top=`0`,e.style.left=`0`,e.style.width=`100%`,e.style.height=`100%`,e.style.pointerEvents=`auto`}function C(e=`/listener`){if(!window.opener)return null;let t=t=>{try{return t.location.origin===window.location.origin&&t.location.pathname===e}catch{return!1}};if(t(window.opener))return window.opener;try{let e=window.opener.frames;for(let n=0;n<e.length;n++)if(t(e[n]))return e[n];return null}catch(t){return console.error(`[findIframeInOpener] Error finding iframe with pathname ${e}:`,t),null}}function w(e,t){if(typeof window>`u`)return;let n=new URL(window.location.href),r=n.searchParams.get(`sso`);r&&(t.then(()=>{e.sendLifecycle({clientLifecycle:`sso-redirect-complete`,data:{compressed:r}}),console.log(`[SSO URL Listener] Forwarded compressed SSO data to iframe`)}).catch(e=>{console.error(`[SSO URL Listener] Failed to forward SSO data:`,e)}),n.searchParams.delete(`sso`),window.history.replaceState({},``,n.toString()),console.log(`[SSO URL Listener] SSO parameter detected and URL cleaned`))}var T=class e{config;iframe;isSetupDone=!1;lastResponse=null;lastRequest=null;constructor(e,t){this.config=e,this.iframe=t,this.lastRequest=null,this.lastResponse=null}setLastResponse(e,t){this.lastResponse={message:e,response:t,timestamp:Date.now()}}setLastRequest(e){this.lastRequest={event:e,timestamp:Date.now()}}updateSetupStatus(e){this.isSetupDone=e}base64Encode(e){try{return btoa(JSON.stringify(e))}catch(e){return console.warn(`Failed to encode debug data`,e),btoa(`Failed to encode data`)}}getIframeStatus(){return this.iframe?{loading:this.iframe.hasAttribute(`loading`),url:this.iframe.src,readyState:this.iframe.contentDocument?.readyState?this.iframe.contentDocument.readyState===`complete`?1:0:-1,contentWindow:!!this.iframe.contentWindow,isConnected:this.iframe.isConnected}:null}getNavigatorInfo(){return navigator?{userAgent:navigator.userAgent,language:navigator.language,onLine:navigator.onLine,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio}:null}gatherDebugInfo(e){let t=this.getIframeStatus(),n=this.getNavigatorInfo(),i=`Unknown`;return e instanceof r?i=`FrakRpcError: ${e.code} '${e.message}'`:e instanceof Error?i=e.message:typeof e==`string`&&(i=e),{timestamp:new Date().toISOString(),encodedUrl:btoa(window.location.href),encodedConfig:this.config?this.base64Encode(this.config):`no-config`,navigatorInfo:n?this.base64Encode(n):`no-navigator`,iframeStatus:t?this.base64Encode(t):`not-iframe`,lastRequest:this.lastRequest?this.base64Encode(this.lastRequest):`No Frak request logged`,lastResponse:this.lastResponse?this.base64Encode(this.lastResponse):`No Frak response logged`,clientStatus:this.isSetupDone?`setup`:`not-setup`,error:i}}static empty(){return new e}formatDebugInfo(e){let t=this.gatherDebugInfo(e);return`
2
+ Debug Information:
3
+ -----------------
4
+ Timestamp: ${t.timestamp}
5
+ URL: ${t.encodedUrl}
6
+ Config: ${t.encodedConfig}
7
+ Navigator Info: ${t.navigatorInfo}
8
+ IFrame Status: ${t.iframeStatus}
9
+ Last Request: ${t.lastRequest}
10
+ Last Response: ${t.lastResponse}
11
+ Client Status: ${t.clientStatus}
12
+ Error: ${t.error}
13
+ `.trim()}};const E=(()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent;if(!(/iPhone|iPad|iPod/i.test(e)||/Macintosh/i.test(e)&&navigator.maxTouchPoints>1))return!1;let t=e.toLowerCase();return t.includes(`instagram`)||t.includes(`fban`)||t.includes(`fbav`)||t.includes(`facebook`)})();function D(e){e?localStorage.setItem(l,e):localStorage.removeItem(l)}function O(e,n,r,i){let a=new URL(window.location.href),o=a.searchParams.get(`fmt`)??void 0;e.contentWindow?.postMessage({clientLifecycle:`handshake-response`,data:{token:n,currentUrl:window.location.href,pendingMergeToken:o,configDomain:i,clientId:t()}},r),o&&(a.searchParams.delete(`fmt`),window.history.replaceState({},``,a.toString()))}function k(e,t){try{let n=new URL(e);return n.searchParams.has(`u`)?(n.searchParams.delete(`u`),n.searchParams.append(`u`,window.location.href),t&&n.searchParams.append(`fmt`,t),n.toString()):e}catch{return e}}function A(e){let t=new URL(window.location.href);e&&t.searchParams.set(`fmt`,e);let n=t.protocol===`http:`?`x-safari-http`:`x-safari-https`;window.location.href=`${n}://${t.host}${t.pathname}${t.search}${t.hash}`}function j(e){return e.includes(`/common/social`)}function M(e,t,n,r){if(m(t)){let i=k(t,r);p(i,{onFallback:()=>{e.contentWindow?.postMessage({clientLifecycle:`deep-link-failed`,data:{originalUrl:i}},n)}})}else if(E&&j(t))A(r);else{let e=k(t,r);window.location.href=e}}function N({iframe:e,targetOrigin:t,configDomain:r}){let i=new n;return{handleEvent:async n=>{if(!(`iframeLifecycle`in n))return;let{iframeLifecycle:a,data:o}=n;switch(a){case`connected`:i.resolve(!0);break;case`do-backup`:D(o.backup);break;case`remove-backup`:localStorage.removeItem(l);break;case`show`:case`hide`:S({iframe:e,isVisible:a===`show`});break;case`handshake`:O(e,o.token,t,r);break;case`redirect`:M(e,o.baseRedirectUrl,t,o.mergeToken);break}},isConnected:i.promise}}function P({config:e,iframe:n}){let o=e?.walletUrl??`https://wallet.frak.id`,c=N({iframe:n,targetOrigin:o,configDomain:e.domain}),l=new T(e,n);if(!n.contentWindow)throw new r(i.configError,`The iframe does not have a content window`);let u=a({emittingTransport:n.contentWindow,listeningTransport:window,targetOrigin:o,middleware:[{async onRequest(e,t){if(!await c.isConnected)throw new r(i.clientNotConnected,`The iframe provider isn't connected yet`);return t}},{onRequest(e,t){return l.setLastRequest(e),t},onResponse(e,t){return l.setLastResponse(e,t),t}}],lifecycleHandlers:{iframeLifecycle:async(e,t)=>{await c.handleEvent(e)}}}),d=F(u,c),f=async()=>{d(),u.cleanup(),n.remove()},p;console.log(`[Frak SDK] Initializing OpenPanel`),p=new s({apiUrl:`https://op-api.gcp.frak.id`,clientId:`6eacc8d7-49ac-4936-95e9-81ef29449570`,trackScreenViews:!0,trackOutgoingLinks:!0,trackAttributes:!1,filter:({type:e,payload:n})=>(e!==`track`||!n?.properties||`sdkVersion`in n.properties||(n.properties={...n.properties,sdkVersion:`0.1.1`,userAnonymousClientId:t()}),!0)}),p.setGlobalProperties({sdkVersion:`0.1.1`,userAnonymousClientId:t()}),p.init();let m=I({config:e,rpcClient:u,lifecycleManager:c}).then(()=>l.updateSetupStatus(!0));return{config:e,debugInfo:l,waitForConnection:c.isConnected,waitForSetup:m,request:u.request,listenerRequest:u.listen,destroy:f,openPanel:p}}function F(e,t){let n,r,i=()=>e.sendLifecycle({clientLifecycle:`heartbeat`});async function a(){i(),n=setInterval(i,1e3),r=setTimeout(()=>{o(),console.log(`Heartbeat timeout: connection failed`)},3e4),await t.isConnected,o()}function o(){n&&clearInterval(n),r&&clearTimeout(r)}return a(),o}async function I({config:e,rpcClient:t,lifecycleManager:n}){await n.isConnected,w(t,n.isConnected);async function r(){let n=e.customizations?.css;if(!n)return;let r={clientLifecycle:`modal-css`,data:{cssLink:n}};t.sendLifecycle(r)}async function i(){let n=e.customizations?.i18n;if(!n)return;let r={clientLifecycle:`modal-i18n`,data:{i18n:n}};t.sendLifecycle(r)}async function a(){if(typeof window>`u`)return;let e=window.localStorage.getItem(l);if(!e)return;let n={clientLifecycle:`restore-backup`,data:{backup:e}};t.sendLifecycle(n)}await Promise.allSettled([r(),i(),a()])}async function L({config:e}){let t=R(e),n=await x({config:t});if(!n){console.error(`Failed to create iframe`);return}let r=P({config:t,iframe:n});if(await r.waitForSetup,!await r.waitForConnection){console.error(`Failed to connect to client`);return}return r}function R(e){let t=g(e.metadata?.currency);return{...e,metadata:{...e.metadata,currency:t}}}export{c as _,x as a,v as c,h as d,d as f,u as g,p as h,b as i,_ as l,f as m,P as n,C as o,m as p,T as r,y as s,L as t,g as u};
@@ -0,0 +1,13 @@
1
+ const e=require(`./trackEvent-T_R9ER2S.cjs`);let t=require(`@frak-labs/frame-connector`),n=require(`@openpanel/web`);function r(n){return(0,t.jsonDecode)(e.f(n))}const i=`nexus-wallet-backup`,a=`frakwallet://`;function o(){let e=navigator.userAgent;return/Android/i.test(e)&&/Chrome\/\d+/i.test(e)}function s(e){return`intent://${e.slice(13)}#Intent;scheme=frakwallet;end`}function c(e,t){let n=t?.timeout??2500,r=!1,i=()=>{document.hidden&&(r=!0)};document.addEventListener(`visibilitychange`,i);let a=o()&&l(e)?s(e):e;window.location.href=a,setTimeout(()=>{document.removeEventListener(`visibilitychange`,i),r||t?.onFallback?.()},n)}function l(e){return e.startsWith(a)}const u={eur:`fr-FR`,usd:`en-US`,gbp:`en-GB`};function d(e){return e&&e in u?e:`eur`}function f(e){return e?u[e]??u.eur:u.eur}function p(e,t){let n=f(t),r=d(t);return e.toLocaleString(n,{style:`currency`,currency:r,minimumFractionDigits:0,maximumFractionDigits:2})}function m(e){return e?`${e}Amount`:`eurAmount`}const h={id:`frak-wallet`,name:`frak-wallet`,title:`Frak Wallet`,allow:`publickey-credentials-get *; clipboard-write; web-share *`,style:{width:`0`,height:`0`,border:`0`,position:`absolute`,zIndex:2000001,top:`-1000px`,left:`-1000px`,colorScheme:`auto`}};function g({walletBaseUrl:t,config:n}){let r=document.querySelector(`#frak-wallet`);r&&r.remove();let i=document.createElement(`iframe`);i.id=h.id,i.name=h.name,i.allow=h.allow,i.style.zIndex=h.style.zIndex.toString(),_({iframe:i,isVisible:!1});let a=n?.walletUrl??t??`https://wallet.frak.id`,o=e.h();return i.src=`${a}/listener?clientId=${encodeURIComponent(o)}`,new Promise(e=>{i.addEventListener(`load`,()=>e(i)),document.body.appendChild(i)})}function _({iframe:e,isVisible:t}){if(!t){e.style.width=`0`,e.style.height=`0`,e.style.border=`0`,e.style.position=`fixed`,e.style.top=`-1000px`,e.style.left=`-1000px`;return}e.style.position=`fixed`,e.style.top=`0`,e.style.left=`0`,e.style.width=`100%`,e.style.height=`100%`,e.style.pointerEvents=`auto`}function v(e=`/listener`){if(!window.opener)return null;let t=t=>{try{return t.location.origin===window.location.origin&&t.location.pathname===e}catch{return!1}};if(t(window.opener))return window.opener;try{let e=window.opener.frames;for(let n=0;n<e.length;n++)if(t(e[n]))return e[n];return null}catch(t){return console.error(`[findIframeInOpener] Error finding iframe with pathname ${e}:`,t),null}}function y(e,t){if(typeof window>`u`)return;let n=new URL(window.location.href),r=n.searchParams.get(`sso`);r&&(t.then(()=>{e.sendLifecycle({clientLifecycle:`sso-redirect-complete`,data:{compressed:r}}),console.log(`[SSO URL Listener] Forwarded compressed SSO data to iframe`)}).catch(e=>{console.error(`[SSO URL Listener] Failed to forward SSO data:`,e)}),n.searchParams.delete(`sso`),window.history.replaceState({},``,n.toString()),console.log(`[SSO URL Listener] SSO parameter detected and URL cleaned`))}var b=class e{config;iframe;isSetupDone=!1;lastResponse=null;lastRequest=null;constructor(e,t){this.config=e,this.iframe=t,this.lastRequest=null,this.lastResponse=null}setLastResponse(e,t){this.lastResponse={message:e,response:t,timestamp:Date.now()}}setLastRequest(e){this.lastRequest={event:e,timestamp:Date.now()}}updateSetupStatus(e){this.isSetupDone=e}base64Encode(e){try{return btoa(JSON.stringify(e))}catch(e){return console.warn(`Failed to encode debug data`,e),btoa(`Failed to encode data`)}}getIframeStatus(){return this.iframe?{loading:this.iframe.hasAttribute(`loading`),url:this.iframe.src,readyState:this.iframe.contentDocument?.readyState?this.iframe.contentDocument.readyState===`complete`?1:0:-1,contentWindow:!!this.iframe.contentWindow,isConnected:this.iframe.isConnected}:null}getNavigatorInfo(){return navigator?{userAgent:navigator.userAgent,language:navigator.language,onLine:navigator.onLine,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio}:null}gatherDebugInfo(e){let n=this.getIframeStatus(),r=this.getNavigatorInfo(),i=`Unknown`;return e instanceof t.FrakRpcError?i=`FrakRpcError: ${e.code} '${e.message}'`:e instanceof Error?i=e.message:typeof e==`string`&&(i=e),{timestamp:new Date().toISOString(),encodedUrl:btoa(window.location.href),encodedConfig:this.config?this.base64Encode(this.config):`no-config`,navigatorInfo:r?this.base64Encode(r):`no-navigator`,iframeStatus:n?this.base64Encode(n):`not-iframe`,lastRequest:this.lastRequest?this.base64Encode(this.lastRequest):`No Frak request logged`,lastResponse:this.lastResponse?this.base64Encode(this.lastResponse):`No Frak response logged`,clientStatus:this.isSetupDone?`setup`:`not-setup`,error:i}}static empty(){return new e}formatDebugInfo(e){let t=this.gatherDebugInfo(e);return`
2
+ Debug Information:
3
+ -----------------
4
+ Timestamp: ${t.timestamp}
5
+ URL: ${t.encodedUrl}
6
+ Config: ${t.encodedConfig}
7
+ Navigator Info: ${t.navigatorInfo}
8
+ IFrame Status: ${t.iframeStatus}
9
+ Last Request: ${t.lastRequest}
10
+ Last Response: ${t.lastResponse}
11
+ Client Status: ${t.clientStatus}
12
+ Error: ${t.error}
13
+ `.trim()}};const x=(()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent;if(!(/iPhone|iPad|iPod/i.test(e)||/Macintosh/i.test(e)&&navigator.maxTouchPoints>1))return!1;let t=e.toLowerCase();return t.includes(`instagram`)||t.includes(`fban`)||t.includes(`fbav`)||t.includes(`facebook`)})();function S(e){e?localStorage.setItem(i,e):localStorage.removeItem(i)}function C(t,n,r,i){let a=new URL(window.location.href),o=a.searchParams.get(`fmt`)??void 0;t.contentWindow?.postMessage({clientLifecycle:`handshake-response`,data:{token:n,currentUrl:window.location.href,pendingMergeToken:o,configDomain:i,clientId:e.h()}},r),o&&(a.searchParams.delete(`fmt`),window.history.replaceState({},``,a.toString()))}function w(e,t){try{let n=new URL(e);return n.searchParams.has(`u`)?(n.searchParams.delete(`u`),n.searchParams.append(`u`,window.location.href),t&&n.searchParams.append(`fmt`,t),n.toString()):e}catch{return e}}function T(e){let t=new URL(window.location.href);e&&t.searchParams.set(`fmt`,e);let n=t.protocol===`http:`?`x-safari-http`:`x-safari-https`;window.location.href=`${n}://${t.host}${t.pathname}${t.search}${t.hash}`}function E(e){return e.includes(`/common/social`)}function D(e,t,n,r){if(l(t)){let i=w(t,r);c(i,{onFallback:()=>{e.contentWindow?.postMessage({clientLifecycle:`deep-link-failed`,data:{originalUrl:i}},n)}})}else if(x&&E(t))T(r);else{let e=w(t,r);window.location.href=e}}function O({iframe:e,targetOrigin:n,configDomain:r}){let a=new t.Deferred;return{handleEvent:async t=>{if(!(`iframeLifecycle`in t))return;let{iframeLifecycle:o,data:s}=t;switch(o){case`connected`:a.resolve(!0);break;case`do-backup`:S(s.backup);break;case`remove-backup`:localStorage.removeItem(i);break;case`show`:case`hide`:_({iframe:e,isVisible:o===`show`});break;case`handshake`:C(e,s.token,n,r);break;case`redirect`:D(e,s.baseRedirectUrl,n,s.mergeToken);break}},isConnected:a.promise}}function k({config:r,iframe:i}){let a=r?.walletUrl??`https://wallet.frak.id`,o=O({iframe:i,targetOrigin:a,configDomain:r.domain}),s=new b(r,i);if(!i.contentWindow)throw new t.FrakRpcError(t.RpcErrorCodes.configError,`The iframe does not have a content window`);let c=(0,t.createRpcClient)({emittingTransport:i.contentWindow,listeningTransport:window,targetOrigin:a,middleware:[{async onRequest(e,n){if(!await o.isConnected)throw new t.FrakRpcError(t.RpcErrorCodes.clientNotConnected,`The iframe provider isn't connected yet`);return n}},{onRequest(e,t){return s.setLastRequest(e),t},onResponse(e,t){return s.setLastResponse(e,t),t}}],lifecycleHandlers:{iframeLifecycle:async(e,t)=>{await o.handleEvent(e)}}}),l=A(c,o),u=async()=>{l(),c.cleanup(),i.remove()},d;console.log(`[Frak SDK] Initializing OpenPanel`),d=new n.OpenPanel({apiUrl:`https://op-api.gcp.frak.id`,clientId:`6eacc8d7-49ac-4936-95e9-81ef29449570`,trackScreenViews:!0,trackOutgoingLinks:!0,trackAttributes:!1,filter:({type:t,payload:n})=>(t!==`track`||!n?.properties||`sdkVersion`in n.properties||(n.properties={...n.properties,sdkVersion:`0.1.1`,userAnonymousClientId:e.h()}),!0)}),d.setGlobalProperties({sdkVersion:`0.1.1`,userAnonymousClientId:e.h()}),d.init();let f=j({config:r,rpcClient:c,lifecycleManager:o}).then(()=>s.updateSetupStatus(!0));return{config:r,debugInfo:s,waitForConnection:o.isConnected,waitForSetup:f,request:c.request,listenerRequest:c.listen,destroy:u,openPanel:d}}function A(e,t){let n,r,i=()=>e.sendLifecycle({clientLifecycle:`heartbeat`});async function a(){i(),n=setInterval(i,1e3),r=setTimeout(()=>{o(),console.log(`Heartbeat timeout: connection failed`)},3e4),await t.isConnected,o()}function o(){n&&clearInterval(n),r&&clearTimeout(r)}return a(),o}async function j({config:e,rpcClient:t,lifecycleManager:n}){await n.isConnected,y(t,n.isConnected);async function r(){let n=e.customizations?.css;if(!n)return;let r={clientLifecycle:`modal-css`,data:{cssLink:n}};t.sendLifecycle(r)}async function a(){let n=e.customizations?.i18n;if(!n)return;let r={clientLifecycle:`modal-i18n`,data:{i18n:n}};t.sendLifecycle(r)}async function o(){if(typeof window>`u`)return;let e=window.localStorage.getItem(i);if(!e)return;let n={clientLifecycle:`restore-backup`,data:{backup:e}};t.sendLifecycle(n)}await Promise.allSettled([r(),a(),o()])}async function M({config:e}){let t=N(e),n=await g({config:t});if(!n){console.error(`Failed to create iframe`);return}let r=k({config:t,iframe:n});if(await r.waitForSetup,!await r.waitForConnection){console.error(`Failed to connect to client`);return}return r}function N(e){let t=d(e.metadata?.currency);return{...e,metadata:{...e.metadata,currency:t}}}Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return d}});
@@ -0,0 +1,536 @@
1
+ import { A as SiweAuthenticateReturnType, D as SendTransactionReturnType, E as SendTransactionModalStepType, F as PrepareSsoParamsType, I as PrepareSsoReturnType, M as LoginModalStepType, R as FinalActionType, S as ModalRpcMetadata, T as ModalStepTypes, a as FrakClient, d as GetMerchantInformationReturnType, g as DisplayEmbeddedWalletResultType, h as DisplayEmbeddedWalletParamsType, i as FrakContext, j as SiweAuthenticationParams, l as WalletStatusReturnType, m as SendInteractionParamsType, w as ModalRpcStepsResultType, x as DisplayModalParamsType, z as FinalModalStepType } from "./openSso-BCJGchIb.cjs";
2
+
3
+ //#region src/actions/displayEmbeddedWallet.d.ts
4
+ /**
5
+ * Function used to display the Frak embedded wallet popup
6
+ * @param client - The current Frak Client
7
+ * @param params - The parameter used to customise the embedded wallet
8
+ * @returns The embedded wallet display result
9
+ */
10
+ declare function displayEmbeddedWallet(client: FrakClient, params: DisplayEmbeddedWalletParamsType): Promise<DisplayEmbeddedWalletResultType>;
11
+ //#endregion
12
+ //#region src/actions/displayModal.d.ts
13
+ /**
14
+ * Function used to display a modal
15
+ * @param client - The current Frak Client
16
+ * @param args
17
+ * @param args.steps - The different steps of the modal
18
+ * @param args.metadata - The metadata for the modal (customization, etc)
19
+ * @returns The result of each modal steps
20
+ *
21
+ * @description This function will display a modal to the user with the provided steps and metadata.
22
+ *
23
+ * @remarks
24
+ * - The UI of the displayed modal can be configured with the `customCss` property in the `customizations.css` field of the top-level config.
25
+ * - The `login` step will be automatically skipped if the user is already logged in. It's safe to include this step in all cases to ensure proper user state.
26
+ * - Steps are automatically reordered in the following sequence:
27
+ * 1. `login` (if needed)
28
+ * 2. All other steps in the order specified
29
+ * 3. `success` (if included, always last)
30
+ *
31
+ * @example
32
+ * Simple sharing modal with steps:
33
+ * 1. Login (Skipped if already logged in)
34
+ * 2. Display a success message with sharing link option
35
+ *
36
+ * ```ts
37
+ * const results = await displayModal(frakConfig, {
38
+ * steps: {
39
+ * // Simple login with no SSO, nor customization
40
+ * login: { allowSso: false },
41
+ * // Success message
42
+ * final: {
43
+ * action: { key: "reward" },
44
+ * // Skip this step, it will be only displayed in the stepper within the modal
45
+ * autoSkip: true,
46
+ * },
47
+ * },
48
+ * });
49
+ *
50
+ * console.log("Login step - wallet", results.login.wallet);
51
+ * ```
52
+ *
53
+ * @example
54
+ * A full modal example, with a few customization options, with the steps:
55
+ * 1. Login (Skipped if already logged in)
56
+ * 2. Authenticate via SIWE
57
+ * 3. Send a transaction
58
+ * 4. Display a success message with sharing link options
59
+ *
60
+ * ```ts
61
+ * const results = await displayModal(frakConfig, {
62
+ * steps: {
63
+ * // Login step
64
+ * login: {
65
+ * allowSso: true,
66
+ * ssoMetadata: {
67
+ * logoUrl: "https://my-app.com/logo.png",
68
+ * homepageLink: "https://my-app.com",
69
+ * },
70
+ * },
71
+ * // Siwe authentication
72
+ * siweAuthenticate: {
73
+ * siwe: {
74
+ * domain: "my-app.com",
75
+ * uri: "https://my-app.com/",
76
+ * nonce: generateSiweNonce(),
77
+ * version: "1",
78
+ * },
79
+ * },
80
+ * // Send batched transaction
81
+ * sendTransaction: {
82
+ * tx: [
83
+ * { to: "0xdeadbeef", data: "0xdeadbeef" },
84
+ * { to: "0xdeadbeef", data: "0xdeadbeef" },
85
+ * ],
86
+ * },
87
+ * // Success message with sharing options
88
+ * final: {
89
+ * action: {
90
+ * key: "sharing",
91
+ * options: {
92
+ * popupTitle: "Share the app",
93
+ * text: "Discover my super app website",
94
+ * link: "https://my-app.com",
95
+ * },
96
+ * },
97
+ * dismissedMetadata: {
98
+ * title: "Dismiss",
99
+ * description: "You won't be rewarded for this sharing action",
100
+ * },
101
+ * },
102
+ * },
103
+ * metadata: {
104
+ * // Header of desktop modals
105
+ * header: {
106
+ * title: "My-App",
107
+ * icon: "https://my-app.com/logo.png",
108
+ * },
109
+ * // Context that will be present in every modal steps
110
+ * context: "My-app overkill flow",
111
+ * },
112
+ * });
113
+ * ```
114
+ */
115
+ declare function displayModal<T extends ModalStepTypes[] = ModalStepTypes[]>(client: FrakClient, {
116
+ steps,
117
+ metadata
118
+ }: DisplayModalParamsType<T>): Promise<ModalRpcStepsResultType<T>>;
119
+ //#endregion
120
+ //#region src/actions/ensureIdentity.d.ts
121
+ /**
122
+ * Ensure the current wallet ↔ clientId link exists on the backend.
123
+ *
124
+ * Called automatically by {@link watchWalletStatus} when a connected wallet
125
+ * status is received. Acts as a failsafe: if the primary merge (SSO, pairing,
126
+ * login/register) missed or silently failed, this ensures the link is
127
+ * eventually established.
128
+ *
129
+ * The call is:
130
+ * - **Idempotent** — if already linked, backend returns immediately
131
+ * - **Deduplicated** — only fires once per browser session per merchant
132
+ * - **Fire-and-forget** — errors are logged but never thrown
133
+ *
134
+ * @param interactionToken - The SDK JWT from wallet status (x-wallet-sdk-auth)
135
+ *
136
+ * @example
137
+ * ```ts
138
+ * // Usually called automatically via watchWalletStatus side effect.
139
+ * // Can also be called manually if needed:
140
+ * await ensureIdentity("eyJhbGciOi...");
141
+ * ```
142
+ */
143
+ declare function ensureIdentity(interactionToken: string): Promise<void>;
144
+ //#endregion
145
+ //#region src/actions/getMerchantInformation.d.ts
146
+ /**
147
+ * Fetch the current merchant information (name, rewards, tiers) from the wallet iframe
148
+ * @param client - The current Frak Client
149
+ * @returns The merchant information including available reward tiers
150
+ *
151
+ * @see {@link @frak-labs/core-sdk!index.GetMerchantInformationReturnType | `GetMerchantInformationReturnType`} for the return type shape
152
+ */
153
+ declare function getMerchantInformation(client: FrakClient): Promise<GetMerchantInformationReturnType>;
154
+ //#endregion
155
+ //#region src/actions/prepareSso.d.ts
156
+ /**
157
+ * Generate SSO URL without opening popup
158
+ *
159
+ * This is a **synchronous**, client-side function that generates the SSO URL
160
+ * without any RPC calls to the wallet iframe. Use this when you need:
161
+ * - Custom URL modifications before opening popup
162
+ * - Pre-generation for advanced popup strategies
163
+ * - URL inspection/logging before SSO flow
164
+ *
165
+ * @param client - The current Frak Client
166
+ * @param args - The SSO parameters
167
+ * @returns Object containing the generated ssoUrl
168
+ *
169
+ * @example
170
+ * ```ts
171
+ * // Generate URL for inspection
172
+ * const { ssoUrl } = prepareSso(client, {
173
+ * metadata: { logoUrl: "..." },
174
+ * directExit: true
175
+ * });
176
+ * console.log("Opening SSO:", ssoUrl);
177
+ *
178
+ * // Add custom params
179
+ * const customUrl = `${ssoUrl}&tracking=abc123`;
180
+ * await openSso(client, { metadata, ssoPopupUrl: customUrl });
181
+ * ```
182
+ *
183
+ * @remarks
184
+ * For most use cases, just use `openSso()` which handles URL generation automatically.
185
+ * Only use `prepareSso()` when you need explicit control over the URL.
186
+ */
187
+ declare function prepareSso(client: FrakClient, args: PrepareSsoParamsType): Promise<PrepareSsoReturnType>;
188
+ //#endregion
189
+ //#region src/actions/referral/processReferral.d.ts
190
+ /**
191
+ * The different states of the referral process
192
+ * @inline
193
+ */
194
+ type ReferralState = "idle" | "processing" | "success" | "no-wallet" | "error" | "no-referrer" | "self-referral";
195
+ /**
196
+ * Options for the referral auto-interaction process
197
+ */
198
+ type ProcessReferralOptions = {
199
+ /**
200
+ * If we want to always append the url with the frak context or not
201
+ * @defaultValue false
202
+ */
203
+ alwaysAppendUrl?: boolean;
204
+ };
205
+ /**
206
+ * This function handle all the heavy lifting of the referral interaction process
207
+ * 1. Check if the user has been referred or not (if not, early exit)
208
+ * 2. Then check if the user is logged in or not
209
+ * 2.1 If not logged in, try a soft login, if it fail, display a modal for the user to login
210
+ * 3. Check if that's not a self-referral (if yes, early exit)
211
+ * 4. Track the referral event
212
+ * 5. Update the current url with the right data
213
+ * 6. Return the resulting referral state
214
+ *
215
+ * If any error occurs during the process, the function will catch it and return an error state
216
+ *
217
+ * @param client - The current Frak Client
218
+ * @param args
219
+ * @param args.walletStatus - The current user wallet status
220
+ * @param args.frakContext - The current frak context
221
+ * @param args.modalConfig - The modal configuration to display if the user is not logged in
222
+ * @param args.options - Some options for the referral interaction
223
+ * @returns A promise with the resulting referral state
224
+ *
225
+ * @see {@link displayModal} for more details about the displayed modal
226
+ * @see {@link @frak-labs/core-sdk!ModalStepTypes} for more details on each modal steps types
227
+ */
228
+ declare function processReferral(client: FrakClient, {
229
+ walletStatus,
230
+ frakContext,
231
+ modalConfig,
232
+ options
233
+ }: {
234
+ walletStatus?: WalletStatusReturnType;
235
+ frakContext?: Partial<FrakContext> | null;
236
+ modalConfig?: DisplayEmbeddedWalletParamsType;
237
+ options?: ProcessReferralOptions;
238
+ }): Promise<ReferralState>;
239
+ //#endregion
240
+ //#region src/actions/referral/referralInteraction.d.ts
241
+ /**
242
+ * Function used to handle referral interactions
243
+ * @param client - The current Frak Client
244
+ * @param args
245
+ * @param args.modalConfig - The modal configuration to display if the user is not logged in
246
+ * @param args.options - Some options for the referral interaction
247
+ *
248
+ * @returns A promise with the resulting referral state, or undefined in case of an error
249
+ *
250
+ * @description This function will automatically handle the referral interaction process
251
+ *
252
+ * @see {@link processReferral} for more details on the automatic referral handling process
253
+ * @see {@link @frak-labs/core-sdk!ModalStepTypes} for more details on each modal steps types
254
+ */
255
+ declare function referralInteraction(client: FrakClient, {
256
+ modalConfig,
257
+ options
258
+ }?: {
259
+ modalConfig?: DisplayEmbeddedWalletParamsType;
260
+ options?: ProcessReferralOptions;
261
+ }): Promise<("no-referrer" | "self-referral" | "success" | "idle" | "processing" | "no-wallet" | "error") | undefined>;
262
+ //#endregion
263
+ //#region src/actions/sendInteraction.d.ts
264
+ /**
265
+ * Send an interaction to the backend via the listener RPC.
266
+ * Fire-and-forget: errors are caught and logged, not thrown.
267
+ *
268
+ * @param client - The Frak client instance
269
+ * @param params - The interaction parameters
270
+ *
271
+ * @description Sends a user interaction event through the wallet iframe RPC. Supports three interaction types: arrival tracking, sharing events, and custom interactions.
272
+ *
273
+ * @example
274
+ * Track a user arrival with referral attribution:
275
+ * ```ts
276
+ * await sendInteraction(client, {
277
+ * type: "arrival",
278
+ * referrerWallet: "0x1234...abcd",
279
+ * landingUrl: window.location.href,
280
+ * utmSource: "twitter",
281
+ * utmMedium: "social",
282
+ * utmCampaign: "launch-2026",
283
+ * });
284
+ * ```
285
+ *
286
+ * @example
287
+ * Track a sharing event:
288
+ * ```ts
289
+ * await sendInteraction(client, { type: "sharing" });
290
+ * ```
291
+ *
292
+ * @example
293
+ * Send a custom interaction:
294
+ * ```ts
295
+ * await sendInteraction(client, {
296
+ * type: "custom",
297
+ * customType: "newsletter_signup",
298
+ * data: { email: "user@example.com" },
299
+ * });
300
+ * ```
301
+ */
302
+ declare function sendInteraction(client: FrakClient, params: SendInteractionParamsType): Promise<void>;
303
+ //#endregion
304
+ //#region src/actions/trackPurchaseStatus.d.ts
305
+ /**
306
+ * Function used to track the status of a purchase
307
+ * when a purchase is tracked, the `purchaseCompleted` interactions will be automatically send for the user when we receive the purchase confirmation via webhook.
308
+ *
309
+ * @param args.customerId - The customer id that made the purchase (on your side)
310
+ * @param args.orderId - The order id of the purchase (on your side)
311
+ * @param args.token - The token of the purchase
312
+ * @param args.merchantId - Optional explicit merchant id to use for the tracking request
313
+ *
314
+ * @description This function will send a request to the backend to listen for the purchase status.
315
+ *
316
+ * @example
317
+ * async function trackPurchase(checkout) {
318
+ * const payload = {
319
+ * customerId: checkout.order.customer.id,
320
+ * orderId: checkout.order.id,
321
+ * token: checkout.token,
322
+ * merchantId: "your-merchant-id",
323
+ * };
324
+ *
325
+ * await trackPurchaseStatus(payload);
326
+ * }
327
+ *
328
+ * @remarks
329
+ * - Merchant id is resolved in this order: explicit `args.merchantId`, `frak-merchant-id` from session storage, then `fetchMerchantId()`.
330
+ * - This function supports anonymous users and will use the `x-frak-client-id` header when available.
331
+ * - At least one identity source must exist (`frak-wallet-interaction-token` or `x-frak-client-id`), otherwise the tracking request is skipped.
332
+ * - This function will print a warning if used in a non-browser environment or if no identity / merchant id can be resolved.
333
+ */
334
+ declare function trackPurchaseStatus(args: {
335
+ customerId: string | number;
336
+ orderId: string | number;
337
+ token: string;
338
+ merchantId?: string;
339
+ }): Promise<void>;
340
+ //#endregion
341
+ //#region src/actions/watchWalletStatus.d.ts
342
+ /**
343
+ * Function used to watch the current frak wallet status
344
+ * @param client - The current Frak Client
345
+ * @param callback - The callback that will receive any wallet status change
346
+ * @returns A promise resolving with the initial wallet status
347
+ *
348
+ * @description This function will return the current wallet status, and will listen to any change in the wallet status.
349
+ *
350
+ * @example
351
+ * await watchWalletStatus(frakConfig, (status: WalletStatusReturnType) => {
352
+ * if (status.key === "connected") {
353
+ * console.log("Wallet connected:", status.wallet);
354
+ * } else {
355
+ * console.log("Wallet not connected");
356
+ * }
357
+ * });
358
+ */
359
+ declare function watchWalletStatus(client: FrakClient, callback?: (status: WalletStatusReturnType) => void): Promise<WalletStatusReturnType>;
360
+ //#endregion
361
+ //#region src/actions/wrapper/modalBuilder.d.ts
362
+ /**
363
+ * Represent the type of the modal step builder
364
+ */
365
+ type ModalStepBuilder<Steps extends ModalStepTypes[] = ModalStepTypes[]> = {
366
+ /**
367
+ * The current modal params
368
+ */
369
+ params: DisplayModalParamsType<Steps>;
370
+ /**
371
+ * Add a send transaction step to the modal
372
+ */
373
+ sendTx: (options: SendTransactionModalStepType["params"]) => ModalStepBuilder<[...Steps, SendTransactionModalStepType]>;
374
+ /**
375
+ * Add a final step of type reward to the modal
376
+ */
377
+ reward: (options?: Omit<FinalModalStepType["params"], "action">) => ModalStepBuilder<[...Steps, FinalModalStepType]>;
378
+ /**
379
+ * Add a final step of type sharing to the modal
380
+ */
381
+ sharing: (sharingOptions?: Extract<FinalActionType, {
382
+ key: "sharing";
383
+ }>["options"], options?: Omit<FinalModalStepType["params"], "action">) => ModalStepBuilder<[...Steps, FinalModalStepType]>;
384
+ /**
385
+ * Display the modal
386
+ * @param metadataOverride - Function returning optional metadata to override the current modal metadata
387
+ */
388
+ display: (metadataOverride?: (current?: ModalRpcMetadata) => ModalRpcMetadata | undefined) => Promise<ModalRpcStepsResultType<Steps>>;
389
+ };
390
+ /**
391
+ * Represent the output type of the modal builder
392
+ */
393
+ type ModalBuilder = ModalStepBuilder<[LoginModalStepType]>;
394
+ /**
395
+ * Helper to craft Frak modal, and share a base initial config
396
+ * @param client - The current Frak Client
397
+ * @param args
398
+ * @param args.metadata - Common modal metadata (customisation, language etc)
399
+ * @param args.login - Login step parameters
400
+ *
401
+ * @description This function will create a modal builder with the provided metadata and login parameters.
402
+ *
403
+ * @example
404
+ * Here is an example of how to use the `modalBuilder` to create and display a sharing modal:
405
+ *
406
+ * ```js
407
+ * // Create the modal builder
408
+ * const modalBuilder = window.FrakSDK.modalBuilder(frakClient, baseModalConfig);
409
+ *
410
+ * // Configure the information to be shared via the sharing link
411
+ * const sharingConfig = {
412
+ * popupTitle: "Share this with your friends",
413
+ * text: "Discover our product!",
414
+ * link: window.location.href,
415
+ * };
416
+ *
417
+ * // Display the sharing modal
418
+ * function modalShare() {
419
+ * modalBuilder.sharing(sharingConfig).display();
420
+ * }
421
+ * ```
422
+ *
423
+ * @see {@link ModalStepTypes} for more info about each modal step types and their parameters
424
+ * @see {@link ModalRpcMetadata} for more info about the metadata that can be passed to the modal
425
+ * @see {@link ModalRpcStepsResultType} for more info about the result of each modal steps
426
+ * @see {@link displayModal} for more info about how the modal is displayed
427
+ */
428
+ declare function modalBuilder(client: FrakClient, {
429
+ metadata,
430
+ login
431
+ }: {
432
+ metadata?: ModalRpcMetadata;
433
+ login?: LoginModalStepType["params"];
434
+ }): ModalBuilder;
435
+ //#endregion
436
+ //#region src/actions/wrapper/sendTransaction.d.ts
437
+ /**
438
+ * Parameters to directly show a modal used to send a transaction
439
+ * @inline
440
+ */
441
+ type SendTransactionParams = {
442
+ /**
443
+ * The transaction to be sent (either a single tx or multiple ones)
444
+ */
445
+ tx: SendTransactionModalStepType["params"]["tx"];
446
+ /**
447
+ * Custom metadata to be passed to the modal
448
+ */
449
+ metadata?: ModalRpcMetadata;
450
+ };
451
+ /**
452
+ * Function used to send a user transaction, simple wrapper around the displayModal function to ease the send transaction process
453
+ * @param client - The current Frak Client
454
+ * @param args - The parameters
455
+ * @returns The hash of the transaction that was sent in a promise
456
+ *
457
+ * @description This function will display a modal to the user with the provided transaction and metadata.
458
+ *
459
+ * @example
460
+ * const { hash } = await sendTransaction(frakConfig, {
461
+ * tx: {
462
+ * to: "0xdeadbeef",
463
+ * value: toHex(100n),
464
+ * },
465
+ * metadata: {
466
+ * header: {
467
+ * title: "Sending eth",
468
+ * },
469
+ * context: "Send 100wei to 0xdeadbeef",
470
+ * },
471
+ * });
472
+ * console.log("Transaction hash:", hash);
473
+ */
474
+ declare function sendTransaction(client: FrakClient, {
475
+ tx,
476
+ metadata
477
+ }: SendTransactionParams): Promise<SendTransactionReturnType>;
478
+ //#endregion
479
+ //#region src/actions/wrapper/siweAuthenticate.d.ts
480
+ /**
481
+ * Parameter used to directly show a modal used to authenticate with SIWE
482
+ * @inline
483
+ */
484
+ type SiweAuthenticateModalParams = {
485
+ /**
486
+ * Partial SIWE params, since we can rebuild them from the SDK if they are empty
487
+ *
488
+ * If no parameters provider, some fields will be recomputed from the current configuration and environment.
489
+ * - `statement` will be set to a default value
490
+ * - `nonce` will be generated
491
+ * - `uri` will be set to the current domain
492
+ * - `version` will be set to "1"
493
+ * - `domain` will be set to the current window domain
494
+ *
495
+ * @default {}
496
+ */
497
+ siwe?: Partial<SiweAuthenticationParams>;
498
+ /**
499
+ * Custom metadata to be passed to the modal
500
+ */
501
+ metadata?: ModalRpcMetadata;
502
+ };
503
+ /**
504
+ * Function used to launch a siwe authentication
505
+ * @param client - The current Frak Client
506
+ * @param args - The parameters
507
+ * @returns The SIWE authentication result (message + signature) in a promise
508
+ *
509
+ * @description This function will display a modal to the user with the provided SIWE parameters and metadata.
510
+ *
511
+ * @example
512
+ * import { siweAuthenticate } from "@frak-labs/core-sdk/actions";
513
+ * import { parseSiweMessage } from "viem/siwe";
514
+ *
515
+ * const { signature, message } = await siweAuthenticate(frakConfig, {
516
+ * siwe: {
517
+ * statement: "Sign in to My App",
518
+ * domain: "my-app.com",
519
+ * expirationTimeTimestamp: Date.now() + 1000 * 60 * 5,
520
+ * },
521
+ * metadata: {
522
+ * header: {
523
+ * title: "Sign in",
524
+ * },
525
+ * context: "Sign in to My App",
526
+ * },
527
+ * });
528
+ * console.log("Parsed final message:", parseSiweMessage(message));
529
+ * console.log("Siwe signature:", signature);
530
+ */
531
+ declare function siweAuthenticate(client: FrakClient, {
532
+ siwe,
533
+ metadata
534
+ }: SiweAuthenticateModalParams): Promise<SiweAuthenticateReturnType>;
535
+ //#endregion
536
+ export { displayModal as _, ModalBuilder as a, watchWalletStatus as c, referralInteraction as d, ProcessReferralOptions as f, ensureIdentity as g, getMerchantInformation as h, sendTransaction as i, trackPurchaseStatus as l, prepareSso as m, siweAuthenticate as n, ModalStepBuilder as o, processReferral as p, SendTransactionParams as r, modalBuilder as s, SiweAuthenticateModalParams as t, sendInteraction as u, displayEmbeddedWallet as v };
@@ -0,0 +1 @@
1
+ import{a as e,h as t,o as n,r,t as i}from"./trackEvent-M2RLTQ2p.js";import{isAddressEqual as a}from"viem";import{Deferred as o,FrakRpcError as s,RpcErrorCodes as c}from"@frak-labs/frame-connector";import{generateSiweNonce as l}from"viem/siwe";async function u(e,t){return await e.request({method:`frak_displayEmbeddedWallet`,params:[t,e.config.metadata]})}async function d(e,{steps:t,metadata:n}){return await e.request({method:`frak_displayModal`,params:[t,n,e.config.metadata]})}async function f(e){if(typeof window>`u`)return;let i=t();if(!i)return;let a=await r();if(!a)return;let o=`frak-identity-ensured-${a}`;if(!window.sessionStorage.getItem(o))try{let t=n();(await fetch(`${t}/user/identity/ensure`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"x-wallet-sdk-auth":e,"x-frak-client-id":i},body:JSON.stringify({merchantId:a})})).ok&&window.sessionStorage.setItem(o,`1`)}catch{}}async function p(e){return await e.request({method:`frak_getMerchantInformation`})}async function m(e,t){let{metadata:n,customizations:r}=e.config;return await e.request({method:`frak_prepareSso`,params:[t,n.name,r?.css]})}async function h(e,n){try{await e.request({method:`frak_sendInteraction`,params:[n,{clientId:t()}]})}catch{console.warn(`[Frak SDK] Failed to send interaction:`,n.type)}}async function g(t,{walletStatus:n,frakContext:r,modalConfig:a,options:o}){if(!r?.r)return`no-referrer`;i(t,`user_referred_started`,{properties:{referrer:r?.r,walletStatus:n?.key}}),h(t,{type:`arrival`,referrerWallet:r.r,landingUrl:typeof window<`u`?window.location.href:void 0});let c=!1;async function l(){if(!c)return c=!0,v(t,{modalConfig:{...a,loggedIn:{action:{key:`referred`}}},walletStatus:n})}try{let{status:a,currentWallet:s}=await _({initialWalletStatus:n,getFreshWalletStatus:l,frakContext:r});return e.replaceUrl({url:window.location?.href,context:o?.alwaysAppendUrl?{r:s}:null}),i(t,`user_referred_completed`,{properties:{status:a,referrer:r?.r,wallet:s}}),a}catch(a){return console.log(`Error processing referral`,{error:a}),i(t,`user_referred_error`,{properties:{referrer:r?.r,error:a instanceof s?`[${a.code}] ${a.name} - ${a.message}`:a instanceof Error?a.message:`undefined`}}),e.replaceUrl({url:window.location?.href,context:o?.alwaysAppendUrl?{r:n?.wallet}:null}),y(a)}}async function _({initialWalletStatus:e,getFreshWalletStatus:t,frakContext:n}){let r=e?.wallet;return r||=await t(),r&&a(n.r,r)?{status:`self-referral`,currentWallet:r}:{status:`success`,currentWallet:r}}async function v(e,{modalConfig:t,walletStatus:n}){return n?.key===`connected`?n.wallet??void 0:(await u(e,t??{}))?.wallet??void 0}function y(e){if(e instanceof s)switch(e.code){case c.walletNotConnected:return`no-wallet`;default:return`error`}return`error`}async function b(t,{modalConfig:n,options:r}={}){let i=e.parse({url:window.location.href}),a=await S(t);try{return await g(t,{walletStatus:a,frakContext:i,modalConfig:n,options:r})}catch(e){console.warn(`Error processing referral`,{error:e})}}async function x(e){if(typeof window>`u`){console.warn(`[Frak] No window found, can't track purchase`);return}let i=window.sessionStorage.getItem(`frak-wallet-interaction-token`),a=t();if(!i&&!a){console.warn(`[Frak] No identity found, skipping purchase check`);return}let o=window.sessionStorage.getItem(`frak-merchant-id`),s=e.merchantId??o??await r();if(!s){console.warn(`[Frak] No merchant id found, skipping purchase check`);return}let c={Accept:`application/json`,"Content-Type":`application/json`};i&&(c[`x-wallet-sdk-auth`]=i),a&&(c[`x-frak-client-id`]=a);let l=n();await fetch(`${l}/user/track/purchase`,{method:`POST`,headers:c,body:JSON.stringify({customerId:e.customerId,orderId:e.orderId,token:e.token,merchantId:s})})}function S(e,t){if(!t)return e.request({method:`frak_listenToWalletStatus`}).then(t=>(C(e,t),t));let n=new o,r=!1;return e.listenerRequest({method:`frak_listenToWalletStatus`},i=>{C(e,i),t(i),r||=(n.resolve(i),!0)}),n.promise}function C(e,t){typeof window>`u`||(e.openPanel?.setGlobalProperties({wallet:t.wallet??null}),t.interactionToken?(window.sessionStorage.setItem(`frak-wallet-interaction-token`,t.interactionToken),f(t.interactionToken)):window.sessionStorage.removeItem(`frak-wallet-interaction-token`))}function w(e,{metadata:t,login:n}){return T(e,{steps:{login:n??{}},metadata:t})}function T(e,t){function n(n){return T(e,{...t,steps:{...t.steps,sendTransaction:n}})}function r(n){return T(e,{...t,steps:{...t.steps,final:{...n,action:{key:`reward`}}}})}function i(n,r){return T(e,{...t,steps:{...t.steps,final:{...r,action:{key:`sharing`,options:n}}}})}async function a(n){return n&&(t.metadata=n(t.metadata??{})),await d(e,t)}return{params:t,sendTx:n,reward:r,sharing:i,display:a}}async function E(e,{tx:t,metadata:n}){return(await d(e,{metadata:n,steps:{login:{},sendTransaction:{tx:t}}})).sendTransaction}async function D(e,{siwe:t,metadata:n}){let r=e.config?.domain??window.location.host,i=t?.statement??`I confirm that I want to use my Frak wallet on: ${e.config.metadata.name}`;return(await d(e,{metadata:n,steps:{login:{},siweAuthenticate:{siwe:{...t,statement:i,nonce:t?.nonce??l(),uri:t?.uri??`https://${r}`,version:t?.version??`1`,domain:r}}}})).siweAuthenticate}export{x as a,h as c,f as d,d as f,S as i,m as l,E as n,b as o,u as p,w as r,g as s,D as t,p as u};