@frak-labs/core-sdk 0.1.0 → 0.1.1-beta.4dfea079

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 (130) 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-CscYhyUi.d.cts +525 -0
  12. package/dist/computeLegacyProductId-WbD1gXV9.d.ts +525 -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-CC1-loUk.d.cts +1019 -0
  18. package/dist/openSso-tkqaDQLV.d.ts +1019 -0
  19. package/dist/setupClient-BjIbK6XJ.cjs +13 -0
  20. package/dist/setupClient-D_HId3e2.js +13 -0
  21. package/dist/siweAuthenticate-B_Z2OZmj.cjs +1 -0
  22. package/dist/siweAuthenticate-CQ4OfPuA.js +1 -0
  23. package/dist/siweAuthenticate-CR4Dpji6.d.cts +467 -0
  24. package/dist/siweAuthenticate-udoruuy9.d.ts +467 -0
  25. package/dist/trackEvent-CGIryq5h.cjs +1 -0
  26. package/dist/trackEvent-YfUh4jrx.js +1 -0
  27. package/package.json +24 -30
  28. package/src/actions/displayEmbeddedWallet.test.ts +194 -0
  29. package/src/actions/displayEmbeddedWallet.ts +20 -0
  30. package/src/actions/displayModal.test.ts +388 -0
  31. package/src/actions/displayModal.ts +120 -0
  32. package/src/actions/getMerchantInformation.test.ts +116 -0
  33. package/src/actions/getMerchantInformation.ts +9 -0
  34. package/src/actions/index.ts +29 -0
  35. package/src/actions/openSso.ts +116 -0
  36. package/src/actions/prepareSso.test.ts +223 -0
  37. package/src/actions/prepareSso.ts +48 -0
  38. package/src/actions/referral/processReferral.test.ts +248 -0
  39. package/src/actions/referral/processReferral.ts +232 -0
  40. package/src/actions/referral/referralInteraction.test.ts +147 -0
  41. package/src/actions/referral/referralInteraction.ts +52 -0
  42. package/src/actions/sendInteraction.ts +24 -0
  43. package/src/actions/trackPurchaseStatus.test.ts +287 -0
  44. package/src/actions/trackPurchaseStatus.ts +56 -0
  45. package/src/actions/watchWalletStatus.test.ts +372 -0
  46. package/src/actions/watchWalletStatus.ts +93 -0
  47. package/src/actions/wrapper/modalBuilder.test.ts +239 -0
  48. package/src/actions/wrapper/modalBuilder.ts +203 -0
  49. package/src/actions/wrapper/sendTransaction.test.ts +164 -0
  50. package/src/actions/wrapper/sendTransaction.ts +62 -0
  51. package/src/actions/wrapper/siweAuthenticate.test.ts +290 -0
  52. package/src/actions/wrapper/siweAuthenticate.ts +94 -0
  53. package/src/bundle.ts +2 -0
  54. package/src/clients/DebugInfo.test.ts +418 -0
  55. package/src/clients/DebugInfo.ts +182 -0
  56. package/src/clients/createIFrameFrakClient.ts +289 -0
  57. package/src/clients/index.ts +3 -0
  58. package/src/clients/setupClient.test.ts +343 -0
  59. package/src/clients/setupClient.ts +73 -0
  60. package/src/clients/transports/iframeLifecycleManager.test.ts +558 -0
  61. package/src/clients/transports/iframeLifecycleManager.ts +174 -0
  62. package/src/constants/interactionTypes.ts +15 -0
  63. package/src/constants/locales.ts +14 -0
  64. package/src/index.ts +110 -0
  65. package/src/types/client.ts +14 -0
  66. package/src/types/compression.ts +22 -0
  67. package/src/types/config.ts +117 -0
  68. package/src/types/context.ts +13 -0
  69. package/src/types/index.ts +75 -0
  70. package/src/types/lifecycle/client.ts +69 -0
  71. package/src/types/lifecycle/iframe.ts +41 -0
  72. package/src/types/lifecycle/index.ts +2 -0
  73. package/src/types/rpc/displayModal.ts +82 -0
  74. package/src/types/rpc/embedded/index.ts +68 -0
  75. package/src/types/rpc/embedded/loggedIn.ts +55 -0
  76. package/src/types/rpc/embedded/loggedOut.ts +28 -0
  77. package/src/types/rpc/interaction.ts +30 -0
  78. package/src/types/rpc/merchantInformation.ts +77 -0
  79. package/src/types/rpc/modal/final.ts +46 -0
  80. package/src/types/rpc/modal/generic.ts +46 -0
  81. package/src/types/rpc/modal/index.ts +16 -0
  82. package/src/types/rpc/modal/login.ts +36 -0
  83. package/src/types/rpc/modal/siweAuthenticate.ts +37 -0
  84. package/src/types/rpc/modal/transaction.ts +33 -0
  85. package/src/types/rpc/sso.ts +80 -0
  86. package/src/types/rpc/walletStatus.ts +29 -0
  87. package/src/types/rpc.ts +146 -0
  88. package/src/types/tracking.ts +60 -0
  89. package/src/types/transport.ts +34 -0
  90. package/src/utils/FrakContext.test.ts +407 -0
  91. package/src/utils/FrakContext.ts +158 -0
  92. package/src/utils/backendUrl.test.ts +83 -0
  93. package/src/utils/backendUrl.ts +62 -0
  94. package/src/utils/clientId.test.ts +41 -0
  95. package/src/utils/clientId.ts +40 -0
  96. package/src/utils/compression/b64.test.ts +181 -0
  97. package/src/utils/compression/b64.ts +29 -0
  98. package/src/utils/compression/compress.test.ts +123 -0
  99. package/src/utils/compression/compress.ts +11 -0
  100. package/src/utils/compression/decompress.test.ts +149 -0
  101. package/src/utils/compression/decompress.ts +11 -0
  102. package/src/utils/compression/index.ts +3 -0
  103. package/src/utils/computeLegacyProductId.ts +11 -0
  104. package/src/utils/constants.test.ts +23 -0
  105. package/src/utils/constants.ts +14 -0
  106. package/src/utils/deepLinkWithFallback.test.ts +243 -0
  107. package/src/utils/deepLinkWithFallback.ts +97 -0
  108. package/src/utils/formatAmount.test.ts +113 -0
  109. package/src/utils/formatAmount.ts +18 -0
  110. package/src/utils/getCurrencyAmountKey.test.ts +44 -0
  111. package/src/utils/getCurrencyAmountKey.ts +15 -0
  112. package/src/utils/getSupportedCurrency.test.ts +51 -0
  113. package/src/utils/getSupportedCurrency.ts +14 -0
  114. package/src/utils/getSupportedLocale.test.ts +64 -0
  115. package/src/utils/getSupportedLocale.ts +16 -0
  116. package/src/utils/iframeHelper.test.ts +450 -0
  117. package/src/utils/iframeHelper.ts +147 -0
  118. package/src/utils/index.ts +36 -0
  119. package/src/utils/merchantId.test.ts +564 -0
  120. package/src/utils/merchantId.ts +122 -0
  121. package/src/utils/sso.ts +126 -0
  122. package/src/utils/ssoUrlListener.test.ts +252 -0
  123. package/src/utils/ssoUrlListener.ts +60 -0
  124. package/src/utils/trackEvent.test.ts +180 -0
  125. package/src/utils/trackEvent.ts +31 -0
  126. package/cdn/bundle.js.LICENSE.txt +0 -10
  127. package/dist/interactions.cjs +0 -1
  128. package/dist/interactions.d.cts +0 -182
  129. package/dist/interactions.d.ts +0 -182
  130. package/dist/interactions.js +0 -1
package/dist/bundle.js CHANGED
@@ -1,13 +1 @@
1
- import{Deferred as e,FrakRpcError as t,RpcErrorCodes as n,compressJson as r,createRpcClient as a,decompressJson as o}from"@frak-labs/frame-connector";import{createClientCompressionMiddleware as i}from"@frak-labs/frame-connector/middleware";import{OpenPanel as s}from"@openpanel/web";import{bytesToHex as c,concatHex as l,encodeAbiParameters as u,hexToBytes as d,isAddressEqual as f,keccak256 as p,pad as m,toHex as w}from"viem";import{generateSiweNonce as h}from"viem/siwe";let g="nexus-wallet-backup";class y{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?+("complete"===this.iframe.contentDocument.readyState):-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(),a="Unknown";return e instanceof t?a=`FrakRpcError: ${e.code} '${e.message}'`:e instanceof Error?a=e.message:"string"==typeof e&&(a=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:a}}static empty(){return new y}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()}}let k={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 b({walletBaseUrl:e,config:t}){let n=document.querySelector("#frak-wallet");n&&n.remove();let r=document.createElement("iframe");return r.id=k.id,r.name=k.name,r.allow=k.allow,r.style.zIndex=k.style.zIndex.toString(),S({iframe:r,isVisible:!1}),document.body.appendChild(r),new Promise(n=>{r?.addEventListener("load",()=>n(r)),r.src=`${t?.walletUrl??e??"https://wallet.frak.id"}/listener`})}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 I({config:r,iframe:o}){let c,l=r?.walletUrl??"https://wallet.frak.id",u=function({iframe:t}){let n=new e;return{handleEvent:async e=>{if(!("iframeLifecycle"in e))return;let{iframeLifecycle:r,data:a}=e;switch(r){case"connected":n.resolve(!0);break;case"do-backup":a.backup?localStorage.setItem(g,a.backup):localStorage.removeItem(g);break;case"remove-backup":localStorage.removeItem(g);break;case"show":case"hide":S({iframe:t,isVisible:"show"===r});break;case"handshake":t.contentWindow?.postMessage({clientLifecycle:"handshake-response",data:{token:a.token,currentUrl:window.location.href}},"*");break;case"redirect":{let e=new URL(a.baseRedirectUrl);e.searchParams.has("u")?(e.searchParams.delete("u"),e.searchParams.append("u",window.location.href),window.location.href=e.toString()):window.location.href=a.baseRedirectUrl}}},isConnected:n.promise}}({iframe:o}),d=new y(r,o);if(!o.contentWindow)throw new t(n.configError,"The iframe does not have a content window");let f=a({emittingTransport:o.contentWindow,listeningTransport:window,targetOrigin:l,middleware:[{async onRequest(e,r){if(!await u.isConnected)throw new t(n.clientNotConnected,"The iframe provider isn't connected yet");return r}},i(),{onRequest:(e,t)=>(d.setLastRequest(e),t),onResponse:(e,t)=>(d.setLastResponse(e,t),t)}],lifecycleHandlers:{iframeLifecycle:async(e,t)=>{await u.handleEvent(e)}}}),p=function(e,t){let n,r,a=()=>e.sendLifecycle({clientLifecycle:"heartbeat"});function o(){n&&clearInterval(n),r&&clearTimeout(r)}return async function(){a(),n=setInterval(a,1e3),r=setTimeout(()=>{o(),console.log("Heartbeat timeout: connection failed")},3e4),await t.isConnected,o()}(),o}(f,u),m=async()=>{p(),f.cleanup(),o.remove()};console.log("[Frak SDK] Initializing OpenPanel"),(c=new s({apiUrl:"https://op-api.gcp.frak.id",clientId:"f305d11d-b93b-487c-80d4-92deb7903e98",trackScreenViews:!0,trackOutgoingLinks:!0,trackAttributes:!1,filter:({type:e,payload:t})=>!("track"===e&&t?.properties)||("sdkVersion"in t.properties||(t.properties={...t.properties,sdkVersion:"0.1.0"}),!0)})).setGlobalProperties({sdkVersion:"0.1.0"}),c.init();let w=v({config:r,rpcClient:f,lifecycleManager:u}).then(()=>d.updateSetupStatus(!0));return{config:r,debugInfo:d,waitForConnection:u.isConnected,waitForSetup:w,request:f.request,listenerRequest:f.listen,destroy:m,openPanel:c}}async function v({config:e,rpcClient:t,lifecycleManager:n}){async function r(){let n=e.customizations?.css;n&&t.sendLifecycle({clientLifecycle:"modal-css",data:{cssLink:n}})}async function a(){let n=e.customizations?.i18n;n&&t.sendLifecycle({clientLifecycle:"modal-i18n",data:{i18n:n}})}async function o(){if("undefined"==typeof window)return;let e=window.localStorage.getItem(g);e&&t.sendLifecycle({clientLifecycle:"restore-backup",data:{backup:e}})}await n.isConnected,function(e,t){if("undefined"==typeof window)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"))}(t,n.isConnected),await Promise.allSettled([r(),a(),o()])}let R={eur:"fr-FR",usd:"en-US",gbp:"en-GB"};function L(e){return e&&e in R?e:"eur"}async function x({config:e}){let t=function(e){let t=L(e.metadata?.currency);return{...e,metadata:{...e.metadata,currency:t}}}(e),n=await b({config:t});if(!n)return void console.error("Failed to create iframe");let r=I({config:t,iframe:n});return(await r.waitForSetup,await r.waitForConnection)?r:void console.error("Failed to connect to client")}function F(e){return btoa(Array.from(e,e=>String.fromCharCode(e)).join("")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(e){let t=e.length%4;return Uint8Array.from(atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(e.length+(0===t?0:4-t),"=")),e=>e.charCodeAt(0))}function T(e){return F(r(e))}function E(e){return o(C(e))}let D="fCtx";function P(e){if(e?.r)try{let t=d(e.r);return F(t)}catch(t){console.error("Error compressing Frak context",{e:t,context:e})}}function U(e){if(e&&0!==e.length)try{let t=C(e);return{r:c(t,{size:20})}}catch(t){console.error("Error decompressing Frak context",{e:t,context:e})}}function q({url:e}){if(!e)return null;let t=new URL(e).searchParams.get(D);return t?U(t):null}function A({url:e,context:t}){if(!e)return null;let n=q({url:e}),r=n?{...n,...t}:t;if(!r.r)return null;let a=P(r);if(!a)return null;let o=new URL(e);return o.searchParams.set(D,a),o.toString()}function $(e){let t=new URL(e);return t.searchParams.delete(D),t.toString()}let O={compress:P,decompress:U,parse:q,update:A,remove:$,replaceUrl:function({url:e,context:t}){let n;if(!window.location?.href||"undefined"==typeof window)return void console.error("No window found, can't update context");let r=e??window.location.href;(n=null!==t?A({url:r,context:t}):$(r))&&window.history.replaceState(null,"",n.toString())}};function W(e){return e?R[e]??R.eur:R.eur}function z(e){return e?`${e}Amount`:"eurAmount"}function N(e,t){let n=W(t),r=L(t);return e.toLocaleString(n,{style:"currency",currency:r,minimumFractionDigits:0,maximumFractionDigits:2})}function _(e,t,n={}){if(!e)return void console.debug("[Frak] No client provided, skipping event tracking");try{e.openPanel?.track(t,n)}catch(e){console.debug("[Frak] Failed to track event:",t,e)}}let M={dapp:1,press:2,webshop:3,retail:4,referral:30,purchase:31},V=Object.entries(M).reduce((e,[t,n])=>(e[t]=BigInt(1)<<BigInt(n),e),{}),B={press:{openArticle:"0xc0a24ffb",readArticle:"0xd5bd0fbe"},dapp:{proofVerifiableStorageUpdate:"0x2ab2aeef",callableVerifiableStorageUpdate:"0xa07da986"},webshop:{open:"0xb311798f"},referral:{referred:"0x010cc3b9",createLink:"0xb2c0f17c"},purchase:{started:"0xd87e90c3",completed:"0x8403aeb4",unsafeCompleted:"0x4d5b14e0"},retail:{customerMeeting:"0x74489004"}};function j(t,n){if(!n)return t.request({method:"frak_listenToWalletStatus"}).then(e=>(G(t,e),e));let r=new e,a=!1;return t.listenerRequest({method:"frak_listenToWalletStatus"},e=>{G(t,e),n(e),a||(r.resolve(e),a=!0)}),r.promise}function G(e,t){"undefined"!=typeof window&&(e.openPanel?.setGlobalProperties({wallet:t.wallet??null}),t.interactionToken?window.sessionStorage.setItem("frak-wallet-interaction-token",t.interactionToken):window.sessionStorage.removeItem("frak-wallet-interaction-token"))}async function J(e,{productId:t,interaction:n,validation:r}){let a=t??function({domain:e}){return p(w((e??window.location.host).replace("www.","")))}(e.config);return await e.request({method:"frak_sendInteraction",params:[a,n,r]})}async function H(e,{steps:t,metadata:n}){return await e.request({method:"frak_displayModal",params:[t,n,e.config.metadata]})}async function K(e,t){return await e.request({method:"frak_displayEmbeddedWallet",params:[t,e.config.metadata]})}async function Q(e,t){let{metadata:n,customizations:r}=e.config;return await e.request({method:"frak_sso",params:[t,n.name,r?.css]})??{}}async function X(e){return await e.request({method:"frak_getProductInformation"})}async function Y(e){if("undefined"==typeof window)return void console.warn("[Frak] No window found, can't track purchase");let t=window.sessionStorage.getItem("frak-wallet-interaction-token");if(!t)return void console.warn("[Frak] No frak session found, skipping purchase check");await fetch("https://backend.frak.id/interactions/listenForPurchase",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","x-wallet-sdk-auth":t},body:JSON.stringify(e)})}async function Z(e,{siwe:t,metadata:n}){let r=e.config?.domain??window.location.host,a=t?.statement??`I confirm that I want to use my Frak wallet on: ${e.config.metadata.name}`,o={...t,statement:a,nonce:t?.nonce??h(),uri:t?.uri??`https://${r}`,version:t?.version??"1",domain:r};return(await H(e,{metadata:n,steps:{login:{},siweAuthenticate:{siwe:o}}})).siweAuthenticate}async function ee(e,{tx:t,metadata:n}){return(await H(e,{metadata:n,steps:{login:{},sendTransaction:{tx:t}}})).sendTransaction}function et(e,{metadata:t,login:n,openSession:r}){return function e(t,n){async function r(e){return e&&(n.metadata=e(n.metadata??{})),await H(t,n)}return{params:n,sendTx:function(r){return e(t,{...n,steps:{...n.steps,sendTransaction:r}})},reward:function(r){return e(t,{...n,steps:{...n.steps,final:{...r,action:{key:"reward"}}}})},sharing:function(r,a){return e(t,{...n,steps:{...n.steps,final:{...a,action:{key:"sharing",options:r}}}})},display:r}}(e,{steps:{login:n??{},openSession:r??{}},metadata:t})}let en={createLink:()=>({handlerTypeDenominator:w(M.referral),interactionData:B.referral.createLink}),referred({referrer:e}){let t=l([B.referral.referred,m(e,{size:32})]);return{handlerTypeDenominator:w(M.referral),interactionData:t}}};async function er(e,{walletStatus:r,frakContext:a,modalConfig:o,productId:i,options:s}){let c=!1;async function l(){if(!c)return c=!0,eo(e,{modalConfig:{...o,loggedIn:{action:{key:"referred"}}},walletStatus:r})}async function u(t){let n=en.referred({referrer:t});await Promise.allSettled([J(e,{productId:i,interaction:n}),_(e,"user_referred",{properties:{referrer:t}})])}try{let{status:e,currentWallet:t}=await ea({initialWalletStatus:r,getFreshWalletStatus:l,pushReferralInteraction:u,frakContext:a});return O.replaceUrl({url:window.location?.href,context:s?.alwaysAppendUrl?{r:t}:null}),e}catch(e){return console.log("Error processing referral",{error:e}),O.replaceUrl({url:window.location?.href,context:s?.alwaysAppendUrl?{r:r?.wallet}:null}),function(e){if(e instanceof t)switch(e.code){case n.walletNotConnected:return"no-wallet";case n.serverErrorForInteractionDelegation:return"no-session"}return"error"}(e)}}async function ea({initialWalletStatus:e,getFreshWalletStatus:t,pushReferralInteraction:n,frakContext:r}){let a=e?.wallet;return r?.r?(a||(a=await t()),a&&f(r.r,a))?{status:"self-referral",currentWallet:a}:(e?.interactionSession||(a=await t()),await n(r.r),{status:"success",currentWallet:a}):{status:"no-referrer",currentWallet:a}}async function eo(e,{modalConfig:t,walletStatus:n}){if(!n?.interactionSession){let n=await K(e,t??{});return n?.wallet??void 0}return n.wallet??void 0}async function ei(e,{productId:t,modalConfig:n,options:r}={}){let a=O.parse({url:window.location.href}),o=await j(e);try{return await er(e,{walletStatus:o,frakContext:a,modalConfig:n,productId:t,options:r})}catch(e){console.warn("Error processing referral",{error:e})}}let es={openArticle({articleId:e}){let t=l([B.press.openArticle,m(e,{size:32})]);return{handlerTypeDenominator:w(M.press),interactionData:t}},readArticle({articleId:e}){let t=l([B.press.readArticle,m(e,{size:32})]);return{handlerTypeDenominator:w(M.press),interactionData:t}}},ec={startPurchase({purchaseId:e}){let t=l([B.purchase.started,m(e,{size:32})]);return{handlerTypeDenominator:w(M.purchase),interactionData:t}},completedPurchase({purchaseId:e,proof:t}){let n=u([{type:"uint256"},{type:"bytes32[]"}],[BigInt(e),t]),r=l([B.purchase.completed,n]);return{handlerTypeDenominator:w(M.purchase),interactionData:r}},unsafeCompletedPurchase({purchaseId:e}){let t=l([B.purchase.unsafeCompleted,m(e,{size:32})]);return{handlerTypeDenominator:w(M.purchase),interactionData:t}}},el={open:()=>({handlerTypeDenominator:w(M.webshop),interactionData:B.webshop.open})},eu={customerMeeting({agencyId:e}){let t=l([B.retail.customerMeeting,m(e,{size:32})]);return{handlerTypeDenominator:w(M.retail),interactionData:t}}};export{y as DebugInfoGatherer,O as FrakContextManager,es as PressInteractionEncoder,ec as PurchaseInteractionEncoder,en as ReferralInteractionEncoder,eu as RetailInteractionEncoder,el as WebShopInteractionEncoder,C as base64urlDecode,F as base64urlEncode,k as baseIframeProps,T as compressJsonToB64,I as createIFrameFrakClient,b as createIframe,E as decompressJsonFromB64,K as displayEmbeddedWallet,H as displayModal,N as formatAmount,z as getCurrencyAmountKey,X as getProductInformation,L as getSupportedCurrency,W as getSupportedLocale,B as interactionTypes,R as locales,et as modalBuilder,Q as openSso,er as processReferral,M as productTypes,V as productTypesMask,ei as referralInteraction,J as sendInteraction,ee as sendTransaction,x as setupClient,Z as siweAuthenticate,_ as trackEvent,Y as trackPurchaseStatus,j as watchWalletStatus};
1
+ import{a as e,c as t,d as n,f as r,i,l as a,n as o,o as s,r as c,s as l,t as u,u as d}from"./trackEvent-YfUh4jrx.js";import{_ as f,a as p,b as m,c as h,d as g,f as _,g as v,h as y,i as b,l as x,m as S,n as C,o as w,p as T,r as E,s as D,t as O,u as k,v as A,y as j}from"./setupClient-D_HId3e2.js";import{a as M,c as N,d as P,f as F,i as I,l as L,n as R,o as z,r as B,s as V,t as H,u as U}from"./siweAuthenticate-CQ4OfPuA.js";export{m as DEEP_LINK_SCHEME,j as DebugInfoGatherer,o as FrakContextManager,a as base64urlDecode,d as base64urlEncode,_ as baseIframeProps,C as clearMerchantIdCache,t as compressJsonToB64,r as computeLegacyProductId,g as createIFrameFrakClient,T as createIframe,k as decompressJsonFromB64,F as displayEmbeddedWallet,P as displayModal,E as fetchMerchantId,S as findIframeInOpener,w as formatAmount,l as generateSsoUrl,c as getBackendUrl,n as getClientId,p as getCurrencyAmountKey,U as getMerchantInformation,h as getSupportedCurrency,D as getSupportedLocale,y as isChromiumAndroid,v as isFrakDeepLink,x as locales,B as modalBuilder,i as openSso,L as prepareSso,V as processReferral,z as referralInteraction,b as resolveMerchantId,N as sendInteraction,R as sendTransaction,O as setupClient,H as siweAuthenticate,e as ssoPopupFeatures,s as ssoPopupName,f as toAndroidIntentUrl,u as trackEvent,M as trackPurchaseStatus,A as triggerDeepLinkWithFallback,I as watchWalletStatus};
@@ -0,0 +1,525 @@
1
+ import { F as PrepareSsoParamsType, G as FrakWalletSdkConfig, L as SsoMetadata, W as Currency, a as FrakClient, i as FrakContext, p as TokenAmountType } from "./openSso-CC1-loUk.cjs";
2
+ import { RpcMessage, RpcResponse } from "@frak-labs/frame-connector";
3
+ import { Address, Hex } from "viem";
4
+
5
+ //#region src/types/compression.d.ts
6
+ /**
7
+ * The received encoded data from a client
8
+ * -> The encoded should contain a HashProtectedData once decoded
9
+ * @ignore
10
+ */
11
+ type CompressedData = Uint8Array;
12
+ /**
13
+ * The encoded data to send to a client / received by a client
14
+ * @ignore
15
+ */
16
+ type HashProtectedData<DataType> = Readonly<DataType & {
17
+ validationHash: string;
18
+ }>;
19
+ /**
20
+ * Represent a key provider used for the hashed and secure compression
21
+ * @ignore
22
+ */
23
+ type KeyProvider<DataType> = (value: DataType) => string[];
24
+ //#endregion
25
+ //#region src/types/tracking.d.ts
26
+ /**
27
+ * UTM parameters for marketing attribution
28
+ * @category Tracking
29
+ */
30
+ type UtmParams = {
31
+ source?: string;
32
+ medium?: string;
33
+ campaign?: string;
34
+ term?: string;
35
+ content?: string;
36
+ };
37
+ /**
38
+ * Parameters for tracking an arrival event
39
+ * @category Tracking
40
+ */
41
+ type TrackArrivalParams = {
42
+ /**
43
+ * The referrer wallet address (from fCtx URL param)
44
+ */
45
+ referrerWallet?: Address;
46
+ /**
47
+ * The landing page URL (defaults to current page)
48
+ */
49
+ landingUrl?: string;
50
+ /**
51
+ * UTM parameters for marketing attribution
52
+ */
53
+ utmParams?: UtmParams;
54
+ };
55
+ /**
56
+ * Result from tracking an arrival event
57
+ * @category Tracking
58
+ */
59
+ type TrackArrivalResult = {
60
+ success: boolean;
61
+ identityGroupId?: string;
62
+ touchpointId?: string;
63
+ error?: string;
64
+ };
65
+ /**
66
+ * Internal params passed to the trackArrival action
67
+ * Includes merchantId resolved from config or fetch
68
+ * @internal
69
+ */
70
+ type TrackArrivalInternalParams = TrackArrivalParams & {
71
+ /**
72
+ * The merchant ID (UUID from dashboard)
73
+ */
74
+ merchantId: string;
75
+ };
76
+ //#endregion
77
+ //#region src/clients/createIFrameFrakClient.d.ts
78
+ /**
79
+ * Create a new iframe Frak client
80
+ * @param args
81
+ * @param args.config - The configuration to use for the Frak Wallet SDK
82
+ * @param args.iframe - The iframe to use for the communication
83
+ * @returns The created Frak Client
84
+ *
85
+ * @example
86
+ * const frakConfig: FrakWalletSdkConfig = {
87
+ * metadata: {
88
+ * name: "My app title",
89
+ * },
90
+ * }
91
+ * const iframe = await createIframe({ config: frakConfig });
92
+ * const client = createIFrameFrakClient({ config: frakConfig, iframe });
93
+ */
94
+ declare function createIFrameFrakClient({
95
+ config,
96
+ iframe
97
+ }: {
98
+ config: FrakWalletSdkConfig;
99
+ iframe: HTMLIFrameElement;
100
+ }): FrakClient;
101
+ //#endregion
102
+ //#region src/clients/DebugInfo.d.ts
103
+ /** @ignore */
104
+ declare class DebugInfoGatherer {
105
+ private config?;
106
+ private iframe?;
107
+ private isSetupDone;
108
+ private lastResponse;
109
+ private lastRequest;
110
+ constructor(config?: FrakWalletSdkConfig, iframe?: HTMLIFrameElement);
111
+ setLastResponse(message: RpcMessage, response: RpcResponse): void;
112
+ setLastRequest(event: RpcMessage): void;
113
+ updateSetupStatus(status: boolean): void;
114
+ private base64Encode;
115
+ /**
116
+ * Extract information from the iframe status
117
+ */
118
+ private getIframeStatus;
119
+ private getNavigatorInfo;
120
+ private gatherDebugInfo;
121
+ static empty(): DebugInfoGatherer;
122
+ /**
123
+ * Format Frak debug information
124
+ */
125
+ formatDebugInfo(error: Error | unknown | string): string;
126
+ }
127
+ //#endregion
128
+ //#region src/clients/setupClient.d.ts
129
+ /**
130
+ * Directly setup the Frak client with an iframe
131
+ * Return when the FrakClient is ready (setup and communication estbalished with the wallet)
132
+ *
133
+ * @param config - The configuration to use for the Frak Wallet SDK
134
+ * @returns a Promise with the Frak Client
135
+ *
136
+ * @example
137
+ * const frakConfig: FrakWalletSdkConfig = {
138
+ * metadata: {
139
+ * name: "My app title",
140
+ * },
141
+ * }
142
+ * const client = await setupClient({ config: frakConfig });
143
+ */
144
+ declare function setupClient({
145
+ config
146
+ }: {
147
+ config: FrakWalletSdkConfig;
148
+ }): Promise<FrakClient | undefined>;
149
+ //#endregion
150
+ //#region src/constants/locales.d.ts
151
+ /**
152
+ * The keys for each locales
153
+ * @inline
154
+ */
155
+ type LocalesKey = keyof typeof locales;
156
+ /**
157
+ * Map the currency to the locale
158
+ */
159
+ declare const locales: {
160
+ readonly eur: "fr-FR";
161
+ readonly usd: "en-US";
162
+ readonly gbp: "en-GB";
163
+ };
164
+ //#endregion
165
+ //#region src/utils/backendUrl.d.ts
166
+ /**
167
+ * Get the backend URL for API calls
168
+ * Tries to derive from SDK config, falls back to production
169
+ *
170
+ * @param walletUrl - Optional wallet URL to derive from (overrides global config)
171
+ */
172
+ declare function getBackendUrl(walletUrl?: string): string;
173
+ //#endregion
174
+ //#region src/utils/clientId.d.ts
175
+ /**
176
+ * Client ID utilities for anonymous tracking
177
+ * Generates and persists a UUID fingerprint for referral attribution
178
+ */
179
+ /**
180
+ * Get the client ID from localStorage, creating one if it doesn't exist
181
+ * @returns The client ID (UUID format)
182
+ */
183
+ declare function getClientId(): string;
184
+ //#endregion
185
+ //#region src/utils/compression/b64.d.ts
186
+ /**
187
+ * Encode a buffer to a base64url encoded string
188
+ * @param buffer The buffer to encode
189
+ * @returns The encoded string
190
+ */
191
+ declare function base64urlEncode(buffer: Uint8Array): string;
192
+ /**
193
+ * Decode a base64url encoded string
194
+ * @param value The value to decode
195
+ * @returns The decoded value
196
+ */
197
+ declare function base64urlDecode(value: string): Uint8Array;
198
+ //#endregion
199
+ //#region src/utils/compression/compress.d.ts
200
+ /**
201
+ * Compress json data
202
+ * @param data
203
+ * @ignore
204
+ */
205
+ declare function compressJsonToB64(data: unknown): string;
206
+ //#endregion
207
+ //#region src/utils/compression/decompress.d.ts
208
+ /**
209
+ * Decompress json data
210
+ * @param data
211
+ * @ignore
212
+ */
213
+ declare function decompressJsonFromB64<T>(data: string): T | null;
214
+ //#endregion
215
+ //#region src/utils/constants.d.ts
216
+ /**
217
+ * Deep link scheme for Frak Wallet mobile app
218
+ */
219
+ declare const DEEP_LINK_SCHEME = "frakwallet://";
220
+ //#endregion
221
+ //#region src/utils/deepLinkWithFallback.d.ts
222
+ /**
223
+ * Options for deep link with fallback
224
+ */
225
+ type DeepLinkFallbackOptions = {
226
+ /** Timeout in ms before triggering fallback (default: 2500ms) */timeout?: number; /** Callback invoked when fallback is triggered (app not installed) */
227
+ onFallback?: () => void;
228
+ };
229
+ /**
230
+ * Check if running on a Chromium-based Android browser.
231
+ *
232
+ * On Chrome Android, custom scheme deep links (e.g. frakwallet://) trigger
233
+ * a confirmation bar ("Continue to Frak Wallet?"). Using intent:// URLs
234
+ * instead bypasses this for Chromium browsers while keeping custom scheme
235
+ * fallback for non-Chromium browsers (e.g. Firefox) where it works fine.
236
+ */
237
+ declare function isChromiumAndroid(): boolean;
238
+ /**
239
+ * Convert a frakwallet:// deep link to an Android intent:// URL.
240
+ *
241
+ * Intent URLs let Chromium browsers open the app directly without
242
+ * showing the "Continue to app?" confirmation bar.
243
+ *
244
+ * Format: intent://path#Intent;scheme=frakwallet;package=id.frak.wallet;end
245
+ */
246
+ declare function toAndroidIntentUrl(deepLink: string): string;
247
+ /**
248
+ * Trigger a deep link with visibility-based fallback detection.
249
+ *
250
+ * Uses the Page Visibility API to detect if the app opened (page goes hidden).
251
+ * If the page remains visible after the timeout, assumes app is not installed
252
+ * and invokes the onFallback callback.
253
+ *
254
+ * On Chromium Android, converts custom scheme to intent:// URL to avoid
255
+ * the "Continue to app?" confirmation bar.
256
+ *
257
+ * @param deepLink - The deep link URL to trigger (e.g., "frakwallet://wallet")
258
+ * @param options - Optional configuration (timeout, onFallback callback)
259
+ */
260
+ declare function triggerDeepLinkWithFallback(deepLink: string, options?: DeepLinkFallbackOptions): void;
261
+ /**
262
+ * Check if a URL is a Frak deep link
263
+ */
264
+ declare function isFrakDeepLink(url: string): boolean;
265
+ //#endregion
266
+ //#region src/utils/FrakContext.d.ts
267
+ /**
268
+ * Compress the current Frak context
269
+ * @param context - The context to be compressed
270
+ * @returns A compressed string containing the Frak context
271
+ */
272
+ declare function compress(context?: Partial<FrakContext>): string | undefined;
273
+ /**
274
+ * Decompress the given Frak context
275
+ * @param context - The raw context to be decompressed into a `FrakContext`
276
+ * @returns The decompressed Frak context, or undefined if it fails
277
+ */
278
+ declare function decompress(context?: string): FrakContext | undefined;
279
+ /**
280
+ * Parse the current URL into a Frak Context
281
+ * @param args
282
+ * @param args.url - The url to parse
283
+ * @returns The parsed Frak context
284
+ */
285
+ declare function parse({
286
+ url
287
+ }: {
288
+ url: string;
289
+ }): FrakContext | null | undefined;
290
+ /**
291
+ * Populate the current url with the given Frak context
292
+ * @param args
293
+ * @param args.url - The url to update
294
+ * @param args.context - The context to update
295
+ * @returns The new url with the Frak context
296
+ */
297
+ declare function update({
298
+ url,
299
+ context
300
+ }: {
301
+ url?: string;
302
+ context: Partial<FrakContext>;
303
+ }): string | null;
304
+ /**
305
+ * Remove Frak context from current url
306
+ * @param url - The url to update
307
+ * @returns The new url without the Frak context
308
+ */
309
+ declare function remove(url: string): string;
310
+ /**
311
+ * Replace the current url with the given Frak context
312
+ * @param args
313
+ * @param args.url - The url to update
314
+ * @param args.context - The context to update
315
+ */
316
+ declare function replaceUrl({
317
+ url: baseUrl,
318
+ context
319
+ }: {
320
+ url?: string;
321
+ context: Partial<FrakContext> | null;
322
+ }): void;
323
+ /**
324
+ * Export our frak context
325
+ */
326
+ declare const FrakContextManager: {
327
+ compress: typeof compress;
328
+ decompress: typeof decompress;
329
+ parse: typeof parse;
330
+ update: typeof update;
331
+ remove: typeof remove;
332
+ replaceUrl: typeof replaceUrl;
333
+ };
334
+ //#endregion
335
+ //#region src/utils/formatAmount.d.ts
336
+ declare function formatAmount(amount: number, currency?: Currency): string;
337
+ //#endregion
338
+ //#region src/utils/getCurrencyAmountKey.d.ts
339
+ /**
340
+ * Get the currency amount key for a given currency
341
+ * @param currency - The currency to use
342
+ * @returns The currency amount key
343
+ */
344
+ declare function getCurrencyAmountKey(currency?: Currency): keyof TokenAmountType;
345
+ //#endregion
346
+ //#region src/utils/getSupportedCurrency.d.ts
347
+ /**
348
+ * Get the supported currency for a given currency
349
+ * @param currency - The currency to use
350
+ * @returns The supported currency
351
+ */
352
+ declare function getSupportedCurrency(currency?: Currency): Currency;
353
+ //#endregion
354
+ //#region src/utils/getSupportedLocale.d.ts
355
+ /**
356
+ * Get the supported locale for a given currency
357
+ * @param currency - The currency to use
358
+ * @returns The supported locale
359
+ */
360
+ declare function getSupportedLocale(currency?: Currency): (typeof locales)[LocalesKey];
361
+ //#endregion
362
+ //#region src/utils/iframeHelper.d.ts
363
+ /**
364
+ * Base props for the iframe
365
+ * @ignore
366
+ */
367
+ declare const baseIframeProps: {
368
+ id: string;
369
+ name: string;
370
+ title: string;
371
+ allow: string;
372
+ style: {
373
+ width: string;
374
+ height: string;
375
+ border: string;
376
+ position: string;
377
+ zIndex: number;
378
+ top: string;
379
+ left: string;
380
+ colorScheme: string;
381
+ };
382
+ };
383
+ /**
384
+ * Create the Frak iframe
385
+ * @param args
386
+ * @param args.walletBaseUrl - Use `config.walletUrl` instead. Will be removed in future versions.
387
+ * @param args.config - The configuration object containing iframe options, including the replacement for `walletBaseUrl`.
388
+ */
389
+ declare function createIframe({
390
+ walletBaseUrl,
391
+ config
392
+ }: {
393
+ walletBaseUrl?: string;
394
+ config?: FrakWalletSdkConfig;
395
+ }): Promise<HTMLIFrameElement | undefined>;
396
+ /**
397
+ * Find an iframe within window.opener by pathname
398
+ *
399
+ * When a popup is opened via window.open from an iframe, window.opener points to
400
+ * the parent window, not the iframe itself. This utility searches through all frames
401
+ * in window.opener to find an iframe matching the specified pathname.
402
+ *
403
+ * @param pathname - The pathname to search for (default: "/listener")
404
+ * @returns The matching iframe window, or null if not found
405
+ *
406
+ * @example
407
+ * ```typescript
408
+ * // Find the default /listener iframe
409
+ * const listenerIframe = findIframeInOpener();
410
+ *
411
+ * // Find a custom iframe
412
+ * const customIframe = findIframeInOpener("/my-custom-iframe");
413
+ * ```
414
+ */
415
+ declare function findIframeInOpener(pathname?: string): Window | null;
416
+ //#endregion
417
+ //#region src/utils/merchantId.d.ts
418
+ /**
419
+ * Merchant ID utilities for auto-fetching from backend
420
+ */
421
+ /**
422
+ * Fetch merchantId from backend by domain
423
+ *
424
+ * @param domain - The domain to lookup (defaults to current hostname)
425
+ * @param walletUrl - Optional wallet URL to derive backend URL
426
+ * @returns The merchantId if found, undefined otherwise
427
+ *
428
+ * @example
429
+ * ```ts
430
+ * const merchantId = await fetchMerchantId("shop.example.com");
431
+ * if (merchantId) {
432
+ * // Use merchantId for tracking
433
+ * }
434
+ * ```
435
+ */
436
+ declare function fetchMerchantId(domain?: string, walletUrl?: string): Promise<string | undefined>;
437
+ /**
438
+ * Clear the cached merchantId
439
+ * Useful for testing or when switching domains
440
+ */
441
+ declare function clearMerchantIdCache(): void;
442
+ /**
443
+ * Get merchantId from config or auto-fetch from backend
444
+ *
445
+ * @param config - The SDK config that may contain merchantId
446
+ * @param walletUrl - Optional wallet URL to derive backend URL
447
+ * @returns The merchantId if available (from config or fetch), undefined otherwise
448
+ */
449
+ declare function resolveMerchantId(config: {
450
+ metadata?: {
451
+ merchantId?: string;
452
+ };
453
+ }, walletUrl?: string): Promise<string | undefined>;
454
+ //#endregion
455
+ //#region src/utils/sso.d.ts
456
+ type AppSpecificSsoMetadata = SsoMetadata & {
457
+ name: string;
458
+ css?: string;
459
+ };
460
+ /**
461
+ * The full SSO params that will be used for compression
462
+ */
463
+ type FullSsoParams = Omit<PrepareSsoParamsType, "metadata"> & {
464
+ metadata: AppSpecificSsoMetadata;
465
+ merchantId: string;
466
+ clientId: string;
467
+ };
468
+ /**
469
+ * Generate SSO URL with compressed parameters
470
+ * This mirrors the wallet's getOpenSsoLink() function
471
+ *
472
+ * @param walletUrl - Base wallet URL (e.g., "https://wallet.frak.id")
473
+ * @param params - SSO parameters
474
+ * @param productId - Product identifier
475
+ * @param name - Application name
476
+ * @param css - Optional custom CSS
477
+ * @returns Complete SSO URL ready to open in popup or redirect
478
+ *
479
+ * @example
480
+ * ```ts
481
+ * const ssoUrl = generateSsoUrl(
482
+ * "https://wallet.frak.id",
483
+ * { metadata: { logoUrl: "..." }, directExit: true },
484
+ * "0x123...",
485
+ * "My App"
486
+ * );
487
+ * // Returns: https://wallet.frak.id/sso?p=<compressed_base64>
488
+ * ```
489
+ */
490
+ declare function generateSsoUrl(walletUrl: string, params: PrepareSsoParamsType, merchantId: string, name: string, css?: string, clientId?: string): string;
491
+ /**
492
+ * Type of compressed the sso data
493
+ */
494
+ type CompressedSsoData = {
495
+ id?: Hex;
496
+ cId: string;
497
+ r?: string;
498
+ d?: boolean;
499
+ l?: "en" | "fr";
500
+ m: string;
501
+ md: {
502
+ n: string;
503
+ css?: string;
504
+ l?: string;
505
+ h?: string;
506
+ };
507
+ };
508
+ //#endregion
509
+ //#region src/utils/trackEvent.d.ts
510
+ type FrakEvent = "share_button_clicked" | "wallet_button_clicked" | "open_in_app_clicked" | "open_in_app_login_clicked" | "app_not_installed" | "share_modal_error" | "user_referred_started" | "user_referred_completed" | "user_referred_error";
511
+ type EventProps = Record<string, unknown>;
512
+ declare function trackEvent(client: FrakClient | undefined, event: FrakEvent, props?: EventProps): void;
513
+ //#endregion
514
+ //#region src/utils/computeLegacyProductId.d.ts
515
+ /**
516
+ * Compute the legacy product id from a domain
517
+ * @ignore
518
+ */
519
+ declare function computeLegacyProductId({
520
+ domain
521
+ }?: {
522
+ domain?: string;
523
+ }): `0x${string}`;
524
+ //#endregion
525
+ export { getBackendUrl as A, CompressedData as B, triggerDeepLinkWithFallback as C, base64urlDecode as D, compressJsonToB64 as E, createIFrameFrakClient as F, KeyProvider as H, TrackArrivalInternalParams as I, TrackArrivalParams as L, locales as M, setupClient as N, base64urlEncode as O, DebugInfoGatherer as P, TrackArrivalResult as R, toAndroidIntentUrl as S, decompressJsonFromB64 as T, HashProtectedData as V, formatAmount as _, CompressedSsoData as a, isChromiumAndroid as b, clearMerchantIdCache as c, baseIframeProps as d, createIframe as f, getCurrencyAmountKey as g, getSupportedCurrency as h, AppSpecificSsoMetadata as i, LocalesKey as j, getClientId as k, fetchMerchantId as l, getSupportedLocale as m, FrakEvent as n, FullSsoParams as o, findIframeInOpener as p, trackEvent as r, generateSsoUrl as s, computeLegacyProductId as t, resolveMerchantId as u, FrakContextManager as v, DEEP_LINK_SCHEME as w, isFrakDeepLink as x, DeepLinkFallbackOptions as y, UtmParams as z };