@frak-labs/core-sdk 1.1.4 → 1.1.5-beta.727c2f3f
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.
- package/cdn/bundle.js +1 -1
- package/dist/actions-DrZ_PIs1.cjs +2 -0
- package/dist/actions-DrZ_PIs1.cjs.map +1 -0
- package/dist/actions-HG5M8wX7.js +2 -0
- package/dist/actions-HG5M8wX7.js.map +1 -0
- package/dist/actions.cjs +1 -1
- package/dist/actions.d.cts +3 -3
- package/dist/actions.d.ts +3 -3
- package/dist/actions.js +1 -1
- package/dist/bundle.cjs +1 -1
- package/dist/bundle.d.cts +4 -4
- package/dist/bundle.d.ts +4 -4
- package/dist/bundle.js +1 -1
- package/dist/frakContext-Bgidv-Se.js +2 -0
- package/dist/frakContext-Bgidv-Se.js.map +1 -0
- package/dist/frakContext-CeVlWFcX.cjs +2 -0
- package/dist/frakContext-CeVlWFcX.cjs.map +1 -0
- package/dist/{index-lcImYQyL.d.ts → index-BJMazhpm.d.ts} +3 -2
- package/dist/{index-Cm1PNC9z.d.ts → index-BysidNLB.d.ts} +7 -6
- package/dist/{index-DR4n-QOe.d.cts → index-C1A3I4x1.d.cts} +3 -2
- package/dist/{index-Cumn_FNI.d.cts → index-k1lfbVkl.d.cts} +7 -6
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/{openSso-DRLH4D9a.d.ts → openSso-B0igO6Iu.d.cts} +9 -3
- package/dist/{openSso-BErs7_Bg.d.cts → openSso-BWeD0Fb2.d.ts} +9 -3
- package/dist/src-CCJgTN1H.cjs +2 -0
- package/dist/src-CCJgTN1H.cjs.map +1 -0
- package/dist/src-DKLOAY9w.js +2 -0
- package/dist/src-DKLOAY9w.js.map +1 -0
- package/package.json +4 -3
- package/src/actions/referral/processReferral.test.ts +4 -4
- package/src/actions/referral/processReferral.ts +4 -4
- package/src/clients/createIFrameFrakClient.ts +7 -7
- package/src/clients/transports/iframeLifecycleManager.ts +5 -21
- package/src/config/sdkConfigStore.ts +6 -3
- package/src/types/rpc/merchantInformation.ts +13 -6
- package/src/utils/analytics/events/lifecycle.ts +1 -1
- package/src/utils/analytics/events/referral.ts +3 -3
- package/src/utils/browser/deepLinkWithFallback.ts +4 -1
- package/src/utils/browser/inAppBrowser.ts +2 -2
- package/src/utils/cache/withCache.ts +30 -11
- package/src/utils/iframe/iframeHelper.test.ts +39 -0
- package/src/utils/iframe/iframeHelper.ts +31 -2
- package/dist/actions-D5GbNcvt.cjs +0 -1
- package/dist/actions-DE2dHqtp.js +0 -1
- package/dist/frakContext-Bl17GGa3.cjs +0 -1
- package/dist/frakContext-DmI5CaSw.js +0 -1
- package/dist/src-5vpUuhfY.js +0 -1
- package/dist/src-BQsjMpvA.cjs +0 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e,a as t,d as n,f as r,g as i,h as a,l as o,m as s,o as c,p as l,s as u,t as d,u as f,v as p,y as m}from"./frakContext-
|
|
1
|
+
import{_ as e,a as t,d as n,f as r,g as i,h as a,l as o,m as s,o as c,p as l,s as u,t as d,u as f,v as p,y as m}from"./frakContext-Bgidv-Se.js";import{a as h,c as g,d as _,f 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}from"./src-DKLOAY9w.js";export{y as DEEP_LINK_SCHEME,d as FrakContextManager,l as base64urlDecode,s as base64urlEncode,g as baseIframeProps,e as clearAllCache,r as compressJsonToB64,D as createIFrameFrakClient,w as decompressJsonFromB64,t as deleteQueryParamCaseInsensitive,x as findIframeInOpener,b as formatAmount,n as generateSsoUrl,i as getBackendUrl,m as getClientId,E as getCurrencyAmountKey,c as getQueryParamCaseInsensitive,h as getSupportedCurrency,k as isIOS,_ as isInAppBrowser,v as isMobile,O as mergeAttribution,T as redirectToExternalBrowser,a as sdkConfigStore,C as setupClient,o as ssoPopupFeatures,f as ssoPopupName,u as trackEvent,S as triggerDeepLinkWithFallback,p as withCache};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { LifecycleMessage, RpcClient } from "@frak-labs/frame-connector";
|
|
2
1
|
import { OpenPanel } from "@openpanel/web";
|
|
3
2
|
import { Address, Hex } from "viem";
|
|
3
|
+
import { LifecycleMessage, RpcClient } from "@frak-labs/frame-connector";
|
|
4
4
|
import { SiweMessage } from "viem/siwe";
|
|
5
5
|
|
|
6
6
|
//#region src/types/tracking.d.ts
|
|
@@ -989,12 +989,17 @@ type TokenAmountType = {
|
|
|
989
989
|
gbpAmount: number;
|
|
990
990
|
};
|
|
991
991
|
/**
|
|
992
|
-
* A tier definition for tiered rewards
|
|
992
|
+
* A tier definition for tiered rewards — pays either a flat token amount
|
|
993
|
+
* or a percent of the tier field value
|
|
993
994
|
*/
|
|
994
995
|
type RewardTier = {
|
|
995
996
|
minValue: number;
|
|
996
997
|
maxValue?: number;
|
|
997
998
|
amount: TokenAmountType;
|
|
999
|
+
} | {
|
|
1000
|
+
minValue: number;
|
|
1001
|
+
maxValue?: number;
|
|
1002
|
+
percent: number;
|
|
998
1003
|
};
|
|
999
1004
|
/**
|
|
1000
1005
|
* Estimated reward amount — discriminated union by payout type
|
|
@@ -1387,4 +1392,5 @@ declare const ssoPopupName = "frak-sso";
|
|
|
1387
1392
|
*/
|
|
1388
1393
|
declare function openSso(client: FrakClient, inputArgs: OpenSsoParamsType): Promise<OpenSsoReturnType>;
|
|
1389
1394
|
//#endregion
|
|
1390
|
-
export { SdkResolvedConfig as $, ModalRpcStepsResultType as A, OpenSsoReturnType as B, LoggedInEmbeddedView as C, DisplayModalParamsType as D, SharingPageProduct as E, SiweAuthenticateModalStepType as F, FinalModalStepType as G, PrepareSsoReturnType as H, SiweAuthenticateReturnType as I, IFrameLifecycleEvent as J, ModalStepMetadata as K, SiweAuthenticationParams as L, SendTransactionModalStepType as M, SendTransactionReturnType as N, ModalRpcMetadata as O, SendTransactionTxType as P, ResolvedSdkConfig as Q, LoginModalStepType as R, EmbeddedViewActionSharing as S, DisplaySharingPageResultType as T, SsoMetadata as U, PrepareSsoParamsType as V, FinalActionType as W, MerchantConfigResponse as X, ClientLifecycleEvent as Y, ResolvedPlacement as Z, SendInteractionParamsType as _, FrakContextV1 as a, LocalizedI18nConfig as at, LoggedOutEmbeddedView as b, FrakLifecycleEvent as c, TrackArrivalParams as ct, WalletStatusReturnType as d, Currency as et, UserReferralStatusType as f, TokenAmountType as g, RewardTier as h, FrakContext as i, ListenerPreloadOption as it, ModalStepTypes as j, ModalRpcStepsInput as k, IFrameTransport as l, TrackArrivalResult as lt, GetMerchantInformationReturnType as m, ssoPopupFeatures as n, I18nConfig as nt, FrakContextV2 as o, AttributionDefaults as ot, EstimatedReward as p, InteractionTypeKey as q, ssoPopupName as r, Language as rt, FrakClient as s, AttributionParams as st, openSso as t, FrakWalletSdkConfig as tt, IFrameRpcSchema as u, UtmParams as ut, DisplayEmbeddedWalletParamsType as v, DisplaySharingPageParamsType as w, EmbeddedViewActionReferred as x, DisplayEmbeddedWalletResultType as y, OpenSsoParamsType as z };
|
|
1395
|
+
export { SdkResolvedConfig as $, ModalRpcStepsResultType as A, OpenSsoReturnType as B, LoggedInEmbeddedView as C, DisplayModalParamsType as D, SharingPageProduct as E, SiweAuthenticateModalStepType as F, FinalModalStepType as G, PrepareSsoReturnType as H, SiweAuthenticateReturnType as I, IFrameLifecycleEvent as J, ModalStepMetadata as K, SiweAuthenticationParams as L, SendTransactionModalStepType as M, SendTransactionReturnType as N, ModalRpcMetadata as O, SendTransactionTxType as P, ResolvedSdkConfig as Q, LoginModalStepType as R, EmbeddedViewActionSharing as S, DisplaySharingPageResultType as T, SsoMetadata as U, PrepareSsoParamsType as V, FinalActionType as W, MerchantConfigResponse as X, ClientLifecycleEvent as Y, ResolvedPlacement as Z, SendInteractionParamsType as _, FrakContextV1 as a, LocalizedI18nConfig as at, LoggedOutEmbeddedView as b, FrakLifecycleEvent as c, TrackArrivalParams as ct, WalletStatusReturnType as d, Currency as et, UserReferralStatusType as f, TokenAmountType as g, RewardTier as h, FrakContext as i, ListenerPreloadOption as it, ModalStepTypes as j, ModalRpcStepsInput as k, IFrameTransport as l, TrackArrivalResult as lt, GetMerchantInformationReturnType as m, ssoPopupFeatures as n, I18nConfig as nt, FrakContextV2 as o, AttributionDefaults as ot, EstimatedReward as p, InteractionTypeKey as q, ssoPopupName as r, Language as rt, FrakClient as s, AttributionParams as st, openSso as t, FrakWalletSdkConfig as tt, IFrameRpcSchema as u, UtmParams as ut, DisplayEmbeddedWalletParamsType as v, DisplaySharingPageParamsType as w, EmbeddedViewActionReferred as x, DisplayEmbeddedWalletResultType as y, OpenSsoParamsType as z };
|
|
1396
|
+
//# sourceMappingURL=openSso-B0igO6Iu.d.cts.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { LifecycleMessage, RpcClient } from "@frak-labs/frame-connector";
|
|
1
2
|
import { OpenPanel } from "@openpanel/web";
|
|
2
3
|
import { Address, Hex } from "viem";
|
|
3
|
-
import { LifecycleMessage, RpcClient } from "@frak-labs/frame-connector";
|
|
4
4
|
import { SiweMessage } from "viem/siwe";
|
|
5
5
|
|
|
6
6
|
//#region src/types/tracking.d.ts
|
|
@@ -989,12 +989,17 @@ type TokenAmountType = {
|
|
|
989
989
|
gbpAmount: number;
|
|
990
990
|
};
|
|
991
991
|
/**
|
|
992
|
-
* A tier definition for tiered rewards
|
|
992
|
+
* A tier definition for tiered rewards — pays either a flat token amount
|
|
993
|
+
* or a percent of the tier field value
|
|
993
994
|
*/
|
|
994
995
|
type RewardTier = {
|
|
995
996
|
minValue: number;
|
|
996
997
|
maxValue?: number;
|
|
997
998
|
amount: TokenAmountType;
|
|
999
|
+
} | {
|
|
1000
|
+
minValue: number;
|
|
1001
|
+
maxValue?: number;
|
|
1002
|
+
percent: number;
|
|
998
1003
|
};
|
|
999
1004
|
/**
|
|
1000
1005
|
* Estimated reward amount — discriminated union by payout type
|
|
@@ -1387,4 +1392,5 @@ declare const ssoPopupName = "frak-sso";
|
|
|
1387
1392
|
*/
|
|
1388
1393
|
declare function openSso(client: FrakClient, inputArgs: OpenSsoParamsType): Promise<OpenSsoReturnType>;
|
|
1389
1394
|
//#endregion
|
|
1390
|
-
export { SdkResolvedConfig as $, ModalRpcStepsResultType as A, OpenSsoReturnType as B, LoggedInEmbeddedView as C, DisplayModalParamsType as D, SharingPageProduct as E, SiweAuthenticateModalStepType as F, FinalModalStepType as G, PrepareSsoReturnType as H, SiweAuthenticateReturnType as I, IFrameLifecycleEvent as J, ModalStepMetadata as K, SiweAuthenticationParams as L, SendTransactionModalStepType as M, SendTransactionReturnType as N, ModalRpcMetadata as O, SendTransactionTxType as P, ResolvedSdkConfig as Q, LoginModalStepType as R, EmbeddedViewActionSharing as S, DisplaySharingPageResultType as T, SsoMetadata as U, PrepareSsoParamsType as V, FinalActionType as W, MerchantConfigResponse as X, ClientLifecycleEvent as Y, ResolvedPlacement as Z, SendInteractionParamsType as _, FrakContextV1 as a, LocalizedI18nConfig as at, LoggedOutEmbeddedView as b, FrakLifecycleEvent as c, TrackArrivalParams as ct, WalletStatusReturnType as d, Currency as et, UserReferralStatusType as f, TokenAmountType as g, RewardTier as h, FrakContext as i, ListenerPreloadOption as it, ModalStepTypes as j, ModalRpcStepsInput as k, IFrameTransport as l, TrackArrivalResult as lt, GetMerchantInformationReturnType as m, ssoPopupFeatures as n, I18nConfig as nt, FrakContextV2 as o, AttributionDefaults as ot, EstimatedReward as p, InteractionTypeKey as q, ssoPopupName as r, Language as rt, FrakClient as s, AttributionParams as st, openSso as t, FrakWalletSdkConfig as tt, IFrameRpcSchema as u, UtmParams as ut, DisplayEmbeddedWalletParamsType as v, DisplaySharingPageParamsType as w, EmbeddedViewActionReferred as x, DisplayEmbeddedWalletResultType as y, OpenSsoParamsType as z };
|
|
1395
|
+
export { SdkResolvedConfig as $, ModalRpcStepsResultType as A, OpenSsoReturnType as B, LoggedInEmbeddedView as C, DisplayModalParamsType as D, SharingPageProduct as E, SiweAuthenticateModalStepType as F, FinalModalStepType as G, PrepareSsoReturnType as H, SiweAuthenticateReturnType as I, IFrameLifecycleEvent as J, ModalStepMetadata as K, SiweAuthenticationParams as L, SendTransactionModalStepType as M, SendTransactionReturnType as N, ModalRpcMetadata as O, SendTransactionTxType as P, ResolvedSdkConfig as Q, LoginModalStepType as R, EmbeddedViewActionSharing as S, DisplaySharingPageResultType as T, SsoMetadata as U, PrepareSsoParamsType as V, FinalActionType as W, MerchantConfigResponse as X, ClientLifecycleEvent as Y, ResolvedPlacement as Z, SendInteractionParamsType as _, FrakContextV1 as a, LocalizedI18nConfig as at, LoggedOutEmbeddedView as b, FrakLifecycleEvent as c, TrackArrivalParams as ct, WalletStatusReturnType as d, Currency as et, UserReferralStatusType as f, TokenAmountType as g, RewardTier as h, FrakContext as i, ListenerPreloadOption as it, ModalStepTypes as j, ModalRpcStepsInput as k, IFrameTransport as l, TrackArrivalResult as lt, GetMerchantInformationReturnType as m, ssoPopupFeatures as n, I18nConfig as nt, FrakContextV2 as o, AttributionDefaults as ot, EstimatedReward as p, InteractionTypeKey as q, ssoPopupName as r, Language as rt, FrakClient as s, AttributionParams as st, openSso as t, FrakWalletSdkConfig as tt, IFrameRpcSchema as u, UtmParams as ut, DisplayEmbeddedWalletParamsType as v, DisplaySharingPageParamsType as w, EmbeddedViewActionReferred as x, DisplayEmbeddedWalletResultType as y, OpenSsoParamsType as z };
|
|
1396
|
+
//# sourceMappingURL=openSso-BWeD0Fb2.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require(`./frakContext-CeVlWFcX.cjs`);let t=require(`@frak-labs/frame-connector`),n=require(`@openpanel/web`);const r=`nexus-wallet-backup`,i=`frakwallet://`;function a(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`))}function o(){let e=navigator.userAgent;return/Android/i.test(e)&&/Chrome\/\d+/i.test(e)}const s=i.replace(`://`,``);function c(e){return`intent://${e.slice(13)}#Intent;scheme=${s};end`}function l(e,t){let n=t?.timeout??2500,r=!1,i=()=>{document.hidden&&(r=!0)};document.addEventListener(`visibilitychange`,i);let a=o()&&u(e)?c(e):e;window.location.href=a,setTimeout(()=>{document.removeEventListener(`visibilitychange`,i),r||t?.onFallback?.()},n)}function u(e){return e.startsWith(i)}function d(){if(typeof navigator>`u`)return!1;let e=navigator.userAgent;return!!(/iPhone|iPad|iPod/i.test(e)||/Macintosh/i.test(e)&&navigator.maxTouchPoints>1)}const f=d();function p(){return typeof navigator>`u`?!1:f?!0:/Android|webOS|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function m(){if(typeof navigator>`u`)return!1;let e=navigator.userAgent.toLowerCase();return e.includes(`instagram`)||e.includes(`fban`)||e.includes(`fbav`)||e.includes(`facebook`)}const h=m();function g(e){f&&e.startsWith(`https://`)?window.location.href=`x-safari-https://${e.slice(8)}`:f&&e.startsWith(`http://`)?window.location.href=`x-safari-http://${e.slice(7)}`:window.location.href=`https://backend.frak.id/common/social?u=${encodeURIComponent(e)}`}const _={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 v({walletBaseUrl:t,config:n}){let r=document.querySelector(`#frak-wallet`);r&&r.remove();let i=document.createElement(`iframe`);i.id=_.id,i.name=_.name,i.allow=_.allow,i.style.zIndex=_.style.zIndex.toString(),b({iframe:i,isVisible:!1});let a=n?.walletUrl??t??`https://wallet.frak.id`,o=e.y();return S(a),S(e.g(a)),i.src=y({walletUrl:a,clientId:o,preload:n?.preload}),new Promise(e=>{i.addEventListener(`load`,()=>e(i)),document.body.appendChild(i)})}function y({walletUrl:e,clientId:t,preload:n}){let r=`${e}/listener?clientId=${encodeURIComponent(t)}`;return!n||n.length===0?r:`${r}#preload=${n.join(`,`)}`}function b({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 x(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 S(e){if(!(typeof document>`u`))try{let t=new URL(e).origin,n=`link[rel="preconnect"][data-frak-preconnect="${t}"]`;if(document.head.querySelector(n))return;let r=document.createElement(`link`);r.rel=`preconnect`,r.href=t,r.crossOrigin=``,r.dataset.frakPreconnect=t,document.head.appendChild(r)}catch{}}const C=f&&h;function w(e){e?localStorage.setItem(r,e):localStorage.removeItem(r)}function T(e,t){try{let n=new URL(e);if(!n.searchParams.has(`u`))return e;let r=O(window.location.href,t);return n.searchParams.delete(`u`),n.searchParams.append(`u`,r),n.toString()}catch{return e}}function E(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 D(e){return e.includes(`/common/social`)}function O(e,t){if(!t)return e;try{let n=new URL(e);return n.searchParams.set(`fmt`,t),n.toString()}catch{return`${e}${e.includes(`?`)?`&`:`?`}fmt=${encodeURIComponent(t)}`}}function k(e,t,n,r,i){if(i){let e=T(t,r);window.open(e,`_blank`);return}if(u(t)){let i=T(t,r);l(i,{onFallback:()=>{e.contentWindow?.postMessage({clientLifecycle:`deep-link-failed`,data:{originalUrl:i}},n)}})}else if(C&&D(t))E(r);else{let e=T(t,r);window.location.href=e}}function A({iframe:e,targetOrigin:n}){let i=new t.Deferred;return{handleEvent:t=>{if(!(`iframeLifecycle`in t))return;let{iframeLifecycle:a,data:o}=t;switch(a){case`connected`:i.resolve(!0);break;case`do-backup`:w(o.backup);break;case`remove-backup`:localStorage.removeItem(r);break;case`show`:case`hide`:b({iframe:e,isVisible:a===`show`});break;case`redirect`:k(e,o.baseRedirectUrl,n,o.mergeToken,o.openInNewTab);break}},isConnected:i.promise}}function j({config:r,iframe:i}){let a=r?.walletUrl??`https://wallet.frak.id`,o=typeof navigator<`u`?navigator.language?.split(`-`)[0]:void 0,s=r.metadata.lang??(o===`en`||o===`fr`?o:void 0),c=r.domain??(typeof window<`u`?window.location.hostname:``);e.h.setCacheScope(c,s),e.h.reset();let l=e.h.isCacheFresh?void 0:e.h.resolve(r.domain,r.walletUrl,s),u=A({iframe:i,targetOrigin:a}),d=new t.Deferred,f=Date.now();if(!i.contentWindow)throw new t.FrakRpcError(t.RpcErrorCodes.configError,`The iframe does not have a content window`);let p=(0,t.createRpcClient)({emittingTransport:i.contentWindow,listeningTransport:window,targetOrigin:a,middleware:[{async onRequest(e,n){if(!await u.isConnected)throw new t.FrakRpcError(t.RpcErrorCodes.clientNotConnected,`The iframe provider isn't connected yet`);return await d.promise,n}}],lifecycleHandlers:{iframeLifecycle:(e,t)=>{u.handleEvent(e)}}}),m=M(p,u),h=async()=>{m(),p.cleanup(),i.remove(),e._(),e.h.clearCache(),e.h.reset()},g;{console.log(`[Frak SDK] Initializing OpenPanel`),g=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||`sdk_version`in n.properties||(n.properties={...n.properties,sdk_version:`1.1.5`,user_anonymous_client_id:e.y()}),!0)}),g.setGlobalProperties({sdk_version:`1.1.5`,user_anonymous_client_id:e.y()}),g.init(),g.track(`sdk_initialized`,{sdk_version:`1.1.5`});let t=!1,r=setTimeout(()=>{t||(t=!0,g?.track(`sdk_iframe_handshake_failed`,{reason:`timeout`}))},3e4);u.isConnected.then(()=>{t||(t=!0,clearTimeout(r),g?.track(`sdk_iframe_connected`,{handshake_duration_ms:Date.now()-f}))}).catch(()=>{t||(t=!0,clearTimeout(r),g?.track(`sdk_iframe_handshake_failed`,{reason:`unknown`}))})}let _=N({config:r,rpcClient:p,lifecycleManager:u,configPromise:l,contextSent:d,openPanel:g}).then(()=>{}).catch(e=>{throw d.reject(e),e});return{config:r,waitForConnection:u.isConnected,waitForSetup:_,request:p.request,listenerRequest:p.listen,destroy:h,openPanel:g}}function M(e,t){let n,r,i=()=>e.sendLifecycle({clientLifecycle:`heartbeat`});async function a(){i(),n=setInterval(i,250),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 N({config:t,rpcClient:n,lifecycleManager:i,configPromise:o,contextSent:s,openPanel:c}){await i.isConnected,a(n,i.isConnected);let l=new URL(window.location.href),u=l.searchParams.get(`fmt`)??void 0;u&&(l.searchParams.delete(`fmt`),window.history.replaceState({},``,l.toString()));let d=n=>{let r=n?.merchantId??t.metadata.merchantId??``,i=n?.domain??``,a=n?.allowedDomains??[],o=n?.sdkConfig,s=o?.attribution||t.attribution?{...t.attribution,...o?.attribution}:void 0;e.h.setConfig(o?{isResolved:!0,merchantId:r,domain:i,allowedDomains:a,hasRawSdkConfig:!0,name:o.name??t.metadata.name,logoUrl:o.logoUrl??t.metadata.logoUrl,homepageLink:o.homepageLink??t.metadata.homepageLink,lang:o.lang??t.metadata.lang,currency:o.currency??t.metadata.currency,hidden:o.hidden,css:o.css,translations:o.translations,placements:o.placements,components:o.components,attribution:s}:{isResolved:!0,merchantId:r,domain:i,allowedDomains:a,name:t.metadata.name,logoUrl:t.metadata.logoUrl,homepageLink:t.metadata.homepageLink,lang:t.metadata.lang,currency:t.metadata.currency,attribution:s})},f=!1,p=t=>{let r=f?void 0:u;f=!0;let i=t.hasRawSdkConfig?{name:t.name,logoUrl:t.logoUrl,homepageLink:t.homepageLink,lang:t.lang,currency:t.currency,hidden:t.hidden,css:t.css,translations:t.translations,placements:t.placements,attribution:t.attribution}:t.attribution?{attribution:t.attribution}:void 0,a=e.y();if(c){let e=c.global??{};c.setGlobalProperties({...e,merchant_id:t.merchantId,domain:t.domain??``})}n.sendLifecycle({clientLifecycle:`resolved-config`,data:{merchantId:t.merchantId,domain:t.domain??``,allowedDomains:t.allowedDomains??[],sourceUrl:window.location.href,...a&&{sdkAnonymousId:a},...r&&{pendingMergeToken:r},...i&&{sdkConfig:i}}})};e.h.isResolved&&(p(e.h.getConfig()),s.resolve()),o&&(d(await o),p(e.h.getConfig()),s.resolve());async function m(){let e=t.customizations?.css;e&&n.sendLifecycle({clientLifecycle:`modal-css`,data:{cssLink:e}})}async function h(){let e=t.customizations?.i18n;e&&n.sendLifecycle({clientLifecycle:`modal-i18n`,data:{i18n:e}})}async function g(){if(typeof window>`u`)return;let e=window.localStorage.getItem(r);e&&n.sendLifecycle({clientLifecycle:`restore-backup`,data:{backup:e}})}(await Promise.allSettled([m(),h(),g()])).some(e=>e.status===`rejected`)&&c?.track(`sdk_iframe_handshake_failed`,{reason:`asset_push`})}function P(n){return(0,t.jsonDecode)(e.p(n))}const F={eur:`fr-FR`,usd:`en-US`,gbp:`en-GB`};function I(e){return e&&e in F?e:`eur`}function L(e){return e?F[e]??F.eur:F.eur}function R(e,t){let n=L(t),r=I(t);return e.toLocaleString(n,{style:`currency`,currency:r,minimumFractionDigits:0,maximumFractionDigits:2})}function z(e){return e?`${e}Amount`:`eurAmount`}async function B({config:e}){let t=V(e),n=await v({config:t});if(!n){console.error(`Failed to create iframe`);return}let r=j({config:t,iframe:n});if(await r.waitForSetup,!await r.waitForConnection){console.error(`Failed to connect to client`);return}return r}function V(e){let t=I(e.metadata?.currency);return{...e,metadata:{...e.metadata,currency:t}}}function H({perCall:e,defaults:t,productUtmContent:n}){if(e===null)return;let r=e!==void 0,i=t!==void 0&&Object.keys(t).length>0;if(!r&&!i&&!(n!==void 0&&n!==``))return;let a={...t,...e??{}},o=n??e?.utmContent;return o!==void 0&&o!==``?a.utmContent=o:delete a.utmContent,a}Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return f}});
|
|
2
|
+
//# sourceMappingURL=src-CCJgTN1H.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-CCJgTN1H.cjs","names":["getClientId","getBackendUrl","Deferred","sdkConfigStore","Deferred","FrakRpcError","RpcErrorCodes","OpenPanel","getClientId","base64urlDecode"],"sources":["../src/constants.ts","../src/clients/ssoUrlListener.ts","../src/utils/browser/deepLinkWithFallback.ts","../src/utils/browser/inAppBrowser.ts","../src/utils/iframe/iframeHelper.ts","../src/clients/transports/iframeLifecycleManager.ts","../src/clients/createIFrameFrakClient.ts","../src/utils/compression/decompress.ts","../src/constants/locales.ts","../src/utils/format/getSupportedCurrency.ts","../src/utils/format/getSupportedLocale.ts","../src/utils/format/formatAmount.ts","../src/utils/format/getCurrencyAmountKey.ts","../src/clients/setupClient.ts","../src/context/mergeAttribution.ts"],"sourcesContent":["/**\n * The backup key for client side backup if needed\n */\nexport const BACKUP_KEY = \"nexus-wallet-backup\";\n\n/**\n * Deep link scheme for Frak Wallet mobile app.\n *\n * Replaced at build time via tsdown/Vite `define`. Defaults to the prod scheme;\n * in-monorepo dev builds (listener at wallet-dev.frak.id) override this with\n * `frakwallet-dev://` so deep links open the dev wallet variant (id.frak.wallet.dev).\n * External integrators consuming the published NPM/CDN bundle always see the prod scheme.\n */\nexport const DEEP_LINK_SCHEME: string =\n process.env.DEEP_LINK_SCHEME ?? \"frakwallet://\";\n","import type { RpcClient } from \"@frak-labs/frame-connector\";\nimport type { FrakLifecycleEvent } from \"../types\";\nimport type { IFrameRpcSchema } from \"../types/rpc\";\n\n/**\n * Listen for SSO redirect with compressed data in URL\n * Forwards compressed data to iframe via lifecycle event\n * Cleans URL immediately after detection\n *\n * Performance: One-shot URL check, no polling, no re-renders\n *\n * @param rpcClient - RPC client instance to send lifecycle events\n * @param waitForConnection - Promise that resolves when iframe is connected\n */\nexport function setupSsoUrlListener(\n rpcClient: RpcClient<IFrameRpcSchema, FrakLifecycleEvent>,\n waitForConnection: Promise<boolean>\n): void {\n if (typeof window === \"undefined\") {\n return;\n }\n\n // One-shot URL check - no need for MutationObserver or polling\n const url = new URL(window.location.href);\n const compressedSso = url.searchParams.get(\"sso\");\n\n // Early return if no SSO parameter\n if (!compressedSso) {\n return;\n }\n\n // Forward compressed data directly to iframe (no decompression on SDK side)\n // Iframe will decompress and process\n waitForConnection\n .then(() => {\n // Send lifecycle event with compressed string\n // This is a one-way notification, no response expected\n rpcClient.sendLifecycle({\n clientLifecycle: \"sso-redirect-complete\",\n data: { compressed: compressedSso },\n });\n\n console.log(\n \"[SSO URL Listener] Forwarded compressed SSO data to iframe\"\n );\n })\n .catch((error) => {\n console.error(\n \"[SSO URL Listener] Failed to forward SSO data:\",\n error\n );\n });\n\n // Clean URL immediately to prevent exposure in browser history\n // Use replaceState to avoid navigation/re-render\n url.searchParams.delete(\"sso\");\n window.history.replaceState({}, \"\", url.toString());\n\n console.log(\"[SSO URL Listener] SSO parameter detected and URL cleaned\");\n}\n","import { DEEP_LINK_SCHEME } from \"../../constants\";\n\n/**\n * Options for deep link with fallback\n */\nexport type DeepLinkFallbackOptions = {\n /** Timeout in ms before triggering fallback (default: 2500ms) */\n timeout?: number;\n /** Callback invoked when fallback is triggered (app not installed) */\n onFallback?: () => void;\n};\n\n/**\n * Check if running on a Chromium-based Android browser.\n *\n * On Chrome Android, custom scheme deep links (e.g. frakwallet://) trigger\n * a confirmation bar (\"Continue to Frak Wallet?\"). Using intent:// URLs\n * instead bypasses this for Chromium browsers while keeping custom scheme\n * fallback for non-Chromium browsers (e.g. Firefox) where it works fine.\n */\nexport function isChromiumAndroid(): boolean {\n const ua = navigator.userAgent;\n return /Android/i.test(ua) && /Chrome\\/\\d+/i.test(ua);\n}\n\n/**\n * Convert a Frak deep link to an Android intent:// URL.\n *\n * Intent URLs let Chromium browsers open the app directly without\n * showing the \"Continue to app?\" confirmation bar.\n *\n * Note: We intentionally omit the `package` parameter. Including it\n * causes Chrome to redirect to the Play Store when the app is not\n * installed, which breaks the visibility-based fallback detection.\n * Without `package`, Chrome simply does nothing when the app is\n * missing, allowing the fallback mechanism to fire correctly.\n *\n * The scheme is derived from `DEEP_LINK_SCHEME` so the dev variant\n * (`frakwallet-dev://`) routes to the dev app shell, not prod.\n *\n * Format: intent://path#Intent;scheme=<scheme>;end\n */\nconst DEEP_LINK_SCHEME_NAME = /* @__PURE__ */ DEEP_LINK_SCHEME.replace(\n \"://\",\n \"\"\n);\n\nexport function toAndroidIntentUrl(deepLink: string): string {\n // Extract everything after the scheme (e.g. \"frakwallet://\" or \"frakwallet-dev://\")\n const path = deepLink.slice(DEEP_LINK_SCHEME.length);\n return `intent://${path}#Intent;scheme=${DEEP_LINK_SCHEME_NAME};end`;\n}\n\n/**\n * Trigger a deep link with visibility-based fallback detection.\n *\n * Uses the Page Visibility API to detect if the app opened (page goes hidden).\n * If the page remains visible after the timeout, assumes app is not installed\n * and invokes the onFallback callback.\n *\n * On Chromium Android, converts custom scheme to intent:// URL to avoid\n * the \"Continue to app?\" confirmation bar.\n *\n * @param deepLink - The deep link URL to trigger (e.g., \"frakwallet://wallet\")\n * @param options - Optional configuration (timeout, onFallback callback)\n */\nexport function triggerDeepLinkWithFallback(\n deepLink: string,\n options?: DeepLinkFallbackOptions\n): void {\n const timeout = options?.timeout ?? 2500;\n\n // Track if the app opened (page went to background)\n let appOpened = false;\n\n const onVisibilityChange = () => {\n if (document.hidden) {\n appOpened = true;\n }\n };\n\n // Start listening for visibility changes\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n\n // On Chromium Android, use intent:// to avoid confirmation bar\n const url =\n isChromiumAndroid() && isFrakDeepLink(deepLink)\n ? toAndroidIntentUrl(deepLink)\n : deepLink;\n\n // Trigger the deep link\n window.location.href = url;\n\n // Check after timeout if app opened\n setTimeout(() => {\n // Clean up listener\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n\n if (!appOpened) {\n // App didn't open - trigger fallback callback\n options?.onFallback?.();\n }\n }, timeout);\n}\n\n/**\n * Check if a URL is a Frak deep link\n */\nexport function isFrakDeepLink(url: string): boolean {\n return url.startsWith(DEEP_LINK_SCHEME);\n}\n","/**\n * Check if the current device runs iOS (including iPadOS 13+).\n */\nfunction checkIsIOS(): boolean {\n if (typeof navigator === \"undefined\") return false;\n const ua = navigator.userAgent;\n // Standard iOS devices\n if (/iPhone|iPad|iPod/i.test(ua)) return true;\n // iPadOS 13+ reports as Macintosh — detect via touch support\n if (/Macintosh/i.test(ua) && navigator.maxTouchPoints > 1) return true;\n return false;\n}\n\n/**\n * Whether the current device runs iOS (including iPadOS 13+).\n */\nexport const isIOS: boolean = /* @__PURE__ */ checkIsIOS();\n\n/**\n * Check if the current device is a mobile device (iOS, iPadOS, Android,\n * webOS, BlackBerry, IEMobile, Opera Mini). Reuses {@link isIOS} so the\n * iPadOS-13+ Macintosh heuristic stays in one place.\n */\nexport function isMobile(): boolean {\n if (typeof navigator === \"undefined\") return false;\n if (isIOS) return true;\n return /Android|webOS|BlackBerry|IEMobile|Opera Mini/i.test(\n navigator.userAgent\n );\n}\n\n/**\n * Check if the current browser is a social media in-app browser\n * (Instagram, Facebook WebView).\n */\nfunction checkInAppBrowser(): boolean {\n if (typeof navigator === \"undefined\") return false;\n const ua = navigator.userAgent.toLowerCase();\n return (\n ua.includes(\"instagram\") ||\n ua.includes(\"fban\") ||\n ua.includes(\"fbav\") ||\n ua.includes(\"facebook\")\n );\n}\n\n/**\n * Whether the current browser is a social media in-app browser\n * (Instagram, Facebook).\n */\nexport const isInAppBrowser: boolean = /* @__PURE__ */ checkInAppBrowser();\n\n/**\n * Redirect to external browser from in-app WebView.\n *\n * - **iOS**: Uses `x-safari-https://` scheme — server-side 302 redirects\n * to custom URL schemes are silently swallowed by WKWebView.\n * Direct `window.location.href` assignment works (confirmed iOS 17+).\n *\n * - **Android**: Uses backend `/common/social` endpoint which returns a PDF\n * Content-Type response, forcing the WebView to hand off to the default browser.\n *\n * @param targetUrl - The URL to open in the external browser\n */\nexport function redirectToExternalBrowser(targetUrl: string): void {\n if (isIOS && targetUrl.startsWith(\"https://\")) {\n window.location.href = `x-safari-https://${targetUrl.slice(8)}`;\n } else if (isIOS && targetUrl.startsWith(\"http://\")) {\n window.location.href = `x-safari-http://${targetUrl.slice(7)}`;\n } else {\n window.location.href = `${process.env.BACKEND_URL}/common/social?u=${encodeURIComponent(targetUrl)}`;\n }\n}\n","import { getBackendUrl } from \"../../config/backendUrl\";\nimport { getClientId } from \"../../config/clientId\";\nimport type { FrakWalletSdkConfig, ListenerPreloadOption } from \"../../types\";\n\n/**\n * Base props for the iframe\n * @ignore\n */\nexport const baseIframeProps = {\n id: \"frak-wallet\",\n name: \"frak-wallet\",\n title: \"Frak Wallet\",\n allow: \"publickey-credentials-get *; clipboard-write; web-share *\",\n style: {\n width: \"0\",\n height: \"0\",\n border: \"0\",\n position: \"absolute\",\n zIndex: 2000001,\n top: \"-1000px\",\n left: \"-1000px\",\n colorScheme: \"auto\",\n },\n};\n\n/**\n * Create the Frak iframe\n * @param args\n * @param args.walletBaseUrl - Use `config.walletUrl` instead. Will be removed in future versions.\n * @param args.config - The configuration object containing iframe options, including the replacement for `walletBaseUrl`.\n */\nexport function createIframe({\n walletBaseUrl,\n config,\n}: {\n walletBaseUrl?: string;\n config?: FrakWalletSdkConfig;\n}): Promise<HTMLIFrameElement | undefined> {\n // Check if the iframe is already created\n const alreadyCreatedIFrame = document.querySelector(\"#frak-wallet\");\n\n // If the iframe is already created, remove it\n if (alreadyCreatedIFrame) {\n alreadyCreatedIFrame.remove();\n }\n\n const iframe = document.createElement(\"iframe\");\n\n // Set the base iframe props\n iframe.id = baseIframeProps.id;\n iframe.name = baseIframeProps.name;\n iframe.allow = baseIframeProps.allow;\n iframe.style.zIndex = baseIframeProps.style.zIndex.toString();\n\n changeIframeVisibility({ iframe, isVisible: false });\n\n // Set src BEFORE appending to DOM to avoid about:blank load event\n const walletUrl =\n config?.walletUrl ?? walletBaseUrl ?? \"https://wallet.frak.id\";\n const clientId = getClientId();\n\n // Preconnect to the wallet + backend origins so the handshake doesn't pay\n // for a cold DNS/TLS round-trip on partner sites that didn't warm them.\n preconnect(walletUrl);\n preconnect(getBackendUrl(walletUrl));\n\n iframe.src = buildListenerUrl({\n walletUrl,\n clientId,\n preload: config?.preload,\n });\n\n return new Promise((resolve) => {\n iframe.addEventListener(\"load\", () => resolve(iframe));\n document.body.appendChild(iframe);\n });\n}\n\n/**\n * Build the listener iframe URL.\n *\n * Query params:\n * - `clientId` — anonymous SDK client identifier used for funnel joining.\n *\n * Hash params (consumed by `apps/listener/app/bootstrap.ts#setupPreloadHints`):\n * - `preload=modal,sharing` — idle-warms the matching Ring 1 + Ring 2 chunks.\n * Skipped entirely when no preload hints are provided so the listener\n * doesn't pay for warm-ups that nobody asked for.\n */\nfunction buildListenerUrl({\n walletUrl,\n clientId,\n preload,\n}: {\n walletUrl: string;\n clientId: string;\n preload?: ListenerPreloadOption[];\n}): string {\n const base = `${walletUrl}/listener?clientId=${encodeURIComponent(clientId)}`;\n if (!preload || preload.length === 0) return base;\n return `${base}#preload=${preload.join(\",\")}`;\n}\n\n/**\n * Change the visibility of the given iframe\n * @ignore\n */\nexport function changeIframeVisibility({\n iframe,\n isVisible,\n}: {\n iframe: HTMLIFrameElement;\n isVisible: boolean;\n}) {\n if (!isVisible) {\n iframe.style.width = \"0\";\n iframe.style.height = \"0\";\n iframe.style.border = \"0\";\n iframe.style.position = \"fixed\";\n iframe.style.top = \"-1000px\";\n iframe.style.left = \"-1000px\";\n return;\n }\n\n iframe.style.position = \"fixed\";\n iframe.style.top = \"0\";\n iframe.style.left = \"0\";\n iframe.style.width = \"100%\";\n iframe.style.height = \"100%\";\n iframe.style.pointerEvents = \"auto\";\n}\n\n/**\n * Find an iframe within window.opener by pathname\n *\n * When a popup is opened via window.open from an iframe, window.opener points to\n * the parent window, not the iframe itself. This utility searches through all frames\n * in window.opener to find an iframe matching the specified pathname.\n *\n * @param pathname - The pathname to search for (default: \"/listener\")\n * @returns The matching iframe window, or null if not found\n *\n * @example\n * ```typescript\n * // Find the default /listener iframe\n * const listenerIframe = findIframeInOpener();\n *\n * // Find a custom iframe\n * const customIframe = findIframeInOpener(\"/my-custom-iframe\");\n * ```\n */\nexport function findIframeInOpener(pathname = \"/listener\"): Window | null {\n if (!window.opener) return null;\n\n const frameCheck = (frame: Window) => {\n try {\n return (\n frame.location.origin === window.location.origin &&\n frame.location.pathname === pathname\n );\n } catch {\n // Cross-origin frame, skip\n return false;\n }\n };\n\n // Check if the openner window is the right one\n if (frameCheck(window.opener)) return window.opener;\n\n // Search through frames in window.opener\n try {\n const frames = window.opener.frames;\n for (let i = 0; i < frames.length; i++) {\n if (frameCheck(frames[i])) {\n return frames[i];\n }\n }\n return null;\n } catch (error) {\n console.error(\n `[findIframeInOpener] Error finding iframe with pathname ${pathname}:`,\n error\n );\n return null;\n }\n}\n\n/**\n * Inject a `<link rel=\"preconnect\">` for the given origin. Idempotent — browsers\n * de-duplicate preconnects per origin automatically, but we also guard on a data\n * attribute to avoid spamming the <head> in SPA re-inits.\n */\nfunction preconnect(url: string): void {\n if (typeof document === \"undefined\") return;\n try {\n const origin = new URL(url).origin;\n const selector = `link[rel=\"preconnect\"][data-frak-preconnect=\"${origin}\"]`;\n if (document.head.querySelector(selector)) return;\n const link = document.createElement(\"link\");\n link.rel = \"preconnect\";\n link.href = origin;\n link.crossOrigin = \"\";\n link.dataset.frakPreconnect = origin;\n document.head.appendChild(link);\n } catch {\n // Invalid URL — nothing to preconnect.\n }\n}\n","import { Deferred } from \"@frak-labs/frame-connector\";\nimport { BACKUP_KEY } from \"../../constants\";\nimport type { FrakLifecycleEvent } from \"../../types\";\nimport {\n isFrakDeepLink,\n triggerDeepLinkWithFallback,\n} from \"../../utils/browser/deepLinkWithFallback\";\nimport { isInAppBrowser, isIOS } from \"../../utils/browser/inAppBrowser\";\nimport { changeIframeVisibility } from \"../../utils/iframe/iframeHelper\";\n\n// iOS in-app browsers (Instagram, Facebook) silently swallow server-side 302\n// redirects to custom URL schemes (x-safari-https://) in WKWebView; direct\n// window.location.href assignment works.\nconst isIOSInAppBrowser = isIOS && isInAppBrowser;\n\n/** @ignore */\nexport type IframeLifecycleManager = {\n isConnected: Promise<boolean>;\n handleEvent: (messageEvent: FrakLifecycleEvent) => void;\n};\n\n/**\n * Handle backup storage\n */\nfunction handleBackup(backup: string | undefined): void {\n if (backup) {\n localStorage.setItem(BACKUP_KEY, backup);\n } else {\n localStorage.removeItem(BACKUP_KEY);\n }\n}\n\n/**\n * Compute final redirect URL with parameter substitution\n */\nfunction computeRedirectUrl(\n baseRedirectUrl: string,\n mergeToken?: string\n): string {\n try {\n const redirectUrl = new URL(baseRedirectUrl);\n if (!redirectUrl.searchParams.has(\"u\")) {\n return baseRedirectUrl;\n }\n\n // Append merge token to the page URL so it survives\n // the backend /common/social redirect chain\n const finalPageUrl = appendMergeToken(window.location.href, mergeToken);\n\n redirectUrl.searchParams.delete(\"u\");\n redirectUrl.searchParams.append(\"u\", finalPageUrl);\n\n return redirectUrl.toString();\n } catch {\n return baseRedirectUrl;\n }\n}\n\n/**\n * Redirect current page to Safari via x-safari-https:// scheme.\n * Used on iOS in-app browsers where backend 302 → custom scheme fails.\n */\nfunction redirectToSafari(mergeToken?: string) {\n const url = new URL(window.location.href);\n if (mergeToken) {\n url.searchParams.set(\"fmt\", mergeToken);\n }\n const scheme =\n url.protocol === \"http:\" ? \"x-safari-http\" : \"x-safari-https\";\n window.location.href = `${scheme}://${url.host}${url.pathname}${url.search}${url.hash}`;\n}\n\n/**\n * Check if this is a social/in-app-browser escape redirect (contains /common/social)\n */\nfunction isSocialRedirect(url: string): boolean {\n return url.includes(\"/common/social\");\n}\n\n/**\n * Append merge token to a URL as the `fmt` query parameter.\n */\nfunction appendMergeToken(urlString: string, mergeToken?: string): string {\n if (!mergeToken) return urlString;\n try {\n const url = new URL(urlString);\n url.searchParams.set(\"fmt\", mergeToken);\n return url.toString();\n } catch {\n const sep = urlString.includes(\"?\") ? \"&\" : \"?\";\n return `${urlString}${sep}fmt=${encodeURIComponent(mergeToken)}`;\n }\n}\n\n/**\n * Handle redirect with deep link fallback\n */\nfunction handleRedirect(\n iframe: HTMLIFrameElement,\n baseRedirectUrl: string,\n targetOrigin: string,\n mergeToken?: string,\n openInNewTab?: boolean\n): void {\n // If requested, open in a new tab instead of navigating the current page.\n // This preserves the merchant page while triggering universal links.\n // Requires the iframe postMessage to include user activation delegation.\n if (openInNewTab) {\n const finalUrl = computeRedirectUrl(baseRedirectUrl, mergeToken);\n window.open(finalUrl, \"_blank\");\n return;\n }\n\n if (isFrakDeepLink(baseRedirectUrl)) {\n const finalUrl = computeRedirectUrl(baseRedirectUrl, mergeToken);\n triggerDeepLinkWithFallback(finalUrl, {\n onFallback: () => {\n iframe.contentWindow?.postMessage(\n {\n clientLifecycle: \"deep-link-failed\",\n data: { originalUrl: finalUrl },\n },\n targetOrigin\n );\n },\n });\n } else if (isIOSInAppBrowser && isSocialRedirect(baseRedirectUrl)) {\n // iOS WKWebView silently swallows 302 redirects to custom URL\n // schemes — bypass the server redirect entirely\n redirectToSafari(mergeToken);\n } else {\n const finalUrl = computeRedirectUrl(baseRedirectUrl, mergeToken);\n window.location.href = finalUrl;\n }\n}\n\n/**\n * Create a new iframe lifecycle handler\n * @param args\n * @param args.iframe - The iframe element used for wallet communication\n * @param args.targetOrigin - The wallet URL origin for postMessage security\n * @ignore\n */\nexport function createIFrameLifecycleManager({\n iframe,\n targetOrigin,\n}: {\n iframe: HTMLIFrameElement;\n targetOrigin: string;\n}): IframeLifecycleManager {\n // Create the isConnected listener\n const isConnectedDeferred = new Deferred<boolean>();\n\n // Build the handler itself\n const handler = (messageEvent: FrakLifecycleEvent) => {\n if (!(\"iframeLifecycle\" in messageEvent)) return;\n\n const { iframeLifecycle: event, data } = messageEvent;\n\n switch (event) {\n // Resolve the isConnected promise\n case \"connected\":\n isConnectedDeferred.resolve(true);\n break;\n // Perform a frak backup\n case \"do-backup\":\n handleBackup(data.backup);\n break;\n // Remove frak backup\n case \"remove-backup\":\n localStorage.removeItem(BACKUP_KEY);\n break;\n // Change iframe visibility\n case \"show\":\n case \"hide\":\n changeIframeVisibility({ iframe, isVisible: event === \"show\" });\n break;\n // Redirect handling\n case \"redirect\":\n handleRedirect(\n iframe,\n data.baseRedirectUrl,\n targetOrigin,\n data.mergeToken,\n data.openInNewTab\n );\n break;\n }\n };\n\n return {\n handleEvent: handler,\n isConnected: isConnectedDeferred.promise,\n };\n}\n","import {\n createRpcClient,\n Deferred,\n FrakRpcError,\n type RpcClient,\n RpcErrorCodes,\n} from \"@frak-labs/frame-connector\";\nimport { OpenPanel } from \"@openpanel/web\";\nimport { getClientId } from \"../config/clientId\";\nimport { sdkConfigStore } from \"../config/sdkConfigStore\";\nimport { BACKUP_KEY } from \"../constants\";\nimport type { FrakLifecycleEvent } from \"../types\";\nimport type { FrakClient } from \"../types/client\";\nimport type { FrakWalletSdkConfig } from \"../types/config\";\nimport type { SdkResolvedConfig } from \"../types/resolvedConfig\";\nimport type { IFrameRpcSchema } from \"../types/rpc\";\nimport { clearAllCache } from \"../utils/cache\";\nimport { setupSsoUrlListener } from \"./ssoUrlListener\";\nimport {\n createIFrameLifecycleManager,\n type IframeLifecycleManager,\n} from \"./transports/iframeLifecycleManager\";\n\ntype SdkRpcClient = RpcClient<IFrameRpcSchema, FrakLifecycleEvent>;\ntype MerchantConfigResult = Awaited<ReturnType<typeof sdkConfigStore.resolve>>;\n\n/**\n * Create a new iframe Frak client\n * @param args\n * @param args.config - The configuration to use for the Frak Wallet SDK.\n * When `config.domain` is set, it is used to resolve the correct merchant config in tunneled/proxied environments (e.g. Shopify dev with Cloudflare tunnel).\n * @param args.iframe - The iframe to use for the communication\n * @returns The created Frak Client\n *\n * @example\n * const frakConfig: FrakWalletSdkConfig = {\n * metadata: {\n * name: \"My app title\",\n * },\n * }\n * const iframe = await createIframe({ config: frakConfig });\n * const client = createIFrameFrakClient({ config: frakConfig, iframe });\n */\nexport function createIFrameFrakClient({\n config,\n iframe,\n}: {\n config: FrakWalletSdkConfig;\n iframe: HTMLIFrameElement;\n}): FrakClient {\n const frakWalletUrl = config?.walletUrl ?? \"https://wallet.frak.id\";\n\n const browserLang =\n typeof navigator !== \"undefined\"\n ? navigator.language?.split(\"-\")[0]\n : undefined;\n const detectedLang =\n config.metadata.lang ??\n (browserLang === \"en\" || browserLang === \"fr\"\n ? browserLang\n : undefined);\n const targetDomain =\n config.domain ??\n (typeof window !== \"undefined\" ? window.location.hostname : \"\");\n sdkConfigStore.setCacheScope(targetDomain, detectedLang);\n sdkConfigStore.reset();\n\n // Skip fetch entirely if cache is fresh, otherwise fetch (SWR)\n const configPromise = sdkConfigStore.isCacheFresh\n ? undefined\n : sdkConfigStore.resolve(config.domain, config.walletUrl, detectedLang);\n\n // Create lifecycle manager\n const lifecycleManager = createIFrameLifecycleManager({\n iframe,\n targetOrigin: frakWalletUrl,\n });\n\n // Resolved after first resolved-config is sent to iframe (prevents RPC before context exists)\n const contextSent = new Deferred<void>();\n\n // Handshake timing: measured from client creation until the iframe\n // lifecycle manager resolves the `isConnected` promise.\n const handshakeStartedAt = Date.now();\n\n // Validate iframe\n if (!iframe.contentWindow) {\n throw new FrakRpcError(\n RpcErrorCodes.configError,\n \"The iframe does not have a content window\"\n );\n }\n\n // Create RPC client with middleware and lifecycle handlers\n const rpcClient = createRpcClient<IFrameRpcSchema, FrakLifecycleEvent>({\n emittingTransport: iframe.contentWindow,\n listeningTransport: window,\n targetOrigin: frakWalletUrl,\n middleware: [\n // Ensure we are connected and context is sent before sending request\n {\n async onRequest(_message, ctx) {\n const isConnected = await lifecycleManager.isConnected;\n if (!isConnected) {\n throw new FrakRpcError(\n RpcErrorCodes.clientNotConnected,\n \"The iframe provider isn't connected yet\"\n );\n }\n await contextSent.promise;\n return ctx;\n },\n },\n ],\n // Add lifecycle handlers to process iframe lifecycle events\n lifecycleHandlers: {\n iframeLifecycle: (event, _context) => {\n // Delegate to lifecycle manager (cast for type compatibility)\n lifecycleManager.handleEvent(event);\n },\n },\n });\n\n // Setup heartbeat\n const stopHeartbeat = setupHeartbeat(rpcClient, lifecycleManager);\n\n const destroy = async () => {\n stopHeartbeat();\n rpcClient.cleanup();\n iframe.remove();\n clearAllCache();\n sdkConfigStore.clearCache();\n sdkConfigStore.reset();\n };\n\n // Init open panel\n let openPanel: OpenPanel | undefined;\n if (\n process.env.OPEN_PANEL_API_URL &&\n process.env.OPEN_PANEL_SDK_CLIENT_ID\n ) {\n console.log(\"[Frak SDK] Initializing OpenPanel\");\n openPanel = new OpenPanel({\n apiUrl: process.env.OPEN_PANEL_API_URL,\n clientId: process.env.OPEN_PANEL_SDK_CLIENT_ID,\n trackScreenViews: true,\n trackOutgoingLinks: true,\n trackAttributes: false,\n // We use a filter to ensure we got the open panel instance initialized\n // A bit hacky, but this way we are sure that we got everything needed for the first event ever sent\n filter: ({ type, payload }) => {\n if (type !== \"track\") return true;\n if (!payload?.properties) return true;\n\n // Check if we we got the properties once initialized\n if (!(\"sdk_version\" in payload.properties)) {\n payload.properties = {\n ...payload.properties,\n sdk_version: process.env.SDK_VERSION,\n user_anonymous_client_id: getClientId(),\n };\n }\n\n return true;\n },\n });\n openPanel.setGlobalProperties({\n sdk_version: process.env.SDK_VERSION,\n user_anonymous_client_id: getClientId(),\n });\n openPanel.init();\n openPanel.track(\"sdk_initialized\", {\n sdk_version: process.env.SDK_VERSION,\n });\n\n // Race the connection against the heartbeat timeout so we can\n // distinguish \"connected\" from \"timeout\" cleanly without touching\n // the heartbeat plumbing. 30s matches `HEARTBEAT_TIMEOUT`.\n let settled = false;\n const timeoutHandle = setTimeout(() => {\n if (settled) return;\n settled = true;\n openPanel?.track(\"sdk_iframe_handshake_failed\", {\n reason: \"timeout\",\n });\n }, 30_000);\n lifecycleManager.isConnected\n .then(() => {\n if (settled) return;\n settled = true;\n clearTimeout(timeoutHandle);\n openPanel?.track(\"sdk_iframe_connected\", {\n handshake_duration_ms: Date.now() - handshakeStartedAt,\n });\n })\n .catch(() => {\n if (settled) return;\n settled = true;\n clearTimeout(timeoutHandle);\n openPanel?.track(\"sdk_iframe_handshake_failed\", {\n reason: \"unknown\",\n });\n });\n }\n\n // Perform the post connection setup\n const waitForSetup = postConnectionSetup({\n config,\n rpcClient,\n lifecycleManager,\n configPromise,\n contextSent,\n openPanel,\n })\n .then(() => {})\n .catch((err) => {\n contextSent.reject(err);\n throw err;\n });\n\n return {\n config,\n waitForConnection: lifecycleManager.isConnected,\n waitForSetup,\n request: rpcClient.request,\n listenerRequest: rpcClient.listen,\n destroy,\n openPanel,\n };\n}\n\n/**\n * Setup the heartbeat\n * @param rpcClient - RPC client to send lifecycle events\n * @param lifecycleManager - Lifecycle manager to track connection\n */\nfunction setupHeartbeat(\n rpcClient: SdkRpcClient,\n lifecycleManager: IframeLifecycleManager\n) {\n const HEARTBEAT_INTERVAL = 250; // Fallback discovery ping until we are connected\n const HEARTBEAT_TIMEOUT = 30_000; // 30 seconds timeout\n let heartbeatInterval: NodeJS.Timeout;\n let timeoutId: NodeJS.Timeout;\n\n const sendHeartbeat = () =>\n rpcClient.sendLifecycle({\n clientLifecycle: \"heartbeat\",\n });\n\n // Start sending heartbeats\n async function startHeartbeat() {\n sendHeartbeat(); // Send initial heartbeat\n heartbeatInterval = setInterval(sendHeartbeat, HEARTBEAT_INTERVAL);\n\n // Set up timeout\n timeoutId = setTimeout(() => {\n stopHeartbeat();\n console.log(\"Heartbeat timeout: connection failed\");\n }, HEARTBEAT_TIMEOUT);\n\n // Once connected, stop it\n await lifecycleManager.isConnected;\n\n // We are now connected, stop the heartbeat\n stopHeartbeat();\n }\n\n // Stop sending heartbeats\n function stopHeartbeat() {\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n }\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n\n startHeartbeat();\n\n // Return cleanup function\n return stopHeartbeat;\n}\n\n/**\n * Perform the post connection setup\n * @param config - SDK configuration\n * @param rpcClient - RPC client to send lifecycle events\n * @param lifecycleManager - Lifecycle manager to track connection\n */\nasync function postConnectionSetup({\n config,\n rpcClient,\n lifecycleManager,\n configPromise,\n contextSent,\n openPanel,\n}: {\n config: FrakWalletSdkConfig;\n rpcClient: SdkRpcClient;\n lifecycleManager: IframeLifecycleManager;\n configPromise: Promise<MerchantConfigResult> | undefined;\n contextSent: Deferred<void>;\n openPanel: OpenPanel | undefined;\n}): Promise<void> {\n await lifecycleManager.isConnected;\n\n setupSsoUrlListener(rpcClient, lifecycleManager.isConnected);\n\n // Read and consume the pending merge token from URL (SSO identity merge)\n const url = new URL(window.location.href);\n const pendingMergeToken = url.searchParams.get(\"fmt\") ?? undefined;\n if (pendingMergeToken) {\n url.searchParams.delete(\"fmt\");\n window.history.replaceState({}, \"\", url.toString());\n }\n\n // Merge a raw backend response with SDK metadata and persist to store\n const mergeAndSetConfig = (merchantConfig: MerchantConfigResult) => {\n const merchantId =\n merchantConfig?.merchantId ?? config.metadata.merchantId ?? \"\";\n const domain = merchantConfig?.domain ?? \"\";\n const allowedDomains = merchantConfig?.allowedDomains ?? [];\n const raw = merchantConfig?.sdkConfig;\n\n // Per-field merge: backend wins over SDK static config.\n const mergedAttribution =\n raw?.attribution || config.attribution\n ? { ...config.attribution, ...raw?.attribution }\n : undefined;\n\n sdkConfigStore.setConfig(\n raw\n ? {\n isResolved: true,\n merchantId,\n domain,\n allowedDomains,\n hasRawSdkConfig: true,\n name: raw.name ?? config.metadata.name,\n logoUrl: raw.logoUrl ?? config.metadata.logoUrl,\n homepageLink:\n raw.homepageLink ?? config.metadata.homepageLink,\n lang: raw.lang ?? config.metadata.lang,\n currency: raw.currency ?? config.metadata.currency,\n hidden: raw.hidden,\n css: raw.css,\n translations: raw.translations,\n placements: raw.placements,\n components: raw.components,\n attribution: mergedAttribution,\n }\n : {\n isResolved: true,\n merchantId,\n domain,\n allowedDomains,\n name: config.metadata.name,\n logoUrl: config.metadata.logoUrl,\n homepageLink: config.metadata.homepageLink,\n lang: config.metadata.lang,\n currency: config.metadata.currency,\n attribution: mergedAttribution,\n }\n );\n };\n\n // Send the resolved-config lifecycle event to the iframe.\n // This is where we also update SDK-side OpenPanel global props with\n // `merchantId` + `domain` (first time they are known) so every\n // subsequent SDK event is merchant-attributed. We pass\n // `sdkAnonymousId` through so the listener can join SDK funnels.\n let mergeTokenConsumed = false;\n const sendLifecycleConfig = (resolved: SdkResolvedConfig) => {\n const token = mergeTokenConsumed ? undefined : pendingMergeToken;\n mergeTokenConsumed = true;\n\n const sdkConfig = resolved.hasRawSdkConfig\n ? {\n name: resolved.name,\n logoUrl: resolved.logoUrl,\n homepageLink: resolved.homepageLink,\n lang: resolved.lang,\n currency: resolved.currency,\n hidden: resolved.hidden,\n css: resolved.css,\n translations: resolved.translations,\n placements: resolved.placements,\n attribution: resolved.attribution,\n }\n : resolved.attribution\n ? { attribution: resolved.attribution }\n : undefined;\n\n const sdkAnonymousId = getClientId();\n\n if (openPanel) {\n const current = openPanel.global ?? {};\n openPanel.setGlobalProperties({\n ...current,\n merchant_id: resolved.merchantId,\n domain: resolved.domain ?? \"\",\n });\n }\n\n rpcClient.sendLifecycle({\n clientLifecycle: \"resolved-config\",\n data: {\n merchantId: resolved.merchantId,\n domain: resolved.domain ?? \"\",\n allowedDomains: resolved.allowedDomains ?? [],\n sourceUrl: window.location.href,\n ...(sdkAnonymousId && { sdkAnonymousId }),\n ...(token && { pendingMergeToken: token }),\n ...(sdkConfig && { sdkConfig }),\n },\n });\n };\n\n // SWR: if we have cached data, send it to the iframe immediately\n if (sdkConfigStore.isResolved) {\n sendLifecycleConfig(sdkConfigStore.getConfig());\n contextSent.resolve();\n }\n\n // If a fetch is running (stale/missing cache), wait for fresh data and update\n if (configPromise) {\n const merchantConfig = await configPromise;\n mergeAndSetConfig(merchantConfig);\n sendLifecycleConfig(sdkConfigStore.getConfig());\n contextSent.resolve();\n }\n\n // Push raw CSS if needed\n async function pushCss() {\n const cssLink = config.customizations?.css;\n if (!cssLink) return;\n rpcClient.sendLifecycle({\n clientLifecycle: \"modal-css\" as const,\n data: { cssLink },\n });\n }\n\n // Push i18n if needed\n async function pushI18n() {\n const i18n = config.customizations?.i18n;\n if (!i18n) return;\n rpcClient.sendLifecycle({\n clientLifecycle: \"modal-i18n\" as const,\n data: { i18n },\n });\n }\n\n // Push local backup if needed\n async function pushBackup() {\n if (typeof window === \"undefined\") return;\n const backup = window.localStorage.getItem(BACKUP_KEY);\n if (!backup) return;\n rpcClient.sendLifecycle({\n clientLifecycle: \"restore-backup\" as const,\n data: { backup },\n });\n }\n\n // Inspect each setup result — a failed CSS/i18n/backup push leaves the\n // partner UI in a broken-but-connected state (iframe reports\n // `sdk_iframe_connected`, user sees no modal styles / wrong locale).\n // Surface it as a distinct handshake reason so dashboards can\n // distinguish timeout vs. asset-push failures.\n const results = await Promise.allSettled([\n pushCss(),\n pushI18n(),\n pushBackup(),\n ]);\n const hasFailedAssetPush = results.some((r) => r.status === \"rejected\");\n if (hasFailedAssetPush) {\n openPanel?.track(\"sdk_iframe_handshake_failed\", {\n reason: \"asset_push\",\n });\n }\n}\n","import { jsonDecode } from \"@frak-labs/frame-connector\";\nimport { base64urlDecode } from \"./b64\";\n\n/**\n * Decompress json data\n * @param data\n * @ignore\n */\nexport function decompressJsonFromB64<T>(data: string): T | null {\n return jsonDecode<T>(base64urlDecode(data));\n}\n","/**\n * The keys for each locales\n * @inline\n */\nexport type LocalesKey = keyof typeof locales;\n\n/**\n * Map the currency to the locale\n */\nexport const locales = {\n eur: \"fr-FR\",\n usd: \"en-US\",\n gbp: \"en-GB\",\n} as const;\n","import { locales } from \"../../constants/locales\";\nimport type { Currency } from \"../../types\";\n\n/**\n * Get the supported currency for a given currency\n * @param currency - The currency to use\n * @returns The supported currency\n */\nexport function getSupportedCurrency(currency?: Currency): Currency {\n if (!currency) {\n return \"eur\";\n }\n return currency in locales ? currency : \"eur\";\n}\n","import { type LocalesKey, locales } from \"../../constants/locales\";\nimport type { Currency } from \"../../types\";\n\n/**\n * Get the supported locale for a given currency\n * @param currency - The currency to use\n * @returns The supported locale\n */\nexport function getSupportedLocale(\n currency?: Currency\n): (typeof locales)[LocalesKey] {\n if (!currency) {\n return locales.eur;\n }\n return locales[currency] ?? locales.eur;\n}\n","import type { Currency } from \"../../types\";\nimport { getSupportedCurrency } from \"./getSupportedCurrency\";\nimport { getSupportedLocale } from \"./getSupportedLocale\";\n\n/**\n * Format a numeric amount as a localized currency string\n * @param amount - The raw numeric amount to format\n * @param currency - Optional currency config; defaults to EUR/fr-FR when omitted\n * @returns Localized currency string (e.g. \"1 500 €\", \"$1,500\")\n */\nexport function formatAmount(amount: number, currency?: Currency) {\n // Get the supported locale (e.g. \"fr-FR\")\n const supportedLocale = getSupportedLocale(currency);\n\n // Get the supported currency (e.g. \"eur\")\n const supportedCurrency = getSupportedCurrency(currency);\n\n return amount.toLocaleString(supportedLocale, {\n style: \"currency\",\n currency: supportedCurrency,\n minimumFractionDigits: 0,\n maximumFractionDigits: 2,\n });\n}\n","import type { Currency, TokenAmountType } from \"../../types\";\n\n/**\n * Get the currency amount key for a given currency\n * @param currency - The currency to use\n * @returns The currency amount key\n */\nexport function getCurrencyAmountKey(\n currency?: Currency\n): keyof TokenAmountType {\n if (!currency) {\n return \"eurAmount\";\n }\n return `${currency}Amount` as keyof TokenAmountType;\n}\n","import { createIFrameFrakClient } from \"../clients\";\nimport type { FrakClient, FrakWalletSdkConfig } from \"../types\";\nimport { createIframe, getSupportedCurrency } from \"../utils\";\n\n/**\n * Directly setup the Frak client with an iframe\n * Return when the FrakClient is ready (setup and communication estbalished with the wallet)\n *\n * @param config - The configuration to use for the Frak Wallet SDK\n * @returns a Promise with the Frak Client\n *\n * @example\n * const frakConfig: FrakWalletSdkConfig = {\n * metadata: {\n * name: \"My app title\",\n * },\n * }\n * const client = await setupClient({ config: frakConfig });\n */\nexport async function setupClient({\n config,\n}: {\n config: FrakWalletSdkConfig;\n}): Promise<FrakClient | undefined> {\n // Prepare the config\n const preparedConfig = prepareConfig(config);\n\n // Create our iframe\n const iframe = await createIframe({\n config: preparedConfig,\n });\n\n if (!iframe) {\n console.error(\"Failed to create iframe\");\n return;\n }\n\n // Create our client\n const client = createIFrameFrakClient({\n config: preparedConfig,\n iframe,\n });\n\n // Wait for the client to be all setup\n await client.waitForSetup;\n\n // Wait for the connection to be established\n const waitForConnection = await client.waitForConnection;\n if (!waitForConnection) {\n console.error(\"Failed to connect to client\");\n return;\n }\n\n return client;\n}\n\n/**\n * Prepare the config for the Frak Client\n * @param config - The configuration to use for the Frak Wallet SDK\n * @returns The prepared configuration with the supported currency\n */\nfunction prepareConfig(config: FrakWalletSdkConfig): FrakWalletSdkConfig {\n // Get the supported currency (e.g. \"eur\")\n const supportedCurrency = getSupportedCurrency(config.metadata?.currency);\n\n return {\n ...config,\n metadata: {\n ...config.metadata,\n currency: supportedCurrency,\n },\n };\n}\n","import type { AttributionDefaults, AttributionParams } from \"../types/tracking\";\n\n/**\n * Inputs for {@link mergeAttribution}.\n */\nexport type MergeAttributionInput = {\n /**\n * Per-call attribution override passed to actions like `displaySharingPage`.\n *\n * - `null` explicitly disables attribution (no UTM/ref/via params are added).\n * - `undefined` means \"no per-call override\" — defaults apply if present.\n * - An object (including `{}`) merges field-by-field with defaults.\n */\n perCall: AttributionParams | null | undefined;\n /**\n * Pre-merged merchant-level defaults (backend config > SDK static config).\n * `utm_content` is intentionally absent from this shape.\n */\n defaults?: AttributionDefaults;\n /**\n * Per-product `utm_content` override (from the currently selected\n * `SharingPageProduct`). Takes precedence over `perCall.utmContent`.\n */\n productUtmContent?: string;\n};\n\n/**\n * Merge the three attribution layers into a single {@link AttributionParams}\n * value suitable for `FrakContextManager.update`.\n *\n * Priority per field:\n * 1. `perCall` (wins)\n * 2. `defaults` (merchant-level, backend > SDK static, already pre-merged)\n * 3. Hardcoded fallbacks resolved later by `FrakContextManager`\n *\n * Special rules:\n * - `perCall === null` returns `undefined` (explicit disable: no UTM/ref/via).\n * - `perCall === undefined` (no opinion) yields at least `{}` so `FrakContextManager`\n * applies its hardcoded defaults (utm_source=frak, utm_medium=referral,\n * utm_campaign=<merchantId>, ref=<clientId>, via=frak).\n * - `utm_content` never comes from `defaults`; only `productUtmContent` or\n * `perCall.utmContent` can populate it.\n */\nexport function mergeAttribution({\n perCall,\n defaults,\n productUtmContent,\n}: MergeAttributionInput): AttributionParams | undefined {\n // Explicit disable\n if (perCall === null) return undefined;\n\n const hasPerCall = perCall !== undefined;\n const hasDefaults =\n defaults !== undefined && Object.keys(defaults).length > 0;\n const hasProductUtm =\n productUtmContent !== undefined && productUtmContent !== \"\";\n\n if (!hasPerCall && !hasDefaults && !hasProductUtm) return undefined;\n\n // Per-field merge: per-call wins over defaults.\n const merged: AttributionParams = {\n ...defaults,\n ...(perCall ?? {}),\n };\n\n // utm_content priority: productUtmContent > perCall.utmContent; never from defaults.\n const utmContent = productUtmContent ?? perCall?.utmContent;\n if (utmContent !== undefined && utmContent !== \"\") {\n merged.utmContent = utmContent;\n } else {\n delete merged.utmContent;\n }\n\n return merged;\n}\n"],"mappings":"sHAGA,MAAa,EAAa,sBAUb,EAAA,gBCCb,SAAgB,EACZ,EACA,EACI,CACJ,GAAI,OAAO,OAAW,IAClB,OAIJ,IAAM,EAAM,IAAI,IAAI,OAAO,SAAS,IAAI,EAClC,EAAgB,EAAI,aAAa,IAAI,KAAK,EAG3C,IAML,EACK,SAAW,CAGR,EAAU,cAAc,CACpB,gBAAiB,wBACjB,KAAM,CAAE,WAAY,CAAc,CACtC,CAAC,EAED,QAAQ,IACJ,4DACJ,CACJ,CAAC,EACA,MAAO,GAAU,CACd,QAAQ,MACJ,iDACA,CACJ,CACJ,CAAC,EAIL,EAAI,aAAa,OAAO,KAAK,EAC7B,OAAO,QAAQ,aAAa,CAAC,EAAG,GAAI,EAAI,SAAS,CAAC,EAElD,QAAQ,IAAI,2DAA2D,EAC3E,CCvCA,SAAgB,GAA6B,CACzC,IAAM,EAAK,UAAU,UACrB,MAAO,WAAW,KAAK,CAAE,GAAK,eAAe,KAAK,CAAE,CACxD,CAmBA,MAAM,EAAwC,EAAiB,QAC3D,MACA,EACJ,EAEA,SAAgB,EAAmB,EAA0B,CAGzD,MAAO,YADM,EAAS,MAAM,EACN,EAAE,iBAAiB,EAAsB,KACnE,CAeA,SAAgB,EACZ,EACA,EACI,CACJ,IAAM,EAAU,GAAS,SAAW,KAGhC,E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e,EAAiB,CAC1C,MAAO,WACP,SAAU,EACV,sBAAuB,EACvB,sBAAuB,CAC3B,CAAC,CACL,CChBA,SAAgB,EACZ,EACqB,CAIrB,OAHK,EAGE,GAAG,EAAS,QAFR,WAGf,CCKA,eAAsB,EAAY,CAC9B,UAGgC,CAEhC,IAAM,EAAiB,EAAc,CAAM,EAGrC,EAAS,MAAM,EAAa,CAC9B,OAAQ,CACZ,CAAC,EAED,GAAI,CAAC,EAAQ,CACT,QAAQ,MAAM,yBAAyB,EACvC,MACJ,CAGA,IAAM,EAAS,EAAuB,CAClC,OAAQ,EACR,QACJ,CAAC,EAOD,GAJA,MAAM,EAAO,aAIT,CAAC,MAD2B,EAAO,kBACf,CACpB,QAAQ,MAAM,6BAA6B,EAC3C,MACJ,CAEA,OAAO,CACX,CAOA,SAAS,EAAc,EAAkD,CAErE,IAAM,EAAoB,EAAqB,EAAO,UAAU,QAAQ,EAExE,MAAO,CACH,GAAG,EACH,SAAU,CACN,GAAG,EAAO,SACV,SAAU,CACd,CACJ,CACJ,CC7BA,SAAgB,EAAiB,CAC7B,UACA,WACA,qBACqD,CAErD,GAAI,IAAY,KAAM,OAEtB,IAAM,EAAa,IAAY,IAAA,GACzB,EACF,IAAa,IAAA,IAAa,OAAO,KAAK,CAAQ,EAAE,OAAS,EAI7D,GAAI,CAAC,GAAc,CAAC,GAAe,EAF/B,IAAsB,IAAA,IAAa,IAAsB,IAEV,OAGnD,IAAM,EAA4B,CAC9B,GAAG,EACH,GAAI,GAAW,CAAC,CACpB,EAGM,EAAa,GAAqB,GAAS,WAOjD,OANI,IAAe,IAAA,IAAa,IAAe,GAC3C,EAAO,WAAa,EAEpB,OAAO,EAAO,WAGX,CACX"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{_ as e,g as t,h as n,p as r,y as i}from"./frakContext-Bgidv-Se.js";import{Deferred as a,FrakRpcError as o,RpcErrorCodes as s,createRpcClient as c,jsonDecode as l}from"@frak-labs/frame-connector";import{OpenPanel as u}from"@openpanel/web";const d=`nexus-wallet-backup`,f=`frakwallet://`;function p(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`))}function m(){let e=navigator.userAgent;return/Android/i.test(e)&&/Chrome\/\d+/i.test(e)}const h=f.replace(`://`,``);function g(e){return`intent://${e.slice(13)}#Intent;scheme=${h};end`}function _(e,t){let n=t?.timeout??2500,r=!1,i=()=>{document.hidden&&(r=!0)};document.addEventListener(`visibilitychange`,i);let a=m()&&v(e)?g(e):e;window.location.href=a,setTimeout(()=>{document.removeEventListener(`visibilitychange`,i),r||t?.onFallback?.()},n)}function v(e){return e.startsWith(f)}function y(){if(typeof navigator>`u`)return!1;let e=navigator.userAgent;return!!(/iPhone|iPad|iPod/i.test(e)||/Macintosh/i.test(e)&&navigator.maxTouchPoints>1)}const b=y();function x(){return typeof navigator>`u`?!1:b?!0:/Android|webOS|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function S(){if(typeof navigator>`u`)return!1;let e=navigator.userAgent.toLowerCase();return e.includes(`instagram`)||e.includes(`fban`)||e.includes(`fbav`)||e.includes(`facebook`)}const C=S();function w(e){b&&e.startsWith(`https://`)?window.location.href=`x-safari-https://${e.slice(8)}`:b&&e.startsWith(`http://`)?window.location.href=`x-safari-http://${e.slice(7)}`:window.location.href=`https://backend.frak.id/common/social?u=${encodeURIComponent(e)}`}const T={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 E({walletBaseUrl:e,config:n}){let r=document.querySelector(`#frak-wallet`);r&&r.remove();let a=document.createElement(`iframe`);a.id=T.id,a.name=T.name,a.allow=T.allow,a.style.zIndex=T.style.zIndex.toString(),O({iframe:a,isVisible:!1});let o=n?.walletUrl??e??`https://wallet.frak.id`,s=i();return A(o),A(t(o)),a.src=D({walletUrl:o,clientId:s,preload:n?.preload}),new Promise(e=>{a.addEventListener(`load`,()=>e(a)),document.body.appendChild(a)})}function D({walletUrl:e,clientId:t,preload:n}){let r=`${e}/listener?clientId=${encodeURIComponent(t)}`;return!n||n.length===0?r:`${r}#preload=${n.join(`,`)}`}function O({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 k(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 A(e){if(!(typeof document>`u`))try{let t=new URL(e).origin,n=`link[rel="preconnect"][data-frak-preconnect="${t}"]`;if(document.head.querySelector(n))return;let r=document.createElement(`link`);r.rel=`preconnect`,r.href=t,r.crossOrigin=``,r.dataset.frakPreconnect=t,document.head.appendChild(r)}catch{}}const j=b&&C;function M(e){e?localStorage.setItem(d,e):localStorage.removeItem(d)}function N(e,t){try{let n=new URL(e);if(!n.searchParams.has(`u`))return e;let r=I(window.location.href,t);return n.searchParams.delete(`u`),n.searchParams.append(`u`,r),n.toString()}catch{return e}}function P(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 F(e){return e.includes(`/common/social`)}function I(e,t){if(!t)return e;try{let n=new URL(e);return n.searchParams.set(`fmt`,t),n.toString()}catch{return`${e}${e.includes(`?`)?`&`:`?`}fmt=${encodeURIComponent(t)}`}}function L(e,t,n,r,i){if(i){let e=N(t,r);window.open(e,`_blank`);return}if(v(t)){let i=N(t,r);_(i,{onFallback:()=>{e.contentWindow?.postMessage({clientLifecycle:`deep-link-failed`,data:{originalUrl:i}},n)}})}else if(j&&F(t))P(r);else{let e=N(t,r);window.location.href=e}}function R({iframe:e,targetOrigin:t}){let n=new a;return{handleEvent:r=>{if(!(`iframeLifecycle`in r))return;let{iframeLifecycle:i,data:a}=r;switch(i){case`connected`:n.resolve(!0);break;case`do-backup`:M(a.backup);break;case`remove-backup`:localStorage.removeItem(d);break;case`show`:case`hide`:O({iframe:e,isVisible:i===`show`});break;case`redirect`:L(e,a.baseRedirectUrl,t,a.mergeToken,a.openInNewTab);break}},isConnected:n.promise}}function z({config:t,iframe:r}){let l=t?.walletUrl??`https://wallet.frak.id`,d=typeof navigator<`u`?navigator.language?.split(`-`)[0]:void 0,f=t.metadata.lang??(d===`en`||d===`fr`?d:void 0),p=t.domain??(typeof window<`u`?window.location.hostname:``);n.setCacheScope(p,f),n.reset();let m=n.isCacheFresh?void 0:n.resolve(t.domain,t.walletUrl,f),h=R({iframe:r,targetOrigin:l}),g=new a,_=Date.now();if(!r.contentWindow)throw new o(s.configError,`The iframe does not have a content window`);let v=c({emittingTransport:r.contentWindow,listeningTransport:window,targetOrigin:l,middleware:[{async onRequest(e,t){if(!await h.isConnected)throw new o(s.clientNotConnected,`The iframe provider isn't connected yet`);return await g.promise,t}}],lifecycleHandlers:{iframeLifecycle:(e,t)=>{h.handleEvent(e)}}}),y=B(v,h),b=async()=>{y(),v.cleanup(),r.remove(),e(),n.clearCache(),n.reset()},x;{console.log(`[Frak SDK] Initializing OpenPanel`),x=new u({apiUrl:`https://op-api.gcp.frak.id`,clientId:`6eacc8d7-49ac-4936-95e9-81ef29449570`,trackScreenViews:!0,trackOutgoingLinks:!0,trackAttributes:!1,filter:({type:e,payload:t})=>(e!==`track`||!t?.properties||`sdk_version`in t.properties||(t.properties={...t.properties,sdk_version:`1.1.5`,user_anonymous_client_id:i()}),!0)}),x.setGlobalProperties({sdk_version:`1.1.5`,user_anonymous_client_id:i()}),x.init(),x.track(`sdk_initialized`,{sdk_version:`1.1.5`});let e=!1,t=setTimeout(()=>{e||(e=!0,x?.track(`sdk_iframe_handshake_failed`,{reason:`timeout`}))},3e4);h.isConnected.then(()=>{e||(e=!0,clearTimeout(t),x?.track(`sdk_iframe_connected`,{handshake_duration_ms:Date.now()-_}))}).catch(()=>{e||(e=!0,clearTimeout(t),x?.track(`sdk_iframe_handshake_failed`,{reason:`unknown`}))})}let S=V({config:t,rpcClient:v,lifecycleManager:h,configPromise:m,contextSent:g,openPanel:x}).then(()=>{}).catch(e=>{throw g.reject(e),e});return{config:t,waitForConnection:h.isConnected,waitForSetup:S,request:v.request,listenerRequest:v.listen,destroy:b,openPanel:x}}function B(e,t){let n,r,i=()=>e.sendLifecycle({clientLifecycle:`heartbeat`});async function a(){i(),n=setInterval(i,250),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 V({config:e,rpcClient:t,lifecycleManager:r,configPromise:a,contextSent:o,openPanel:s}){await r.isConnected,p(t,r.isConnected);let c=new URL(window.location.href),l=c.searchParams.get(`fmt`)??void 0;l&&(c.searchParams.delete(`fmt`),window.history.replaceState({},``,c.toString()));let u=t=>{let r=t?.merchantId??e.metadata.merchantId??``,i=t?.domain??``,a=t?.allowedDomains??[],o=t?.sdkConfig,s=o?.attribution||e.attribution?{...e.attribution,...o?.attribution}:void 0;n.setConfig(o?{isResolved:!0,merchantId:r,domain:i,allowedDomains:a,hasRawSdkConfig:!0,name:o.name??e.metadata.name,logoUrl:o.logoUrl??e.metadata.logoUrl,homepageLink:o.homepageLink??e.metadata.homepageLink,lang:o.lang??e.metadata.lang,currency:o.currency??e.metadata.currency,hidden:o.hidden,css:o.css,translations:o.translations,placements:o.placements,components:o.components,attribution:s}:{isResolved:!0,merchantId:r,domain:i,allowedDomains:a,name:e.metadata.name,logoUrl:e.metadata.logoUrl,homepageLink:e.metadata.homepageLink,lang:e.metadata.lang,currency:e.metadata.currency,attribution:s})},f=!1,m=e=>{let n=f?void 0:l;f=!0;let r=e.hasRawSdkConfig?{name:e.name,logoUrl:e.logoUrl,homepageLink:e.homepageLink,lang:e.lang,currency:e.currency,hidden:e.hidden,css:e.css,translations:e.translations,placements:e.placements,attribution:e.attribution}:e.attribution?{attribution:e.attribution}:void 0,a=i();if(s){let t=s.global??{};s.setGlobalProperties({...t,merchant_id:e.merchantId,domain:e.domain??``})}t.sendLifecycle({clientLifecycle:`resolved-config`,data:{merchantId:e.merchantId,domain:e.domain??``,allowedDomains:e.allowedDomains??[],sourceUrl:window.location.href,...a&&{sdkAnonymousId:a},...n&&{pendingMergeToken:n},...r&&{sdkConfig:r}}})};n.isResolved&&(m(n.getConfig()),o.resolve()),a&&(u(await a),m(n.getConfig()),o.resolve());async function h(){let n=e.customizations?.css;n&&t.sendLifecycle({clientLifecycle:`modal-css`,data:{cssLink:n}})}async function g(){let n=e.customizations?.i18n;n&&t.sendLifecycle({clientLifecycle:`modal-i18n`,data:{i18n:n}})}async function _(){if(typeof window>`u`)return;let e=window.localStorage.getItem(d);e&&t.sendLifecycle({clientLifecycle:`restore-backup`,data:{backup:e}})}(await Promise.allSettled([h(),g(),_()])).some(e=>e.status===`rejected`)&&s?.track(`sdk_iframe_handshake_failed`,{reason:`asset_push`})}function H(e){return l(r(e))}const U={eur:`fr-FR`,usd:`en-US`,gbp:`en-GB`};function W(e){return e&&e in U?e:`eur`}function G(e){return e?U[e]??U.eur:U.eur}function K(e,t){let n=G(t),r=W(t);return e.toLocaleString(n,{style:`currency`,currency:r,minimumFractionDigits:0,maximumFractionDigits:2})}function q(e){return e?`${e}Amount`:`eurAmount`}async function J({config:e}){let t=Y(e),n=await E({config:t});if(!n){console.error(`Failed to create iframe`);return}let r=z({config:t,iframe:n});if(await r.waitForSetup,!await r.waitForConnection){console.error(`Failed to connect to client`);return}return r}function Y(e){let t=W(e.metadata?.currency);return{...e,metadata:{...e.metadata,currency:t}}}function X({perCall:e,defaults:t,productUtmContent:n}){if(e===null)return;let r=e!==void 0,i=t!==void 0&&Object.keys(t).length>0;if(!r&&!i&&!(n!==void 0&&n!==``))return;let a={...t,...e??{}},o=n??e?.utmContent;return o!==void 0&&o!==``?a.utmContent=o:delete a.utmContent,a}export{W as a,T as c,C as d,x as f,f as h,K as i,k as l,_ as m,J as n,H as o,w as p,q as r,z as s,X as t,b as u};
|
|
2
|
+
//# sourceMappingURL=src-DKLOAY9w.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-DKLOAY9w.js","names":[],"sources":["../src/constants.ts","../src/clients/ssoUrlListener.ts","../src/utils/browser/deepLinkWithFallback.ts","../src/utils/browser/inAppBrowser.ts","../src/utils/iframe/iframeHelper.ts","../src/clients/transports/iframeLifecycleManager.ts","../src/clients/createIFrameFrakClient.ts","../src/utils/compression/decompress.ts","../src/constants/locales.ts","../src/utils/format/getSupportedCurrency.ts","../src/utils/format/getSupportedLocale.ts","../src/utils/format/formatAmount.ts","../src/utils/format/getCurrencyAmountKey.ts","../src/clients/setupClient.ts","../src/context/mergeAttribution.ts"],"sourcesContent":["/**\n * The backup key for client side backup if needed\n */\nexport const BACKUP_KEY = \"nexus-wallet-backup\";\n\n/**\n * Deep link scheme for Frak Wallet mobile app.\n *\n * Replaced at build time via tsdown/Vite `define`. Defaults to the prod scheme;\n * in-monorepo dev builds (listener at wallet-dev.frak.id) override this with\n * `frakwallet-dev://` so deep links open the dev wallet variant (id.frak.wallet.dev).\n * External integrators consuming the published NPM/CDN bundle always see the prod scheme.\n */\nexport const DEEP_LINK_SCHEME: string =\n process.env.DEEP_LINK_SCHEME ?? \"frakwallet://\";\n","import type { RpcClient } from \"@frak-labs/frame-connector\";\nimport type { FrakLifecycleEvent } from \"../types\";\nimport type { IFrameRpcSchema } from \"../types/rpc\";\n\n/**\n * Listen for SSO redirect with compressed data in URL\n * Forwards compressed data to iframe via lifecycle event\n * Cleans URL immediately after detection\n *\n * Performance: One-shot URL check, no polling, no re-renders\n *\n * @param rpcClient - RPC client instance to send lifecycle events\n * @param waitForConnection - Promise that resolves when iframe is connected\n */\nexport function setupSsoUrlListener(\n rpcClient: RpcClient<IFrameRpcSchema, FrakLifecycleEvent>,\n waitForConnection: Promise<boolean>\n): void {\n if (typeof window === \"undefined\") {\n return;\n }\n\n // One-shot URL check - no need for MutationObserver or polling\n const url = new URL(window.location.href);\n const compressedSso = url.searchParams.get(\"sso\");\n\n // Early return if no SSO parameter\n if (!compressedSso) {\n return;\n }\n\n // Forward compressed data directly to iframe (no decompression on SDK side)\n // Iframe will decompress and process\n waitForConnection\n .then(() => {\n // Send lifecycle event with compressed string\n // This is a one-way notification, no response expected\n rpcClient.sendLifecycle({\n clientLifecycle: \"sso-redirect-complete\",\n data: { compressed: compressedSso },\n });\n\n console.log(\n \"[SSO URL Listener] Forwarded compressed SSO data to iframe\"\n );\n })\n .catch((error) => {\n console.error(\n \"[SSO URL Listener] Failed to forward SSO data:\",\n error\n );\n });\n\n // Clean URL immediately to prevent exposure in browser history\n // Use replaceState to avoid navigation/re-render\n url.searchParams.delete(\"sso\");\n window.history.replaceState({}, \"\", url.toString());\n\n console.log(\"[SSO URL Listener] SSO parameter detected and URL cleaned\");\n}\n","import { DEEP_LINK_SCHEME } from \"../../constants\";\n\n/**\n * Options for deep link with fallback\n */\nexport type DeepLinkFallbackOptions = {\n /** Timeout in ms before triggering fallback (default: 2500ms) */\n timeout?: number;\n /** Callback invoked when fallback is triggered (app not installed) */\n onFallback?: () => void;\n};\n\n/**\n * Check if running on a Chromium-based Android browser.\n *\n * On Chrome Android, custom scheme deep links (e.g. frakwallet://) trigger\n * a confirmation bar (\"Continue to Frak Wallet?\"). Using intent:// URLs\n * instead bypasses this for Chromium browsers while keeping custom scheme\n * fallback for non-Chromium browsers (e.g. Firefox) where it works fine.\n */\nexport function isChromiumAndroid(): boolean {\n const ua = navigator.userAgent;\n return /Android/i.test(ua) && /Chrome\\/\\d+/i.test(ua);\n}\n\n/**\n * Convert a Frak deep link to an Android intent:// URL.\n *\n * Intent URLs let Chromium browsers open the app directly without\n * showing the \"Continue to app?\" confirmation bar.\n *\n * Note: We intentionally omit the `package` parameter. Including it\n * causes Chrome to redirect to the Play Store when the app is not\n * installed, which breaks the visibility-based fallback detection.\n * Without `package`, Chrome simply does nothing when the app is\n * missing, allowing the fallback mechanism to fire correctly.\n *\n * The scheme is derived from `DEEP_LINK_SCHEME` so the dev variant\n * (`frakwallet-dev://`) routes to the dev app shell, not prod.\n *\n * Format: intent://path#Intent;scheme=<scheme>;end\n */\nconst DEEP_LINK_SCHEME_NAME = /* @__PURE__ */ DEEP_LINK_SCHEME.replace(\n \"://\",\n \"\"\n);\n\nexport function toAndroidIntentUrl(deepLink: string): string {\n // Extract everything after the scheme (e.g. \"frakwallet://\" or \"frakwallet-dev://\")\n const path = deepLink.slice(DEEP_LINK_SCHEME.length);\n return `intent://${path}#Intent;scheme=${DEEP_LINK_SCHEME_NAME};end`;\n}\n\n/**\n * Trigger a deep link with visibility-based fallback detection.\n *\n * Uses the Page Visibility API to detect if the app opened (page goes hidden).\n * If the page remains visible after the timeout, assumes app is not installed\n * and invokes the onFallback callback.\n *\n * On Chromium Android, converts custom scheme to intent:// URL to avoid\n * the \"Continue to app?\" confirmation bar.\n *\n * @param deepLink - The deep link URL to trigger (e.g., \"frakwallet://wallet\")\n * @param options - Optional configuration (timeout, onFallback callback)\n */\nexport function triggerDeepLinkWithFallback(\n deepLink: string,\n options?: DeepLinkFallbackOptions\n): void {\n const timeout = options?.timeout ?? 2500;\n\n // Track if the app opened (page went to background)\n let appOpened = false;\n\n const onVisibilityChange = () => {\n if (document.hidden) {\n appOpened = true;\n }\n };\n\n // Start listening for visibility changes\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n\n // On Chromium Android, use intent:// to avoid confirmation bar\n const url =\n isChromiumAndroid() && isFrakDeepLink(deepLink)\n ? toAndroidIntentUrl(deepLink)\n : deepLink;\n\n // Trigger the deep link\n window.location.href = url;\n\n // Check after timeout if app opened\n setTimeout(() => {\n // Clean up listener\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n\n if (!appOpened) {\n // App didn't open - trigger fallback callback\n options?.onFallback?.();\n }\n }, timeout);\n}\n\n/**\n * Check if a URL is a Frak deep link\n */\nexport function isFrakDeepLink(url: string): boolean {\n return url.startsWith(DEEP_LINK_SCHEME);\n}\n","/**\n * Check if the current device runs iOS (including iPadOS 13+).\n */\nfunction checkIsIOS(): boolean {\n if (typeof navigator === \"undefined\") return false;\n const ua = navigator.userAgent;\n // Standard iOS devices\n if (/iPhone|iPad|iPod/i.test(ua)) return true;\n // iPadOS 13+ reports as Macintosh — detect via touch support\n if (/Macintosh/i.test(ua) && navigator.maxTouchPoints > 1) return true;\n return false;\n}\n\n/**\n * Whether the current device runs iOS (including iPadOS 13+).\n */\nexport const isIOS: boolean = /* @__PURE__ */ checkIsIOS();\n\n/**\n * Check if the current device is a mobile device (iOS, iPadOS, Android,\n * webOS, BlackBerry, IEMobile, Opera Mini). Reuses {@link isIOS} so the\n * iPadOS-13+ Macintosh heuristic stays in one place.\n */\nexport function isMobile(): boolean {\n if (typeof navigator === \"undefined\") return false;\n if (isIOS) return true;\n return /Android|webOS|BlackBerry|IEMobile|Opera Mini/i.test(\n navigator.userAgent\n );\n}\n\n/**\n * Check if the current browser is a social media in-app browser\n * (Instagram, Facebook WebView).\n */\nfunction checkInAppBrowser(): boolean {\n if (typeof navigator === \"undefined\") return false;\n const ua = navigator.userAgent.toLowerCase();\n return (\n ua.includes(\"instagram\") ||\n ua.includes(\"fban\") ||\n ua.includes(\"fbav\") ||\n ua.includes(\"facebook\")\n );\n}\n\n/**\n * Whether the current browser is a social media in-app browser\n * (Instagram, Facebook).\n */\nexport const isInAppBrowser: boolean = /* @__PURE__ */ checkInAppBrowser();\n\n/**\n * Redirect to external browser from in-app WebView.\n *\n * - **iOS**: Uses `x-safari-https://` scheme — server-side 302 redirects\n * to custom URL schemes are silently swallowed by WKWebView.\n * Direct `window.location.href` assignment works (confirmed iOS 17+).\n *\n * - **Android**: Uses backend `/common/social` endpoint which returns a PDF\n * Content-Type response, forcing the WebView to hand off to the default browser.\n *\n * @param targetUrl - The URL to open in the external browser\n */\nexport function redirectToExternalBrowser(targetUrl: string): void {\n if (isIOS && targetUrl.startsWith(\"https://\")) {\n window.location.href = `x-safari-https://${targetUrl.slice(8)}`;\n } else if (isIOS && targetUrl.startsWith(\"http://\")) {\n window.location.href = `x-safari-http://${targetUrl.slice(7)}`;\n } else {\n window.location.href = `${process.env.BACKEND_URL}/common/social?u=${encodeURIComponent(targetUrl)}`;\n }\n}\n","import { getBackendUrl } from \"../../config/backendUrl\";\nimport { getClientId } from \"../../config/clientId\";\nimport type { FrakWalletSdkConfig, ListenerPreloadOption } from \"../../types\";\n\n/**\n * Base props for the iframe\n * @ignore\n */\nexport const baseIframeProps = {\n id: \"frak-wallet\",\n name: \"frak-wallet\",\n title: \"Frak Wallet\",\n allow: \"publickey-credentials-get *; clipboard-write; web-share *\",\n style: {\n width: \"0\",\n height: \"0\",\n border: \"0\",\n position: \"absolute\",\n zIndex: 2000001,\n top: \"-1000px\",\n left: \"-1000px\",\n colorScheme: \"auto\",\n },\n};\n\n/**\n * Create the Frak iframe\n * @param args\n * @param args.walletBaseUrl - Use `config.walletUrl` instead. Will be removed in future versions.\n * @param args.config - The configuration object containing iframe options, including the replacement for `walletBaseUrl`.\n */\nexport function createIframe({\n walletBaseUrl,\n config,\n}: {\n walletBaseUrl?: string;\n config?: FrakWalletSdkConfig;\n}): Promise<HTMLIFrameElement | undefined> {\n // Check if the iframe is already created\n const alreadyCreatedIFrame = document.querySelector(\"#frak-wallet\");\n\n // If the iframe is already created, remove it\n if (alreadyCreatedIFrame) {\n alreadyCreatedIFrame.remove();\n }\n\n const iframe = document.createElement(\"iframe\");\n\n // Set the base iframe props\n iframe.id = baseIframeProps.id;\n iframe.name = baseIframeProps.name;\n iframe.allow = baseIframeProps.allow;\n iframe.style.zIndex = baseIframeProps.style.zIndex.toString();\n\n changeIframeVisibility({ iframe, isVisible: false });\n\n // Set src BEFORE appending to DOM to avoid about:blank load event\n const walletUrl =\n config?.walletUrl ?? walletBaseUrl ?? \"https://wallet.frak.id\";\n const clientId = getClientId();\n\n // Preconnect to the wallet + backend origins so the handshake doesn't pay\n // for a cold DNS/TLS round-trip on partner sites that didn't warm them.\n preconnect(walletUrl);\n preconnect(getBackendUrl(walletUrl));\n\n iframe.src = buildListenerUrl({\n walletUrl,\n clientId,\n preload: config?.preload,\n });\n\n return new Promise((resolve) => {\n iframe.addEventListener(\"load\", () => resolve(iframe));\n document.body.appendChild(iframe);\n });\n}\n\n/**\n * Build the listener iframe URL.\n *\n * Query params:\n * - `clientId` — anonymous SDK client identifier used for funnel joining.\n *\n * Hash params (consumed by `apps/listener/app/bootstrap.ts#setupPreloadHints`):\n * - `preload=modal,sharing` — idle-warms the matching Ring 1 + Ring 2 chunks.\n * Skipped entirely when no preload hints are provided so the listener\n * doesn't pay for warm-ups that nobody asked for.\n */\nfunction buildListenerUrl({\n walletUrl,\n clientId,\n preload,\n}: {\n walletUrl: string;\n clientId: string;\n preload?: ListenerPreloadOption[];\n}): string {\n const base = `${walletUrl}/listener?clientId=${encodeURIComponent(clientId)}`;\n if (!preload || preload.length === 0) return base;\n return `${base}#preload=${preload.join(\",\")}`;\n}\n\n/**\n * Change the visibility of the given iframe\n * @ignore\n */\nexport function changeIframeVisibility({\n iframe,\n isVisible,\n}: {\n iframe: HTMLIFrameElement;\n isVisible: boolean;\n}) {\n if (!isVisible) {\n iframe.style.width = \"0\";\n iframe.style.height = \"0\";\n iframe.style.border = \"0\";\n iframe.style.position = \"fixed\";\n iframe.style.top = \"-1000px\";\n iframe.style.left = \"-1000px\";\n return;\n }\n\n iframe.style.position = \"fixed\";\n iframe.style.top = \"0\";\n iframe.style.left = \"0\";\n iframe.style.width = \"100%\";\n iframe.style.height = \"100%\";\n iframe.style.pointerEvents = \"auto\";\n}\n\n/**\n * Find an iframe within window.opener by pathname\n *\n * When a popup is opened via window.open from an iframe, window.opener points to\n * the parent window, not the iframe itself. This utility searches through all frames\n * in window.opener to find an iframe matching the specified pathname.\n *\n * @param pathname - The pathname to search for (default: \"/listener\")\n * @returns The matching iframe window, or null if not found\n *\n * @example\n * ```typescript\n * // Find the default /listener iframe\n * const listenerIframe = findIframeInOpener();\n *\n * // Find a custom iframe\n * const customIframe = findIframeInOpener(\"/my-custom-iframe\");\n * ```\n */\nexport function findIframeInOpener(pathname = \"/listener\"): Window | null {\n if (!window.opener) return null;\n\n const frameCheck = (frame: Window) => {\n try {\n return (\n frame.location.origin === window.location.origin &&\n frame.location.pathname === pathname\n );\n } catch {\n // Cross-origin frame, skip\n return false;\n }\n };\n\n // Check if the openner window is the right one\n if (frameCheck(window.opener)) return window.opener;\n\n // Search through frames in window.opener\n try {\n const frames = window.opener.frames;\n for (let i = 0; i < frames.length; i++) {\n if (frameCheck(frames[i])) {\n return frames[i];\n }\n }\n return null;\n } catch (error) {\n console.error(\n `[findIframeInOpener] Error finding iframe with pathname ${pathname}:`,\n error\n );\n return null;\n }\n}\n\n/**\n * Inject a `<link rel=\"preconnect\">` for the given origin. Idempotent — browsers\n * de-duplicate preconnects per origin automatically, but we also guard on a data\n * attribute to avoid spamming the <head> in SPA re-inits.\n */\nfunction preconnect(url: string): void {\n if (typeof document === \"undefined\") return;\n try {\n const origin = new URL(url).origin;\n const selector = `link[rel=\"preconnect\"][data-frak-preconnect=\"${origin}\"]`;\n if (document.head.querySelector(selector)) return;\n const link = document.createElement(\"link\");\n link.rel = \"preconnect\";\n link.href = origin;\n link.crossOrigin = \"\";\n link.dataset.frakPreconnect = origin;\n document.head.appendChild(link);\n } catch {\n // Invalid URL — nothing to preconnect.\n }\n}\n","import { Deferred } from \"@frak-labs/frame-connector\";\nimport { BACKUP_KEY } from \"../../constants\";\nimport type { FrakLifecycleEvent } from \"../../types\";\nimport {\n isFrakDeepLink,\n triggerDeepLinkWithFallback,\n} from \"../../utils/browser/deepLinkWithFallback\";\nimport { isInAppBrowser, isIOS } from \"../../utils/browser/inAppBrowser\";\nimport { changeIframeVisibility } from \"../../utils/iframe/iframeHelper\";\n\n// iOS in-app browsers (Instagram, Facebook) silently swallow server-side 302\n// redirects to custom URL schemes (x-safari-https://) in WKWebView; direct\n// window.location.href assignment works.\nconst isIOSInAppBrowser = isIOS && isInAppBrowser;\n\n/** @ignore */\nexport type IframeLifecycleManager = {\n isConnected: Promise<boolean>;\n handleEvent: (messageEvent: FrakLifecycleEvent) => void;\n};\n\n/**\n * Handle backup storage\n */\nfunction handleBackup(backup: string | undefined): void {\n if (backup) {\n localStorage.setItem(BACKUP_KEY, backup);\n } else {\n localStorage.removeItem(BACKUP_KEY);\n }\n}\n\n/**\n * Compute final redirect URL with parameter substitution\n */\nfunction computeRedirectUrl(\n baseRedirectUrl: string,\n mergeToken?: string\n): string {\n try {\n const redirectUrl = new URL(baseRedirectUrl);\n if (!redirectUrl.searchParams.has(\"u\")) {\n return baseRedirectUrl;\n }\n\n // Append merge token to the page URL so it survives\n // the backend /common/social redirect chain\n const finalPageUrl = appendMergeToken(window.location.href, mergeToken);\n\n redirectUrl.searchParams.delete(\"u\");\n redirectUrl.searchParams.append(\"u\", finalPageUrl);\n\n return redirectUrl.toString();\n } catch {\n return baseRedirectUrl;\n }\n}\n\n/**\n * Redirect current page to Safari via x-safari-https:// scheme.\n * Used on iOS in-app browsers where backend 302 → custom scheme fails.\n */\nfunction redirectToSafari(mergeToken?: string) {\n const url = new URL(window.location.href);\n if (mergeToken) {\n url.searchParams.set(\"fmt\", mergeToken);\n }\n const scheme =\n url.protocol === \"http:\" ? \"x-safari-http\" : \"x-safari-https\";\n window.location.href = `${scheme}://${url.host}${url.pathname}${url.search}${url.hash}`;\n}\n\n/**\n * Check if this is a social/in-app-browser escape redirect (contains /common/social)\n */\nfunction isSocialRedirect(url: string): boolean {\n return url.includes(\"/common/social\");\n}\n\n/**\n * Append merge token to a URL as the `fmt` query parameter.\n */\nfunction appendMergeToken(urlString: string, mergeToken?: string): string {\n if (!mergeToken) return urlString;\n try {\n const url = new URL(urlString);\n url.searchParams.set(\"fmt\", mergeToken);\n return url.toString();\n } catch {\n const sep = urlString.includes(\"?\") ? \"&\" : \"?\";\n return `${urlString}${sep}fmt=${encodeURIComponent(mergeToken)}`;\n }\n}\n\n/**\n * Handle redirect with deep link fallback\n */\nfunction handleRedirect(\n iframe: HTMLIFrameElement,\n baseRedirectUrl: string,\n targetOrigin: string,\n mergeToken?: string,\n openInNewTab?: boolean\n): void {\n // If requested, open in a new tab instead of navigating the current page.\n // This preserves the merchant page while triggering universal links.\n // Requires the iframe postMessage to include user activation delegation.\n if (openInNewTab) {\n const finalUrl = computeRedirectUrl(baseRedirectUrl, mergeToken);\n window.open(finalUrl, \"_blank\");\n return;\n }\n\n if (isFrakDeepLink(baseRedirectUrl)) {\n const finalUrl = computeRedirectUrl(baseRedirectUrl, mergeToken);\n triggerDeepLinkWithFallback(finalUrl, {\n onFallback: () => {\n iframe.contentWindow?.postMessage(\n {\n clientLifecycle: \"deep-link-failed\",\n data: { originalUrl: finalUrl },\n },\n targetOrigin\n );\n },\n });\n } else if (isIOSInAppBrowser && isSocialRedirect(baseRedirectUrl)) {\n // iOS WKWebView silently swallows 302 redirects to custom URL\n // schemes — bypass the server redirect entirely\n redirectToSafari(mergeToken);\n } else {\n const finalUrl = computeRedirectUrl(baseRedirectUrl, mergeToken);\n window.location.href = finalUrl;\n }\n}\n\n/**\n * Create a new iframe lifecycle handler\n * @param args\n * @param args.iframe - The iframe element used for wallet communication\n * @param args.targetOrigin - The wallet URL origin for postMessage security\n * @ignore\n */\nexport function createIFrameLifecycleManager({\n iframe,\n targetOrigin,\n}: {\n iframe: HTMLIFrameElement;\n targetOrigin: string;\n}): IframeLifecycleManager {\n // Create the isConnected listener\n const isConnectedDeferred = new Deferred<boolean>();\n\n // Build the handler itself\n const handler = (messageEvent: FrakLifecycleEvent) => {\n if (!(\"iframeLifecycle\" in messageEvent)) return;\n\n const { iframeLifecycle: event, data } = messageEvent;\n\n switch (event) {\n // Resolve the isConnected promise\n case \"connected\":\n isConnectedDeferred.resolve(true);\n break;\n // Perform a frak backup\n case \"do-backup\":\n handleBackup(data.backup);\n break;\n // Remove frak backup\n case \"remove-backup\":\n localStorage.removeItem(BACKUP_KEY);\n break;\n // Change iframe visibility\n case \"show\":\n case \"hide\":\n changeIframeVisibility({ iframe, isVisible: event === \"show\" });\n break;\n // Redirect handling\n case \"redirect\":\n handleRedirect(\n iframe,\n data.baseRedirectUrl,\n targetOrigin,\n data.mergeToken,\n data.openInNewTab\n );\n break;\n }\n };\n\n return {\n handleEvent: handler,\n isConnected: isConnectedDeferred.promise,\n };\n}\n","import {\n createRpcClient,\n Deferred,\n FrakRpcError,\n type RpcClient,\n RpcErrorCodes,\n} from \"@frak-labs/frame-connector\";\nimport { OpenPanel } from \"@openpanel/web\";\nimport { getClientId } from \"../config/clientId\";\nimport { sdkConfigStore } from \"../config/sdkConfigStore\";\nimport { BACKUP_KEY } from \"../constants\";\nimport type { FrakLifecycleEvent } from \"../types\";\nimport type { FrakClient } from \"../types/client\";\nimport type { FrakWalletSdkConfig } from \"../types/config\";\nimport type { SdkResolvedConfig } from \"../types/resolvedConfig\";\nimport type { IFrameRpcSchema } from \"../types/rpc\";\nimport { clearAllCache } from \"../utils/cache\";\nimport { setupSsoUrlListener } from \"./ssoUrlListener\";\nimport {\n createIFrameLifecycleManager,\n type IframeLifecycleManager,\n} from \"./transports/iframeLifecycleManager\";\n\ntype SdkRpcClient = RpcClient<IFrameRpcSchema, FrakLifecycleEvent>;\ntype MerchantConfigResult = Awaited<ReturnType<typeof sdkConfigStore.resolve>>;\n\n/**\n * Create a new iframe Frak client\n * @param args\n * @param args.config - The configuration to use for the Frak Wallet SDK.\n * When `config.domain` is set, it is used to resolve the correct merchant config in tunneled/proxied environments (e.g. Shopify dev with Cloudflare tunnel).\n * @param args.iframe - The iframe to use for the communication\n * @returns The created Frak Client\n *\n * @example\n * const frakConfig: FrakWalletSdkConfig = {\n * metadata: {\n * name: \"My app title\",\n * },\n * }\n * const iframe = await createIframe({ config: frakConfig });\n * const client = createIFrameFrakClient({ config: frakConfig, iframe });\n */\nexport function createIFrameFrakClient({\n config,\n iframe,\n}: {\n config: FrakWalletSdkConfig;\n iframe: HTMLIFrameElement;\n}): FrakClient {\n const frakWalletUrl = config?.walletUrl ?? \"https://wallet.frak.id\";\n\n const browserLang =\n typeof navigator !== \"undefined\"\n ? navigator.language?.split(\"-\")[0]\n : undefined;\n const detectedLang =\n config.metadata.lang ??\n (browserLang === \"en\" || browserLang === \"fr\"\n ? browserLang\n : undefined);\n const targetDomain =\n config.domain ??\n (typeof window !== \"undefined\" ? window.location.hostname : \"\");\n sdkConfigStore.setCacheScope(targetDomain, detectedLang);\n sdkConfigStore.reset();\n\n // Skip fetch entirely if cache is fresh, otherwise fetch (SWR)\n const configPromise = sdkConfigStore.isCacheFresh\n ? undefined\n : sdkConfigStore.resolve(config.domain, config.walletUrl, detectedLang);\n\n // Create lifecycle manager\n const lifecycleManager = createIFrameLifecycleManager({\n iframe,\n targetOrigin: frakWalletUrl,\n });\n\n // Resolved after first resolved-config is sent to iframe (prevents RPC before context exists)\n const contextSent = new Deferred<void>();\n\n // Handshake timing: measured from client creation until the iframe\n // lifecycle manager resolves the `isConnected` promise.\n const handshakeStartedAt = Date.now();\n\n // Validate iframe\n if (!iframe.contentWindow) {\n throw new FrakRpcError(\n RpcErrorCodes.configError,\n \"The iframe does not have a content window\"\n );\n }\n\n // Create RPC client with middleware and lifecycle handlers\n const rpcClient = createRpcClient<IFrameRpcSchema, FrakLifecycleEvent>({\n emittingTransport: iframe.contentWindow,\n listeningTransport: window,\n targetOrigin: frakWalletUrl,\n middleware: [\n // Ensure we are connected and context is sent before sending request\n {\n async onRequest(_message, ctx) {\n const isConnected = await lifecycleManager.isConnected;\n if (!isConnected) {\n throw new FrakRpcError(\n RpcErrorCodes.clientNotConnected,\n \"The iframe provider isn't connected yet\"\n );\n }\n await contextSent.promise;\n return ctx;\n },\n },\n ],\n // Add lifecycle handlers to process iframe lifecycle events\n lifecycleHandlers: {\n iframeLifecycle: (event, _context) => {\n // Delegate to lifecycle manager (cast for type compatibility)\n lifecycleManager.handleEvent(event);\n },\n },\n });\n\n // Setup heartbeat\n const stopHeartbeat = setupHeartbeat(rpcClient, lifecycleManager);\n\n const destroy = async () => {\n stopHeartbeat();\n rpcClient.cleanup();\n iframe.remove();\n clearAllCache();\n sdkConfigStore.clearCache();\n sdkConfigStore.reset();\n };\n\n // Init open panel\n let openPanel: OpenPanel | undefined;\n if (\n process.env.OPEN_PANEL_API_URL &&\n process.env.OPEN_PANEL_SDK_CLIENT_ID\n ) {\n console.log(\"[Frak SDK] Initializing OpenPanel\");\n openPanel = new OpenPanel({\n apiUrl: process.env.OPEN_PANEL_API_URL,\n clientId: process.env.OPEN_PANEL_SDK_CLIENT_ID,\n trackScreenViews: true,\n trackOutgoingLinks: true,\n trackAttributes: false,\n // We use a filter to ensure we got the open panel instance initialized\n // A bit hacky, but this way we are sure that we got everything needed for the first event ever sent\n filter: ({ type, payload }) => {\n if (type !== \"track\") return true;\n if (!payload?.properties) return true;\n\n // Check if we we got the properties once initialized\n if (!(\"sdk_version\" in payload.properties)) {\n payload.properties = {\n ...payload.properties,\n sdk_version: process.env.SDK_VERSION,\n user_anonymous_client_id: getClientId(),\n };\n }\n\n return true;\n },\n });\n openPanel.setGlobalProperties({\n sdk_version: process.env.SDK_VERSION,\n user_anonymous_client_id: getClientId(),\n });\n openPanel.init();\n openPanel.track(\"sdk_initialized\", {\n sdk_version: process.env.SDK_VERSION,\n });\n\n // Race the connection against the heartbeat timeout so we can\n // distinguish \"connected\" from \"timeout\" cleanly without touching\n // the heartbeat plumbing. 30s matches `HEARTBEAT_TIMEOUT`.\n let settled = false;\n const timeoutHandle = setTimeout(() => {\n if (settled) return;\n settled = true;\n openPanel?.track(\"sdk_iframe_handshake_failed\", {\n reason: \"timeout\",\n });\n }, 30_000);\n lifecycleManager.isConnected\n .then(() => {\n if (settled) return;\n settled = true;\n clearTimeout(timeoutHandle);\n openPanel?.track(\"sdk_iframe_connected\", {\n handshake_duration_ms: Date.now() - handshakeStartedAt,\n });\n })\n .catch(() => {\n if (settled) return;\n settled = true;\n clearTimeout(timeoutHandle);\n openPanel?.track(\"sdk_iframe_handshake_failed\", {\n reason: \"unknown\",\n });\n });\n }\n\n // Perform the post connection setup\n const waitForSetup = postConnectionSetup({\n config,\n rpcClient,\n lifecycleManager,\n configPromise,\n contextSent,\n openPanel,\n })\n .then(() => {})\n .catch((err) => {\n contextSent.reject(err);\n throw err;\n });\n\n return {\n config,\n waitForConnection: lifecycleManager.isConnected,\n waitForSetup,\n request: rpcClient.request,\n listenerRequest: rpcClient.listen,\n destroy,\n openPanel,\n };\n}\n\n/**\n * Setup the heartbeat\n * @param rpcClient - RPC client to send lifecycle events\n * @param lifecycleManager - Lifecycle manager to track connection\n */\nfunction setupHeartbeat(\n rpcClient: SdkRpcClient,\n lifecycleManager: IframeLifecycleManager\n) {\n const HEARTBEAT_INTERVAL = 250; // Fallback discovery ping until we are connected\n const HEARTBEAT_TIMEOUT = 30_000; // 30 seconds timeout\n let heartbeatInterval: NodeJS.Timeout;\n let timeoutId: NodeJS.Timeout;\n\n const sendHeartbeat = () =>\n rpcClient.sendLifecycle({\n clientLifecycle: \"heartbeat\",\n });\n\n // Start sending heartbeats\n async function startHeartbeat() {\n sendHeartbeat(); // Send initial heartbeat\n heartbeatInterval = setInterval(sendHeartbeat, HEARTBEAT_INTERVAL);\n\n // Set up timeout\n timeoutId = setTimeout(() => {\n stopHeartbeat();\n console.log(\"Heartbeat timeout: connection failed\");\n }, HEARTBEAT_TIMEOUT);\n\n // Once connected, stop it\n await lifecycleManager.isConnected;\n\n // We are now connected, stop the heartbeat\n stopHeartbeat();\n }\n\n // Stop sending heartbeats\n function stopHeartbeat() {\n if (heartbeatInterval) {\n clearInterval(heartbeatInterval);\n }\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n\n startHeartbeat();\n\n // Return cleanup function\n return stopHeartbeat;\n}\n\n/**\n * Perform the post connection setup\n * @param config - SDK configuration\n * @param rpcClient - RPC client to send lifecycle events\n * @param lifecycleManager - Lifecycle manager to track connection\n */\nasync function postConnectionSetup({\n config,\n rpcClient,\n lifecycleManager,\n configPromise,\n contextSent,\n openPanel,\n}: {\n config: FrakWalletSdkConfig;\n rpcClient: SdkRpcClient;\n lifecycleManager: IframeLifecycleManager;\n configPromise: Promise<MerchantConfigResult> | undefined;\n contextSent: Deferred<void>;\n openPanel: OpenPanel | undefined;\n}): Promise<void> {\n await lifecycleManager.isConnected;\n\n setupSsoUrlListener(rpcClient, lifecycleManager.isConnected);\n\n // Read and consume the pending merge token from URL (SSO identity merge)\n const url = new URL(window.location.href);\n const pendingMergeToken = url.searchParams.get(\"fmt\") ?? undefined;\n if (pendingMergeToken) {\n url.searchParams.delete(\"fmt\");\n window.history.replaceState({}, \"\", url.toString());\n }\n\n // Merge a raw backend response with SDK metadata and persist to store\n const mergeAndSetConfig = (merchantConfig: MerchantConfigResult) => {\n const merchantId =\n merchantConfig?.merchantId ?? config.metadata.merchantId ?? \"\";\n const domain = merchantConfig?.domain ?? \"\";\n const allowedDomains = merchantConfig?.allowedDomains ?? [];\n const raw = merchantConfig?.sdkConfig;\n\n // Per-field merge: backend wins over SDK static config.\n const mergedAttribution =\n raw?.attribution || config.attribution\n ? { ...config.attribution, ...raw?.attribution }\n : undefined;\n\n sdkConfigStore.setConfig(\n raw\n ? {\n isResolved: true,\n merchantId,\n domain,\n allowedDomains,\n hasRawSdkConfig: true,\n name: raw.name ?? config.metadata.name,\n logoUrl: raw.logoUrl ?? config.metadata.logoUrl,\n homepageLink:\n raw.homepageLink ?? config.metadata.homepageLink,\n lang: raw.lang ?? config.metadata.lang,\n currency: raw.currency ?? config.metadata.currency,\n hidden: raw.hidden,\n css: raw.css,\n translations: raw.translations,\n placements: raw.placements,\n components: raw.components,\n attribution: mergedAttribution,\n }\n : {\n isResolved: true,\n merchantId,\n domain,\n allowedDomains,\n name: config.metadata.name,\n logoUrl: config.metadata.logoUrl,\n homepageLink: config.metadata.homepageLink,\n lang: config.metadata.lang,\n currency: config.metadata.currency,\n attribution: mergedAttribution,\n }\n );\n };\n\n // Send the resolved-config lifecycle event to the iframe.\n // This is where we also update SDK-side OpenPanel global props with\n // `merchantId` + `domain` (first time they are known) so every\n // subsequent SDK event is merchant-attributed. We pass\n // `sdkAnonymousId` through so the listener can join SDK funnels.\n let mergeTokenConsumed = false;\n const sendLifecycleConfig = (resolved: SdkResolvedConfig) => {\n const token = mergeTokenConsumed ? undefined : pendingMergeToken;\n mergeTokenConsumed = true;\n\n const sdkConfig = resolved.hasRawSdkConfig\n ? {\n name: resolved.name,\n logoUrl: resolved.logoUrl,\n homepageLink: resolved.homepageLink,\n lang: resolved.lang,\n currency: resolved.currency,\n hidden: resolved.hidden,\n css: resolved.css,\n translations: resolved.translations,\n placements: resolved.placements,\n attribution: resolved.attribution,\n }\n : resolved.attribution\n ? { attribution: resolved.attribution }\n : undefined;\n\n const sdkAnonymousId = getClientId();\n\n if (openPanel) {\n const current = openPanel.global ?? {};\n openPanel.setGlobalProperties({\n ...current,\n merchant_id: resolved.merchantId,\n domain: resolved.domain ?? \"\",\n });\n }\n\n rpcClient.sendLifecycle({\n clientLifecycle: \"resolved-config\",\n data: {\n merchantId: resolved.merchantId,\n domain: resolved.domain ?? \"\",\n allowedDomains: resolved.allowedDomains ?? [],\n sourceUrl: window.location.href,\n ...(sdkAnonymousId && { sdkAnonymousId }),\n ...(token && { pendingMergeToken: token }),\n ...(sdkConfig && { sdkConfig }),\n },\n });\n };\n\n // SWR: if we have cached data, send it to the iframe immediately\n if (sdkConfigStore.isResolved) {\n sendLifecycleConfig(sdkConfigStore.getConfig());\n contextSent.resolve();\n }\n\n // If a fetch is running (stale/missing cache), wait for fresh data and update\n if (configPromise) {\n const merchantConfig = await configPromise;\n mergeAndSetConfig(merchantConfig);\n sendLifecycleConfig(sdkConfigStore.getConfig());\n contextSent.resolve();\n }\n\n // Push raw CSS if needed\n async function pushCss() {\n const cssLink = config.customizations?.css;\n if (!cssLink) return;\n rpcClient.sendLifecycle({\n clientLifecycle: \"modal-css\" as const,\n data: { cssLink },\n });\n }\n\n // Push i18n if needed\n async function pushI18n() {\n const i18n = config.customizations?.i18n;\n if (!i18n) return;\n rpcClient.sendLifecycle({\n clientLifecycle: \"modal-i18n\" as const,\n data: { i18n },\n });\n }\n\n // Push local backup if needed\n async function pushBackup() {\n if (typeof window === \"undefined\") return;\n const backup = window.localStorage.getItem(BACKUP_KEY);\n if (!backup) return;\n rpcClient.sendLifecycle({\n clientLifecycle: \"restore-backup\" as const,\n data: { backup },\n });\n }\n\n // Inspect each setup result — a failed CSS/i18n/backup push leaves the\n // partner UI in a broken-but-connected state (iframe reports\n // `sdk_iframe_connected`, user sees no modal styles / wrong locale).\n // Surface it as a distinct handshake reason so dashboards can\n // distinguish timeout vs. asset-push failures.\n const results = await Promise.allSettled([\n pushCss(),\n pushI18n(),\n pushBackup(),\n ]);\n const hasFailedAssetPush = results.some((r) => r.status === \"rejected\");\n if (hasFailedAssetPush) {\n openPanel?.track(\"sdk_iframe_handshake_failed\", {\n reason: \"asset_push\",\n });\n }\n}\n","import { jsonDecode } from \"@frak-labs/frame-connector\";\nimport { base64urlDecode } from \"./b64\";\n\n/**\n * Decompress json data\n * @param data\n * @ignore\n */\nexport function decompressJsonFromB64<T>(data: string): T | null {\n return jsonDecode<T>(base64urlDecode(data));\n}\n","/**\n * The keys for each locales\n * @inline\n */\nexport type LocalesKey = keyof typeof locales;\n\n/**\n * Map the currency to the locale\n */\nexport const locales = {\n eur: \"fr-FR\",\n usd: \"en-US\",\n gbp: \"en-GB\",\n} as const;\n","import { locales } from \"../../constants/locales\";\nimport type { Currency } from \"../../types\";\n\n/**\n * Get the supported currency for a given currency\n * @param currency - The currency to use\n * @returns The supported currency\n */\nexport function getSupportedCurrency(currency?: Currency): Currency {\n if (!currency) {\n return \"eur\";\n }\n return currency in locales ? currency : \"eur\";\n}\n","import { type LocalesKey, locales } from \"../../constants/locales\";\nimport type { Currency } from \"../../types\";\n\n/**\n * Get the supported locale for a given currency\n * @param currency - The currency to use\n * @returns The supported locale\n */\nexport function getSupportedLocale(\n currency?: Currency\n): (typeof locales)[LocalesKey] {\n if (!currency) {\n return locales.eur;\n }\n return locales[currency] ?? locales.eur;\n}\n","import type { Currency } from \"../../types\";\nimport { getSupportedCurrency } from \"./getSupportedCurrency\";\nimport { getSupportedLocale } from \"./getSupportedLocale\";\n\n/**\n * Format a numeric amount as a localized currency string\n * @param amount - The raw numeric amount to format\n * @param currency - Optional currency config; defaults to EUR/fr-FR when omitted\n * @returns Localized currency string (e.g. \"1 500 €\", \"$1,500\")\n */\nexport function formatAmount(amount: number, currency?: Currency) {\n // Get the supported locale (e.g. \"fr-FR\")\n const supportedLocale = getSupportedLocale(currency);\n\n // Get the supported currency (e.g. \"eur\")\n const supportedCurrency = getSupportedCurrency(currency);\n\n return amount.toLocaleString(supportedLocale, {\n style: \"currency\",\n currency: supportedCurrency,\n minimumFractionDigits: 0,\n maximumFractionDigits: 2,\n });\n}\n","import type { Currency, TokenAmountType } from \"../../types\";\n\n/**\n * Get the currency amount key for a given currency\n * @param currency - The currency to use\n * @returns The currency amount key\n */\nexport function getCurrencyAmountKey(\n currency?: Currency\n): keyof TokenAmountType {\n if (!currency) {\n return \"eurAmount\";\n }\n return `${currency}Amount` as keyof TokenAmountType;\n}\n","import { createIFrameFrakClient } from \"../clients\";\nimport type { FrakClient, FrakWalletSdkConfig } from \"../types\";\nimport { createIframe, getSupportedCurrency } from \"../utils\";\n\n/**\n * Directly setup the Frak client with an iframe\n * Return when the FrakClient is ready (setup and communication estbalished with the wallet)\n *\n * @param config - The configuration to use for the Frak Wallet SDK\n * @returns a Promise with the Frak Client\n *\n * @example\n * const frakConfig: FrakWalletSdkConfig = {\n * metadata: {\n * name: \"My app title\",\n * },\n * }\n * const client = await setupClient({ config: frakConfig });\n */\nexport async function setupClient({\n config,\n}: {\n config: FrakWalletSdkConfig;\n}): Promise<FrakClient | undefined> {\n // Prepare the config\n const preparedConfig = prepareConfig(config);\n\n // Create our iframe\n const iframe = await createIframe({\n config: preparedConfig,\n });\n\n if (!iframe) {\n console.error(\"Failed to create iframe\");\n return;\n }\n\n // Create our client\n const client = createIFrameFrakClient({\n config: preparedConfig,\n iframe,\n });\n\n // Wait for the client to be all setup\n await client.waitForSetup;\n\n // Wait for the connection to be established\n const waitForConnection = await client.waitForConnection;\n if (!waitForConnection) {\n console.error(\"Failed to connect to client\");\n return;\n }\n\n return client;\n}\n\n/**\n * Prepare the config for the Frak Client\n * @param config - The configuration to use for the Frak Wallet SDK\n * @returns The prepared configuration with the supported currency\n */\nfunction prepareConfig(config: FrakWalletSdkConfig): FrakWalletSdkConfig {\n // Get the supported currency (e.g. \"eur\")\n const supportedCurrency = getSupportedCurrency(config.metadata?.currency);\n\n return {\n ...config,\n metadata: {\n ...config.metadata,\n currency: supportedCurrency,\n },\n };\n}\n","import type { AttributionDefaults, AttributionParams } from \"../types/tracking\";\n\n/**\n * Inputs for {@link mergeAttribution}.\n */\nexport type MergeAttributionInput = {\n /**\n * Per-call attribution override passed to actions like `displaySharingPage`.\n *\n * - `null` explicitly disables attribution (no UTM/ref/via params are added).\n * - `undefined` means \"no per-call override\" — defaults apply if present.\n * - An object (including `{}`) merges field-by-field with defaults.\n */\n perCall: AttributionParams | null | undefined;\n /**\n * Pre-merged merchant-level defaults (backend config > SDK static config).\n * `utm_content` is intentionally absent from this shape.\n */\n defaults?: AttributionDefaults;\n /**\n * Per-product `utm_content` override (from the currently selected\n * `SharingPageProduct`). Takes precedence over `perCall.utmContent`.\n */\n productUtmContent?: string;\n};\n\n/**\n * Merge the three attribution layers into a single {@link AttributionParams}\n * value suitable for `FrakContextManager.update`.\n *\n * Priority per field:\n * 1. `perCall` (wins)\n * 2. `defaults` (merchant-level, backend > SDK static, already pre-merged)\n * 3. Hardcoded fallbacks resolved later by `FrakContextManager`\n *\n * Special rules:\n * - `perCall === null` returns `undefined` (explicit disable: no UTM/ref/via).\n * - `perCall === undefined` (no opinion) yields at least `{}` so `FrakContextManager`\n * applies its hardcoded defaults (utm_source=frak, utm_medium=referral,\n * utm_campaign=<merchantId>, ref=<clientId>, via=frak).\n * - `utm_content` never comes from `defaults`; only `productUtmContent` or\n * `perCall.utmContent` can populate it.\n */\nexport function mergeAttribution({\n perCall,\n defaults,\n productUtmContent,\n}: MergeAttributionInput): AttributionParams | undefined {\n // Explicit disable\n if (perCall === null) return undefined;\n\n const hasPerCall = perCall !== undefined;\n const hasDefaults =\n defaults !== undefined && Object.keys(defaults).length > 0;\n const hasProductUtm =\n productUtmContent !== undefined && productUtmContent !== \"\";\n\n if (!hasPerCall && !hasDefaults && !hasProductUtm) return undefined;\n\n // Per-field merge: per-call wins over defaults.\n const merged: AttributionParams = {\n ...defaults,\n ...(perCall ?? {}),\n };\n\n // utm_content priority: productUtmContent > perCall.utmContent; never from defaults.\n const utmContent = productUtmContent ?? perCall?.utmContent;\n if (utmContent !== undefined && utmContent !== \"\") {\n merged.utmContent = utmContent;\n } else {\n delete merged.utmContent;\n }\n\n return merged;\n}\n"],"mappings":"qPAGA,MAAa,EAAa,sBAUb,EAAA,gBCCb,SAAgB,EACZ,EACA,EACI,CACJ,GAAI,OAAO,OAAW,IAClB,OAIJ,IAAM,EAAM,IAAI,IAAI,OAAO,SAAS,IAAI,EAClC,EAAgB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CAAQ,EAAE,OAAS,EAI7D,GAAI,CAAC,GAAc,CAAC,GAAe,EAF/B,IAAsB,IAAA,IAAa,IAAsB,IAEV,OAGnD,IAAM,EAA4B,CAC9B,GAAG,EACH,GAAI,GAAW,CAAC,CACpB,EAGM,EAAa,GAAqB,GAAS,WAOjD,OANI,IAAe,IAAA,IAAa,IAAe,GAC3C,EAAO,WAAa,EAEpB,OAAO,EAAO,WAGX,CACX"}
|
package/package.json
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"url": "https://twitter.com/QNivelais"
|
|
12
12
|
}
|
|
13
13
|
],
|
|
14
|
-
"version": "1.1.
|
|
14
|
+
"version": "1.1.5-beta.727c2f3f",
|
|
15
15
|
"description": "Core SDK of the Frak wallet, low level library to interact directly with the frak ecosystem.",
|
|
16
16
|
"repository": {
|
|
17
17
|
"url": "https://github.com/frak-id/wallet",
|
|
@@ -37,10 +37,10 @@
|
|
|
37
37
|
"/cdn",
|
|
38
38
|
"/src"
|
|
39
39
|
],
|
|
40
|
-
"browser": "./cdn/bundle.js",
|
|
41
40
|
"exports": {
|
|
42
41
|
".": {
|
|
43
42
|
"development": "./src/index.ts",
|
|
43
|
+
"production": "./src/index.ts",
|
|
44
44
|
"import": {
|
|
45
45
|
"types": "./dist/index.d.ts",
|
|
46
46
|
"default": "./dist/index.js"
|
|
@@ -52,6 +52,7 @@
|
|
|
52
52
|
},
|
|
53
53
|
"./actions": {
|
|
54
54
|
"development": "./src/actions/index.ts",
|
|
55
|
+
"production": "./src/actions/index.ts",
|
|
55
56
|
"import": {
|
|
56
57
|
"types": "./dist/actions.d.ts",
|
|
57
58
|
"default": "./dist/actions.js"
|
|
@@ -91,7 +92,7 @@
|
|
|
91
92
|
"viem": "^2.x"
|
|
92
93
|
},
|
|
93
94
|
"dependencies": {
|
|
94
|
-
"@frak-labs/frame-connector": "0.2.0",
|
|
95
|
+
"@frak-labs/frame-connector": "0.2.0-beta.727c2f3f",
|
|
95
96
|
"@openpanel/web": "^1.4.1"
|
|
96
97
|
},
|
|
97
98
|
"devDependencies": {
|
|
@@ -105,9 +105,9 @@ describe("processReferral", () => {
|
|
|
105
105
|
mockClient,
|
|
106
106
|
"user_referred_started",
|
|
107
107
|
{
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
108
|
+
referrer_client_id: "referrer-client-id",
|
|
109
|
+
referrer_wallet: undefined,
|
|
110
|
+
wallet_status: "connected",
|
|
111
111
|
}
|
|
112
112
|
);
|
|
113
113
|
|
|
@@ -235,7 +235,7 @@ describe("processReferral", () => {
|
|
|
235
235
|
"user_referred_started",
|
|
236
236
|
{
|
|
237
237
|
referrer: "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd",
|
|
238
|
-
|
|
238
|
+
wallet_status: "connected",
|
|
239
239
|
}
|
|
240
240
|
);
|
|
241
241
|
});
|
|
@@ -53,9 +53,9 @@ function trackArrivalIfValid(
|
|
|
53
53
|
): boolean {
|
|
54
54
|
if (isV2Context(frakContext)) {
|
|
55
55
|
trackEvent(client, "user_referred_started", {
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
56
|
+
referrer_client_id: frakContext.c,
|
|
57
|
+
referrer_wallet: frakContext.w,
|
|
58
|
+
wallet_status: walletStatus?.key,
|
|
59
59
|
});
|
|
60
60
|
sendInteraction(client, {
|
|
61
61
|
type: "arrival",
|
|
@@ -70,7 +70,7 @@ function trackArrivalIfValid(
|
|
|
70
70
|
if (isV1Context(frakContext)) {
|
|
71
71
|
trackEvent(client, "user_referred_started", {
|
|
72
72
|
referrer: frakContext.r,
|
|
73
|
-
|
|
73
|
+
wallet_status: walletStatus?.key,
|
|
74
74
|
});
|
|
75
75
|
sendInteraction(client, {
|
|
76
76
|
type: "arrival",
|
|
@@ -153,11 +153,11 @@ export function createIFrameFrakClient({
|
|
|
153
153
|
if (!payload?.properties) return true;
|
|
154
154
|
|
|
155
155
|
// Check if we we got the properties once initialized
|
|
156
|
-
if (!("
|
|
156
|
+
if (!("sdk_version" in payload.properties)) {
|
|
157
157
|
payload.properties = {
|
|
158
158
|
...payload.properties,
|
|
159
|
-
|
|
160
|
-
|
|
159
|
+
sdk_version: process.env.SDK_VERSION,
|
|
160
|
+
user_anonymous_client_id: getClientId(),
|
|
161
161
|
};
|
|
162
162
|
}
|
|
163
163
|
|
|
@@ -165,12 +165,12 @@ export function createIFrameFrakClient({
|
|
|
165
165
|
},
|
|
166
166
|
});
|
|
167
167
|
openPanel.setGlobalProperties({
|
|
168
|
-
|
|
169
|
-
|
|
168
|
+
sdk_version: process.env.SDK_VERSION,
|
|
169
|
+
user_anonymous_client_id: getClientId(),
|
|
170
170
|
});
|
|
171
171
|
openPanel.init();
|
|
172
172
|
openPanel.track("sdk_initialized", {
|
|
173
|
-
|
|
173
|
+
sdk_version: process.env.SDK_VERSION,
|
|
174
174
|
});
|
|
175
175
|
|
|
176
176
|
// Race the connection against the heartbeat timeout so we can
|
|
@@ -398,7 +398,7 @@ async function postConnectionSetup({
|
|
|
398
398
|
const current = openPanel.global ?? {};
|
|
399
399
|
openPanel.setGlobalProperties({
|
|
400
400
|
...current,
|
|
401
|
-
|
|
401
|
+
merchant_id: resolved.merchantId,
|
|
402
402
|
domain: resolved.domain ?? "",
|
|
403
403
|
});
|
|
404
404
|
}
|
|
@@ -5,29 +5,13 @@ import {
|
|
|
5
5
|
isFrakDeepLink,
|
|
6
6
|
triggerDeepLinkWithFallback,
|
|
7
7
|
} from "../../utils/browser/deepLinkWithFallback";
|
|
8
|
+
import { isInAppBrowser, isIOS } from "../../utils/browser/inAppBrowser";
|
|
8
9
|
import { changeIframeVisibility } from "../../utils/iframe/iframeHelper";
|
|
9
10
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
*/
|
|
15
|
-
const isIOSInAppBrowser = (() => {
|
|
16
|
-
if (typeof navigator === "undefined") return false;
|
|
17
|
-
const ua = navigator.userAgent;
|
|
18
|
-
// Standard iOS or iPadOS 13+ (reports as Macintosh with touch)
|
|
19
|
-
const isIOS =
|
|
20
|
-
/iPhone|iPad|iPod/i.test(ua) ||
|
|
21
|
-
(/Macintosh/i.test(ua) && navigator.maxTouchPoints > 1);
|
|
22
|
-
if (!isIOS) return false;
|
|
23
|
-
const lower = ua.toLowerCase();
|
|
24
|
-
return (
|
|
25
|
-
lower.includes("instagram") ||
|
|
26
|
-
lower.includes("fban") ||
|
|
27
|
-
lower.includes("fbav") ||
|
|
28
|
-
lower.includes("facebook")
|
|
29
|
-
);
|
|
30
|
-
})();
|
|
11
|
+
// iOS in-app browsers (Instagram, Facebook) silently swallow server-side 302
|
|
12
|
+
// redirects to custom URL schemes (x-safari-https://) in WKWebView; direct
|
|
13
|
+
// window.location.href assignment works.
|
|
14
|
+
const isIOSInAppBrowser = isIOS && isInAppBrowser;
|
|
31
15
|
|
|
32
16
|
/** @ignore */
|
|
33
17
|
export type IframeLifecycleManager = {
|