import assert from 'node:assert/strict' import { spawn } from 'node:child_process' import { once } from 'node:events' import { mkdtemp, readFile, rm } from 'node:fs/promises' import { createServer } from 'node:http' import { createRequire } from 'node:module' import { tmpdir } from 'node:os' import path from 'node:path' import { setTimeout as delay } from 'node:timers/promises' import { fileURLToPath } from 'node:url' import test from 'node:test' import puppeteer from 'puppeteer-core' const cwd = fileURLToPath(new URL('..', import.meta.url)) const executablePath = process.env.BRAVE_EXECUTABLE || (process.platform === 'darwin' ? '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser' : 'brave-browser') const assetDirectory = fileURLToPath(new URL('../../../packages/browser/dist/', import.meta.url)) async function listen(server) { server.listen(0, '127.0.0.1') await once(server, 'listening') return `http://127.0.0.1:${server.address().port}` } async function waitUntil(check, description, timeout = 30000) { const deadline = Date.now() + timeout while (Date.now() < deadline) { if (await check()) return await delay(100) } throw new Error(`Timed out waiting for ${description}`) } function docusaurus(args, env) { const child = spawn(process.execPath, ['node_modules/@docusaurus/core/bin/docusaurus.mjs', ...args], { cwd, env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'], }) let output = '' child.stdout.on('data', (data) => { output += data }) child.stderr.on('data', (data) => { output += data }) return { child, output: () => output } } async function stop(child) { if (child.exitCode !== null || child.signalCode !== null) return const exited = once(child, 'exit') child.kill('SIGTERM') await exited } function decodeEvents(body) { let parsed try { parsed = JSON.parse(body) } catch { // A form body carries the base64 batch in `data`; a beacon body is the bare base64 text, which capture // decodes the same way. parsed = { data: new URLSearchParams(body).get('data') ?? body } } if (typeof parsed.data === 'string') { parsed = JSON.parse(Buffer.from(parsed.data, 'base64').toString()) } return parsed.batch || (Array.isArray(parsed) ? parsed : [parsed]) } await test('Docusaurus compatibility with the real PostHog SDK', async (t) => { const installedPlugin = createRequire(import.meta.url).resolve('posthog-docusaurus') const builtPlugin = new URL('../../../packages/docusaurus/dist/index.js', import.meta.url) assert.ok( (await readFile(installedPlugin)).equals(await readFile(builtPlugin)), "Repack the plugin, remove this example's node_modules, and run pnpm install to install the current build" ) const events = [] const ingestionErrors = [] const assets = new Map() const api = createServer(async (req, res) => { res.setHeader('Access-Control-Allow-Origin', '*') res.setHeader('Access-Control-Allow-Headers', '*') if (req.method === 'OPTIONS') return res.end() const url = new URL(req.url, 'http://localhost') try { if (url.pathname.endsWith('/config.js')) { res.statusCode = 404 return res.end() } if (url.pathname.endsWith('/config')) { res.setHeader('Content-Type', 'application/json') return res.end(JSON.stringify({ autocapture_opt_out: false })) } if (url.pathname.startsWith('/static/')) { if (!assets.has(url.pathname)) { assets.set( url.pathname, await readFile(path.join(assetDirectory, path.basename(url.pathname)), 'utf8') ) } res.setHeader('Content-Type', 'application/javascript') return res.end(assets.get(url.pathname)) } if (url.pathname === '/e/' || url.pathname === '/i/v0/e/') { let body = '' for await (const chunk of req) body += chunk events.push(...decodeEvents(body)) } res.setHeader('Content-Type', 'application/json') res.end( JSON.stringify( url.pathname.startsWith('/flags') ? { featureFlags: {}, featureFlagPayloads: {}, sessionRecording: false, surveys: [] } : { status: 1 } ) ) } catch (error) { ingestionErrors.push(error.message) res.statusCode = 500 res.end() } }) const apiUrl = await listen(api) t.after(() => { api.closeAllConnections() return new Promise((resolve) => api.close(resolve)) }) const env = { POSTHOG_TEST_API_HOST: apiUrl } const build = docusaurus(['build'], env) const [code] = await once(build.child, 'exit') assert.equal(code, 0, build.output()) const userDataDir = await mkdtemp(path.join(tmpdir(), 'posthog-docusaurus-brave-')) const browser = await puppeteer.launch({ executablePath, userDataDir, headless: true }) t.after(async () => { await browser.close() await rm(userDataDir, { recursive: true, force: true }) }) const browserErrors = [] async function newPage(context = browser) { const page = await context.newPage() page.on('pageerror', (error) => browserErrors.push(error.message)) await page.setRequestInterception(true) page.on('request', (req) => { const url = new URL(req.url()) if (url.hostname === '127.0.0.1' || url.protocol === 'data:') req.continue() else req.abort() }) return page } const page = await newPage() async function startSite(args, extraEnv = {}) { const reservation = createServer() const siteUrl = await listen(reservation) const port = reservation.address().port await new Promise((resolve) => reservation.close(resolve)) const process = docusaurus([...args, '--host', '127.0.0.1', '--port', String(port), '--no-open'], { ...env, ...extraEnv, }) t.after(() => stop(process.child)) await waitUntil( async () => { assert.equal(process.child.exitCode, null, process.output()) try { return (await fetch(siteUrl)).ok } catch { return false } }, 'Docusaurus server', 90000 ) return { ...process, siteUrl } } const production = await startSite(['serve']) await page.goto(production.siteUrl, { waitUntil: 'networkidle0' }) await page.waitForFunction(() => window.posthog?.__loaded) await waitUntil(() => events.some((event) => event.event === '$pageview'), 'initial pageview') console.log('SDK version:', await page.evaluate(() => window.posthog.version)) await t.test('production SSR, hydration and SDK initialization', async () => { const html = await (await fetch(production.siteUrl)).text() assert.match(html, /