@growth-rail/react-native 2.0.2 → 2.0.3
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/CHANGELOG.md +6 -0
- package/dist/index.d.mts +3 -5
- package/dist/index.d.ts +3 -5
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
package/dist/index.d.mts
CHANGED
|
@@ -4,6 +4,7 @@ type GrowthRailOptions = {
|
|
|
4
4
|
projectSecretKey: string;
|
|
5
5
|
cookieDomain?: string;
|
|
6
6
|
autoPageTrack?: boolean;
|
|
7
|
+
appearance?: 'light' | 'dark';
|
|
7
8
|
};
|
|
8
9
|
type AppUserType = {
|
|
9
10
|
attributes: Record<string, unknown>;
|
|
@@ -24,19 +25,16 @@ type TrackReferralResponse = {
|
|
|
24
25
|
};
|
|
25
26
|
type TriggerButtonPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
|
|
26
27
|
type ReferrerTriggerButton = {
|
|
27
|
-
show: boolean;
|
|
28
28
|
position: TriggerButtonPosition;
|
|
29
|
-
displayMode: 'floating' | 'edge';
|
|
29
|
+
displayMode: 'floating' | 'edge' | 'none';
|
|
30
30
|
};
|
|
31
31
|
type ReferrerModalOptions = {
|
|
32
32
|
title: string;
|
|
33
33
|
description: string;
|
|
34
34
|
componentType: 'modal' | 'drawer';
|
|
35
|
+
appearance?: 'light' | 'dark';
|
|
35
36
|
theme: {
|
|
36
37
|
primaryColor: string;
|
|
37
|
-
tintColor: string;
|
|
38
|
-
tintAlpha: number;
|
|
39
|
-
backgroundColor: string;
|
|
40
38
|
};
|
|
41
39
|
};
|
|
42
40
|
interface ReferrerExperience {
|
package/dist/index.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ type GrowthRailOptions = {
|
|
|
4
4
|
projectSecretKey: string;
|
|
5
5
|
cookieDomain?: string;
|
|
6
6
|
autoPageTrack?: boolean;
|
|
7
|
+
appearance?: 'light' | 'dark';
|
|
7
8
|
};
|
|
8
9
|
type AppUserType = {
|
|
9
10
|
attributes: Record<string, unknown>;
|
|
@@ -24,19 +25,16 @@ type TrackReferralResponse = {
|
|
|
24
25
|
};
|
|
25
26
|
type TriggerButtonPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
|
|
26
27
|
type ReferrerTriggerButton = {
|
|
27
|
-
show: boolean;
|
|
28
28
|
position: TriggerButtonPosition;
|
|
29
|
-
displayMode: 'floating' | 'edge';
|
|
29
|
+
displayMode: 'floating' | 'edge' | 'none';
|
|
30
30
|
};
|
|
31
31
|
type ReferrerModalOptions = {
|
|
32
32
|
title: string;
|
|
33
33
|
description: string;
|
|
34
34
|
componentType: 'modal' | 'drawer';
|
|
35
|
+
appearance?: 'light' | 'dark';
|
|
35
36
|
theme: {
|
|
36
37
|
primaryColor: string;
|
|
37
|
-
tintColor: string;
|
|
38
|
-
tintAlpha: number;
|
|
39
|
-
backgroundColor: string;
|
|
40
38
|
};
|
|
41
39
|
};
|
|
42
40
|
interface ReferrerExperience {
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Te=Object.create;var Y=Object.defineProperty;var xe=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var ve=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var Se=(i,e,t)=>e in i?Y(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var De=(i,e)=>{for(var t in e)Y(i,t,{get:e[t],enumerable:!0})},he=(i,e,t,c)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Le(e))!Ie.call(i,a)&&a!==t&&Y(i,a,{get:()=>e[a],enumerable:!(c=xe(e,a))||c.enumerable});return i};var _=(i,e,t)=>(t=i!=null?Te(ve(i)):{},he(e||!i||!i.__esModule?Y(t,"default",{value:i,enumerable:!0}):t,i)),Be=i=>he(Y({},"__esModule",{value:!0}),i);var ee=(i,e,t)=>Se(i,typeof e!="symbol"?e+"":e,t);var Ue={};De(Ue,{GrowthRailProvider:()=>ye,ReferralDashboard:()=>oe,TriggerButton:()=>ne,useGrowthRail:()=>Re});module.exports=Be(Ue);var s=_(require("react")),T=require("react-native"),me=_(require("react-native-play-install-referrer"));var Oe="[GrowthRail]",f={log(i,e,t,c){let a=`${Oe} [${e}] ${t}`;switch(i){case"error":console.error(a,c||"");break;case"warn":console.warn(a,c||"");break;default:console.log(a,c||"");break}}};var te=class{constructor(e){ee(this,"baseUrl");ee(this,"projectSecretKey");ee(this,"_debug",!1);let t=typeof process<"u"&&process.env?.ENV_BASE_URL;this.baseUrl=t||"https://api.growthrail.dev",this.projectSecretKey=e.projectSecretKey}setDebug(e){this._debug=e}async request(e,t,c){let a={"Content-Type":"application/json","X-GrowthRail-ProjectSecret":this.projectSecretKey,Origin:this.baseUrl},y=Date.now();this._debug&&f.log("api","APIClient",`${t} ${e}`,{method:t,endpoint:e,body:c??null});try{let h=await fetch(`${this.baseUrl}${e}`,{method:t,headers:a,body:c?JSON.stringify(c):void 0}),b=Date.now()-y;if(!h.ok){let l="";try{l=await h.text()}catch{}let R=`GrowthRail API Error ${h.status} (${this.baseUrl}${e}): ${h.statusText} - ${l}`;throw this._debug&&f.log("api","APIClient",`\u2717 ${t} ${e}`,{method:t,endpoint:e,status:h.status,duration:b,error:l}),new Error(R)}return this._debug&&f.log("api","APIClient",`\u2713 ${t} ${e}`,{method:t,endpoint:e,status:h.status,duration:b}),h.json()}catch(h){let b=Date.now()-y;throw this._debug&&f.log("api","APIClient",`\u2717 ${t} ${e} \u2014 Network error`,{method:t,endpoint:e,duration:b,error:String(h)}),console.error("GrowthRail SDK Error:",h),h}}async getNewUserExperience(){return this.request("/api/v1/sdk/new-user-experience","POST")}async initAppUser(e){return this.request("/api/v1/sdk/init-app-user","POST",{clientProvidedId:e})}async trackReferral(e,t){return this.request("/api/v1/sdk/track-referral","POST",{referralCode:e,rewardEventName:t})}async trackRewardEvent(e,t,c){return this.request("/api/v1/sdk/track-reward-event","POST",{refereeId:e,referralTrackingId:t,eventName:c})}async checkDeferredDeepLink(e){return this.request("/api/v1/sdk/match-link","POST",{fingerprint:e})}};var J=_(require("@react-native-async-storage/async-storage")),re={TRACKED_REFERRAL:"growth-rail-tracked-referral",IS_FIRST_LAUNCH:"growth-rail-is-first-launch"},O=class{static async setTrackedReferral(e){await J.default.setItem(re.TRACKED_REFERRAL,e)}static async getTrackedReferral(){return await J.default.getItem(re.TRACKED_REFERRAL)}static async isFirstLaunch(){return await J.default.getItem(re.IS_FIRST_LAUNCH)===null?(await J.default.setItem(re.IS_FIRST_LAUNCH,"false"),!0):!1}};var o=_(require("react")),r=require("react-native");var{width:pe,height:fe}=r.Dimensions.get("window"),oe=({visible:i,options:e,onClose:t})=>{let c=ie(),[a,y]=(0,o.useState)(null),[h,b]=(0,o.useState)(!1),[l,R]=(0,o.useState)(!1),u=(0,o.useRef)(new r.Animated.Value(0)).current,V=(0,o.useRef)(new r.Animated.Value(0)).current,I=e?.title||"Invite Friends & Earn",P=e?.theme?.primaryColor||"#2563eb",K=e?.theme?.backgroundColor||"#ffffff",q=e?.theme?.tintColor||"#000000",ae=e?.theme?.tintAlpha??.5,S=(e?.componentType||"modal")==="drawer",D=e?.position||"bottom-right",ue="#111827",X="#6b7280";(0,o.useEffect)(()=>{i?(a||se(),r.Animated.parallel([r.Animated.timing(V,{toValue:1,duration:300,useNativeDriver:!0}),r.Animated.spring(u,{toValue:1,useNativeDriver:!0,tension:50,friction:8})]).start()):(u.setValue(0),V.setValue(0))},[i]);let W=()=>{r.Animated.parallel([r.Animated.timing(V,{toValue:0,duration:250,useNativeDriver:!0}),r.Animated.timing(u,{toValue:0,duration:250,useNativeDriver:!0})]).start(()=>{t()})},se=async()=>{b(!0);try{if(c.isUserReady){let F=await c.getReferralLink();y(F||null)}}catch(F){console.error("GrowthRail: Failed to load referral link",F)}finally{b(!1)}},le=()=>{a&&(r.Clipboard.setString(a),R(!0),setTimeout(()=>R(!1),2e3))},A=F=>{if(!a)return;let U="",$=encodeURIComponent(a),E=encodeURIComponent("Check this out!");switch(F){case"twitter":U=`https://twitter.com/intent/tweet?url=${$}&text=${E}`;break;case"facebook":U=`https://www.facebook.com/sharer/sharer.php?u=${$}`;break;case"linkedin":U=`https://www.linkedin.com/sharing/share-offsite/?url=${$}`;break;case"whatsapp":U=`whatsapp://send?text=${E}%20${$}`;break;case"email":U=`mailto:?subject=Check this out&body=${E}%20${$}`;break}U&&r.Linking.openURL(U).catch(()=>{})},N=()=>q||"#000000",z=[];S?D.includes("right")?z=[{translateX:u.interpolate({inputRange:[0,1],outputRange:[pe,0]})}]:D.includes("left")?z=[{translateX:u.interpolate({inputRange:[0,1],outputRange:[-pe,0]})}]:z=[{translateY:u.interpolate({inputRange:[0,1],outputRange:[fe,0]})}]:z=[{scale:u.interpolate({inputRange:[0,1],outputRange:[.9,1]})},{translateY:u.interpolate({inputRange:[0,1],outputRange:[20,0]})}];let M=D.includes("top"),G=D.includes("right"),B=D.includes("left"),ce=S?{position:"absolute",...M?{top:100}:{bottom:100},...G?{right:0}:B?{left:0}:{left:0,right:0},width:G||B?"85%":"100%",maxHeight:G||B?fe-200:"80%"}:{};return o.default.createElement(r.Modal,{visible:i,transparent:!0,animationType:"none",onRequestClose:W},o.default.createElement(r.View,{style:n.fullScreen},o.default.createElement(r.Animated.View,{style:[n.overlay,{backgroundColor:N(),opacity:V.interpolate({inputRange:[0,1],outputRange:[0,ae]})}]},o.default.createElement(r.TouchableOpacity,{style:n.fullScreen,activeOpacity:1,onPress:W})),o.default.createElement(r.Animated.View,{style:[S?ce:n.centeredModalContainer,{backgroundColor:K,transform:z},S&&G&&{borderTopLeftRadius:24,borderBottomLeftRadius:24},S&&B&&{borderTopRightRadius:24,borderBottomRightRadius:24},S&&!G&&!B&&D.includes("bottom")&&{borderTopLeftRadius:24,borderTopRightRadius:24},S&&!G&&!B&&D.includes("top")&&{borderBottomLeftRadius:24,borderBottomRightRadius:24},!S&&{borderRadius:24,opacity:u}]},o.default.createElement(r.View,{style:n.contentWrapper},S&&!G&&!B&&D.includes("bottom")&&o.default.createElement(r.View,{style:n.drawerHandle}),o.default.createElement(r.TouchableOpacity,{style:n.closeBtn,onPress:W},o.default.createElement(r.Text,{style:n.closeIcon},"\u2715")),o.default.createElement(r.ScrollView,{contentContainerStyle:n.scrollContent,showsVerticalScrollIndicator:!1},o.default.createElement(r.View,{style:n.header},o.default.createElement(r.View,{style:n.iconLgContainer},o.default.createElement(r.View,{style:n.bowContainerLg},o.default.createElement(r.View,{style:[n.bowLoopLg,n.bowLeftLg,{borderColor:P}]}),o.default.createElement(r.View,{style:[n.bowLoopLg,n.bowRightLg,{borderColor:P}]})),o.default.createElement(r.View,{style:[n.giftLidLg,{backgroundColor:P}]}),o.default.createElement(r.View,{style:[n.giftBodyLg,{borderColor:P}]},o.default.createElement(r.View,{style:[n.ribbonVerticalLg,{backgroundColor:"#fff",opacity:.3}]}))),o.default.createElement(r.Text,{style:[n.title,{color:ue}]},I),o.default.createElement(r.Text,{style:[n.subtitle,{color:X}]},e?.description||"Share your unique link and earn rewards for every friend who signs up.")),c.isUserReady?h?o.default.createElement(r.ActivityIndicator,{size:"large",color:P,style:n.loader}):o.default.createElement(r.View,{style:n.mainContent},o.default.createElement(r.Text,{style:n.label},"YOUR UNIQUE LINK"),o.default.createElement(r.View,{style:n.inputGroup},o.default.createElement(r.Text,{numberOfLines:1,style:n.input},a||"Initializing..."),o.default.createElement(r.TouchableOpacity,{style:[n.copyBtn,{backgroundColor:l?"#10b981":P}],onPress:le},o.default.createElement(r.Text,{style:n.copyBtnText},l?"Copied!":"Copy"))),o.default.createElement(r.View,{style:n.shareLabelContainer},o.default.createElement(r.View,{style:n.divider}),o.default.createElement(r.Text,{style:n.shareLabel},"Share via"),o.default.createElement(r.View,{style:n.divider})),o.default.createElement(r.View,{style:n.socialContainer},o.default.createElement(Q,{platform:"twitter",color:"#000000",onPress:()=>A("twitter"),icon:"\u{1D54F}"}),o.default.createElement(Q,{platform:"facebook",color:"#1877F2",onPress:()=>A("facebook"),icon:"f"}),o.default.createElement(Q,{platform:"linkedin",color:"#0A66C2",onPress:()=>A("linkedin"),icon:"in"}),o.default.createElement(Q,{platform:"whatsapp",color:"#25D366",onPress:()=>A("whatsapp"),icon:"W"}),o.default.createElement(Q,{platform:"email",color:"#888888",onPress:()=>A("email"),icon:"\u2709"}))):o.default.createElement(r.View,{style:n.loadingBox},o.default.createElement(r.Text,{style:{color:X,textAlign:"center"}},"Please log in to view your referral dashboard.")),o.default.createElement(r.View,{style:n.footer},o.default.createElement(r.Text,{style:n.poweredBy},"Powered by ",o.default.createElement(r.Text,{style:n.brand,onPress:()=>r.Linking.openURL("https://growthrail.com")},"Growth Rail"))))))))},Q=({color:i,onPress:e,icon:t})=>o.default.createElement(r.TouchableOpacity,{style:[n.socialBtn,{borderColor:"#e5e7eb"}],onPress:e},o.default.createElement(r.Text,{style:[n.socialIcon,{color:i}]},t)),n=r.StyleSheet.create({fullScreen:{flex:1},overlay:{...r.StyleSheet.absoluteFillObject},centeredModalContainer:{width:"90%",maxWidth:400,alignSelf:"center",marginTop:fe*.15,overflow:"hidden",shadowColor:"#000",shadowOffset:{width:0,height:20},shadowOpacity:.25,shadowRadius:30,elevation:20},contentWrapper:{paddingTop:r.Platform.OS==="ios"?20:0},drawerHandle:{width:40,height:4,backgroundColor:"#e5e7eb",borderRadius:2,alignSelf:"center",marginTop:12},scrollContent:{padding:32,alignItems:"center"},closeBtn:{position:"absolute",top:20,right:20,zIndex:10,width:32,height:32,borderRadius:16,backgroundColor:"#f3f4f6",justifyContent:"center",alignItems:"center"},closeIcon:{fontSize:14,color:"#9ca3af"},header:{alignItems:"center",marginBottom:28,width:"100%"},socialIcon:{fontSize:18,fontWeight:"bold"},title:{fontSize:22,fontWeight:"700",letterSpacing:-.5,marginBottom:8,textAlign:"center"},subtitle:{fontSize:14,lineHeight:20,textAlign:"center",paddingHorizontal:10},loadingBox:{padding:16,backgroundColor:"#f9fafb",borderRadius:12,width:"100%",alignItems:"center",borderWidth:1,borderColor:"#e5e7eb",marginTop:20},loader:{marginVertical:20},mainContent:{width:"100%"},label:{fontSize:12,fontWeight:"600",color:"#6b7280",marginBottom:8,letterSpacing:.5},inputGroup:{flexDirection:"row",alignItems:"center",backgroundColor:"#f9fafb",borderWidth:1,borderColor:"#e5e7eb",borderRadius:12,padding:6,marginBottom:24},input:{flex:1,paddingHorizontal:12,fontSize:14,color:"#111827",fontFamily:r.Platform.OS==="ios"?"Menlo":"monospace"},copyBtn:{paddingVertical:8,paddingHorizontal:16,borderRadius:8,justifyContent:"center",alignItems:"center"},copyBtnText:{color:"#fff",fontSize:13,fontWeight:"600"},shareLabelContainer:{flexDirection:"row",alignItems:"center",marginBottom:16,marginTop:8},divider:{flex:1,height:1,backgroundColor:"#e5e7eb"},shareLabel:{marginHorizontal:12,fontSize:13,fontWeight:"500",color:"#6b7280"},socialContainer:{flexDirection:"row",justifyContent:"center",gap:12},socialBtn:{width:44,height:44,borderRadius:22,backgroundColor:"#fff",borderWidth:1,justifyContent:"center",alignItems:"center"},iconLgContainer:{width:60,height:60,justifyContent:"center",alignItems:"center",marginBottom:16},bowContainerLg:{flexDirection:"row",position:"absolute",top:2,zIndex:2},bowLoopLg:{width:20,height:16,borderWidth:3,borderColor:"#e5e7eb",borderRadius:10},bowLeftLg:{marginRight:-2,transform:[{rotate:"-15deg"}]},bowRightLg:{marginLeft:-2,transform:[{rotate:"15deg"}]},giftLidLg:{width:44,height:10,backgroundColor:"#f3f4f6",borderRadius:2,marginTop:12,zIndex:3},giftBodyLg:{width:36,height:24,borderWidth:3,borderTopWidth:0,borderBottomLeftRadius:4,borderBottomRightRadius:4,justifyContent:"center",alignItems:"center",marginTop:-2},ribbonVerticalLg:{width:4,height:"100%",opacity:.1},footer:{marginTop:32,alignItems:"center"},poweredBy:{fontSize:11,color:"#9ca3af"},brand:{fontWeight:"600",textDecorationLine:"underline"}});var C=_(require("react")),w=require("react-native"),ne=({onPress:i,options:e})=>{let t=e?.modal?.theme?.primaryColor||"#2563eb",c=e?.trigger?.position||"bottom-right",y=(e?.trigger?.displayMode||"floating")==="edge",h=c.includes("right"),b=c.includes("top"),l=(0,C.useRef)(new w.Animated.Value(-1)).current;(0,C.useEffect)(()=>{let I=()=>{l.setValue(-1),w.Animated.timing(l,{toValue:2,duration:3e3,easing:w.Easing.linear,useNativeDriver:!0}).start(()=>{setTimeout(I,1e3)})};I()},[]);let R=l.interpolate({inputRange:[-1,2],outputRange:y?[-50,100]:[-60,120]}),u={"bottom-right":{bottom:100,right:0},"bottom-left":{bottom:100,left:0},"top-right":{top:100,right:0},"top-left":{top:100,left:0}};y||(u["bottom-right"]={bottom:30,right:20},u["bottom-left"]={bottom:30,left:20},u["top-right"]={top:60,right:20},u["top-left"]={top:60,left:20});let V=()=>C.default.createElement(w.View,{style:k.iconContainer},C.default.createElement(w.View,{style:k.bowContainer},C.default.createElement(w.View,{style:[k.bowLoop,k.bowLeft]}),C.default.createElement(w.View,{style:[k.bowLoop,k.bowRight]})),C.default.createElement(w.View,{style:k.giftLid}),C.default.createElement(w.View,{style:k.giftBody},C.default.createElement(w.View,{style:k.ribbonVertical})));return C.default.createElement(w.TouchableOpacity,{style:[y?k.edgeButton:k.floatingButton,{backgroundColor:t},u[c],y&&(h?k.edgeRight:k.edgeLeft)],onPress:i,activeOpacity:.9},C.default.createElement(w.View,{style:k.content},V()),C.default.createElement(w.Animated.View,{style:[k.shimmer,{transform:[{translateX:R},{skewX:"-15deg"}]}]}))},k=w.StyleSheet.create({floatingButton:{position:"absolute",width:60,height:60,borderRadius:30,justifyContent:"center",alignItems:"center",overflow:"hidden",shadowColor:"#000",shadowOffset:{width:0,height:8},shadowOpacity:.2,shadowRadius:12,elevation:8,zIndex:2147483646},edgeButton:{position:"absolute",width:50,height:50,justifyContent:"center",alignItems:"center",overflow:"hidden",shadowColor:"#000",shadowOffset:{width:0,height:4},shadowOpacity:.1,shadowRadius:8,elevation:4,zIndex:2147483646},edgeRight:{borderTopLeftRadius:8,borderBottomLeftRadius:8,paddingLeft:4},edgeLeft:{borderTopRightRadius:8,borderBottomRightRadius:8,paddingRight:4},content:{justifyContent:"center",alignItems:"center"},iconContainer:{width:28,height:28,justifyContent:"center",alignItems:"center"},bowContainer:{flexDirection:"row",position:"absolute",top:0,zIndex:2},bowLoop:{width:10,height:8,borderWidth:2,borderColor:"#fff",borderRadius:5},bowLeft:{marginRight:-1,transform:[{rotate:"-15deg"}]},bowRight:{marginLeft:-1,transform:[{rotate:"15deg"}]},giftLid:{width:22,height:5,backgroundColor:"#fff",borderRadius:1,marginTop:6,zIndex:3},giftBody:{width:18,height:12,borderWidth:2,borderColor:"#fff",borderTopWidth:0,borderBottomLeftRadius:2,borderBottomRightRadius:2,justifyContent:"center",alignItems:"center",marginTop:-1},ribbonVertical:{width:2,height:"100%",backgroundColor:"#fff",opacity:.8},shimmer:{position:"absolute",top:0,left:0,width:50,height:"100%",backgroundColor:"rgba(255, 255, 255, 0.25)"}});var v=_(require("react")),m=require("react-native"),{width:Ve}=m.Dimensions.get("window"),we=({visible:i,options:e,onClose:t})=>{let c=(0,v.useRef)(new m.Animated.Value(0)).current,[a,y]=(0,v.useState)(i),h=e.position.includes("bottom")?"bottom":"top",b=e.position.includes("left")?"left":e.position.includes("right")?"right":"center";if((0,v.useEffect)(()=>{i?(y(!0),m.Animated.spring(c,{toValue:1,useNativeDriver:!0,tension:50,friction:8}).start()):m.Animated.timing(c,{toValue:0,duration:250,useNativeDriver:!0}).start(()=>{y(!1)})},[i]),!a)return null;let l=c.interpolate({inputRange:[0,1],outputRange:[h==="top"?-100:100,0]}),R=c.interpolate({inputRange:[0,1],outputRange:[0,1]}),u={position:"absolute",[h]:m.Platform.OS==="ios"?60:40,zIndex:9999};return b==="center"?(u.left=20,u.right=20,u.alignItems="center"):u[b]=20,v.default.createElement(m.Animated.View,{style:[u,{transform:[{translateY:l}],opacity:R}]},v.default.createElement(m.View,{style:[Z.banner,{backgroundColor:e.themeColor||"#2563eb"}]},v.default.createElement(m.Text,{style:Z.icon},"\u{1F381}"),v.default.createElement(m.Text,{style:Z.text},e.text),v.default.createElement(m.TouchableOpacity,{onPress:t,style:Z.closeBtn},v.default.createElement(m.Text,{style:Z.closeIcon},"\u2715"))))},Z=m.StyleSheet.create({banner:{flexDirection:"row",alignItems:"center",padding:12,paddingHorizontal:16,borderRadius:12,shadowColor:"#000",shadowOffset:{width:0,height:4},shadowOpacity:.15,shadowRadius:10,elevation:5,maxWidth:Ve-40},icon:{fontSize:18,marginRight:10},text:{color:"#fff",fontSize:14,fontWeight:"600",flex:1},closeBtn:{marginLeft:10,padding:4},closeIcon:{color:"rgba(255, 255, 255, 0.8)",fontSize:14,fontWeight:"bold"}});var be=(0,s.createContext)(void 0),ye=({children:i,userId:e,debug:t=!1,...c})=>{let[a,y]=(0,s.useState)(!1),[h,b]=(0,s.useState)(!1),[l,R]=(0,s.useState)(null),u=(0,s.useRef)(new te(c)),V=(0,s.useRef)(!1),I=(0,s.useRef)(null),[P,K]=(0,s.useState)(!1),[q,ae]=(0,s.useState)(),[ge,S]=(0,s.useState)(!1),[D,ue]=(0,s.useState)(),[X,W]=(0,s.useState)(!1),[se,le]=(0,s.useState)();(0,s.useEffect)(()=>{u.current.setDebug(t),t&&f.log("info","Provider","Debug mode enabled")},[t]);let A=(0,s.useCallback)(()=>{let{width:g,height:d}=T.Dimensions.get("window"),p=Intl.DateTimeFormat().resolvedOptions().locale,L=T.PixelRatio.get(),x,j;if(T.Platform.OS==="android"){let de=T.Platform.constants;x=de.Model,j=de.Brand||de.Manufacturer}return{os:T.Platform.OS,platform:T.Platform.OS,osVersion:String(T.Platform.Version),screenWidth:g,screenHeight:d,timezoneOffsetInMinutes:String(new Date().getTimezoneOffset()),locale:p,language:p,deviceModel:x,deviceBrand:j,pixelRatio:L}},[]),N=(0,s.useCallback)(async(g,d)=>{t&&f.log("info","Referral",`Tracking referral code: ${g}`,{referralCode:g,rewardEventName:d});let p=await u.current.trackReferral(g,d);return await O.setTrackedReferral(p.referralTrackingId),t&&f.log("success","Referral",`Referral tracked \u2192 ${p.referralTrackingId}`,p),p},[t]),z=(0,s.useCallback)(async g=>{try{t&&f.log("info","DeepLink",`Received deep link: ${g}`);let d=g.match(/[?&]referralCode=([^&]+)/);d&&(console.log("GrowthRail: Tracking referral from deep link",d[1]),t&&f.log("info","DeepLink",`Found referral code in deep link: ${d[1]}`),await N(d[1]))}catch(d){console.warn("GrowthRail: Error handling deep link",d),t&&f.log("error","DeepLink","Deep link handling failed",{error:String(d)})}},[N,t]),M=(0,s.useCallback)(async()=>{try{t&&f.log("info","Deferred","Checking deferred deep link via fingerprint");let g=A(),{referralTrackingId:d}=await u.current.checkDeferredDeepLink(g);d?(console.log("GrowthRail: Found deferred referral via fingerprinting",d),t&&f.log("success","Deferred",`Deferred referral matched \u2192 ${d}`),await O.setTrackedReferral(d)):t&&f.log("info","Deferred","No deferred referral match found")}catch(g){console.warn("GrowthRail: Fingerprint check failed",g),t&&f.log("error","Deferred","Fingerprint check failed",{error:String(g)})}},[A,t]),G=(0,s.useCallback)(()=>new Promise(g=>{me.default.getInstallReferrerInfo(async(d,p)=>{if(!p&&d&&d.installReferrer)try{let x=decodeURIComponent(d.installReferrer).match(/[?&]referralCode=([^&]+)/);if(x){let{referralTrackingId:j}=await N(x[1]);await O.setTrackedReferral(j),console.log("GrowthRail: Tracked referral via Install Referrer")}}catch(L){console.warn("GrowthRail: Failed to process install referrer",L)}else await M();g()})}),[N,M]),B=(0,s.useCallback)(async g=>{if(l?.id===g&&h)return t&&f.log("info","User",`User ${g} already initialized, skipping`),l;t&&f.log("info","User",`Initializing user: ${g}`);let d=(async()=>{try{let p=await u.current.initAppUser(g),L={...p,id:g};return R(L),b(!0),t&&f.log("success","User",`User initialized: ${g}`,{referralCode:p.referralCode,referralLink:p.referralLink}),p.referrerExperience?.trigger?.show&&(S(!0),t&&f.log("info","UI","Trigger button shown (server-configured)")),L}catch(p){throw I.current=null,t&&f.log("error","User",`User init failed for ${g}`,{error:String(p)}),p}})();return I.current=d,d},[l,h,t]),ce=(0,s.useCallback)(async g=>{t&&f.log("info","Reward",`Tracking reward event: ${g||"(default)"}`);let d=l;!d&&I.current&&(d=await I.current);let p=d?.id||e;if(!p)throw t&&f.log("error","Reward","Cannot track reward \u2014 user not initialized"),new Error("GrowthRail: User must be initialized before tracking a reward event.");let L=await O.getTrackedReferral();if(!L){console.warn("GrowthRail: No referral tracking ID found. Reward event not attributed."),t&&f.log("warn","Reward","No referral tracking ID in storage \u2014 reward not attributed");return}let x=await u.current.trackRewardEvent(p,L,g);return t&&f.log("success","Reward",`Reward event tracked for user ${p}`),x},[l,e,t]),F=(0,s.useCallback)(async()=>await O.getTrackedReferral(),[]),U=(0,s.useCallback)(async()=>{if(l)return l.referralLink;if(I.current)return(await I.current).referralLink},[l]);(0,s.useEffect)(()=>{if(V.current)return;V.current=!0,t&&f.log("info","Provider","SDK initializing\u2026",{platform:T.Platform.OS}),(async()=>{let d=await T.Linking.getInitialURL();t&&f.log("info","DeepLink",`Initial URL: ${d??"(none)"}`),d&&await z(d);let p=T.Linking.addEventListener("url",({url:x})=>z(x)),L=await O.isFirstLaunch();t&&f.log("info","Provider",`First launch: ${L}`),L&&(T.Platform.OS==="android"?await M():await M()),e&&await B(e);try{let x=await u.current.getNewUserExperience(),j=await O.getTrackedReferral();x.banner?.show&&j&&(le(x.banner),W(!0),t&&f.log("info","UI","Banner shown for new user experience"))}catch(x){t&&f.log("warn","Provider","New user experience fetch failed",{error:String(x)})}return y(!0),t&&f.log("success","Provider","SDK initialization complete \u2713"),()=>p.remove()})()},[]),(0,s.useEffect)(()=>{a&&e&&l?.id!==e&&B(e)},[e,a]);let $={isInitialized:a,isUserReady:h,currentUser:l,referralCode:l?.referralCode,referralLink:l?.referralLink,showDashboard:g=>{ae(g),K(!0)},hideDashboard:()=>K(!1),initUser:B,trackReward:ce,getReferralTrackingId:F,getReferralLink:U,isDebugEnabled:t};if(!a)return null;let E=l?.referrerExperience,ke={...E?.modal,...q,position:E?.trigger?.position||q?.position||"bottom-right",theme:{...E?.modal?.theme||{},...q?.theme||{}}},Ce={...E,...D,trigger:{...E?.trigger||{},...D?.trigger||{}}};return s.default.createElement(be.Provider,{value:$},i,s.default.createElement(oe,{visible:P,options:ke,onClose:()=>K(!1)}),ge&&s.default.createElement(ne,{options:Ce,onPress:()=>$.showDashboard()}),X&&s.default.createElement(we,{visible:X,options:se,onClose:()=>W(!1)}))},ie=()=>{let i=(0,s.useContext)(be);if(!i)throw new Error("useGrowthRail must be used within a GrowthRailProvider");return i};var H=require("react");var Re=()=>{let[i,e]=(0,H.useState)(!1),[t,c]=(0,H.useState)(null),a=ie(),y=(0,H.useCallback)(async b=>{e(!0),c(null);try{return await a.initUser(b)}catch(l){let R=l instanceof Error?l:new Error(String(l));throw c(R),R}finally{e(!1)}},[a]),h=(0,H.useCallback)(async b=>{e(!0),c(null);try{await a.trackReward(b)}catch(l){let R=l instanceof Error?l:new Error(String(l));throw c(R),R}finally{e(!1)}},[a]);return{initAppUser:y,trackRewardEvent:h,showReferralDashboard:a.showDashboard,hideReferralDashboard:a.hideDashboard,getReferralTrackingId:a.getReferralTrackingId,getReferralLink:a.getReferralLink,isLoading:i,isInitialized:a.isInitialized,isUserReady:a.isUserReady,error:t,isDebugEnabled:a.isDebugEnabled}};0&&(module.exports={GrowthRailProvider,ReferralDashboard,TriggerButton,useGrowthRail});
|
|
1
|
+
"use strict";var Ce=Object.create;var Y=Object.defineProperty;var xe=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var ve=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty;var Se=(i,e,r)=>e in i?Y(i,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):i[e]=r;var Ie=(i,e)=>{for(var r in e)Y(i,r,{get:e[r],enumerable:!0})},ge=(i,e,r,l)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Te(e))!Le.call(i,n)&&n!==r&&Y(i,n,{get:()=>e[n],enumerable:!(l=xe(e,n))||l.enumerable});return i};var N=(i,e,r)=>(r=i!=null?Ce(ve(i)):{},ge(e||!i||!i.__esModule?Y(r,"default",{value:i,enumerable:!0}):r,i)),De=i=>ge(Y({},"__esModule",{value:!0}),i);var re=(i,e,r)=>Se(i,typeof e!="symbol"?e+"":e,r);var Ve={};Ie(Ve,{GrowthRailProvider:()=>be,ReferralDashboard:()=>ie,TriggerButton:()=>ae,useGrowthRail:()=>me});module.exports=De(Ve);var s=N(require("react")),T=require("react-native"),pe=N(require("react-native-play-install-referrer"));var Be="[GrowthRail]",g={log(i,e,r,l){let n=`${Be} [${e}] ${r}`;switch(i){case"error":console.error(n,l||"");break;case"warn":console.warn(n,l||"");break;default:console.log(n,l||"");break}}};var te=class{constructor(e){re(this,"baseUrl");re(this,"projectSecretKey");re(this,"_debug",!1);let r=typeof process<"u"&&process.env?.ENV_BASE_URL;this.baseUrl=r||"https://api.growthrail.dev",this.projectSecretKey=e.projectSecretKey}setDebug(e){this._debug=e}async request(e,r,l){let n={"Content-Type":"application/json","X-GrowthRail-ProjectSecret":this.projectSecretKey,Origin:this.baseUrl},R=Date.now();this._debug&&g.log("api","APIClient",`${r} ${e}`,{method:r,endpoint:e,body:l??null});try{let p=await fetch(`${this.baseUrl}${e}`,{method:r,headers:n,body:l?JSON.stringify(l):void 0}),y=Date.now()-R;if(!p.ok){let c="";try{c=await p.text()}catch{}let k=`GrowthRail API Error ${p.status} (${this.baseUrl}${e}): ${p.statusText} - ${c}`;throw this._debug&&g.log("api","APIClient",`\u2717 ${r} ${e}`,{method:r,endpoint:e,status:p.status,duration:y,error:c}),new Error(k)}return this._debug&&g.log("api","APIClient",`\u2713 ${r} ${e}`,{method:r,endpoint:e,status:p.status,duration:y}),p.json()}catch(p){let y=Date.now()-R;throw this._debug&&g.log("api","APIClient",`\u2717 ${r} ${e} \u2014 Network error`,{method:r,endpoint:e,duration:y,error:String(p)}),console.error("GrowthRail SDK Error:",p),p}}async getNewUserExperience(){return this.request("/api/v1/sdk/new-user-experience","POST")}async initAppUser(e){return this.request("/api/v1/sdk/init-app-user","POST",{clientProvidedId:e})}async trackReferral(e,r){return this.request("/api/v1/sdk/track-referral","POST",{referralCode:e,rewardEventName:r})}async trackRewardEvent(e,r,l){return this.request("/api/v1/sdk/track-reward-event","POST",{refereeId:e,referralTrackingId:r,eventName:l})}async checkDeferredDeepLink(e){return this.request("/api/v1/sdk/match-link","POST",{fingerprint:e})}};var X=N(require("@react-native-async-storage/async-storage")),oe={TRACKED_REFERRAL:"growth-rail-tracked-referral",IS_FIRST_LAUNCH:"growth-rail-is-first-launch"},B=class{static async setTrackedReferral(e){await X.default.setItem(oe.TRACKED_REFERRAL,e)}static async getTrackedReferral(){return await X.default.getItem(oe.TRACKED_REFERRAL)}static async isFirstLaunch(){return await X.default.getItem(oe.IS_FIRST_LAUNCH)===null?(await X.default.setItem(oe.IS_FIRST_LAUNCH,"false"),!0):!1}};var o=N(require("react")),t=require("react-native");var{width:We,height:ue}=t.Dimensions.get("window"),ie=({visible:i,options:e,onClose:r})=>{let l=ne(),[n,R]=(0,o.useState)(null),[p,y]=(0,o.useState)(!1),[c,k]=(0,o.useState)(!1),h=(0,o.useRef)(new t.Animated.Value(0)).current,O=(0,o.useRef)(new t.Animated.Value(0)).current,D=(0,t.useColorScheme)(),v=(e?.appearance||D||"light")==="dark",_=e?.title||"Invite Friends & Earn",V=e?.theme?.primaryColor||"#2563eb",E=(e?.componentType||"modal")==="drawer",G=e?.position||"bottom-right",d={background:v?"#111827":"#ffffff",text:v?"#f9fafb":"#111827",textSecondary:v?"#9ca3af":"#6b7280",border:v?"#374151":"#e5e7eb",inputBg:v?"#1f2937":"#f9fafb",closeBtnBg:v?"#1f2937":"#f3f4f6",closeIcon:v?"#6b7280":"#9ca3af",drawerHandle:v?"#4b5563":"#e5e7eb",overlay:"#000000",overlayOpacity:.5};(0,o.useEffect)(()=>{i?(n||Z(),t.Animated.parallel([t.Animated.timing(O,{toValue:1,duration:300,useNativeDriver:!0}),t.Animated.spring(h,{toValue:1,useNativeDriver:!0,tension:50,friction:8})]).start()):(h.setValue(0),O.setValue(0))},[i]);let $=()=>{t.Animated.parallel([t.Animated.timing(O,{toValue:0,duration:250,useNativeDriver:!0}),t.Animated.timing(h,{toValue:0,duration:250,useNativeDriver:!0})]).start(()=>{r()})},Z=async()=>{y(!0);try{if(l.isUserReady){let A=await l.getReferralLink();R(A||null)}}catch(A){console.error("GrowthRail: Failed to load referral link",A)}finally{y(!1)}},se=()=>{n&&(t.Clipboard.setString(n),k(!0),setTimeout(()=>k(!1),2e3))},z=A=>{if(!n)return;let U="",F=encodeURIComponent(n),W=encodeURIComponent("Check this out!");switch(A){case"twitter":U=`https://twitter.com/intent/tweet?url=${F}&text=${W}`;break;case"facebook":U=`https://www.facebook.com/sharer/sharer.php?u=${F}`;break;case"linkedin":U=`https://www.linkedin.com/sharing/share-offsite/?url=${F}`;break;case"whatsapp":U=`whatsapp://send?text=${W}%20${F}`;break;case"email":U=`mailto:?subject=Check this out&body=${W}%20${F}`;break}U&&t.Linking.openURL(U).catch(()=>{})},ee=()=>d.overlay,P=[];E?P=[{translateY:h.interpolate({inputRange:[0,1],outputRange:[ue,0]})}]:P=[{scale:h.interpolate({inputRange:[0,1],outputRange:[.9,1]})},{translateY:h.interpolate({inputRange:[0,1],outputRange:[20,0]})}];let le=G.includes("top"),H=G.includes("right"),ye=G.includes("left"),K=E?{position:"absolute",bottom:0,left:0,right:0,width:"100%",maxHeight:"90%"}:{};return o.default.createElement(t.Modal,{visible:i,transparent:!0,animationType:"none",onRequestClose:$},o.default.createElement(t.View,{style:a.fullScreen},o.default.createElement(t.Animated.View,{style:[a.overlay,{backgroundColor:ee(),opacity:O.interpolate({inputRange:[0,1],outputRange:[0,d.overlayOpacity]})}]},o.default.createElement(t.TouchableOpacity,{style:a.fullScreen,activeOpacity:1,onPress:$})),o.default.createElement(t.Animated.View,{style:[E?K:a.centeredModalContainer,{backgroundColor:d.background,transform:P},E&&{borderTopLeftRadius:24,borderTopRightRadius:24,borderBottomLeftRadius:0,borderBottomRightRadius:0},!E&&{borderRadius:24,opacity:h,borderColor:d.border,borderWidth:v?1:0}]},o.default.createElement(t.View,{style:a.contentWrapper},E&&o.default.createElement(t.View,{style:[a.drawerHandle,{backgroundColor:d.drawerHandle}]}),o.default.createElement(t.TouchableOpacity,{style:[a.closeBtn,{backgroundColor:d.closeBtnBg}],onPress:$},o.default.createElement(t.Text,{style:[a.closeIcon,{color:d.closeIcon}]},"\u2715")),o.default.createElement(t.ScrollView,{contentContainerStyle:a.scrollContent,showsVerticalScrollIndicator:!1},o.default.createElement(t.View,{style:a.header},o.default.createElement(t.View,{style:a.iconLgContainer},o.default.createElement(t.View,{style:a.bowContainerLg},o.default.createElement(t.View,{style:[a.bowLoopLg,a.bowLeftLg,{borderColor:V}]}),o.default.createElement(t.View,{style:[a.bowLoopLg,a.bowRightLg,{borderColor:V}]})),o.default.createElement(t.View,{style:[a.giftLidLg,{backgroundColor:V}]}),o.default.createElement(t.View,{style:[a.giftBodyLg,{borderColor:V}]},o.default.createElement(t.View,{style:[a.ribbonVerticalLg,{backgroundColor:"#fff",opacity:.3}]}))),o.default.createElement(t.Text,{style:[a.title,{color:d.text}]},_),o.default.createElement(t.Text,{style:[a.subtitle,{color:d.textSecondary}]},e?.description||"Share your unique link and earn rewards for every friend who signs up.")),l.isUserReady?p?o.default.createElement(t.ActivityIndicator,{size:"large",color:V,style:a.loader}):o.default.createElement(t.View,{style:a.mainContent},o.default.createElement(t.Text,{style:[a.label,{color:d.textSecondary}]},"YOUR UNIQUE LINK"),o.default.createElement(t.View,{style:[a.inputGroup,{backgroundColor:d.inputBg,borderColor:d.border}]},o.default.createElement(t.Text,{numberOfLines:1,style:[a.input,{color:d.text}]},n||"Initializing..."),o.default.createElement(t.TouchableOpacity,{style:[a.copyBtn,{backgroundColor:c?"#10b981":V}],onPress:se},o.default.createElement(t.Text,{style:a.copyBtnText},c?"Copied!":"Copy"))),o.default.createElement(t.View,{style:a.shareLabelContainer},o.default.createElement(t.View,{style:[a.divider,{backgroundColor:d.border}]}),o.default.createElement(t.Text,{style:[a.shareLabel,{color:d.textSecondary}]},"Share via"),o.default.createElement(t.View,{style:[a.divider,{backgroundColor:d.border}]})),o.default.createElement(t.View,{style:a.socialContainer},o.default.createElement(J,{platform:"twitter",color:v?"#FFFFFF":"#000000",onPress:()=>z("twitter"),icon:"\u{1D54F}",borderColor:d.border,bgColor:d.background}),o.default.createElement(J,{platform:"facebook",color:"#1877F2",onPress:()=>z("facebook"),icon:"f",borderColor:d.border,bgColor:d.background}),o.default.createElement(J,{platform:"linkedin",color:"#0A66C2",onPress:()=>z("linkedin"),icon:"in",borderColor:d.border,bgColor:d.background}),o.default.createElement(J,{platform:"whatsapp",color:"#25D366",onPress:()=>z("whatsapp"),icon:"W",borderColor:d.border,bgColor:d.background}),o.default.createElement(J,{platform:"email",color:d.textSecondary,onPress:()=>z("email"),icon:"\u2709",borderColor:d.border,bgColor:d.background}))):o.default.createElement(t.View,{style:[a.loadingBox,{backgroundColor:d.inputBg,borderColor:d.border}]},o.default.createElement(t.Text,{style:{color:d.textSecondary,textAlign:"center"}},"Please log in to view your referral dashboard.")),o.default.createElement(t.View,{style:a.footer},o.default.createElement(t.Text,{style:[a.poweredBy,{color:d.textSecondary}]},"Powered by ",o.default.createElement(t.Text,{style:[a.brand,{color:V}],onPress:()=>t.Linking.openURL("https://growthrail.com")},"Growth Rail"))))))))},J=({color:i,onPress:e,icon:r,borderColor:l,bgColor:n})=>o.default.createElement(t.TouchableOpacity,{style:[a.socialBtn,{borderColor:l,backgroundColor:n}],onPress:e},o.default.createElement(t.Text,{style:[a.socialIcon,{color:i}]},r)),a=t.StyleSheet.create({fullScreen:{flex:1},overlay:{...t.StyleSheet.absoluteFillObject},centeredModalContainer:{width:"90%",maxWidth:400,alignSelf:"center",marginTop:ue*.15,overflow:"hidden",shadowColor:"#000",shadowOffset:{width:0,height:20},shadowOpacity:.25,shadowRadius:30,elevation:20},contentWrapper:{paddingTop:t.Platform.OS==="ios"?20:0},drawerHandle:{width:40,height:4,backgroundColor:"#e5e7eb",borderRadius:2,alignSelf:"center",marginTop:12},scrollContent:{padding:32,alignItems:"center"},closeBtn:{position:"absolute",top:20,right:20,zIndex:10,width:32,height:32,borderRadius:16,backgroundColor:"#f3f4f6",justifyContent:"center",alignItems:"center"},closeIcon:{fontSize:14,color:"#9ca3af"},header:{alignItems:"center",marginBottom:28,width:"100%"},socialIcon:{fontSize:18,fontWeight:"bold"},title:{fontSize:22,fontWeight:"700",letterSpacing:-.5,marginBottom:8,textAlign:"center"},subtitle:{fontSize:14,lineHeight:20,textAlign:"center",paddingHorizontal:10},loadingBox:{padding:16,backgroundColor:"#f9fafb",borderRadius:12,width:"100%",alignItems:"center",borderWidth:1,borderColor:"#e5e7eb",marginTop:20},loader:{marginVertical:20},mainContent:{width:"100%"},label:{fontSize:12,fontWeight:"600",color:"#6b7280",marginBottom:8,letterSpacing:.5},inputGroup:{flexDirection:"row",alignItems:"center",backgroundColor:"#f9fafb",borderWidth:1,borderColor:"#e5e7eb",borderRadius:12,padding:6,marginBottom:24},input:{flex:1,paddingHorizontal:12,fontSize:14,color:"#111827",fontFamily:t.Platform.OS==="ios"?"Menlo":"monospace"},copyBtn:{paddingVertical:8,paddingHorizontal:16,borderRadius:8,justifyContent:"center",alignItems:"center"},copyBtnText:{color:"#fff",fontSize:13,fontWeight:"600"},shareLabelContainer:{flexDirection:"row",alignItems:"center",marginBottom:16,marginTop:8},divider:{flex:1,height:1,backgroundColor:"#e5e7eb"},shareLabel:{marginHorizontal:12,fontSize:13,fontWeight:"500",color:"#6b7280"},socialContainer:{flexDirection:"row",justifyContent:"center",gap:12},socialBtn:{width:44,height:44,borderRadius:22,backgroundColor:"#fff",borderWidth:1,justifyContent:"center",alignItems:"center"},iconLgContainer:{width:60,height:60,justifyContent:"center",alignItems:"center",marginBottom:16},bowContainerLg:{flexDirection:"row",position:"absolute",top:2,zIndex:2},bowLoopLg:{width:20,height:16,borderWidth:3,borderColor:"#e5e7eb",borderRadius:10},bowLeftLg:{marginRight:-2,transform:[{rotate:"-15deg"}]},bowRightLg:{marginLeft:-2,transform:[{rotate:"15deg"}]},giftLidLg:{width:44,height:10,backgroundColor:"#f3f4f6",borderRadius:2,marginTop:12,zIndex:3},giftBodyLg:{width:36,height:24,borderWidth:3,borderTopWidth:0,borderBottomLeftRadius:4,borderBottomRightRadius:4,justifyContent:"center",alignItems:"center",marginTop:-2},ribbonVerticalLg:{width:4,height:"100%",opacity:.1},footer:{marginTop:32,alignItems:"center"},poweredBy:{fontSize:11,color:"#9ca3af"},brand:{fontWeight:"600",textDecorationLine:"underline"}});var x=N(require("react")),b=require("react-native"),ae=({onPress:i,options:e})=>{let r=e?.modal?.theme?.primaryColor||"#2563eb",l=e?.trigger?.position||"bottom-right",R=(e?.trigger?.displayMode||"floating")==="edge",p=l.includes("right"),y=l.includes("top"),c=(0,x.useRef)(new b.Animated.Value(-1)).current;(0,x.useEffect)(()=>{let D=()=>{c.setValue(-1),b.Animated.timing(c,{toValue:2,duration:3e3,easing:b.Easing.linear,useNativeDriver:!0}).start(()=>{setTimeout(D,1e3)})};D()},[]);let k=c.interpolate({inputRange:[-1,2],outputRange:R?[-50,100]:[-60,120]}),h={"bottom-right":{bottom:100,right:0},"bottom-left":{bottom:100,left:0},"top-right":{top:100,right:0},"top-left":{top:100,left:0}};R||(h["bottom-right"]={bottom:30,right:20},h["bottom-left"]={bottom:30,left:20},h["top-right"]={top:60,right:20},h["top-left"]={top:60,left:20});let O=()=>x.default.createElement(b.View,{style:C.iconContainer},x.default.createElement(b.View,{style:C.bowContainer},x.default.createElement(b.View,{style:[C.bowLoop,C.bowLeft]}),x.default.createElement(b.View,{style:[C.bowLoop,C.bowRight]})),x.default.createElement(b.View,{style:C.giftLid}),x.default.createElement(b.View,{style:C.giftBody},x.default.createElement(b.View,{style:C.ribbonVertical})));return x.default.createElement(b.TouchableOpacity,{style:[R?C.edgeButton:C.floatingButton,{backgroundColor:r},h[l],R&&(p?C.edgeRight:C.edgeLeft)],onPress:i,activeOpacity:.9},x.default.createElement(b.View,{style:C.content},O()),x.default.createElement(b.Animated.View,{style:[C.shimmer,{transform:[{translateX:k},{skewX:"-15deg"}]}]}))},C=b.StyleSheet.create({floatingButton:{position:"absolute",width:60,height:60,borderRadius:30,justifyContent:"center",alignItems:"center",overflow:"hidden",shadowColor:"#000",shadowOffset:{width:0,height:8},shadowOpacity:.2,shadowRadius:12,elevation:8,zIndex:2147483646},edgeButton:{position:"absolute",width:50,height:50,justifyContent:"center",alignItems:"center",overflow:"hidden",shadowColor:"#000",shadowOffset:{width:0,height:4},shadowOpacity:.1,shadowRadius:8,elevation:4,zIndex:2147483646},edgeRight:{borderTopLeftRadius:8,borderBottomLeftRadius:8,paddingLeft:4},edgeLeft:{borderTopRightRadius:8,borderBottomRightRadius:8,paddingRight:4},content:{justifyContent:"center",alignItems:"center"},iconContainer:{width:28,height:28,justifyContent:"center",alignItems:"center"},bowContainer:{flexDirection:"row",position:"absolute",top:0,zIndex:2},bowLoop:{width:10,height:8,borderWidth:2,borderColor:"#fff",borderRadius:5},bowLeft:{marginRight:-1,transform:[{rotate:"-15deg"}]},bowRight:{marginLeft:-1,transform:[{rotate:"15deg"}]},giftLid:{width:22,height:5,backgroundColor:"#fff",borderRadius:1,marginTop:6,zIndex:3},giftBody:{width:18,height:12,borderWidth:2,borderColor:"#fff",borderTopWidth:0,borderBottomLeftRadius:2,borderBottomRightRadius:2,justifyContent:"center",alignItems:"center",marginTop:-1},ribbonVertical:{width:2,height:"100%",backgroundColor:"#fff",opacity:.8},shimmer:{position:"absolute",top:0,left:0,width:50,height:"100%",backgroundColor:"rgba(255, 255, 255, 0.25)"}});var I=N(require("react")),m=require("react-native"),{width:Oe}=m.Dimensions.get("window"),he=({visible:i,options:e,onClose:r})=>{let l=(0,I.useRef)(new m.Animated.Value(0)).current,[n,R]=(0,I.useState)(i),p=e.position.includes("bottom")?"bottom":"top",y=e.position.includes("left")?"left":e.position.includes("right")?"right":"center";if((0,I.useEffect)(()=>{i?(R(!0),m.Animated.spring(l,{toValue:1,useNativeDriver:!0,tension:50,friction:8}).start()):m.Animated.timing(l,{toValue:0,duration:250,useNativeDriver:!0}).start(()=>{R(!1)})},[i]),!n)return null;let c=l.interpolate({inputRange:[0,1],outputRange:[p==="top"?-100:100,0]}),k=l.interpolate({inputRange:[0,1],outputRange:[0,1]}),h={position:"absolute",[p]:m.Platform.OS==="ios"?60:40,zIndex:9999};return y==="center"?(h.left=20,h.right=20,h.alignItems="center"):h[y]=20,I.default.createElement(m.Animated.View,{style:[h,{transform:[{translateY:c}],opacity:k}]},I.default.createElement(m.View,{style:[Q.banner,{backgroundColor:e.themeColor||"#2563eb"}]},I.default.createElement(m.Text,{style:Q.icon},"\u{1F381}"),I.default.createElement(m.Text,{style:Q.text},e.text),I.default.createElement(m.TouchableOpacity,{onPress:r,style:Q.closeBtn},I.default.createElement(m.Text,{style:Q.closeIcon},"\u2715"))))},Q=m.StyleSheet.create({banner:{flexDirection:"row",alignItems:"center",padding:12,paddingHorizontal:16,borderRadius:12,shadowColor:"#000",shadowOffset:{width:0,height:4},shadowOpacity:.15,shadowRadius:10,elevation:5,maxWidth:Oe-40},icon:{fontSize:18,marginRight:10},text:{color:"#fff",fontSize:14,fontWeight:"600",flex:1},closeBtn:{marginLeft:10,padding:4},closeIcon:{color:"rgba(255, 255, 255, 0.8)",fontSize:14,fontWeight:"bold"}});var we=(0,s.createContext)(void 0),be=({children:i,userId:e,debug:r=!1,...l})=>{let[n,R]=(0,s.useState)(!1),[p,y]=(0,s.useState)(!1),[c,k]=(0,s.useState)(null),h=(0,s.useRef)(new te(l)),O=(0,s.useRef)(!1),D=(0,s.useRef)(null),[de,v]=(0,s.useState)(!1),[_,V]=(0,s.useState)(),[fe,E]=(0,s.useState)(!1),[G,d]=(0,s.useState)(),[$,Z]=(0,s.useState)(!1),[se,z]=(0,s.useState)();(0,s.useEffect)(()=>{h.current.setDebug(r),r&&g.log("info","Provider","Debug mode enabled")},[r]);let ee=(0,s.useCallback)(()=>{let{width:u,height:f}=T.Dimensions.get("window"),w=Intl.DateTimeFormat().resolvedOptions().locale,S=T.PixelRatio.get(),L,M;if(T.Platform.OS==="android"){let ce=T.Platform.constants;L=ce.Model,M=ce.Brand||ce.Manufacturer}return{os:T.Platform.OS,platform:T.Platform.OS,osVersion:String(T.Platform.Version),screenWidth:u,screenHeight:f,timezoneOffsetInMinutes:String(new Date().getTimezoneOffset()),locale:w,language:w,deviceModel:L,deviceBrand:M,pixelRatio:S}},[]),P=(0,s.useCallback)(async(u,f)=>{r&&g.log("info","Referral",`Tracking referral code: ${u}`,{referralCode:u,rewardEventName:f});let w=await h.current.trackReferral(u,f);return await B.setTrackedReferral(w.referralTrackingId),r&&g.log("success","Referral",`Referral tracked \u2192 ${w.referralTrackingId}`,w),w},[r]),le=(0,s.useCallback)(async u=>{try{r&&g.log("info","DeepLink",`Received deep link: ${u}`);let f=u.match(/[?&]referralCode=([^&]+)/);f&&(console.log("GrowthRail: Tracking referral from deep link",f[1]),r&&g.log("info","DeepLink",`Found referral code in deep link: ${f[1]}`),await P(f[1]))}catch(f){console.warn("GrowthRail: Error handling deep link",f),r&&g.log("error","DeepLink","Deep link handling failed",{error:String(f)})}},[P,r]),H=(0,s.useCallback)(async()=>{try{r&&g.log("info","Deferred","Checking deferred deep link via fingerprint");let u=ee(),{referralTrackingId:f}=await h.current.checkDeferredDeepLink(u);f?(console.log("GrowthRail: Found deferred referral via fingerprinting",f),r&&g.log("success","Deferred",`Deferred referral matched \u2192 ${f}`),await B.setTrackedReferral(f)):r&&g.log("info","Deferred","No deferred referral match found")}catch(u){console.warn("GrowthRail: Fingerprint check failed",u),r&&g.log("error","Deferred","Fingerprint check failed",{error:String(u)})}},[ee,r]),ye=(0,s.useCallback)(()=>new Promise(u=>{pe.default.getInstallReferrerInfo(async(f,w)=>{if(!w&&f&&f.installReferrer)try{let L=decodeURIComponent(f.installReferrer).match(/[?&]referralCode=([^&]+)/);if(L){let{referralTrackingId:M}=await P(L[1]);await B.setTrackedReferral(M),console.log("GrowthRail: Tracked referral via Install Referrer")}}catch(S){console.warn("GrowthRail: Failed to process install referrer",S)}else await H();u()})}),[P,H]),K=(0,s.useCallback)(async u=>{if(c?.id===u&&p)return r&&g.log("info","User",`User ${u} already initialized, skipping`),c;r&&g.log("info","User",`Initializing user: ${u}`);let f=(async()=>{try{let w=await h.current.initAppUser(u),S={...w,id:u};return k(S),y(!0),r&&g.log("success","User",`User initialized: ${u}`,{referralCode:w.referralCode,referralLink:w.referralLink}),w.referrerExperience?.trigger?.displayMode!=="none"&&(E(!0),r&&g.log("info","UI","Trigger button shown (server-configured)")),S}catch(w){throw D.current=null,r&&g.log("error","User",`User init failed for ${u}`,{error:String(w)}),w}})();return D.current=f,f},[c,p,r]),A=(0,s.useCallback)(async u=>{r&&g.log("info","Reward",`Tracking reward event: ${u||"(default)"}`);let f=c;!f&&D.current&&(f=await D.current);let w=f?.id||e;if(!w)throw r&&g.log("error","Reward","Cannot track reward \u2014 user not initialized"),new Error("GrowthRail: User must be initialized before tracking a reward event.");let S=await B.getTrackedReferral();if(!S){console.warn("GrowthRail: No referral tracking ID found. Reward event not attributed."),r&&g.log("warn","Reward","No referral tracking ID in storage \u2014 reward not attributed");return}let L=await h.current.trackRewardEvent(w,S,u);return r&&g.log("success","Reward",`Reward event tracked for user ${w}`),L},[c,e,r]),U=(0,s.useCallback)(async()=>await B.getTrackedReferral(),[]),F=(0,s.useCallback)(async()=>{if(c)return c.referralLink;if(D.current)return(await D.current).referralLink},[c]);(0,s.useEffect)(()=>{if(O.current)return;O.current=!0,r&&g.log("info","Provider","SDK initializing\u2026",{platform:T.Platform.OS}),(async()=>{let f=await T.Linking.getInitialURL();r&&g.log("info","DeepLink",`Initial URL: ${f??"(none)"}`),f&&await le(f);let w=T.Linking.addEventListener("url",({url:L})=>le(L)),S=await B.isFirstLaunch();r&&g.log("info","Provider",`First launch: ${S}`),S&&(T.Platform.OS==="android"?await H():await H()),e&&await K(e);try{let L=await h.current.getNewUserExperience(),M=await B.getTrackedReferral();L.banner?.show&&M&&(z(L.banner),Z(!0),r&&g.log("info","UI","Banner shown for new user experience"))}catch(L){r&&g.log("warn","Provider","New user experience fetch failed",{error:String(L)})}return R(!0),r&&g.log("success","Provider","SDK initialization complete \u2713"),()=>w.remove()})()},[]),(0,s.useEffect)(()=>{n&&e&&c?.id!==e&&K(e)},[e,n]);let W={isInitialized:n,isUserReady:p,currentUser:c,referralCode:c?.referralCode,referralLink:c?.referralLink,showDashboard:u=>{V(u),v(!0)},hideDashboard:()=>v(!1),initUser:K,trackReward:A,getReferralTrackingId:U,getReferralLink:F,isDebugEnabled:r};if(!n)return null;let q=c?.referrerExperience,Re={...q?.modal,..._,appearance:_?.appearance||q?.modal?.appearance||l.appearance,theme:{...q?.modal?.theme||{},..._?.theme||{}}},ke={...q,...G,trigger:{...q?.trigger||{},...G?.trigger||{}}};return s.default.createElement(we.Provider,{value:W},i,s.default.createElement(ie,{visible:de,options:Re,onClose:()=>v(!1)}),fe&&s.default.createElement(ae,{options:ke,onPress:()=>W.showDashboard()}),$&&s.default.createElement(he,{visible:$,options:se,onClose:()=>Z(!1)}))},ne=()=>{let i=(0,s.useContext)(we);if(!i)throw new Error("useGrowthRail must be used within a GrowthRailProvider");return i};var j=require("react");var me=()=>{let[i,e]=(0,j.useState)(!1),[r,l]=(0,j.useState)(null),n=ne(),R=(0,j.useCallback)(async y=>{e(!0),l(null);try{return await n.initUser(y)}catch(c){let k=c instanceof Error?c:new Error(String(c));throw l(k),k}finally{e(!1)}},[n]),p=(0,j.useCallback)(async y=>{e(!0),l(null);try{await n.trackReward(y)}catch(c){let k=c instanceof Error?c:new Error(String(c));throw l(k),k}finally{e(!1)}},[n]);return{initAppUser:R,trackRewardEvent:p,showReferralDashboard:n.showDashboard,hideReferralDashboard:n.hideDashboard,getReferralTrackingId:n.getReferralTrackingId,getReferralLink:n.getReferralLink,isLoading:i,isInitialized:n.isInitialized,isUserReady:n.isUserReady,error:r,isDebugEnabled:n.isDebugEnabled}};0&&(module.exports={GrowthRailProvider,ReferralDashboard,TriggerButton,useGrowthRail});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Ue=Object.defineProperty;var Ee=(f,e,t)=>e in f?Ue(f,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):f[e]=t;var Q=(f,e,t)=>Ee(f,typeof e!="symbol"?e+"":e,t);import ne,{createContext as rt,useContext as ot,useEffect as me,useState as V,useRef as be,useCallback as U}from"react";import{Linking as Ie,Platform as W,Dimensions as it,PixelRatio as nt}from"react-native";import at from"react-native-play-install-referrer";var Pe="[GrowthRail]",s={log(f,e,t,c){let n=`${Pe} [${e}] ${t}`;switch(f){case"error":console.error(n,c||"");break;case"warn":console.warn(n,c||"");break;default:console.log(n,c||"");break}}};var Z=class{constructor(e){Q(this,"baseUrl");Q(this,"projectSecretKey");Q(this,"_debug",!1);let t=typeof process<"u"&&process.env?.ENV_BASE_URL;this.baseUrl=t||"https://api.growthrail.dev",this.projectSecretKey=e.projectSecretKey}setDebug(e){this._debug=e}async request(e,t,c){let n={"Content-Type":"application/json","X-GrowthRail-ProjectSecret":this.projectSecretKey,Origin:this.baseUrl},w=Date.now();this._debug&&s.log("api","APIClient",`${t} ${e}`,{method:t,endpoint:e,body:c??null});try{let g=await fetch(`${this.baseUrl}${e}`,{method:t,headers:n,body:c?JSON.stringify(c):void 0}),p=Date.now()-w;if(!g.ok){let i="";try{i=await g.text()}catch{}let m=`GrowthRail API Error ${g.status} (${this.baseUrl}${e}): ${g.statusText} - ${i}`;throw this._debug&&s.log("api","APIClient",`\u2717 ${t} ${e}`,{method:t,endpoint:e,status:g.status,duration:p,error:i}),new Error(m)}return this._debug&&s.log("api","APIClient",`\u2713 ${t} ${e}`,{method:t,endpoint:e,status:g.status,duration:p}),g.json()}catch(g){let p=Date.now()-w;throw this._debug&&s.log("api","APIClient",`\u2717 ${t} ${e} \u2014 Network error`,{method:t,endpoint:e,duration:p,error:String(g)}),console.error("GrowthRail SDK Error:",g),g}}async getNewUserExperience(){return this.request("/api/v1/sdk/new-user-experience","POST")}async initAppUser(e){return this.request("/api/v1/sdk/init-app-user","POST",{clientProvidedId:e})}async trackReferral(e,t){return this.request("/api/v1/sdk/track-referral","POST",{referralCode:e,rewardEventName:t})}async trackRewardEvent(e,t,c){return this.request("/api/v1/sdk/track-reward-event","POST",{refereeId:e,referralTrackingId:t,eventName:c})}async checkDeferredDeepLink(e){return this.request("/api/v1/sdk/match-link","POST",{fingerprint:e})}};import ee from"@react-native-async-storage/async-storage";var te={TRACKED_REFERRAL:"growth-rail-tracked-referral",IS_FIRST_LAUNCH:"growth-rail-is-first-launch"},v=class{static async setTrackedReferral(e){await ee.setItem(te.TRACKED_REFERRAL,e)}static async getTrackedReferral(){return await ee.getItem(te.TRACKED_REFERRAL)}static async isFirstLaunch(){return await ee.getItem(te.IS_FIRST_LAUNCH)===null?(await ee.setItem(te.IS_FIRST_LAUNCH,"false"),!0):!1}};import r,{useEffect as Ae,useState as fe,useRef as ke}from"react";import{Modal as ze,View as h,Text as L,StyleSheet as Ce,TouchableOpacity as re,Clipboard as Ge,ActivityIndicator as $e,Linking as Te,ScrollView as Fe,Platform as xe,Animated as I,Dimensions as We}from"react-native";var{width:Le,height:ge}=We.get("window"),ue=({visible:f,options:e,onClose:t})=>{let c=oe(),[n,w]=fe(null),[g,p]=fe(!1),[i,m]=fe(!1),d=ke(new I.Value(0)).current,D=ke(new I.Value(0)).current,k=e?.title||"Invite Friends & Earn",E=e?.theme?.primaryColor||"#2563eb",K=e?.theme?.backgroundColor||"#ffffff",q=e?.theme?.tintColor||"#000000",ae=e?.theme?.tintAlpha??.5,C=(e?.componentType||"modal")==="drawer",T=e?.position||"bottom-right",Re="#111827",X="#6b7280";Ae(()=>{f?(n||se(),I.parallel([I.timing(D,{toValue:1,duration:300,useNativeDriver:!0}),I.spring(d,{toValue:1,useNativeDriver:!0,tension:50,friction:8})]).start()):(d.setValue(0),D.setValue(0))},[f]);let N=()=>{I.parallel([I.timing(D,{toValue:0,duration:250,useNativeDriver:!0}),I.timing(d,{toValue:0,duration:250,useNativeDriver:!0})]).start(()=>{t()})},se=async()=>{p(!0);try{if(c.isUserReady){let F=await c.getReferralLink();w(F||null)}}catch(F){console.error("GrowthRail: Failed to load referral link",F)}finally{p(!1)}},le=()=>{n&&(Ge.setString(n),m(!0),setTimeout(()=>m(!1),2e3))},P=F=>{if(!n)return;let B="",G=encodeURIComponent(n),O=encodeURIComponent("Check this out!");switch(F){case"twitter":B=`https://twitter.com/intent/tweet?url=${G}&text=${O}`;break;case"facebook":B=`https://www.facebook.com/sharer/sharer.php?u=${G}`;break;case"linkedin":B=`https://www.linkedin.com/sharing/share-offsite/?url=${G}`;break;case"whatsapp":B=`whatsapp://send?text=${O}%20${G}`;break;case"email":B=`mailto:?subject=Check this out&body=${O}%20${G}`;break}B&&Te.openURL(B).catch(()=>{})},M=()=>q||"#000000",A=[];C?T.includes("right")?A=[{translateX:d.interpolate({inputRange:[0,1],outputRange:[Le,0]})}]:T.includes("left")?A=[{translateX:d.interpolate({inputRange:[0,1],outputRange:[-Le,0]})}]:A=[{translateY:d.interpolate({inputRange:[0,1],outputRange:[ge,0]})}]:A=[{scale:d.interpolate({inputRange:[0,1],outputRange:[.9,1]})},{translateY:d.interpolate({inputRange:[0,1],outputRange:[20,0]})}];let j=T.includes("top"),z=T.includes("right"),x=T.includes("left"),ce=C?{position:"absolute",...j?{top:100}:{bottom:100},...z?{right:0}:x?{left:0}:{left:0,right:0},width:z||x?"85%":"100%",maxHeight:z||x?ge-200:"80%"}:{};return r.createElement(ze,{visible:f,transparent:!0,animationType:"none",onRequestClose:N},r.createElement(h,{style:o.fullScreen},r.createElement(I.View,{style:[o.overlay,{backgroundColor:M(),opacity:D.interpolate({inputRange:[0,1],outputRange:[0,ae]})}]},r.createElement(re,{style:o.fullScreen,activeOpacity:1,onPress:N})),r.createElement(I.View,{style:[C?ce:o.centeredModalContainer,{backgroundColor:K,transform:A},C&&z&&{borderTopLeftRadius:24,borderBottomLeftRadius:24},C&&x&&{borderTopRightRadius:24,borderBottomRightRadius:24},C&&!z&&!x&&T.includes("bottom")&&{borderTopLeftRadius:24,borderTopRightRadius:24},C&&!z&&!x&&T.includes("top")&&{borderBottomLeftRadius:24,borderBottomRightRadius:24},!C&&{borderRadius:24,opacity:d}]},r.createElement(h,{style:o.contentWrapper},C&&!z&&!x&&T.includes("bottom")&&r.createElement(h,{style:o.drawerHandle}),r.createElement(re,{style:o.closeBtn,onPress:N},r.createElement(L,{style:o.closeIcon},"\u2715")),r.createElement(Fe,{contentContainerStyle:o.scrollContent,showsVerticalScrollIndicator:!1},r.createElement(h,{style:o.header},r.createElement(h,{style:o.iconLgContainer},r.createElement(h,{style:o.bowContainerLg},r.createElement(h,{style:[o.bowLoopLg,o.bowLeftLg,{borderColor:E}]}),r.createElement(h,{style:[o.bowLoopLg,o.bowRightLg,{borderColor:E}]})),r.createElement(h,{style:[o.giftLidLg,{backgroundColor:E}]}),r.createElement(h,{style:[o.giftBodyLg,{borderColor:E}]},r.createElement(h,{style:[o.ribbonVerticalLg,{backgroundColor:"#fff",opacity:.3}]}))),r.createElement(L,{style:[o.title,{color:Re}]},k),r.createElement(L,{style:[o.subtitle,{color:X}]},e?.description||"Share your unique link and earn rewards for every friend who signs up.")),c.isUserReady?g?r.createElement($e,{size:"large",color:E,style:o.loader}):r.createElement(h,{style:o.mainContent},r.createElement(L,{style:o.label},"YOUR UNIQUE LINK"),r.createElement(h,{style:o.inputGroup},r.createElement(L,{numberOfLines:1,style:o.input},n||"Initializing..."),r.createElement(re,{style:[o.copyBtn,{backgroundColor:i?"#10b981":E}],onPress:le},r.createElement(L,{style:o.copyBtnText},i?"Copied!":"Copy"))),r.createElement(h,{style:o.shareLabelContainer},r.createElement(h,{style:o.divider}),r.createElement(L,{style:o.shareLabel},"Share via"),r.createElement(h,{style:o.divider})),r.createElement(h,{style:o.socialContainer},r.createElement(Y,{platform:"twitter",color:"#000000",onPress:()=>P("twitter"),icon:"\u{1D54F}"}),r.createElement(Y,{platform:"facebook",color:"#1877F2",onPress:()=>P("facebook"),icon:"f"}),r.createElement(Y,{platform:"linkedin",color:"#0A66C2",onPress:()=>P("linkedin"),icon:"in"}),r.createElement(Y,{platform:"whatsapp",color:"#25D366",onPress:()=>P("whatsapp"),icon:"W"}),r.createElement(Y,{platform:"email",color:"#888888",onPress:()=>P("email"),icon:"\u2709"}))):r.createElement(h,{style:o.loadingBox},r.createElement(L,{style:{color:X,textAlign:"center"}},"Please log in to view your referral dashboard.")),r.createElement(h,{style:o.footer},r.createElement(L,{style:o.poweredBy},"Powered by ",r.createElement(L,{style:o.brand,onPress:()=>Te.openURL("https://growthrail.com")},"Growth Rail"))))))))},Y=({color:f,onPress:e,icon:t})=>r.createElement(re,{style:[o.socialBtn,{borderColor:"#e5e7eb"}],onPress:e},r.createElement(L,{style:[o.socialIcon,{color:f}]},t)),o=Ce.create({fullScreen:{flex:1},overlay:{...Ce.absoluteFillObject},centeredModalContainer:{width:"90%",maxWidth:400,alignSelf:"center",marginTop:ge*.15,overflow:"hidden",shadowColor:"#000",shadowOffset:{width:0,height:20},shadowOpacity:.25,shadowRadius:30,elevation:20},contentWrapper:{paddingTop:xe.OS==="ios"?20:0},drawerHandle:{width:40,height:4,backgroundColor:"#e5e7eb",borderRadius:2,alignSelf:"center",marginTop:12},scrollContent:{padding:32,alignItems:"center"},closeBtn:{position:"absolute",top:20,right:20,zIndex:10,width:32,height:32,borderRadius:16,backgroundColor:"#f3f4f6",justifyContent:"center",alignItems:"center"},closeIcon:{fontSize:14,color:"#9ca3af"},header:{alignItems:"center",marginBottom:28,width:"100%"},socialIcon:{fontSize:18,fontWeight:"bold"},title:{fontSize:22,fontWeight:"700",letterSpacing:-.5,marginBottom:8,textAlign:"center"},subtitle:{fontSize:14,lineHeight:20,textAlign:"center",paddingHorizontal:10},loadingBox:{padding:16,backgroundColor:"#f9fafb",borderRadius:12,width:"100%",alignItems:"center",borderWidth:1,borderColor:"#e5e7eb",marginTop:20},loader:{marginVertical:20},mainContent:{width:"100%"},label:{fontSize:12,fontWeight:"600",color:"#6b7280",marginBottom:8,letterSpacing:.5},inputGroup:{flexDirection:"row",alignItems:"center",backgroundColor:"#f9fafb",borderWidth:1,borderColor:"#e5e7eb",borderRadius:12,padding:6,marginBottom:24},input:{flex:1,paddingHorizontal:12,fontSize:14,color:"#111827",fontFamily:xe.OS==="ios"?"Menlo":"monospace"},copyBtn:{paddingVertical:8,paddingHorizontal:16,borderRadius:8,justifyContent:"center",alignItems:"center"},copyBtnText:{color:"#fff",fontSize:13,fontWeight:"600"},shareLabelContainer:{flexDirection:"row",alignItems:"center",marginBottom:16,marginTop:8},divider:{flex:1,height:1,backgroundColor:"#e5e7eb"},shareLabel:{marginHorizontal:12,fontSize:13,fontWeight:"500",color:"#6b7280"},socialContainer:{flexDirection:"row",justifyContent:"center",gap:12},socialBtn:{width:44,height:44,borderRadius:22,backgroundColor:"#fff",borderWidth:1,justifyContent:"center",alignItems:"center"},iconLgContainer:{width:60,height:60,justifyContent:"center",alignItems:"center",marginBottom:16},bowContainerLg:{flexDirection:"row",position:"absolute",top:2,zIndex:2},bowLoopLg:{width:20,height:16,borderWidth:3,borderColor:"#e5e7eb",borderRadius:10},bowLeftLg:{marginRight:-2,transform:[{rotate:"-15deg"}]},bowRightLg:{marginLeft:-2,transform:[{rotate:"15deg"}]},giftLidLg:{width:44,height:10,backgroundColor:"#f3f4f6",borderRadius:2,marginTop:12,zIndex:3},giftBodyLg:{width:36,height:24,borderWidth:3,borderTopWidth:0,borderBottomLeftRadius:4,borderBottomRightRadius:4,justifyContent:"center",alignItems:"center",marginTop:-2},ribbonVerticalLg:{width:4,height:"100%",opacity:.1},footer:{marginTop:32,alignItems:"center"},poweredBy:{fontSize:11,color:"#9ca3af"},brand:{fontWeight:"600",textDecorationLine:"underline"}});import S,{useEffect as Ne,useRef as Me}from"react";import{TouchableOpacity as je,View as $,StyleSheet as _e,Animated as he,Easing as He}from"react-native";var pe=({onPress:f,options:e})=>{let t=e?.modal?.theme?.primaryColor||"#2563eb",c=e?.trigger?.position||"bottom-right",w=(e?.trigger?.displayMode||"floating")==="edge",g=c.includes("right"),p=c.includes("top"),i=Me(new he.Value(-1)).current;Ne(()=>{let k=()=>{i.setValue(-1),he.timing(i,{toValue:2,duration:3e3,easing:He.linear,useNativeDriver:!0}).start(()=>{setTimeout(k,1e3)})};k()},[]);let m=i.interpolate({inputRange:[-1,2],outputRange:w?[-50,100]:[-60,120]}),d={"bottom-right":{bottom:100,right:0},"bottom-left":{bottom:100,left:0},"top-right":{top:100,right:0},"top-left":{top:100,left:0}};w||(d["bottom-right"]={bottom:30,right:20},d["bottom-left"]={bottom:30,left:20},d["top-right"]={top:60,right:20},d["top-left"]={top:60,left:20});let D=()=>S.createElement($,{style:b.iconContainer},S.createElement($,{style:b.bowContainer},S.createElement($,{style:[b.bowLoop,b.bowLeft]}),S.createElement($,{style:[b.bowLoop,b.bowRight]})),S.createElement($,{style:b.giftLid}),S.createElement($,{style:b.giftBody},S.createElement($,{style:b.ribbonVertical})));return S.createElement(je,{style:[w?b.edgeButton:b.floatingButton,{backgroundColor:t},d[c],w&&(g?b.edgeRight:b.edgeLeft)],onPress:f,activeOpacity:.9},S.createElement($,{style:b.content},D()),S.createElement(he.View,{style:[b.shimmer,{transform:[{translateX:m},{skewX:"-15deg"}]}]}))},b=_e.create({floatingButton:{position:"absolute",width:60,height:60,borderRadius:30,justifyContent:"center",alignItems:"center",overflow:"hidden",shadowColor:"#000",shadowOffset:{width:0,height:8},shadowOpacity:.2,shadowRadius:12,elevation:8,zIndex:2147483646},edgeButton:{position:"absolute",width:50,height:50,justifyContent:"center",alignItems:"center",overflow:"hidden",shadowColor:"#000",shadowOffset:{width:0,height:4},shadowOpacity:.1,shadowRadius:8,elevation:4,zIndex:2147483646},edgeRight:{borderTopLeftRadius:8,borderBottomLeftRadius:8,paddingLeft:4},edgeLeft:{borderTopRightRadius:8,borderBottomRightRadius:8,paddingRight:4},content:{justifyContent:"center",alignItems:"center"},iconContainer:{width:28,height:28,justifyContent:"center",alignItems:"center"},bowContainer:{flexDirection:"row",position:"absolute",top:0,zIndex:2},bowLoop:{width:10,height:8,borderWidth:2,borderColor:"#fff",borderRadius:5},bowLeft:{marginRight:-1,transform:[{rotate:"-15deg"}]},bowRight:{marginLeft:-1,transform:[{rotate:"15deg"}]},giftLid:{width:22,height:5,backgroundColor:"#fff",borderRadius:1,marginTop:6,zIndex:3},giftBody:{width:18,height:12,borderWidth:2,borderColor:"#fff",borderTopWidth:0,borderBottomLeftRadius:2,borderBottomRightRadius:2,justifyContent:"center",alignItems:"center",marginTop:-1},ribbonVertical:{width:2,height:"100%",backgroundColor:"#fff",opacity:.8},shimmer:{position:"absolute",top:0,left:0,width:50,height:"100%",backgroundColor:"rgba(255, 255, 255, 0.25)"}});import H,{useEffect as Ke,useRef as qe,useState as Xe}from"react";import{View as Ye,Text as we,StyleSheet as Je,Animated as ie,Dimensions as Qe,TouchableOpacity as Ze,Platform as et}from"react-native";var{width:tt}=Qe.get("window"),ve=({visible:f,options:e,onClose:t})=>{let c=qe(new ie.Value(0)).current,[n,w]=Xe(f),g=e.position.includes("bottom")?"bottom":"top",p=e.position.includes("left")?"left":e.position.includes("right")?"right":"center";if(Ke(()=>{f?(w(!0),ie.spring(c,{toValue:1,useNativeDriver:!0,tension:50,friction:8}).start()):ie.timing(c,{toValue:0,duration:250,useNativeDriver:!0}).start(()=>{w(!1)})},[f]),!n)return null;let i=c.interpolate({inputRange:[0,1],outputRange:[g==="top"?-100:100,0]}),m=c.interpolate({inputRange:[0,1],outputRange:[0,1]}),d={position:"absolute",[g]:et.OS==="ios"?60:40,zIndex:9999};return p==="center"?(d.left=20,d.right=20,d.alignItems="center"):d[p]=20,H.createElement(ie.View,{style:[d,{transform:[{translateY:i}],opacity:m}]},H.createElement(Ye,{style:[J.banner,{backgroundColor:e.themeColor||"#2563eb"}]},H.createElement(we,{style:J.icon},"\u{1F381}"),H.createElement(we,{style:J.text},e.text),H.createElement(Ze,{onPress:t,style:J.closeBtn},H.createElement(we,{style:J.closeIcon},"\u2715"))))},J=Je.create({banner:{flexDirection:"row",alignItems:"center",padding:12,paddingHorizontal:16,borderRadius:12,shadowColor:"#000",shadowOffset:{width:0,height:4},shadowOpacity:.15,shadowRadius:10,elevation:5,maxWidth:tt-40},icon:{fontSize:18,marginRight:10},text:{color:"#fff",fontSize:14,fontWeight:"600",flex:1},closeBtn:{marginLeft:10,padding:4},closeIcon:{color:"rgba(255, 255, 255, 0.8)",fontSize:14,fontWeight:"bold"}});var Se=rt(void 0),st=({children:f,userId:e,debug:t=!1,...c})=>{let[n,w]=V(!1),[g,p]=V(!1),[i,m]=V(null),d=be(new Z(c)),D=be(!1),k=be(null),[E,K]=V(!1),[q,ae]=V(),[ye,C]=V(!1),[T,Re]=V(),[X,N]=V(!1),[se,le]=V();me(()=>{d.current.setDebug(t),t&&s.log("info","Provider","Debug mode enabled")},[t]);let P=U(()=>{let{width:l,height:a}=it.get("window"),u=Intl.DateTimeFormat().resolvedOptions().locale,R=nt.get(),y,_;if(W.OS==="android"){let de=W.constants;y=de.Model,_=de.Brand||de.Manufacturer}return{os:W.OS,platform:W.OS,osVersion:String(W.Version),screenWidth:l,screenHeight:a,timezoneOffsetInMinutes:String(new Date().getTimezoneOffset()),locale:u,language:u,deviceModel:y,deviceBrand:_,pixelRatio:R}},[]),M=U(async(l,a)=>{t&&s.log("info","Referral",`Tracking referral code: ${l}`,{referralCode:l,rewardEventName:a});let u=await d.current.trackReferral(l,a);return await v.setTrackedReferral(u.referralTrackingId),t&&s.log("success","Referral",`Referral tracked \u2192 ${u.referralTrackingId}`,u),u},[t]),A=U(async l=>{try{t&&s.log("info","DeepLink",`Received deep link: ${l}`);let a=l.match(/[?&]referralCode=([^&]+)/);a&&(console.log("GrowthRail: Tracking referral from deep link",a[1]),t&&s.log("info","DeepLink",`Found referral code in deep link: ${a[1]}`),await M(a[1]))}catch(a){console.warn("GrowthRail: Error handling deep link",a),t&&s.log("error","DeepLink","Deep link handling failed",{error:String(a)})}},[M,t]),j=U(async()=>{try{t&&s.log("info","Deferred","Checking deferred deep link via fingerprint");let l=P(),{referralTrackingId:a}=await d.current.checkDeferredDeepLink(l);a?(console.log("GrowthRail: Found deferred referral via fingerprinting",a),t&&s.log("success","Deferred",`Deferred referral matched \u2192 ${a}`),await v.setTrackedReferral(a)):t&&s.log("info","Deferred","No deferred referral match found")}catch(l){console.warn("GrowthRail: Fingerprint check failed",l),t&&s.log("error","Deferred","Fingerprint check failed",{error:String(l)})}},[P,t]),z=U(()=>new Promise(l=>{at.getInstallReferrerInfo(async(a,u)=>{if(!u&&a&&a.installReferrer)try{let y=decodeURIComponent(a.installReferrer).match(/[?&]referralCode=([^&]+)/);if(y){let{referralTrackingId:_}=await M(y[1]);await v.setTrackedReferral(_),console.log("GrowthRail: Tracked referral via Install Referrer")}}catch(R){console.warn("GrowthRail: Failed to process install referrer",R)}else await j();l()})}),[M,j]),x=U(async l=>{if(i?.id===l&&g)return t&&s.log("info","User",`User ${l} already initialized, skipping`),i;t&&s.log("info","User",`Initializing user: ${l}`);let a=(async()=>{try{let u=await d.current.initAppUser(l),R={...u,id:l};return m(R),p(!0),t&&s.log("success","User",`User initialized: ${l}`,{referralCode:u.referralCode,referralLink:u.referralLink}),u.referrerExperience?.trigger?.show&&(C(!0),t&&s.log("info","UI","Trigger button shown (server-configured)")),R}catch(u){throw k.current=null,t&&s.log("error","User",`User init failed for ${l}`,{error:String(u)}),u}})();return k.current=a,a},[i,g,t]),ce=U(async l=>{t&&s.log("info","Reward",`Tracking reward event: ${l||"(default)"}`);let a=i;!a&&k.current&&(a=await k.current);let u=a?.id||e;if(!u)throw t&&s.log("error","Reward","Cannot track reward \u2014 user not initialized"),new Error("GrowthRail: User must be initialized before tracking a reward event.");let R=await v.getTrackedReferral();if(!R){console.warn("GrowthRail: No referral tracking ID found. Reward event not attributed."),t&&s.log("warn","Reward","No referral tracking ID in storage \u2014 reward not attributed");return}let y=await d.current.trackRewardEvent(u,R,l);return t&&s.log("success","Reward",`Reward event tracked for user ${u}`),y},[i,e,t]),F=U(async()=>await v.getTrackedReferral(),[]),B=U(async()=>{if(i)return i.referralLink;if(k.current)return(await k.current).referralLink},[i]);me(()=>{if(D.current)return;D.current=!0,t&&s.log("info","Provider","SDK initializing\u2026",{platform:W.OS}),(async()=>{let a=await Ie.getInitialURL();t&&s.log("info","DeepLink",`Initial URL: ${a??"(none)"}`),a&&await A(a);let u=Ie.addEventListener("url",({url:y})=>A(y)),R=await v.isFirstLaunch();t&&s.log("info","Provider",`First launch: ${R}`),R&&(W.OS==="android"?await j():await j()),e&&await x(e);try{let y=await d.current.getNewUserExperience(),_=await v.getTrackedReferral();y.banner?.show&&_&&(le(y.banner),N(!0),t&&s.log("info","UI","Banner shown for new user experience"))}catch(y){t&&s.log("warn","Provider","New user experience fetch failed",{error:String(y)})}return w(!0),t&&s.log("success","Provider","SDK initialization complete \u2713"),()=>u.remove()})()},[]),me(()=>{n&&e&&i?.id!==e&&x(e)},[e,n]);let G={isInitialized:n,isUserReady:g,currentUser:i,referralCode:i?.referralCode,referralLink:i?.referralLink,showDashboard:l=>{ae(l),K(!0)},hideDashboard:()=>K(!1),initUser:x,trackReward:ce,getReferralTrackingId:F,getReferralLink:B,isDebugEnabled:t};if(!n)return null;let O=i?.referrerExperience,Oe={...O?.modal,...q,position:O?.trigger?.position||q?.position||"bottom-right",theme:{...O?.modal?.theme||{},...q?.theme||{}}},Ve={...O,...T,trigger:{...O?.trigger||{},...T?.trigger||{}}};return ne.createElement(Se.Provider,{value:G},f,ne.createElement(ue,{visible:E,options:Oe,onClose:()=>K(!1)}),ye&&ne.createElement(pe,{options:Ve,onPress:()=>G.showDashboard()}),X&&ne.createElement(ve,{visible:X,options:se,onClose:()=>N(!1)}))},oe=()=>{let f=ot(Se);if(!f)throw new Error("useGrowthRail must be used within a GrowthRailProvider");return f};import{useState as De,useCallback as Be}from"react";var lt=()=>{let[f,e]=De(!1),[t,c]=De(null),n=oe(),w=Be(async p=>{e(!0),c(null);try{return await n.initUser(p)}catch(i){let m=i instanceof Error?i:new Error(String(i));throw c(m),m}finally{e(!1)}},[n]),g=Be(async p=>{e(!0),c(null);try{await n.trackReward(p)}catch(i){let m=i instanceof Error?i:new Error(String(i));throw c(m),m}finally{e(!1)}},[n]);return{initAppUser:w,trackRewardEvent:g,showReferralDashboard:n.showDashboard,hideReferralDashboard:n.hideDashboard,getReferralTrackingId:n.getReferralTrackingId,getReferralLink:n.getReferralLink,isLoading:f,isInitialized:n.isInitialized,isUserReady:n.isUserReady,error:t,isDebugEnabled:n.isDebugEnabled}};export{st as GrowthRailProvider,ue as ReferralDashboard,pe as TriggerButton,lt as useGrowthRail};
|
|
1
|
+
var Ve=Object.defineProperty;var Ue=(f,e,r)=>e in f?Ve(f,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):f[e]=r;var Z=(f,e,r)=>Ue(f,typeof e!="symbol"?e+"":e,r);import ae,{createContext as tr,useContext as or,useEffect as pe,useState as O,useRef as we,useCallback as V}from"react";import{Linking as ve,Platform as G,Dimensions as ir,PixelRatio as nr}from"react-native";import ar from"react-native-play-install-referrer";var Ee="[GrowthRail]",c={log(f,e,r,a){let n=`${Ee} [${e}] ${r}`;switch(f){case"error":console.error(n,a||"");break;case"warn":console.warn(n,a||"");break;default:console.log(n,a||"");break}}};var ee=class{constructor(e){Z(this,"baseUrl");Z(this,"projectSecretKey");Z(this,"_debug",!1);let r=typeof process<"u"&&process.env?.ENV_BASE_URL;this.baseUrl=r||"https://api.growthrail.dev",this.projectSecretKey=e.projectSecretKey}setDebug(e){this._debug=e}async request(e,r,a){let n={"Content-Type":"application/json","X-GrowthRail-ProjectSecret":this.projectSecretKey,Origin:this.baseUrl},b=Date.now();this._debug&&c.log("api","APIClient",`${r} ${e}`,{method:r,endpoint:e,body:a??null});try{let u=await fetch(`${this.baseUrl}${e}`,{method:r,headers:n,body:a?JSON.stringify(a):void 0}),w=Date.now()-b;if(!u.ok){let i="";try{i=await u.text()}catch{}let m=`GrowthRail API Error ${u.status} (${this.baseUrl}${e}): ${u.statusText} - ${i}`;throw this._debug&&c.log("api","APIClient",`\u2717 ${r} ${e}`,{method:r,endpoint:e,status:u.status,duration:w,error:i}),new Error(m)}return this._debug&&c.log("api","APIClient",`\u2713 ${r} ${e}`,{method:r,endpoint:e,status:u.status,duration:w}),u.json()}catch(u){let w=Date.now()-b;throw this._debug&&c.log("api","APIClient",`\u2717 ${r} ${e} \u2014 Network error`,{method:r,endpoint:e,duration:w,error:String(u)}),console.error("GrowthRail SDK Error:",u),u}}async getNewUserExperience(){return this.request("/api/v1/sdk/new-user-experience","POST")}async initAppUser(e){return this.request("/api/v1/sdk/init-app-user","POST",{clientProvidedId:e})}async trackReferral(e,r){return this.request("/api/v1/sdk/track-referral","POST",{referralCode:e,rewardEventName:r})}async trackRewardEvent(e,r,a){return this.request("/api/v1/sdk/track-reward-event","POST",{refereeId:e,referralTrackingId:r,eventName:a})}async checkDeferredDeepLink(e){return this.request("/api/v1/sdk/match-link","POST",{fingerprint:e})}};import re from"@react-native-async-storage/async-storage";var te={TRACKED_REFERRAL:"growth-rail-tracked-referral",IS_FIRST_LAUNCH:"growth-rail-is-first-launch"},v=class{static async setTrackedReferral(e){await re.setItem(te.TRACKED_REFERRAL,e)}static async getTrackedReferral(){return await re.getItem(te.TRACKED_REFERRAL)}static async isFirstLaunch(){return await re.getItem(te.IS_FIRST_LAUNCH)===null?(await re.setItem(te.IS_FIRST_LAUNCH,"false"),!0):!1}};import t,{useEffect as Pe,useState as de,useRef as ye}from"react";import{Modal as ze,View as p,Text as T,StyleSheet as Re,TouchableOpacity as oe,Clipboard as Ae,ActivityIndicator as Fe,Linking as ke,ScrollView as Ge,Platform as Ce,Animated as L,Dimensions as $e,useColorScheme as We}from"react-native";var{width:Rr,height:xe}=$e.get("window"),fe=({visible:f,options:e,onClose:r})=>{let a=ie(),[n,b]=de(null),[u,w]=de(!1),[i,m]=de(!1),g=ye(new L.Value(0)).current,I=ye(new L.Value(0)).current,x=We(),R=(e?.appearance||x||"light")==="dark",_=e?.title||"Invite Friends & Earn",D=e?.theme?.primaryColor||"#2563eb",U=(e?.componentType||"modal")==="drawer",$=e?.position||"bottom-right",s={background:R?"#111827":"#ffffff",text:R?"#f9fafb":"#111827",textSecondary:R?"#9ca3af":"#6b7280",border:R?"#374151":"#e5e7eb",inputBg:R?"#1f2937":"#f9fafb",closeBtnBg:R?"#1f2937":"#f3f4f6",closeIcon:R?"#6b7280":"#9ca3af",drawerHandle:R?"#4b5563":"#e5e7eb",overlay:"#000000",overlayOpacity:.5};Pe(()=>{f?(n||J(),L.parallel([L.timing(I,{toValue:1,duration:300,useNativeDriver:!0}),L.spring(g,{toValue:1,useNativeDriver:!0,tension:50,friction:8})]).start()):(g.setValue(0),I.setValue(0))},[f]);let W=()=>{L.parallel([L.timing(I,{toValue:0,duration:250,useNativeDriver:!0}),L.timing(g,{toValue:0,duration:250,useNativeDriver:!0})]).start(()=>{r()})},J=async()=>{w(!0);try{if(a.isUserReady){let A=await a.getReferralLink();b(A||null)}}catch(A){console.error("GrowthRail: Failed to load referral link",A)}finally{w(!1)}},se=()=>{n&&(Ae.setString(n),m(!0),setTimeout(()=>m(!1),2e3))},z=A=>{if(!n)return;let B="",F=encodeURIComponent(n),M=encodeURIComponent("Check this out!");switch(A){case"twitter":B=`https://twitter.com/intent/tweet?url=${F}&text=${M}`;break;case"facebook":B=`https://www.facebook.com/sharer/sharer.php?u=${F}`;break;case"linkedin":B=`https://www.linkedin.com/sharing/share-offsite/?url=${F}`;break;case"whatsapp":B=`whatsapp://send?text=${M}%20${F}`;break;case"email":B=`mailto:?subject=Check this out&body=${M}%20${F}`;break}B&&ke.openURL(B).catch(()=>{})},Q=()=>s.overlay,E=[];U?E=[{translateY:g.interpolate({inputRange:[0,1],outputRange:[xe,0]})}]:E=[{scale:g.interpolate({inputRange:[0,1],outputRange:[.9,1]})},{translateY:g.interpolate({inputRange:[0,1],outputRange:[20,0]})}];let le=$.includes("top"),H=$.includes("right"),De=$.includes("left"),K=U?{position:"absolute",bottom:0,left:0,right:0,width:"100%",maxHeight:"90%"}:{};return t.createElement(ze,{visible:f,transparent:!0,animationType:"none",onRequestClose:W},t.createElement(p,{style:o.fullScreen},t.createElement(L.View,{style:[o.overlay,{backgroundColor:Q(),opacity:I.interpolate({inputRange:[0,1],outputRange:[0,s.overlayOpacity]})}]},t.createElement(oe,{style:o.fullScreen,activeOpacity:1,onPress:W})),t.createElement(L.View,{style:[U?K:o.centeredModalContainer,{backgroundColor:s.background,transform:E},U&&{borderTopLeftRadius:24,borderTopRightRadius:24,borderBottomLeftRadius:0,borderBottomRightRadius:0},!U&&{borderRadius:24,opacity:g,borderColor:s.border,borderWidth:R?1:0}]},t.createElement(p,{style:o.contentWrapper},U&&t.createElement(p,{style:[o.drawerHandle,{backgroundColor:s.drawerHandle}]}),t.createElement(oe,{style:[o.closeBtn,{backgroundColor:s.closeBtnBg}],onPress:W},t.createElement(T,{style:[o.closeIcon,{color:s.closeIcon}]},"\u2715")),t.createElement(Ge,{contentContainerStyle:o.scrollContent,showsVerticalScrollIndicator:!1},t.createElement(p,{style:o.header},t.createElement(p,{style:o.iconLgContainer},t.createElement(p,{style:o.bowContainerLg},t.createElement(p,{style:[o.bowLoopLg,o.bowLeftLg,{borderColor:D}]}),t.createElement(p,{style:[o.bowLoopLg,o.bowRightLg,{borderColor:D}]})),t.createElement(p,{style:[o.giftLidLg,{backgroundColor:D}]}),t.createElement(p,{style:[o.giftBodyLg,{borderColor:D}]},t.createElement(p,{style:[o.ribbonVerticalLg,{backgroundColor:"#fff",opacity:.3}]}))),t.createElement(T,{style:[o.title,{color:s.text}]},_),t.createElement(T,{style:[o.subtitle,{color:s.textSecondary}]},e?.description||"Share your unique link and earn rewards for every friend who signs up.")),a.isUserReady?u?t.createElement(Fe,{size:"large",color:D,style:o.loader}):t.createElement(p,{style:o.mainContent},t.createElement(T,{style:[o.label,{color:s.textSecondary}]},"YOUR UNIQUE LINK"),t.createElement(p,{style:[o.inputGroup,{backgroundColor:s.inputBg,borderColor:s.border}]},t.createElement(T,{numberOfLines:1,style:[o.input,{color:s.text}]},n||"Initializing..."),t.createElement(oe,{style:[o.copyBtn,{backgroundColor:i?"#10b981":D}],onPress:se},t.createElement(T,{style:o.copyBtnText},i?"Copied!":"Copy"))),t.createElement(p,{style:o.shareLabelContainer},t.createElement(p,{style:[o.divider,{backgroundColor:s.border}]}),t.createElement(T,{style:[o.shareLabel,{color:s.textSecondary}]},"Share via"),t.createElement(p,{style:[o.divider,{backgroundColor:s.border}]})),t.createElement(p,{style:o.socialContainer},t.createElement(Y,{platform:"twitter",color:R?"#FFFFFF":"#000000",onPress:()=>z("twitter"),icon:"\u{1D54F}",borderColor:s.border,bgColor:s.background}),t.createElement(Y,{platform:"facebook",color:"#1877F2",onPress:()=>z("facebook"),icon:"f",borderColor:s.border,bgColor:s.background}),t.createElement(Y,{platform:"linkedin",color:"#0A66C2",onPress:()=>z("linkedin"),icon:"in",borderColor:s.border,bgColor:s.background}),t.createElement(Y,{platform:"whatsapp",color:"#25D366",onPress:()=>z("whatsapp"),icon:"W",borderColor:s.border,bgColor:s.background}),t.createElement(Y,{platform:"email",color:s.textSecondary,onPress:()=>z("email"),icon:"\u2709",borderColor:s.border,bgColor:s.background}))):t.createElement(p,{style:[o.loadingBox,{backgroundColor:s.inputBg,borderColor:s.border}]},t.createElement(T,{style:{color:s.textSecondary,textAlign:"center"}},"Please log in to view your referral dashboard.")),t.createElement(p,{style:o.footer},t.createElement(T,{style:[o.poweredBy,{color:s.textSecondary}]},"Powered by ",t.createElement(T,{style:[o.brand,{color:D}],onPress:()=>ke.openURL("https://growthrail.com")},"Growth Rail"))))))))},Y=({color:f,onPress:e,icon:r,borderColor:a,bgColor:n})=>t.createElement(oe,{style:[o.socialBtn,{borderColor:a,backgroundColor:n}],onPress:e},t.createElement(T,{style:[o.socialIcon,{color:f}]},r)),o=Re.create({fullScreen:{flex:1},overlay:{...Re.absoluteFillObject},centeredModalContainer:{width:"90%",maxWidth:400,alignSelf:"center",marginTop:xe*.15,overflow:"hidden",shadowColor:"#000",shadowOffset:{width:0,height:20},shadowOpacity:.25,shadowRadius:30,elevation:20},contentWrapper:{paddingTop:Ce.OS==="ios"?20:0},drawerHandle:{width:40,height:4,backgroundColor:"#e5e7eb",borderRadius:2,alignSelf:"center",marginTop:12},scrollContent:{padding:32,alignItems:"center"},closeBtn:{position:"absolute",top:20,right:20,zIndex:10,width:32,height:32,borderRadius:16,backgroundColor:"#f3f4f6",justifyContent:"center",alignItems:"center"},closeIcon:{fontSize:14,color:"#9ca3af"},header:{alignItems:"center",marginBottom:28,width:"100%"},socialIcon:{fontSize:18,fontWeight:"bold"},title:{fontSize:22,fontWeight:"700",letterSpacing:-.5,marginBottom:8,textAlign:"center"},subtitle:{fontSize:14,lineHeight:20,textAlign:"center",paddingHorizontal:10},loadingBox:{padding:16,backgroundColor:"#f9fafb",borderRadius:12,width:"100%",alignItems:"center",borderWidth:1,borderColor:"#e5e7eb",marginTop:20},loader:{marginVertical:20},mainContent:{width:"100%"},label:{fontSize:12,fontWeight:"600",color:"#6b7280",marginBottom:8,letterSpacing:.5},inputGroup:{flexDirection:"row",alignItems:"center",backgroundColor:"#f9fafb",borderWidth:1,borderColor:"#e5e7eb",borderRadius:12,padding:6,marginBottom:24},input:{flex:1,paddingHorizontal:12,fontSize:14,color:"#111827",fontFamily:Ce.OS==="ios"?"Menlo":"monospace"},copyBtn:{paddingVertical:8,paddingHorizontal:16,borderRadius:8,justifyContent:"center",alignItems:"center"},copyBtnText:{color:"#fff",fontSize:13,fontWeight:"600"},shareLabelContainer:{flexDirection:"row",alignItems:"center",marginBottom:16,marginTop:8},divider:{flex:1,height:1,backgroundColor:"#e5e7eb"},shareLabel:{marginHorizontal:12,fontSize:13,fontWeight:"500",color:"#6b7280"},socialContainer:{flexDirection:"row",justifyContent:"center",gap:12},socialBtn:{width:44,height:44,borderRadius:22,backgroundColor:"#fff",borderWidth:1,justifyContent:"center",alignItems:"center"},iconLgContainer:{width:60,height:60,justifyContent:"center",alignItems:"center",marginBottom:16},bowContainerLg:{flexDirection:"row",position:"absolute",top:2,zIndex:2},bowLoopLg:{width:20,height:16,borderWidth:3,borderColor:"#e5e7eb",borderRadius:10},bowLeftLg:{marginRight:-2,transform:[{rotate:"-15deg"}]},bowRightLg:{marginLeft:-2,transform:[{rotate:"15deg"}]},giftLidLg:{width:44,height:10,backgroundColor:"#f3f4f6",borderRadius:2,marginTop:12,zIndex:3},giftBodyLg:{width:36,height:24,borderWidth:3,borderTopWidth:0,borderBottomLeftRadius:4,borderBottomRightRadius:4,justifyContent:"center",alignItems:"center",marginTop:-2},ribbonVerticalLg:{width:4,height:"100%",opacity:.1},footer:{marginTop:32,alignItems:"center"},poweredBy:{fontSize:11,color:"#9ca3af"},brand:{fontWeight:"600",textDecorationLine:"underline"}});import S,{useEffect as Me,useRef as Ne}from"react";import{TouchableOpacity as je,View as P,StyleSheet as _e,Animated as ge,Easing as He}from"react-native";var ue=({onPress:f,options:e})=>{let r=e?.modal?.theme?.primaryColor||"#2563eb",a=e?.trigger?.position||"bottom-right",b=(e?.trigger?.displayMode||"floating")==="edge",u=a.includes("right"),w=a.includes("top"),i=Ne(new ge.Value(-1)).current;Me(()=>{let x=()=>{i.setValue(-1),ge.timing(i,{toValue:2,duration:3e3,easing:He.linear,useNativeDriver:!0}).start(()=>{setTimeout(x,1e3)})};x()},[]);let m=i.interpolate({inputRange:[-1,2],outputRange:b?[-50,100]:[-60,120]}),g={"bottom-right":{bottom:100,right:0},"bottom-left":{bottom:100,left:0},"top-right":{top:100,right:0},"top-left":{top:100,left:0}};b||(g["bottom-right"]={bottom:30,right:20},g["bottom-left"]={bottom:30,left:20},g["top-right"]={top:60,right:20},g["top-left"]={top:60,left:20});let I=()=>S.createElement(P,{style:y.iconContainer},S.createElement(P,{style:y.bowContainer},S.createElement(P,{style:[y.bowLoop,y.bowLeft]}),S.createElement(P,{style:[y.bowLoop,y.bowRight]})),S.createElement(P,{style:y.giftLid}),S.createElement(P,{style:y.giftBody},S.createElement(P,{style:y.ribbonVertical})));return S.createElement(je,{style:[b?y.edgeButton:y.floatingButton,{backgroundColor:r},g[a],b&&(u?y.edgeRight:y.edgeLeft)],onPress:f,activeOpacity:.9},S.createElement(P,{style:y.content},I()),S.createElement(ge.View,{style:[y.shimmer,{transform:[{translateX:m},{skewX:"-15deg"}]}]}))},y=_e.create({floatingButton:{position:"absolute",width:60,height:60,borderRadius:30,justifyContent:"center",alignItems:"center",overflow:"hidden",shadowColor:"#000",shadowOffset:{width:0,height:8},shadowOpacity:.2,shadowRadius:12,elevation:8,zIndex:2147483646},edgeButton:{position:"absolute",width:50,height:50,justifyContent:"center",alignItems:"center",overflow:"hidden",shadowColor:"#000",shadowOffset:{width:0,height:4},shadowOpacity:.1,shadowRadius:8,elevation:4,zIndex:2147483646},edgeRight:{borderTopLeftRadius:8,borderBottomLeftRadius:8,paddingLeft:4},edgeLeft:{borderTopRightRadius:8,borderBottomRightRadius:8,paddingRight:4},content:{justifyContent:"center",alignItems:"center"},iconContainer:{width:28,height:28,justifyContent:"center",alignItems:"center"},bowContainer:{flexDirection:"row",position:"absolute",top:0,zIndex:2},bowLoop:{width:10,height:8,borderWidth:2,borderColor:"#fff",borderRadius:5},bowLeft:{marginRight:-1,transform:[{rotate:"-15deg"}]},bowRight:{marginLeft:-1,transform:[{rotate:"15deg"}]},giftLid:{width:22,height:5,backgroundColor:"#fff",borderRadius:1,marginTop:6,zIndex:3},giftBody:{width:18,height:12,borderWidth:2,borderColor:"#fff",borderTopWidth:0,borderBottomLeftRadius:2,borderBottomRightRadius:2,justifyContent:"center",alignItems:"center",marginTop:-1},ribbonVertical:{width:2,height:"100%",backgroundColor:"#fff",opacity:.8},shimmer:{position:"absolute",top:0,left:0,width:50,height:"100%",backgroundColor:"rgba(255, 255, 255, 0.25)"}});import j,{useEffect as Ke,useRef as qe,useState as Ye}from"react";import{View as Xe,Text as he,StyleSheet as Je,Animated as ne,Dimensions as Qe,TouchableOpacity as Ze,Platform as er}from"react-native";var{width:rr}=Qe.get("window"),Te=({visible:f,options:e,onClose:r})=>{let a=qe(new ne.Value(0)).current,[n,b]=Ye(f),u=e.position.includes("bottom")?"bottom":"top",w=e.position.includes("left")?"left":e.position.includes("right")?"right":"center";if(Ke(()=>{f?(b(!0),ne.spring(a,{toValue:1,useNativeDriver:!0,tension:50,friction:8}).start()):ne.timing(a,{toValue:0,duration:250,useNativeDriver:!0}).start(()=>{b(!1)})},[f]),!n)return null;let i=a.interpolate({inputRange:[0,1],outputRange:[u==="top"?-100:100,0]}),m=a.interpolate({inputRange:[0,1],outputRange:[0,1]}),g={position:"absolute",[u]:er.OS==="ios"?60:40,zIndex:9999};return w==="center"?(g.left=20,g.right=20,g.alignItems="center"):g[w]=20,j.createElement(ne.View,{style:[g,{transform:[{translateY:i}],opacity:m}]},j.createElement(Xe,{style:[X.banner,{backgroundColor:e.themeColor||"#2563eb"}]},j.createElement(he,{style:X.icon},"\u{1F381}"),j.createElement(he,{style:X.text},e.text),j.createElement(Ze,{onPress:r,style:X.closeBtn},j.createElement(he,{style:X.closeIcon},"\u2715"))))},X=Je.create({banner:{flexDirection:"row",alignItems:"center",padding:12,paddingHorizontal:16,borderRadius:12,shadowColor:"#000",shadowOffset:{width:0,height:4},shadowOpacity:.15,shadowRadius:10,elevation:5,maxWidth:rr-40},icon:{fontSize:18,marginRight:10},text:{color:"#fff",fontSize:14,fontWeight:"600",flex:1},closeBtn:{marginLeft:10,padding:4},closeIcon:{color:"rgba(255, 255, 255, 0.8)",fontSize:14,fontWeight:"bold"}});var Le=tr(void 0),sr=({children:f,userId:e,debug:r=!1,...a})=>{let[n,b]=O(!1),[u,w]=O(!1),[i,m]=O(null),g=we(new ee(a)),I=we(!1),x=we(null),[be,R]=O(!1),[_,D]=O(),[me,U]=O(!1),[$,s]=O(),[W,J]=O(!1),[se,z]=O();pe(()=>{g.current.setDebug(r),r&&c.log("info","Provider","Debug mode enabled")},[r]);let Q=V(()=>{let{width:d,height:l}=ir.get("window"),h=Intl.DateTimeFormat().resolvedOptions().locale,C=nr.get(),k,N;if(G.OS==="android"){let ce=G.constants;k=ce.Model,N=ce.Brand||ce.Manufacturer}return{os:G.OS,platform:G.OS,osVersion:String(G.Version),screenWidth:d,screenHeight:l,timezoneOffsetInMinutes:String(new Date().getTimezoneOffset()),locale:h,language:h,deviceModel:k,deviceBrand:N,pixelRatio:C}},[]),E=V(async(d,l)=>{r&&c.log("info","Referral",`Tracking referral code: ${d}`,{referralCode:d,rewardEventName:l});let h=await g.current.trackReferral(d,l);return await v.setTrackedReferral(h.referralTrackingId),r&&c.log("success","Referral",`Referral tracked \u2192 ${h.referralTrackingId}`,h),h},[r]),le=V(async d=>{try{r&&c.log("info","DeepLink",`Received deep link: ${d}`);let l=d.match(/[?&]referralCode=([^&]+)/);l&&(console.log("GrowthRail: Tracking referral from deep link",l[1]),r&&c.log("info","DeepLink",`Found referral code in deep link: ${l[1]}`),await E(l[1]))}catch(l){console.warn("GrowthRail: Error handling deep link",l),r&&c.log("error","DeepLink","Deep link handling failed",{error:String(l)})}},[E,r]),H=V(async()=>{try{r&&c.log("info","Deferred","Checking deferred deep link via fingerprint");let d=Q(),{referralTrackingId:l}=await g.current.checkDeferredDeepLink(d);l?(console.log("GrowthRail: Found deferred referral via fingerprinting",l),r&&c.log("success","Deferred",`Deferred referral matched \u2192 ${l}`),await v.setTrackedReferral(l)):r&&c.log("info","Deferred","No deferred referral match found")}catch(d){console.warn("GrowthRail: Fingerprint check failed",d),r&&c.log("error","Deferred","Fingerprint check failed",{error:String(d)})}},[Q,r]),De=V(()=>new Promise(d=>{ar.getInstallReferrerInfo(async(l,h)=>{if(!h&&l&&l.installReferrer)try{let k=decodeURIComponent(l.installReferrer).match(/[?&]referralCode=([^&]+)/);if(k){let{referralTrackingId:N}=await E(k[1]);await v.setTrackedReferral(N),console.log("GrowthRail: Tracked referral via Install Referrer")}}catch(C){console.warn("GrowthRail: Failed to process install referrer",C)}else await H();d()})}),[E,H]),K=V(async d=>{if(i?.id===d&&u)return r&&c.log("info","User",`User ${d} already initialized, skipping`),i;r&&c.log("info","User",`Initializing user: ${d}`);let l=(async()=>{try{let h=await g.current.initAppUser(d),C={...h,id:d};return m(C),w(!0),r&&c.log("success","User",`User initialized: ${d}`,{referralCode:h.referralCode,referralLink:h.referralLink}),h.referrerExperience?.trigger?.displayMode!=="none"&&(U(!0),r&&c.log("info","UI","Trigger button shown (server-configured)")),C}catch(h){throw x.current=null,r&&c.log("error","User",`User init failed for ${d}`,{error:String(h)}),h}})();return x.current=l,l},[i,u,r]),A=V(async d=>{r&&c.log("info","Reward",`Tracking reward event: ${d||"(default)"}`);let l=i;!l&&x.current&&(l=await x.current);let h=l?.id||e;if(!h)throw r&&c.log("error","Reward","Cannot track reward \u2014 user not initialized"),new Error("GrowthRail: User must be initialized before tracking a reward event.");let C=await v.getTrackedReferral();if(!C){console.warn("GrowthRail: No referral tracking ID found. Reward event not attributed."),r&&c.log("warn","Reward","No referral tracking ID in storage \u2014 reward not attributed");return}let k=await g.current.trackRewardEvent(h,C,d);return r&&c.log("success","Reward",`Reward event tracked for user ${h}`),k},[i,e,r]),B=V(async()=>await v.getTrackedReferral(),[]),F=V(async()=>{if(i)return i.referralLink;if(x.current)return(await x.current).referralLink},[i]);pe(()=>{if(I.current)return;I.current=!0,r&&c.log("info","Provider","SDK initializing\u2026",{platform:G.OS}),(async()=>{let l=await ve.getInitialURL();r&&c.log("info","DeepLink",`Initial URL: ${l??"(none)"}`),l&&await le(l);let h=ve.addEventListener("url",({url:k})=>le(k)),C=await v.isFirstLaunch();r&&c.log("info","Provider",`First launch: ${C}`),C&&(G.OS==="android"?await H():await H()),e&&await K(e);try{let k=await g.current.getNewUserExperience(),N=await v.getTrackedReferral();k.banner?.show&&N&&(z(k.banner),J(!0),r&&c.log("info","UI","Banner shown for new user experience"))}catch(k){r&&c.log("warn","Provider","New user experience fetch failed",{error:String(k)})}return b(!0),r&&c.log("success","Provider","SDK initialization complete \u2713"),()=>h.remove()})()},[]),pe(()=>{n&&e&&i?.id!==e&&K(e)},[e,n]);let M={isInitialized:n,isUserReady:u,currentUser:i,referralCode:i?.referralCode,referralLink:i?.referralLink,showDashboard:d=>{D(d),R(!0)},hideDashboard:()=>R(!1),initUser:K,trackReward:A,getReferralTrackingId:B,getReferralLink:F,isDebugEnabled:r};if(!n)return null;let q=i?.referrerExperience,Be={...q?.modal,..._,appearance:_?.appearance||q?.modal?.appearance||a.appearance,theme:{...q?.modal?.theme||{},..._?.theme||{}}},Oe={...q,...$,trigger:{...q?.trigger||{},...$?.trigger||{}}};return ae.createElement(Le.Provider,{value:M},f,ae.createElement(fe,{visible:be,options:Be,onClose:()=>R(!1)}),me&&ae.createElement(ue,{options:Oe,onPress:()=>M.showDashboard()}),W&&ae.createElement(Te,{visible:W,options:se,onClose:()=>J(!1)}))},ie=()=>{let f=or(Le);if(!f)throw new Error("useGrowthRail must be used within a GrowthRailProvider");return f};import{useState as Se,useCallback as Ie}from"react";var lr=()=>{let[f,e]=Se(!1),[r,a]=Se(null),n=ie(),b=Ie(async w=>{e(!0),a(null);try{return await n.initUser(w)}catch(i){let m=i instanceof Error?i:new Error(String(i));throw a(m),m}finally{e(!1)}},[n]),u=Ie(async w=>{e(!0),a(null);try{await n.trackReward(w)}catch(i){let m=i instanceof Error?i:new Error(String(i));throw a(m),m}finally{e(!1)}},[n]);return{initAppUser:b,trackRewardEvent:u,showReferralDashboard:n.showDashboard,hideReferralDashboard:n.hideDashboard,getReferralTrackingId:n.getReferralTrackingId,getReferralLink:n.getReferralLink,isLoading:f,isInitialized:n.isInitialized,isUserReady:n.isUserReady,error:r,isDebugEnabled:n.isDebugEnabled}};export{sr as GrowthRailProvider,fe as ReferralDashboard,ue as TriggerButton,lr as useGrowthRail};
|