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
66 changes: 66 additions & 0 deletions e2e/analytics-path.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { expect, test, type Page } from '@playwright/test'

test.use({ serviceWorkers: 'block' })

test.beforeEach(async ({ page }) => {
await page.route('**/_vercel/insights/**', (route) => route.abort())
await page.route('**://va.vercel-scripts.com/**', (route) => route.abort())
})

async function pageviews(page: Page): Promise<{ path?: string; route?: string | null }[]> {
await page.waitForFunction(() => {
const queue = (window as unknown as { vaq?: unknown[][] }).vaq
return Array.isArray(queue) && queue.some((entry) => entry[0] === 'pageview')
})
return page.evaluate(() => {
const queue = (window as unknown as { vaq?: unknown[][] }).vaq ?? []
return queue
.filter((entry) => entry[0] === 'pageview')
.map((entry) => entry[1] as { path?: string; route?: string | null })
})
}

test('home, locale, and a blog post report clean paths once', async ({ page }) => {
await page.goto('/')
await expect.poll(async () => pageviews(page)).toEqual([{ path: '/', route: '/' }])
await expect(page.locator('vercel-analytics')).toHaveAttribute('data-pathname', '/')

await page.goto('/es')
await expect.poll(async () => pageviews(page)).toEqual([{ path: '/es', route: '/es' }])

await page.goto('/blog/edit-raw-photos-in-browser')
await expect.poll(async () => pageviews(page)).toEqual([
{ path: '/blog/edit-raw-photos-in-browser', route: '/blog/[slug]' },
])
})

test('a query string does not bring back the html pathname', async ({ page }) => {
await page.goto('/?utm=newsletter')
await expect.poll(async () => pageviews(page)).toEqual([{ path: '/', route: '/' }])
})

test('the 404 page reports the URL that missed', async ({ page }) => {
const response = await page.goto('/no-such-page')
expect(response?.status()).toBe(404)
await expect.poll(async () => pageviews(page)).toEqual([{ path: '/no-such-page', route: '/no-such-page' }])
await expect(page.locator('vercel-analytics')).toHaveAttribute('data-pathname', '/no-such-page')
})

test('the editor keeps React analytics and does not add an Astro pageview', async ({ page }) => {
await page.goto('/editor')
await expect(page.getByRole('banner').getByText('Lightframes', { exact: true })).toBeVisible()
await expect(page.locator('vercel-analytics')).toHaveCount(0)
const queued = await page.evaluate(() => {
const queue = (window as unknown as { vaq?: unknown[][] }).vaq ?? []
return queue.filter((entry) => entry[0] === 'pageview')
})
expect(queued).toEqual([])
})

test('an html-shaped miss is reported as requested', async ({ page }) => {
const response = await page.goto('/retired-guide.html')
expect(response?.status()).toBe(404)
await expect.poll(async () => pageviews(page)).toEqual([
{ path: '/retired-guide.html', route: '/retired-guide.html' },
])
})
75 changes: 75 additions & 0 deletions scripts/analytics-path.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import vm from 'node:vm'
import { analyticsPathClient, analyticsPathname } from '../src/site/analyticsPath.ts'

test('file-format pathnames match clean URLs', () => {
assert.equal(analyticsPathname('/index.html', '/'), '/')
assert.equal(analyticsPathname('/es.html', '/es'), '/es')
assert.equal(analyticsPathname('/blog.html', '/blog'), '/blog')
assert.equal(analyticsPathname('/blog/edit-raw-photos-in-browser.html', '/blog/edit-raw-photos-in-browser'), '/blog/edit-raw-photos-in-browser')
assert.equal(analyticsPathname('/es/blog/edit-raw-photos-in-browser.html', '/es'), '/es/blog/edit-raw-photos-in-browser')
assert.equal(analyticsPathname('/', '/'), '/')
assert.equal(analyticsPathname('/editor', '/editor'), '/editor')
assert.equal(analyticsPathname('/tools/raw-photo-editor.html', '/tools/raw-photo-editor'), '/tools/raw-photo-editor')
})

test('the 404 document reports the requested pathname, including a .html miss', () => {
assert.equal(analyticsPathname('/404.html', '/missing'), '/missing')
assert.equal(analyticsPathname('/404', '/missing/page.html'), '/missing/page.html')
assert.equal(analyticsPathname('/404.html', '/404'), '/404')
assert.equal(analyticsPathname('/404.html', ''), '/')
})

test('query and hash on the built pathname are not part of the reported path', () => {
assert.equal(analyticsPathname('/blog.html?utm=1', '/blog'), '/blog')
assert.equal(analyticsPathname('/index.html#top', '/'), '/')
})

function applyClient(built, locationPath) {
const attrs = { 'data-pathname': built }
const el = {
getAttribute(name) {
return Object.prototype.hasOwnProperty.call(attrs, name) ? attrs[name] : null
},
setAttribute(name, value) {
attrs[name] = value
},
}
vm.runInNewContext(analyticsPathClient, {
document: { querySelector: () => el },
location: { pathname: locationPath },
})
return attrs
}

test('the inline script rewrites data-pathname once, before the analytics element upgrades', () => {
const home = applyClient('/index.html', '/')
assert.equal(home['data-pathname'], '/')
assert.equal(home['data-pathname-ready'], '1')

const missing = applyClient('/404.html', '/no-such-page')
assert.equal(missing['data-pathname'], '/no-such-page')

const htmlMiss = applyClient('/404.html', '/old-page.html')
assert.equal(htmlMiss['data-pathname'], '/old-page.html')

vm.runInNewContext(analyticsPathClient, {
document: {
querySelector: () => ({
getAttribute(name) {
return name === 'data-pathname-ready' ? '1' : '/index.html'
},
setAttribute() {
throw new Error('rewrote a pathname that was already applied')
},
}),
},
location: { pathname: '/' },
})

vm.runInNewContext(analyticsPathClient, {
document: { querySelector: () => null },
location: { pathname: '/' },
})
})
17 changes: 17 additions & 0 deletions scripts/sitemap-redirect.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { readFileSync } from 'node:fs'

test('sitemap.xml redirects permanently to the index without catching the real sitemap files', () => {
const config = JSON.parse(readFileSync(new URL('../vercel.json', import.meta.url), 'utf8'))
assert.deepEqual(config.redirects, [
{
source: '/sitemap.xml',
destination: '/sitemap-index.xml',
permanent: true,
},
])
const sources = config.redirects.map((redirect) => redirect.source)
assert.equal(sources.includes('/sitemap-index.xml'), false)
assert.equal(sources.includes('/sitemap-0.xml'), false)
})
31 changes: 31 additions & 0 deletions src/site/analyticsPath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* Pathname `@vercel/analytics/astro` should report.
*
* With `build.format: 'file'`, `Astro.url.pathname` is `/index.html`, `/es.html`, `/404.html`.
* Vercel `cleanUrls` serves those documents at `/`, `/es`, and (for a miss) the address-bar URL.
* The 404 document is always `/404`; `locationPathname` is the request that failed.
*/
export function analyticsPathname(builtPathname: string, locationPathname: string): string {
const cut = builtPathname.search(/[?#]/)
let path = cut === -1 ? builtPathname : builtPathname.slice(0, cut)
if (path.endsWith('/index.html')) path = path.slice(0, -'index.html'.length)
else if (path.endsWith('.html')) path = path.slice(0, -'.html'.length)
if (path.length > 1 && path.endsWith('/')) path = path.slice(0, -1)
if (path === '') path = '/'
if (path === '/404') return locationPathname || '/'
return path
}

/**
* Classic inline script. It has to run while the document is parsing, before the
* deferred `@vercel/analytics/astro` module defines `<vercel-analytics>` and reads
* `data-pathname` for its single pageview.
*/
export const analyticsPathClient = `(() => {
const analyticsPathname = ${analyticsPathname.toString()};
const el = document.querySelector('vercel-analytics');
if (!el || el.getAttribute('data-pathname-ready') === '1') return;
el.setAttribute('data-pathname', analyticsPathname(el.getAttribute('data-pathname') || '', location.pathname));
el.setAttribute('data-pathname-ready', '1');
})();
`
2 changes: 2 additions & 0 deletions src/site/layouts/Base.astro
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import '@fontsource-variable/bricolage-grotesque/opsz.css'
import '@fontsource-variable/figtree'
import Analytics from '@vercel/analytics/astro'
import { analyticsPathClient } from '../analyticsPath'
import Footer from '../components/Footer.astro'
import Header from '../components/Header.astro'
import StarLink from '../components/StarLink.astro'
Expand Down Expand Up @@ -109,6 +110,7 @@ const ogImageAlt = ogImage === SITE.ogImage ? t.ogImageAlt : pageTitle
<Footer lang={lang} />
<StarLink label={t.starGithub} floating />
<Analytics />
<script is:inline set:html={analyticsPathClient}></script>
<script>
// The control stays in the corner. On short screens it would sit on a button or the
// video's own controls, so lift it just clear of those and leave it otherwise.
Expand Down
9 changes: 8 additions & 1 deletion vercel.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,12 @@
"$schema": "https://openapi.vercel.sh/vercel.json",
"framework": "astro",
"cleanUrls": true,
"trailingSlash": false
"trailingSlash": false,
"redirects": [
{
"source": "/sitemap.xml",
"destination": "/sitemap-index.xml",
"permanent": true
}
]
}
Loading