Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,9 @@ jobs:
grep -q 'src="/runtime-config.js"' out/index.html
- name: Install Playwright's Chromium
run: npx playwright install --with-deps chromium
# Includes: a self-hosted install never loads Google's tag.
- name: Self-host checks
run: npx playwright test e2e/selfhost.spec.ts
run: npx playwright test e2e/selfhost.spec.ts e2e/google-analytics.spec.ts --project=chromium
env:
E2E_STATIC: "1"

Expand Down
95 changes: 95 additions & 0 deletions dashboard/e2e/google-analytics.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { expect, test, type BrowserContext, type Route } from "@playwright/test";

// Google Analytics on app.coderhelm.com (components/google-analytics.tsx):
// a page view on the first load and on every client-side route change, with
// the address cut to origin and path. A self-hosted install, and any other
// host, loads nothing. The built dashboard is served as app.coderhelm.com;
// Google's tag is answered here with an empty script, so the page views are
// read from the dataLayer it would have sent.

const APP = "https://app.coderhelm.com";

type Sent = { tag: string[] };

async function serveAsApp(context: BrowserContext, baseURL: string, runtimeConfig: string | null): Promise<Sent> {
const sent: Sent = { tag: [] };
const json = (route: Route, body: unknown, status = 200) =>
route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) });
const api = async (route: Route) => {
const p = new URL(route.request().url()).pathname;
if (p === "/api/me") return json(route, { user_id: "u_1", team_id: "t_1", github_login: "an-admin", email: "admin@coderhelm.com", avatar_url: "", role: "owner" });
if (p === "/api/banners") return json(route, { banners: [] });
if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "your-team", status: "active", current: true }] });
return json(route, { error: "Not mocked" }, 404);
};
await context.route((u) => /^\/(api|auth)\//.test(u.pathname), api);
await context.route(`${APP}/**`, async (route) => {
const u = new URL(route.request().url());
if (/^\/(api|auth)\//.test(u.pathname)) return api(route);
if (u.pathname === "/runtime-config.js" && runtimeConfig !== null) {
return route.fulfill({ contentType: "text/javascript", body: runtimeConfig });
}
const response = await route.fetch({ url: `${baseURL}${u.pathname}${u.search}` });
await route.fulfill({ response });
});
await context.route("https://www.googletagmanager.com/**", (route) => {
sent.tag.push(route.request().url());
return route.fulfill({ contentType: "text/javascript", body: "" });
});
await context.route(/google-analytics\.com|analytics\.google\.com/, (route) => {
sent.tag.push(route.request().url());
return route.fulfill({ status: 204 });
});
return sent;
}

/** The page_view events gtag was given, as page_location values. */
const pageViews = () =>
((window as unknown as { dataLayer?: IArguments[] }).dataLayer ?? [])
.map((a) => Array.from(a))
.filter((a) => a[0] === "event" && a[1] === "page_view")
.map((a) => (a[2] as { page_location: string }).page_location);

test("app.coderhelm.com: page views on the first load and on client-side route changes, origin and path only", async ({ browser, baseURL }) => {
const context = await browser.newContext();
const sent = await serveAsApp(context, baseURL!, null);
const page = await context.newPage();
await page.goto(`${APP}/?tab=secret&id=abc#frag`);
await expect.poll(() => page.evaluate(pageViews)).toEqual([`${APP}/`]);
expect(sent.tag).toEqual(["https://www.googletagmanager.com/gtag/js?id=G-6C41CN6BC6"]);
const config = await page.evaluate(() =>
((window as unknown as { dataLayer: IArguments[] }).dataLayer).map((a) => Array.from(a)).filter((a) => a[0] === "config").at(-1)?.[2],
);
expect(config).toMatchObject({ send_page_view: false, page_location: `${APP}/`, allow_google_signals: false, allow_ad_personalization_signals: false });

// A client-side route change is a page view of its own, on the same document.
await page.getByRole("link", { name: /^Settings(\s|$)/ }).first().click();
await expect(page).toHaveURL(/\/settings\/?/);
await expect.poll(() => page.evaluate(pageViews)).toEqual([`${APP}/`, expect.stringMatching(new RegExp(`^${APP}/settings/?$`))]);
expect(sent.tag).toHaveLength(1);
await context.close();
});

test("a self-hosted install never loads Google's tag, even on app.coderhelm.com", async ({ browser, baseURL }) => {
const context = await browser.newContext();
const sent = await serveAsApp(context, baseURL!, 'window.__CODERHELM_CONFIG__ = { apiUrl: "", streamUrl: "", selfHosted: true };');
const page = await context.newPage();
await page.goto(`${APP}/`);
await expect(page.locator("body")).toBeVisible();
await page.waitForTimeout(1500);
expect(sent.tag).toEqual([]);
expect(await page.evaluate(pageViews)).toEqual([]);
await context.close();
});

test("localhost and previews never load Google's tag", async ({ page }) => {
const tag: string[] = [];
await page.route(/googletagmanager\.com|google-analytics\.com|analytics\.google\.com/, (route) => {
tag.push(route.request().url());
return route.abort();
});
await page.route((u) => /^\/(api|auth)\//.test(u.pathname), (route) => route.fulfill({ status: 401, contentType: "application/json", body: "{}" }));
await page.goto("/");
await page.waitForTimeout(1500);
expect(tag).toEqual([]);
});
75 changes: 55 additions & 20 deletions dashboard/src/components/google-analytics.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"use client";

import Script from "next/script";
import { usePathname } from "next/navigation";
import { useEffect } from "react";
import { isSelfHosted } from "@/lib/runtime-config";

declare global {
interface Window {
Expand All @@ -12,29 +12,64 @@ declare global {

const GA_MEASUREMENT_ID = "G-6C41CN6BC6";

/** The only host the tag runs on: never a self-hosted install, localhost or a preview. */
export const ANALYTICS_HOST = "app.coderhelm.com";

/** Whether this page may send analytics to the hosted dashboard's Google Analytics. */
export function analyticsAllowed(): boolean {
return typeof window !== "undefined" && window.location.hostname === ANALYTICS_HOST && !isSelfHosted();
}

/** Origin and path only: dashboard addresses carry ids and filters after `?`. */
function pageLocation(): string {
return `${window.location.origin}${window.location.pathname}`;
}

let started = false;

function start() {
started = true;
// The same dataLayer lib/gtm.ts pushes to; gtag must push the arguments object itself.
const layer = (window.dataLayer = window.dataLayer ?? []) as unknown[];
window.gtag = function gtag() {
layer.push(arguments);
};
window.gtag("js", new Date());
const s = document.createElement("script");
s.async = true;
s.src = `https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`;
document.head.appendChild(s);
}

/**
* The tag's settings for the page now showing. Setting page_location here
* also stops the tag's own history page views, so each page counts once.
*/
function configure() {
window.gtag("config", GA_MEASUREMENT_ID, {
send_page_view: false,
page_location: pageLocation(),
page_referrer: "",
allow_google_signals: false,
allow_ad_personalization_signals: false,
});
}

/**
* Page views on app.coderhelm.com: the first load and every client-side route
* change. gtag queues calls until its script loads, so the first view is
* never lost. A self-hosted install (runtime-config.js says selfHosted) loads
* nothing.
*/
export function GoogleAnalytics() {
const pathname = usePathname();

useEffect(() => {
if (typeof window.gtag !== "function") return;
window.gtag("event", "page_view", { page_path: pathname });
if (!analyticsAllowed()) return;
if (!started) start();
configure();
window.gtag("event", "page_view", { page_location: pageLocation(), page_title: document.title });
}, [pathname]);

return (
<>
<Script
src={`https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`}
strategy="afterInteractive"
/>
<Script id="gtag-init" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
window.gtag = gtag;
gtag('js', new Date());
gtag('config', '${GA_MEASUREMENT_ID}', { send_page_view: false });
`}
</Script>
</>
);
return null;
}
2 changes: 2 additions & 0 deletions docs/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Metadata, Viewport } from 'next';
import { Geist, Geist_Mono } from 'next/font/google';
import { Analytics } from '@/components/analytics';
import { Provider } from '@/components/provider';
import { SITE } from '@/lib/shared';
import './global.css';
Expand Down Expand Up @@ -33,6 +34,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
<html lang="en" className={`${sans.variable} ${mono.variable}`} suppressHydrationWarning>
<body className="flex min-h-screen flex-col">
<Provider>{children}</Provider>
<Analytics />
</body>
</html>
);
Expand Down
156 changes: 156 additions & 0 deletions docs/components/analytics.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
'use client';

// Google Analytics on docs.coderhelm.com only (lib/analytics.ts says what is
// sent and what never is). Nothing loads on localhost, previews or a
// self-hosted build of the docs. The tag loads once the browser is idle or
// the reader first interacts, so it never competes with the page itself.

import { usePathname } from 'next/navigation';
import { useEffect, useRef } from 'react';
import {
GA_ID,
LINKER_DOMAINS,
PAGE_VIEW_MARK,
cleanUrl,
clickEvent,
isCollectUrl,
outboundHost,
scrubHit,
shouldLoad,
type DocsEvent,
} from '@/lib/analytics';

type Gtag = (...args: unknown[]) => void;
type AnalyticsWindow = Window & { dataLayer?: unknown[]; gtag?: Gtag; __chAnalytics?: boolean };

function active(): boolean {
return typeof window !== 'undefined' && (window as AnalyticsWindow).__chAnalytics === true;
}

/** Sends one docs event; does nothing where analytics is off. */
export function track(event: DocsEvent | null): void {
if (!event || !active()) return;
const { name, ...fields } = event;
(window as AnalyticsWindow).gtag?.('event', name, fields);
}

function here(): string {
return cleanUrl(window.location.href) ?? window.location.origin;
}

/** Every hit leaves through scrubHit(), whichever transport the tag picks. */
function guardTransport(w: AnalyticsWindow) {
const beacon = navigator.sendBeacon?.bind(navigator);
if (beacon) {
navigator.sendBeacon = (url: string | URL, data?: BodyInit | null) => {
const u = String(url);
if (!isCollectUrl(u)) return beacon(url, data);
if (data != null && typeof data !== 'string') return true; // only text bodies are ever built by the tag; anything else is not sent
const hit = scrubHit(u, data);
return hit ? beacon(hit.url, hit.body) : true;
};
}
const fetchFn = w.fetch.bind(w);
w.fetch = (input: RequestInfo | URL, init?: RequestInit) => {
const u = typeof input === 'string' || input instanceof URL ? String(input) : input.url;
if (!isCollectUrl(u)) return fetchFn(input, init);
const body = init?.body;
if (body != null && typeof body !== 'string') return Promise.resolve(new Response(null, { status: 204 }));
const hit = scrubHit(u, body);
if (!hit) return Promise.resolve(new Response(null, { status: 204 }));
return fetchFn(hit.url, { ...init, body: hit.body ?? undefined });
};
// The tag's last fallback is an image request.
const src = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, 'src');
if (src?.set && src.get) {
Object.defineProperty(HTMLImageElement.prototype, 'src', {
configurable: true,
enumerable: src.enumerable,
get: src.get,
set(this: HTMLImageElement, v: string) {
const s = String(v);
if (!isCollectUrl(s)) return src.set!.call(this, v);
const hit = scrubHit(s, null);
if (hit) src.set!.call(this, hit.url);
},
});
}
}

/**
* The tag's settings for the page now showing. Setting page_location here
* also stops the tag's own history page views, so each page counts once.
*/
function configure(w: AnalyticsWindow, referrer: string) {
w.gtag?.('config', GA_ID, {
send_page_view: false,
page_location: here(),
page_referrer: referrer,
allow_google_signals: false,
allow_ad_personalization_signals: false,
linker: { domains: LINKER_DOMAINS, accept_incoming: true },
});
}

function start(w: AnalyticsWindow) {
w.__chAnalytics = true;
guardTransport(w);
w.dataLayer = w.dataLayer || [];
// gtag must push the arguments object itself.
w.gtag = function gtag() {
w.dataLayer!.push(arguments);
};
w.gtag('js', new Date());
configure(w, document.referrer ? cleanUrl(document.referrer) ?? '' : '');

// Load the tag when the browser is idle or the reader first interacts.
let loaded = false;
const load = () => {
if (loaded) return;
loaded = true;
for (const t of INTERACTIONS) window.removeEventListener(t, load, true);
const s = document.createElement('script');
s.async = true;
s.src = `https://www.googletagmanager.com/gtag/js?id=${GA_ID}`;
document.head.appendChild(s);
};
const INTERACTIONS = ['pointerdown', 'keydown', 'scroll', 'touchstart'];
for (const t of INTERACTIONS) window.addEventListener(t, load, { capture: true, passive: true, once: true });
const idle = () => (window.requestIdleCallback ? window.requestIdleCallback(load, { timeout: 4000 }) : setTimeout(load, 2500));
if (document.readyState === 'complete') idle();
else window.addEventListener('load', idle, { once: true });

// Clicks worth counting: copy buttons and links that leave the docs.
document.addEventListener(
'click',
(e) => {
const el = e.target instanceof Element ? e.target : null;
if (!el) return;
const button = el.closest('button');
if (button) return track(clickEvent(button.textContent));
const a = el.closest('a[href]');
const host = a ? outboundHost(a.getAttribute('href') ?? '', window.location.href) : null;
if (host) track({ name: 'outbound_click', link_domain: host });
},
{ capture: true },
);
}

/** Page views, on the first load and on every client-side navigation. */
export function Analytics() {
const pathname = usePathname();
const previous = useRef<string | null>(null);
useEffect(() => {
const w = window as AnalyticsWindow;
if (!shouldLoad(window.location.hostname)) return;
if (!w.__chAnalytics) start(w);
else configure(w, previous.current ?? '');
previous.current = here();
w.gtag?.('event', 'page_view', {
page_location: here(),
page_title: document.title,
[PAGE_VIEW_MARK]: 1,
});
}, [pathname]);
return null;
}
Loading
Loading