All files / scripts/instrumentor/fingerprint patcherContext.ts

100% Statements 18/18
100% Branches 0/0
100% Functions 5/5
100% Lines 18/18

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                                      4x   4x 4x 4x     4x                     4x 4x         4x   4x 2x 2x 2x 2x     4x 2x 2x 2x     4x    
import { WritablePatcherContext } from '../patcher/context'
import { FingerprintLoader } from '../../shared/fingerprint/types'
import { getIntegrationInfo } from '../../../shared/integrationInfo'
import { logger } from '../../shared/logger'
 
export type SetupPatcherContextParams = {
  // Writable patcher context to configure with signals' provider
  patcherCtx: WritablePatcherContext
  fingerprintLoader: Promise<FingerprintLoader>
  endpoint: string
}
 
/**
 * Sets up patcher context for fingerprinting.
 *
 * This function initialises the fingerprinting signals and agent data processing providers by waiting for the document
 * to be ready and then loading the FingerprintJS agent.
 */
export async function setupPatcherContext(params: SetupPatcherContextParams) {
  logger.debug('Setting up signals collection...', document.readyState)
 
  const listener = async () => {
    await setProviders(params)
    document.removeEventListener('DOMContentLoaded', listener)
  }
 
  document.addEventListener('DOMContentLoaded', listener)
}
 
/**
 * Sets the necessary providers for fingerprinting in the patcher context.
 *
 * This function loads the FingerprintJS agent and configures the patcher context
 * with a necessary signals' provider and agent data processor.'
 *
 */
async function setProviders({ fingerprintLoader, endpoint, patcherCtx }: SetupPatcherContextParams) {
  const loader = await fingerprintLoader
  const agent = await loader.start({
    endpoints: endpoint,
    integrationInfo: [getIntegrationInfo('instrumentor')],
  })
 
  logger.debug('FingerprintJS agent loaded', agent)
 
  patcherCtx.setSignalsProvider(async () => {
    logger.debug('Collecting signals...')
    const signals = await agent.collect()
    logger.debug('Signals collected:', signals)
    return signals
  })
 
  patcherCtx.setAgentDataProcessor((data) => {
    logger.debug('Processing agent data:', data)
    loader.handleAgentData(data)
    logger.debug('Agent data processed.')
  })
 
  logger.debug('Patcher context prepared.')
}