All files / worker handler.ts

93.75% Statements 15/16
100% Branches 9/9
100% Functions 1/1
93.75% Lines 15/16

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                          55x   55x 55x   55x   2x     6x                     6x 2x     4x   4x     40x 4x     36x             1x   1x            
import { TypedEnv } from './types'
import { matchUrl } from './urlMatching'
import { handleScriptsInjection } from './handlers/handleScriptsInjection'
import { handleScript } from './handlers/handleScript'
import { getCDNHost, getFpLogLevel, getProtectedApis, getPublicKey, getRoutePrefix } from './env'
 
import { handleError } from './handlers/handleError'
import { fetchOrigin } from './utils/origin'
import { handleProtectedApiCall } from './handlers/handleProtectedApi'
import { IdentificationClient } from './fingerprint/identificationClient'
import { handleProtectedApiOptionsCall } from './handlers/handleProtectedApiOptions'
 
export async function handleRequest(request: Request, env: TypedEnv): Promise<Response> {
  console.info('Handling request', request)
 
  try {
    const matchedUrl = matchUrl(new URL(request.url), request.method, env)
 
    switch (matchedUrl?.type) {
      case 'identification':
        return handleScriptsInjection({ request, env })
 
      case 'script':
        return handleScript({
          request,
          script: matchedUrl.script,
          publicApiKey: getPublicKey(env),
          cdnHost: getCDNHost(env),
          protectedApis: getProtectedApis(env),
          routePrefix: getRoutePrefix(env),
          logLevel: getFpLogLevel(env),
        })
 
      case 'browserCache':
        if (request.method === 'GET') {
          return IdentificationClient.fromEnv(env).browserCache(request)
        }
 
        console.warn(`Invalid method for browser cache request: ${request.method}. Falling back to origin.`)
 
        return fetchOrigin(request)
 
      case 'protection':
        if (matchedUrl.options) {
          return handleProtectedApiOptionsCall({ request, env })
        }
 
        return handleProtectedApiCall({
          request,
          identificationClient: IdentificationClient.fromEnv(env),
          env,
        })
 
      default:
        console.info('No matched url')
 
        return fetchOrigin(request)
    }
  } catch (error) {
    return handleError(error)
  }
}