Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(ci): vendor frontend bundle-size build (#67323)

Paul D'Ambraadfcf028f5a1
diff --git a/.github/workflows/ci-frontend.yml b/.github/workflows/ci-frontend.yml
index bb91bf24045c..a9090a29b403 100644
--- a/.github/workflows/ci-frontend.yml
+++ b/.github/workflows/ci-frontend.yml
@@ -359,7 +359,7 @@ jobs:
with:
filter: blob:none
- # compressed-size-action below checks out the base branch mid-job, which
+ # The bundle-size build below git-resets to the base branch mid-job, which
# removes this repo's local actions from the workspace — a local
# ./.github/actions/pnpm-install would then fail in its post phase. Use
# inline cache steps (remote actions, no workspace-dependent post) sharing
@@ -403,31 +403,36 @@ jobs:
- name: Build products
run: pnpm --filter=@posthog/frontend build:products
- - name: Check frontend bundle size
- uses: preactjs/compressed-size-action@66325aad6443cb7cf89c4bfcd414aea2367cda94 # v2.9.1
- with:
- build-script: '--filter=@posthog/frontend build:with-report'
- install-script: 'pnpm --filter=@posthog/frontend... install'
- compression: 'none'
- # dist-report/ carries the source bundle (posthog-app, exporter, …) and source
- # path in the filename, so strip-hash yields a deterministic identity. dist/ has
- # cross-bundle basename collisions that cause phantom size changes.
- pattern: 'frontend/dist-report/**/*.js'
- # Shared chunk hashes change every build, ignore those
- exclude: '{**/_chunks/chunk*.js}'
- # Only show large changes
- minimum-change-threshold: 1000
- order-by: 'Size:desc'
- strip-hash: "-[A-Za-z0-9]{8}\\.js$"
-
- # The eager graph check runs in --report-only mode inside build:with-report
- # (compressed-size-action runs that for the PR AND base builds — a failing
- # base build must not abort the action for every open PR). These steps post
- # the sticky PR comment and warn on budget breaches from the PR build's report,
- # which carries the checkout sha in its filename because the base build
- # overwrites the plain one. After compressed-size-action the tree is on the
- # BASE branch, so guard for the scripts' absence (also covers branches
- # predating the check).
+ # Vendored replacement for preactjs/compressed-size-action: build the PR branch,
+ # then git-reset to the base branch and rebuild so the bundle-size and eager-graph
+ # reports (both written by build:with-report) get a vs-base baseline. The base
+ # build runs LAST in the same workspace, so the plain report filenames hold the
+ # base numbers while the sha-suffixed ones hold the PR build's — the post scripts
+ # pick the PR report by sha and treat the plain file as the base. Reports are
+ # untracked, so they survive `git reset --hard` onto the base tree. A failing base
+ # build (build:with-report runs the eager-graph check in --report-only) must never
+ # abort the job for every open PR, so budgets are enforced warn-only further down.
+ - name: Build frontend (bundle-size + eager-graph report)
+ run: pnpm --filter=@posthog/frontend build:with-report
+
+ - name: Build base branch for size comparison
+ # A broken base build (install/esbuild — which --report-only does not cover) must
+ # only cost the vs-base delta, never redden every open PR's job. The comment steps
+ # below already degrade to "no base measurement" when the base reports are absent.
+ continue-on-error: true
+ if: github.event_name == 'pull_request'
+ env:
+ BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ run: |
+ git fetch -n origin "$BASE_SHA"
+ git reset --hard "$BASE_SHA"
+ pnpm --filter=@posthog/frontend... install
+ pnpm --filter=@posthog/frontend build:with-report
+
+ # The bundle-size and eager-graph comments read the PR build's report by its
+ # checkout sha (the base build overwrites the plain filename). After the base
+ # build the tree is on the BASE branch, so guard for the scripts' absence (also
+ # covers branches predating a check). Budgets are surfaced warn-only.
- name: Post eager graph comment
if: always() && github.event_name == 'pull_request'
env:
@@ -439,6 +444,17 @@ jobs:
echo "Skipping eager graph comment — script not present on this checkout"
fi
+ - name: Post bundle size comment
+ if: always() && github.event_name == 'pull_request'
+ env:
+ GITHUB_TOKEN: ${{ github.token }}
+ run: |
+ if [ -f frontend/bin/post-bundle-size-comment.mjs ]; then
+ node frontend/bin/post-bundle-size-comment.mjs
+ else
+ echo "Skipping bundle size comment — script not present on this checkout"
+ fi
+
- name: Check eager graph budgets (warn only)
if: always() && github.event_name == 'pull_request'
run: |
diff --git a/frontend/bin/build-bundle-size-report.mjs b/frontend/bin/build-bundle-size-report.mjs
new file mode 100644
index 000000000000..7ec5decf11e4
--- /dev/null
+++ b/frontend/bin/build-bundle-size-report.mjs
@@ -0,0 +1,67 @@
+#!/usr/bin/env node
+import { execSync } from 'node:child_process'
+import fs from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url))
+const frontendDir = path.resolve(__dirname, '..')
+const reportDir = path.join(frontendDir, 'dist-report')
+
+// Mirrors the compressed-size-action config this replaces (ci-frontend.yml):
+// pattern: frontend/dist-report/**/*.js exclude: {**/_chunks/chunk*.js}
+// compression: none strip-hash: -[A-Za-z0-9]{8}\.js$
+// dist-report/ (built by build-bundle-report.mjs) carries the source bundle and source
+// path in each filename, so a stripped hash yields a stable identity across builds.
+const HASH_SUFFIX = /-[A-Za-z0-9]{8}(\.js)$/
+const CHUNK_EXCLUDE = /(^|\/)_chunks\/chunk[^/]*\.js$/
+
+function walk(dir) {
+ const out = []
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name)
+ if (entry.isDirectory()) {
+ out.push(...walk(full))
+ } else if (entry.isFile() && entry.name.endsWith('.js')) {
+ out.push(full)
+ }
+ }
+ return out
+}
+
+if (!fs.existsSync(reportDir)) {
+ console.error(
+ `Bundle size report: ${reportDir} not found — run build-bundle-report.mjs first (build:with-report does).`
+ )
+ process.exit(1)
+}
+
+const files = []
+for (const full of walk(reportDir)) {
+ const identity = path.relative(reportDir, full).split(path.sep).join('/').replace(HASH_SUFFIX, '$1')
+ if (CHUNK_EXCLUDE.test(identity)) {
+ continue
+ }
+ files.push({ file: identity, bytes: fs.statSync(full).size })
+}
+files.sort((a, b) => a.file.localeCompare(b.file))
+
+const report = { files, total: files.reduce((sum, f) => sum + f.bytes, 0) }
+
+// The sha convention matches eager-graph-report: compressed-size-action's replacement
+// builds the PR branch AND the base branch in the same workspace, so the plain filename
+// holds the LAST build's numbers (the base's) and doubles as the vs-base baseline, while
+// the sha-suffixed file identifies the PR build's own report.
+try {
+ report.sha = execSync('git rev-parse HEAD', { cwd: frontendDir, encoding: 'utf-8' }).trim()
+} catch (err) {
+ console.error(`Could not resolve HEAD sha for the bundle size report: ${err.message}`)
+}
+
+const serialized = JSON.stringify(report, null, 2)
+fs.writeFileSync(path.join(frontendDir, 'bundle-size-report.json'), serialized)
+if (report.sha) {
+ fs.writeFileSync(path.join(frontendDir, `bundle-size-report-${report.sha}.json`), serialized)
+}
+
+console.info(`Bundle size report: ${files.length} files, ${(report.total / 1024 / 1024).toFixed(2)} MiB total`)
diff --git a/frontend/bin/check-eager-graph.mjs b/frontend/bin/check-eager-graph.mjs
index d98bd7a2f418..62ee6f9c31d6 100644
--- a/frontend/bin/check-eager-graph.mjs
+++ b/frontend/bin/check-eager-graph.mjs
@@ -9,8 +9,8 @@ const frontendDir = path.resolve(__dirname, '..')
const metaPath = path.join(frontendDir, 'posthog-app-esbuild-meta.json')
// --report-only: record results without failing the build. Used by build:with-report
-// because compressed-size-action runs that script for BOTH the PR build and the base
-// build — a base-branch budget breach must not abort the action for every open PR.
+// because the CI bundle-size job runs that script for BOTH the PR build and the base
+// build — a base-branch budget breach must not abort the job for every open PR.
// Budget breaches are surfaced as warnings in the dedicated workflow step via --assert-report.
const reportOnly = process.argv.includes('--report-only')
@@ -294,7 +294,7 @@ for (const { root, label, budgetBytes, forbidden } of ROOTS) {
// Consumed by the workflow's comment + enforcement steps; written even on failure so
// the PR comment can show what went over. The filename and the embedded sha carry the
-// built tree's HEAD because compressed-size-action runs this for BOTH the PR build and
+// built tree's HEAD because the CI bundle-size job runs this for BOTH the PR build and
// the base build in the same workspace — the PR build's report is found by sha, and the
// plain filename (last write = the base build) doubles as the base-branch measurement
// for the comment's vs-base delta.
diff --git a/frontend/bin/ci-report/update-ci-report.mjs b/frontend/bin/ci-report/update-ci-report.mjs
new file mode 100644
index 000000000000..9fb8fbf65888
--- /dev/null
+++ b/frontend/bin/ci-report/update-ci-report.mjs
@@ -0,0 +1,174 @@
+#!/usr/bin/env node
+import fs from 'node:fs'
+
+// One sticky comment shared by every frontend CI check. Each check owns a delimited
+// section and updates only its own; the header list and section order are rebuilt from
+// the fixed SECTIONS registry every time, so the layout never shifts between runs and
+// readers learn where each check lives. Safe as a plain read-modify-write only because
+// every writer runs sequentially in the single frontend-bundle-size job — do not call
+// this from parallel jobs without a locking strategy.
+export const MARKER = '<!-- posthog-ci-report -->'
+
+// The single source of truth for which sections exist and the order they render in.
+// Adding a check means adding it here — that is deliberate: it keeps the order a
+// reviewed decision rather than an accident of which job happened to write first.
+export const SECTIONS = [
+ { id: 'bundle-size', title: 'Bundle size' },
+ { id: 'eager-graph', title: 'Eager graph' },
+ { id: 'dist-size', title: 'Dist folder size' },
+]
+
+export const STATUS_EMOJI = { ok: '✅', warn: '⚠️', fail: '❌', info: 'ℹ️' }
+
+function emojiFor(status) {
+ return STATUS_EMOJI[status] ?? STATUS_EMOJI.info
+}
+
+function titleFor(id) {
+ return SECTIONS.find((s) => s.id === id)?.title ?? id
+}
+
+// GitHub derives a heading anchor by lowercasing, dropping anything that is not a word
+// char/space/hyphen, and turning spaces into hyphens. The section headings are plain
+// (no emoji), so the same transform yields the anchor the header list links to.
+export function slugify(title) {
+ return title
+ .toLowerCase()
+ .replace(/[^\w\s-]/g, '')
+ .trim()
+ .replace(/\s+/g, '-')
+}
+
+function encodeMeta(meta) {
+ return Buffer.from(JSON.stringify(meta), 'utf-8').toString('base64')
+}
+
+function decodeMeta(encoded) {
+ try {
+ return JSON.parse(Buffer.from(encoded, 'base64').toString('utf-8'))
+ } catch {
+ return {}
+ }
+}
+
+const SECTION_RE =
+ /<!-- ci-report:section:([\w-]+):([A-Za-z0-9+/=]*) -->\n([\s\S]*?)\n<!-- ci-report:section-end:\1 -->/g
+
+// Parse an existing comment body back into a map of id -> { status, summary, inner }.
+// `inner` is the rendered section content, kept verbatim so sections this run does not
+// touch are re-emitted byte-for-byte.
+export function parseSections(body) {
+ const sections = new Map()
+ if (!body) {
+ return sections
+ }
+ for (const match of body.matchAll(SECTION_RE)) {
+ const [, id, encodedMeta, inner] = match
+ const meta = decodeMeta(encodedMeta)
+ sections.set(id, { status: meta.status ?? 'info', summary: meta.summary ?? '', inner })
+ }
+ return sections
+}
+
+export function upsertSection(sections, { id, status = 'info', summary = '', body }) {
+ const next = new Map(sections)
+ next.set(id, { status, summary, inner: `## ${titleFor(id)}\n\n${body}` })
+ return next
+}
+
+// Known sections in registry order first, then any unknown ones (from a legacy comment or
+// a not-yet-registered check) appended alphabetically so nothing is dropped and order stays
+// deterministic across runs.
+function orderedIds(sections) {
+ const known = SECTIONS.map((s) => s.id).filter((id) => sections.has(id))
+ const unknown = [...sections.keys()].filter((id) => !SECTIONS.some((s) => s.id === id)).sort()
+ return [...known, ...unknown]
+}
+
+export function renderComment(sections) {
+ const ids = orderedIds(sections)
+ const header = ids.map((id) => {
+ const { status, summary } = sections.get(id)
+ const title = titleFor(id)
+ const suffix = summary ? ` — ${summary}` : ''
+ return `- ${emojiFor(status)} [${title}](#${slugify(title)})${suffix}`
+ })
+ const blocks = ids.map((id) => {
+ const { status, summary, inner } = sections.get(id)
+ return [
+ `<!-- ci-report:section:${id}:${encodeMeta({ status, summary })} -->`,
+ inner,
+ `<!-- ci-report:section-end:${id} -->`,
+ ].join('\n')
+ })
+ return [MARKER, '## 🤖 CI report', '', ...header, '', ...blocks].join('\n')
+}
+
+async function gh(token, url, options = {}) {
+ const response = await fetch(`https://api.github.com${url}`, {
+ ...options,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ Accept: 'application/vnd.github+json',
+ 'Content-Type': 'application/json',
+ ...options.headers,
+ },
+ })
+ if (!response.ok) {
+ throw new Error(`GitHub API ${options.method || 'GET'} ${url} -> ${response.status}: ${await response.text()}`)
+ }
+ return response.json()
+}
+
+// Post or update this run's section into the shared comment. Fork PRs run with a
+// read-only token, so a failure to read or write is warned and swallowed — the comment
+// is a nicety, never worth a red job.
+export async function postSection({ id, status, summary, body }) {
+ const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN
+ const repo = process.env.GITHUB_REPOSITORY
+ const eventPath = process.env.GITHUB_EVENT_PATH
+ if (!token || !repo || !eventPath) {
+ console.info('Missing GitHub environment (token/repository/event) — skipping comment.')
+ return
+ }
+ const event = JSON.parse(fs.readFileSync(eventPath, 'utf-8'))
+ const prNumber = event.pull_request?.number
+ if (!prNumber) {
+ console.info('Not a pull request event — skipping comment.')
+ return
+ }
+
+ let existing = null
+ try {
+ for (let page = 1; page <= 50 && !existing; page++) {
+ const comments = await gh(token, `/repos/${repo}/issues/${prNumber}/comments?per_page=100&page=${page}`)
+ existing = comments.find((c) => c.body?.includes(MARKER)) ?? null
+ if (comments.length < 100) {
+ break
+ }
+ }
+ } catch (err) {
+ console.warn(`Could not read PR comments (read-only token on fork PRs?): ${err.message}`)
+ return
+ }
+
+ const sections = upsertSection(parseSections(existing?.body ?? ''), { id, status, summary, body })
+ const rendered = renderComment(sections)
+ try {
+ if (existing) {
+ await gh(token, `/repos/${repo}/issues/comments/${existing.id}`, {
+ method: 'PATCH',
+ body: JSON.stringify({ body: rendered }),
+ })
+ console.info(`Updated CI report section "${id}" on comment ${existing.id} (PR #${prNumber}).`)
+ } else {
+ await gh(token, `/repos/${repo}/issues/${prNumber}/comments`, {
+ method: 'POST',
+ body: JSON.stringify({ body: rendered }),
+ })
+ console.info(`Posted CI report with section "${id}" on PR #${prNumber}.`)
+ }
+ } catch (err) {
+ console.warn(`Could not post CI report (read-only token on fork PRs?): ${err.message}`)
+ }
+}
diff --git a/frontend/bin/ci-report/update-ci-report.test.ts b/frontend/bin/ci-report/update-ci-report.test.ts
new file mode 100644
index 000000000000..0c33e3e093b5
--- /dev/null
+++ b/frontend/bin/ci-report/update-ci-report.test.ts
@@ -0,0 +1,100 @@
+import { MARKER, parseSections, renderComment, slugify, STATUS_EMOJI, upsertSection } from './update-ci-report.mjs'
+
+type SectionEntry = { status: string; summary: string; inner: string }
+type SectionState = Map<string, SectionEntry>
+type SectionInput = { id: string; status?: string; summary?: string; body: string }
+
+function build(entries: SectionInput[]): SectionState {
+ let sections: SectionState = new Map()
+ for (const entry of entries) {
+ sections = upsertSection(sections, entry) as SectionState
+ }
+ return sections
+}
+
+function get(sections: SectionState, id: string): SectionEntry {
+ const entry = sections.get(id)
+ if (!entry) {
+ throw new Error(`expected section ${id} to be present`)
+ }
+ return entry
+}
+
+describe('ci-report section helper', () => {
+ it('renders header and section blocks in fixed registry order regardless of write order', () => {
+ // Written eager-graph -> dist-size -> bundle-size; registry order is the reverse.
+ const rendered: string = renderComment(
+ build([
+ { id: 'eager-graph', status: 'ok', summary: 'e', body: 'EAGER' },
+ { id: 'dist-size', status: 'ok', summary: 'd', body: 'DIST' },
+ { id: 'bundle-size', status: 'ok', summary: 'b', body: 'BUNDLE' },
+ ])
+ )
+ const headerOrder = [...rendered.matchAll(/- .+? \[(.+?)\]/g)].map((m) => m[1])
+ expect(headerOrder).toEqual(['Bundle size', 'Eager graph', 'Dist folder size'])
+ expect(rendered.indexOf('BUNDLE')).toBeLessThan(rendered.indexOf('EAGER'))
+ expect(rendered.indexOf('EAGER')).toBeLessThan(rendered.indexOf('DIST'))
+ expect(rendered.startsWith(MARKER)).toBe(true)
+ })
+
+ it('updating one section preserves the others and applies the new body', () => {
+ const original = build([
+ { id: 'bundle-size', status: 'ok', summary: 'b', body: 'BUNDLE BODY' },
+ { id: 'eager-graph', status: 'ok', summary: 'e', body: 'EAGER BODY' },
+ ])
+ const updated = upsertSection(original, {
+ id: 'eager-graph',
+ status: 'fail',
+ summary: 'over budget',
+ body: 'NEW EAGER BODY',
+ })
+ const sections = parseSections(renderComment(updated))
+ expect(get(sections, 'bundle-size')).toEqual(get(original, 'bundle-size'))
+ expect(get(sections, 'eager-graph').inner).toBe('## Eager graph\n\nNEW EAGER BODY')
+ expect(get(sections, 'eager-graph').status).toBe('fail')
+ expect(get(sections, 'eager-graph').summary).toBe('over budget')
+ })
+
+ it('round-trips status and summary so the header reflects sections written by other runs', () => {
+ // A later run parses the persisted comment to rebuild the header — the status of a
+ // section it did not write must survive encode/decode, or the summary list lies.
+ const persisted: string = renderComment(
+ build([{ id: 'bundle-size', status: 'warn', summary: '+120 KiB (2.1%)', body: 'x' }])
+ )
+ const reparsed: string = renderComment(parseSections(persisted))
+ expect(reparsed).toContain(`- ${STATUS_EMOJI.warn} [Bundle size](#bundle-size) — +120 KiB (2.1%)`)
+ })
+
+ it.each([
+ ['ok', STATUS_EMOJI.ok],
+ ['warn', STATUS_EMOJI.warn],
+ ['fail', STATUS_EMOJI.fail],
+ ['info', STATUS_EMOJI.info],
+ ['unknown-status', STATUS_EMOJI.info],
+ ])('header maps status %s to its emoji', (status: string, emoji: string) => {
+ const rendered: string = renderComment(build([{ id: 'bundle-size', status, summary: '', body: 'x' }]))
+ expect(rendered).toContain(`- ${emoji} [Bundle size](#bundle-size)`)
+ })
+
+ it('omits the summary suffix when there is no summary', () => {
+ const rendered: string = renderComment(build([{ id: 'bundle-size', status: 'ok', body: 'x' }]))
+ expect(rendered).toContain(`- ${STATUS_EMOJI.ok} [Bundle size](#bundle-size)\n`)
+ expect(rendered).not.toContain('[Bundle size](#bundle-size) —')
+ })
+
+ it.each([
+ ['Bundle size', 'bundle-size'],
+ ['Dist folder size', 'dist-folder-size'],
+ ['🕸️ Eager graph', 'eager-graph'],
+ ])('slugify(%s) matches the GitHub heading anchor %s', (title: string, slug: string) => {
+ expect(slugify(title)).toBe(slug)
+ })
+
+ it('keeps an unregistered section instead of dropping it, ordered after known ones', () => {
+ const withLegacy = build([{ id: 'bundle-size', status: 'ok', summary: '', body: 'x' }])
+ withLegacy.set('legacy-check', { status: 'info', summary: 'old', inner: '## Legacy\n\nold body' })
+ const rendered: string = renderComment(withLegacy)
+ expect(rendered).toContain('old body')
+ expect(rendered.indexOf('#bundle-size')).toBeLessThan(rendered.indexOf('legacy-check'))
+ })
+})
diff --git a/frontend/bin/post-bundle-size-comment.mjs b/frontend/bin/post-bundle-size-comment.mjs
new file mode 100644
index 000000000000..c22fd2b48795
--- /dev/null
+++ b/frontend/bin/post-bundle-size-comment.mjs
@@ -0,0 +1,191 @@
+#!/usr/bin/env node
+import fs from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url))
+const frontendDir = path.resolve(__dirname, '..')
+
+const MARKER = '<!-- posthog-bundle-size-check -->'
+
+// A file whose size moves by less than this is treated as unchanged, matching the
+// compressed-size-action `minimum-change-threshold: 1000` this replaces.
+const MINIMUM_CHANGE_BYTES = 1000
+
+const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN
+const repo = process.env.GITHUB_REPOSITORY
+const eventPath = process.env.GITHUB_EVENT_PATH
+
+if (!token || !repo || !eventPath) {
+ console.info('Missing GitHub environment (token/repository/event) — skipping comment.')
+ process.exit(0)
+}
+const event = JSON.parse(fs.readFileSync(eventPath, 'utf-8'))
+const prNumber = event.pull_request?.number
+if (!prNumber) {
+ console.info('Not a pull request event — skipping comment.')
+ process.exit(0)
+}
+
+// The base build runs last in the same workspace, so the plain report filename holds the
+// base branch's numbers. The PR build's report carries its checkout sha in the filename —
+// the PR checks out the merge ref (GITHUB_SHA); head sha covers non-merge-ref checkouts.
+const shaCandidates = [process.env.GITHUB_SHA, event.pull_request?.head?.sha].filter(Boolean)
+const shaReportPath = shaCandidates
+ .map((sha) => path.join(frontendDir, `bundle-size-report-${sha}.json`))
+ .find((p) => fs.existsSync(p))
+const reportPath = shaReportPath ?? path.join(frontendDir, 'bundle-size-report.json')
+if (!fs.existsSync(reportPath)) {
+ console.info('No bundle size report found — nothing to post (branch may predate the check).')
+ process.exit(0)
+}
+if (!shaReportPath) {
+ console.warn(
+ `No report found for shas [${shaCandidates.join(', ')}]; falling back to ${reportPath} — ` +
+ `its numbers may be from a different checkout.`
+ )
+}
+
+const report = JSON.parse(fs.readFileSync(reportPath, 'utf-8'))
+
+// The plain filename is the base measurement only when its sha differs from the PR's —
+// otherwise the base build didn't emit a report (base branch predates the check) and the
+// plain file is just the PR's own report.
+const baseReport = (() => {
+ const candidate = path.join(frontendDir, 'bundle-size-report.json')
+ if (!fs.existsSync(candidate)) {
+ return null
+ }
+ try {
+ const parsed = JSON.parse(fs.readFileSync(candidate, 'utf-8'))
+ if (parsed.sha && report.sha && parsed.sha !== report.sha) {
+ return parsed
+ }
+ } catch {
+ return null
+ }
+ return null
+})()
+if (!baseReport) {
+ console.warn('No base-branch report found — the comment will not show a vs-base delta.')
+}
+const baseBytes = Object.fromEntries((baseReport?.files ?? []).map((f) => [f.file, f.bytes]))
+
+function formatBytes(bytes) {
+ const abs = Math.abs(bytes)
+ if (abs >= 1024 * 1024) {
+ return `${(bytes / 1024 / 1024).toFixed(2)} MiB`
+ }
+ if (abs >= 1024) {
+ return `${(bytes / 1024).toFixed(1)} KiB`
+ }
+ return `${bytes} B`
+}
+
+function formatDelta(bytes, baselineBytes) {
+ if (baselineBytes === undefined) {
+ return `🔺 +${formatBytes(bytes)} (new)`
+ }
+ const delta = bytes - baselineBytes
+ if (delta === 0) {
+ return 'no change'
+ }
+ const sign = delta > 0 ? '+' : '-'
+ const magnitude = `${delta > 0 ? '🔺' : '🟢'} ${sign}${formatBytes(Math.abs(delta))}`
+ if (baselineBytes === 0) {
+ return `${magnitude} (new)`
+ }
+ const percent = ((Math.abs(delta) / baselineBytes) * 100).toFixed(1)
+ return `${magnitude} (${sign}${percent}%)`
+}
+
+async function gh(url, options = {}) {
+ const response = await fetch(`https://api.github.com${url}`, {
+ ...options,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ Accept: 'application/vnd.github+json',
+ 'Content-Type': 'application/json',
+ ...options.headers,
+ },
+ })
+ if (!response.ok) {
+ throw new Error(`GitHub API ${options.method || 'GET'} ${url} -> ${response.status}: ${await response.text()}`)
+ }
+ return response.json()
+}
+
+let existing = null
+try {
+ for (let page = 1; page <= 50 && !existing; page++) {
+ const comments = await gh(`/repos/${repo}/issues/${prNumber}/comments?per_page=100&page=${page}`)
+ existing = comments.find((c) => c.body?.includes(MARKER)) ?? null
+ if (comments.length < 100) {
+ break
+ }
+ }
+} catch (err) {
+ // Fork PRs run with a read-only token — the comment is a nicety, never worth a red job.
+ console.warn(`Could not read PR comments (read-only token on fork PRs?): ${err.message}`)
+ process.exit(0)
+}
+
+// Only diff per file when there is a baseline. Without one every file looks "new", which
+// would flood the comment with the whole manifest and make every delta a bogus increase.
+const prFiles = new Map(report.files.map((f) => [f.file, f.bytes]))
+const changed = []
+if (baseReport) {
+ for (const identity of new Set([...prFiles.keys(), ...Object.keys(baseBytes)])) {
+ const prBytes = prFiles.get(identity)
+ const base = baseBytes[identity]
+ const delta = (prBytes ?? 0) - (base ?? 0)
+ if (Math.abs(delta) >= MINIMUM_CHANGE_BYTES) {
+ changed.push({ identity, prBytes, base, delta })
+ }
+ }
+}
+changed.sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta))
+
+const baseTotal = baseReport?.total
+const totalDelta = report.total - (baseTotal ?? 0)
+
+const lines = [
+ MARKER,
+ `## ${baseReport && totalDelta > 0 ? '🔺' : '📦'} Bundle size`,
+ '',
+ 'Uncompressed size of every built `.js` bundle, compared against the base branch.',
+ '',
+ baseReport
+ ? `**Total:** ${formatBytes(report.total)} · ${formatDelta(report.total, baseTotal)}`
+ : `**Total:** ${formatBytes(report.total)} _(no base branch measurement to compare against yet)_`,
+ '',
+]
+
+if (baseReport && changed.length) {
+ lines.push('| File | Size | Δ vs base |', '| --- | --- | --- |')
+ for (const { identity, prBytes, base } of changed) {
+ const size = prBytes === undefined ? '_removed_' : formatBytes(prBytes)
+ lines.push(`| \`${identity}\` | ${size} | ${formatDelta(prBytes ?? 0, base)} |`)
+ }
+ lines.push('')
+} else if (baseReport) {
+ lines.push(`No file changed by more than ${formatBytes(MINIMUM_CHANGE_BYTES)}.`, '')
+}
+
+lines.push(
+ '<sub>Posted automatically by [build-bundle-size-report](https://github.com/PostHog/posthog/blob/master/frontend/bin/build-bundle-size-report.mjs) · uncompressed bytes from dist-report</sub>'
+)
+
+const body = lines.join('\n')
+try {
+ if (existing) {
+ await gh(`/repos/${repo}/issues/comments/${existing.id}`, { method: 'PATCH', body: JSON.stringify({ body }) })
+ console.info(`Updated bundle size comment ${existing.id} on PR #${prNumber}.`)
+ } else {
+ await gh(`/repos/${repo}/issues/${prNumber}/comments`, { method: 'POST', body: JSON.stringify({ body }) })
+ console.info(`Posted bundle size comment on PR #${prNumber}.`)
+ }
+} catch (err) {
+ // Fork PRs run with a read-only token — the comment is a nicety, never worth a red job.
+ console.warn(`Could not post bundle size comment (read-only token on fork PRs?): ${err.message}`)
+}
diff --git a/frontend/bin/post-eager-graph-comment.mjs b/frontend/bin/post-eager-graph-comment.mjs
index c3aa39cdbb79..f0bfc8b38a7b 100644
--- a/frontend/bin/post-eager-graph-comment.mjs
+++ b/frontend/bin/post-eager-graph-comment.mjs
@@ -23,7 +23,7 @@ if (!prNumber) {
process.exit(0)
}
-// compressed-size-action builds the PR branch and then the base branch in the same
+// The CI bundle-size job builds the PR branch and then the base branch in the same
// workspace, so the plain report filename holds the LAST build's (the base's) numbers.
// The PR build's report carries its checkout sha in the filename — that's the one to
// post. The PR build checks out the merge ref, so its sha is GITHUB_SHA; the head sha
diff --git a/frontend/jest.config.ts b/frontend/jest.config.ts
index 2029b9cfbe35..bb9efe8b87bc 100644
--- a/frontend/jest.config.ts
+++ b/frontend/jest.config.ts
@@ -83,6 +83,7 @@ const esmModules = [
function rootDirectories(): string[] {
return [
'<rootDir>/src',
+ '<rootDir>/bin',
'<rootDir>/../products',
'<rootDir>/../packages/quill/packages/charts/src',
'<rootDir>/../packages/quill/packages/components/src',
diff --git a/frontend/package.json b/frontend/package.json
index bb1deb60f94d..50606fe1121e 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -19,7 +19,7 @@
"copy-scripts": "mkdir -p dist/ && ./bin/copy-posthog-js",
"clean": "rm -rf dist && mkdir dist",
"build": "pnpm copy-scripts && pnpm build:esbuild",
- "build:with-report": "pnpm build && node ./bin/build-bundle-report.mjs && node ./bin/check-eager-graph.mjs --report-only",
+ "build:with-report": "pnpm build && node ./bin/build-bundle-report.mjs && node ./bin/build-bundle-size-report.mjs && node ./bin/check-eager-graph.mjs --report-only",
"build:esbuild": "DEBUG=0 node ./build.mjs",
"build:products": "DEBUG=0 node build-products.mjs",
"build:app-urls": "node bin/build-app-url-manifest.mjs",