Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

2.6 KB
Raw Blame
import { compileFile } from '../../compiler/index.js'
import variantsFile from '../../compiler/variants.json' with { type: 'json' }
import { Page } from '@playwright/test'
import { VerifierArgs, VerifierResult } from './types'

const VERIFIER_JS_VARIANT = variantsFile.manualVariants.find(
  (variant) => variant.name === 'verifier.js'
)
const DETECTOR_JS_VARIANT = variantsFile.manualVariants.find(
  (variant) => variant.name === 'detector.js'
)

export async function executeVerifier(
  page: Page,
  {
    responseHeaders,
    maxAttempts,
    timeoutBetweenAttemptsMs,
    ...functionContext
  }: VerifierArgs & { maxAttempts: number; timeoutBetweenAttemptsMs: number }
): Promise<VerifierResult> {
  const verifierCode = (await compileFile(VERIFIER_JS_VARIANT, {
    returnCode: true
  })) as string

  try {
    async function verify() {
      await page.evaluate(verifierCode) // injects window.verifyPlausibleInstallation
      return await page.evaluate(
        (c) => {
          // @ts-expect-error - window.verifyPlausibleInstallation has been injected
          return window.verifyPlausibleInstallation(c)
        },
        { ...functionContext, responseHeaders }
      )
    }

    let lastError
    for (let attempts = 1; attempts <= maxAttempts; attempts++) {
      try {
        const output = await verify()
        return {
          data: {
            ...output.data,
            attempts
          }
        }
      } catch (error) {
        lastError = error
        if (
          error instanceof Error &&
          error.message.toLowerCase().includes('execution context')
        ) {
          await new Promise((resolve) =>
            setTimeout(resolve, timeoutBetweenAttemptsMs)
          )
          continue
        }
        throw error
      }
    }
    throw lastError
  } catch (error) {
    return {
      data: {
        completed: false,
        error: {
          message:
            error instanceof Error ? error.message : JSON.stringify(error)
        }
      }
    }
  }
}

export async function detect(
  page: Page,
  context: {
    url: string
    detectV1: boolean
    timeoutMs?: number
    debug?: boolean
  }
) {
  const { url, detectV1, timeoutMs } = context
  const debug = context.debug ? true : false

  const detectorCode = (await compileFile(DETECTOR_JS_VARIANT, {
    returnCode: true
  })) as string

  await page.goto(url)
  await page.evaluate(detectorCode)

  return await page.evaluate(
    async (d) => {
      // @ts-expect-error - window.scanPageBeforePlausibleInstallation has been injected
      return await window.scanPageBeforePlausibleInstallation(d)
    },
    { detectV1, debug, timeoutMs }
  )
}