All files / src/lib gtm-load.ts

100% Statements 2/2
100% Branches 7/7
100% Functions 2/2
100% Lines 2/2

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                                      87x                               5x    
// Server-side decisions behind GoogleTagManager.astro (#1086). They live here,
// not in the component, so the middleware can apply the same auditor rule
// (see `isSyntheticAuditor` there) and both stay unit-tested: a .astro
// component cannot be rendered by this app's test setup.
 
/**
 * A Lighthouse or headless-browser audit. GTM is left out of its render: the
 * container ships ~130 KiB of unused JS that lands before Lighthouse's quiet
 * point and tanks the Performance score. Real users always get GTM.
 *
 * Signals: a HeadlessChrome / Lighthouse user agent, or the `?_lh` cache-buster
 * our audit runner (scripts/lighthouse/run.ts) appends to every URL —
 * Lighthouse 13 drops "HeadlessChrome" from the network UA, so the UA alone
 * cannot catch it.
 */
export function isSyntheticAuditor(
	userAgent: string | null | undefined,
	url: URL,
): boolean {
	return (
		/HeadlessChrome|Lighthouse|Chrome-Lighthouse/i.test(userAgent ?? "") ||
		url.searchParams.has("_lh")
	);
}
 
/** Whether this render should include the GTM container snippet. */
export function shouldLoadGtm({
	environment,
	containerId,
	auditor,
}: {
	environment: string;
	containerId: string;
	auditor: boolean;
}): boolean {
	return environment !== "local" && Boolean(containerId) && !auditor;
}