()
| 10 | const JWT_STALE_TIME = 9 * 60 * 1000; |
| 11 | |
| 12 | export const useIntercom = (): void => { |
| 13 | const { user } = useAuthContext(); |
| 14 | const bootedWithJwtRef = useRef(false); |
| 15 | |
| 16 | // Fetch JWT in background for authenticated users |
| 17 | const { data: jwtData } = useQuery({ |
| 18 | queryKey: ['intercom-jwt', user?.id], |
| 19 | queryFn: async () => { |
| 20 | const res = await fetch(`${apiUrl}/integrations/intercom/jwt`, { |
| 21 | credentials: 'include', |
| 22 | }); |
| 23 | if (!res.ok) { |
| 24 | throw new Error('Failed to fetch Intercom JWT'); |
| 25 | } |
| 26 | return res.json(); |
| 27 | }, |
| 28 | enabled: !!user && !!INTERCOM_APP_ID, |
| 29 | staleTime: JWT_STALE_TIME, |
| 30 | }); |
| 31 | |
| 32 | // Initial boot - non-blocking, just app_id |
| 33 | useEffect(() => { |
| 34 | if (!INTERCOM_APP_ID) { |
| 35 | return; |
| 36 | } |
| 37 | |
| 38 | Intercom({ |
| 39 | app_id: INTERCOM_APP_ID, |
| 40 | }); |
| 41 | }, []); |
| 42 | |
| 43 | // Re-boot with JWT once available |
| 44 | useEffect(() => { |
| 45 | if (!INTERCOM_APP_ID || !jwtData?.jwt) { |
| 46 | return; |
| 47 | } |
| 48 | |
| 49 | // Shutdown existing session to avoid conflicts |
| 50 | if (bootedWithJwtRef.current) { |
| 51 | shutdown(); |
| 52 | } |
| 53 | |
| 54 | boot({ |
| 55 | app_id: INTERCOM_APP_ID, |
| 56 | intercom_user_jwt: jwtData.jwt, |
| 57 | }); |
| 58 | |
| 59 | bootedWithJwtRef.current = true; |
| 60 | }, [jwtData?.jwt]); |
| 61 | |
| 62 | // Shutdown on unmount |
| 63 | useEffect(() => { |
| 64 | return () => { |
| 65 | if (INTERCOM_APP_ID) { |
| 66 | shutdown(); |
| 67 | } |
| 68 | }; |
| 69 | }, []); |
no test coverage detected