All files useVisitorData.ts

100% Statements 28/28
100% Branches 8/8
100% Functions 3/3
100% Lines 28/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68                        18x 18x 18x 18x   18x   18x 1x     17x 19x 19x 19x 19x   19x 19x 19x   13x 13x   13x   6x 6x   6x   19x       17x 17x 3x 3x       1x         17x                
import type { GetOptions, GetResult } from '@fingerprint/agent'
import type { FingerprintSvelteContext } from './types'
import { writable } from 'svelte/store'
import { getContext, onMount } from 'svelte'
import { FINGERPRINT_CONTEXT } from './symbols'
import type { UseGetVisitorDataResult, UseVisitorDataOptions } from './useVisitorData.types'
 
/** Reactive hook for fetching Fingerprint visitor data. Must be called inside a component wrapped with {@link FingerprintProvider}. */
export function useVisitorData({
  immediate = true,
  ...getOptionsDefaults
}: UseVisitorDataOptions = {}): UseGetVisitorDataResult {
  const dataValue = writable<GetResult | undefined>(undefined)
  const loadingValue = writable(false)
  const isFetchedValue = writable(false)
  const errorValue = writable<Error | undefined>(undefined)
 
  const context = getContext<FingerprintSvelteContext>(FINGERPRINT_CONTEXT)
 
  if (!context) {
    throw new Error('Fingerprint context is missing. Did you forget to wrap your component with <FingerprintProvider>?')
  }
 
  const getData = async (options?: GetOptions): Promise<GetResult> => {
    loadingValue.set(true)
    isFetchedValue.set(false)
    dataValue.set(undefined)
    errorValue.set(undefined)
 
    try {
      const mergedOptions: GetOptions = { ...getOptionsDefaults, ...options }
      const result = await context.getVisitorData(mergedOptions)
 
      dataValue.set(result)
      isFetchedValue.set(true)
 
      return result
    } catch (error) {
      const normalizedError = error instanceof Error ? error : new Error(String(error))
      errorValue.set(normalizedError)
 
      throw normalizedError
    } finally {
      loadingValue.set(false)
    }
  }
 
  onMount(async () => {
    if (immediate) {
      try {
        await getData()
      } catch (error) {
        // getData() rethrows so manual callers can handle errors themselves.
        // Swallow here to avoid an unhandled rejection during onMount — the error is already stored in the error store.
        console.error('Failed to fetch visitor data on mount:', error)
      }
    }
  })
 
  return {
    data: dataValue,
    error: errorValue,
    isLoading: loadingValue,
    isFetched: isFetchedValue,
    getData,
  }
}