: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(frontend): flag components that use a stylesheet they do not import (#126418)
Paul D'Ambrafe1765d5d2ce
diff --git a/.github/workflows/ci-frontend.yml b/.github/workflows/ci-frontend.ymlindex ac8b6e1220e9..0ac8cbecc520 100644--- a/.github/workflows/ci-frontend.yml+++ b/.github/workflows/ci-frontend.yml@@ -820,6 +820,16 @@ jobs:finode frontend/bin/check-layers.mjs+ # Warn-only until the baseline has settled on master; then drop continue-on-error.+ - name: Check frontend stylesheet imports+ continue-on-error: true+ run: |+ if [ ! -f frontend/bin/check-css-coupling.mjs ]; then+ echo "Skipping frontend stylesheet import check, script not present on this checkout"+ exit 0+ fi+ node frontend/bin/check-css-coupling.mjs+# A field removed from a model that a cached query response stores makes every old# cache entry that holds it fail to parse. The author acknowledges the removal with a# cache-impact label, which is read live so a re-run of this job sees a new label.diff --git a/frontend/bin/check-css-coupling.mjs b/frontend/bin/check-css-coupling.mjsnew file mode 100644index 000000000000..d82919cc9556--- /dev/null+++ b/frontend/bin/check-css-coupling.mjs@@ -0,0 +1,106 @@+#!/usr/bin/env node+// Blocks a new component that uses a stylesheet's block class (like `.PropertyFilters`) without importing+// that stylesheet. Such a component renders right only while some other module loads the CSS first, and it+// breaks without warning when that module moves off the page's import path (see cssCoupling.mjs).+//+// node frontend/bin/check-css-coupling.mjs check against the baseline+// node frontend/bin/check-css-coupling.mjs --prune-baseline drop fixed entries, never add one+// node frontend/bin/check-css-coupling.mjs --update-baseline rewrite the baseline, new debt included+// node frontend/bin/check-css-coupling.mjs --report-only list every coupling, never fail+import fs from 'node:fs'+import path from 'node:path'++import { couplingKey, findCouplings } from './cssCoupling.mjs'+import { readImportGraph, repoRoot } from './importGraph.mjs'++const baselinePath = path.join(repoRoot, 'frontend', 'bin', 'css-coupling-baseline.txt')+const BASELINE_HEADER = `# Components that use a stylesheet's block class without importing the stylesheet (see frontend/bin/cssCoupling.mjs).+# Grandfathered debt: the check fails on a coupling that is NOT listed here.+#+# DO NOT EDIT BY HAND. Mechanical output of \`hogli lint:frontend-css-coupling --update-baseline\`.+# Fixed one? Run \`hogli lint:frontend-css-coupling --prune-baseline\` to drop it.+`++function readBaseline() {+ if (!fs.existsSync(baselinePath)) {+ return []+ }+ return fs+ .readFileSync(baselinePath, 'utf8')+ .split('\n')+ .filter((line) => line && !line.startsWith('#'))+}++function writeBaseline(keys) {+ fs.writeFileSync(baselinePath, BASELINE_HEADER + keys.map((key) => `${key}\n`).join(''))+}++const STYLESHEET_ROOTS = ['frontend/src', 'products']+const IGNORED_DIRS = new Set(['node_modules', 'dist', 'generated', '.turbo', '.layer-check-out'])++// Walks the filesystem rather than the import graph, so a stylesheet with no remaining importer is+// still indexed (see findCouplings in cssCoupling.mjs).+function walkStylesheets(dir, out = []) {+ const abs = path.join(repoRoot, dir)+ if (!fs.existsSync(abs)) {+ return out+ }+ for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {+ const rel = path.join(dir, entry.name)+ if (entry.isDirectory()) {+ if (!IGNORED_DIRS.has(entry.name)) {+ walkStylesheets(rel, out)+ }+ } else if (/\.s?css$/.test(entry.name)) {+ out.push(rel)+ }+ }+ return out+}++function describe({ file, className, stylesheets }) {+ return [+ ` ${file} uses .${className}, but does not import ${stylesheets.join(' or ')}.`,+ ` Import the stylesheet in ${path.basename(file)}, or replace .${className} with Tailwind classes.`,+ ].join('\n')+}++const args = process.argv.slice(2)+const files = await readImportGraph()+const stylesheetFiles = STYLESHEET_ROOTS.flatMap((root) => walkStylesheets(root))+const couplings = findCouplings(files, (file) => fs.readFileSync(path.join(repoRoot, file), 'utf8'), stylesheetFiles)+const current = [...new Set(couplings.map(couplingKey))].sort()+const baseline = readBaseline()+const added = couplings.filter((coupling) => !baseline.includes(couplingKey(coupling)))+const fixed = baseline.filter((key) => !current.includes(key))++console.info(+ `CSS couplings: ${current.length} (${baseline.length} in the baseline, ${added.length} new, ${fixed.length} fixed)`+)++if (args.includes('--report-only')) {+ for (const coupling of couplings) {+ console.info(`\n${describe(coupling)}`)+ }+ process.exit(0)+}+if (args.includes('--update-baseline')) {+ writeBaseline(current)+ console.info(`Baseline rewritten with ${current.length} entries.`)+ process.exit(0)+}+if (args.includes('--prune-baseline')) {+ writeBaseline(baseline.filter((key) => current.includes(key)))+ console.info(`Dropped ${fixed.length} fixed entries.`)+ fixed.length = 0+}++for (const coupling of added) {+ console.info(`\nNew CSS coupling:\n${describe(coupling)}`)+}+if (fixed.length) {+ console.info(+ `\n${fixed.length} baseline entries are fixed. Run \`hogli lint:frontend-css-coupling --prune-baseline\` to lock in the win.`+ )+}+process.exit(added.length || fixed.length ? 1 : 0)diff --git a/frontend/bin/check-layers.mjs b/frontend/bin/check-layers.mjsindex c33a7b2fdd20..d1d324760c57 100644--- a/frontend/bin/check-layers.mjs+++ b/frontend/bin/check-layers.mjs@@ -9,16 +9,13 @@import { execSync } from 'node:child_process'import fs from 'node:fs'import path from 'node:path'-import { fileURLToPath } from 'node:url'-import { esbuildBuild } from '@posthog/esbuilder'--import { AUTHENTICATED_SHELL, BOOT_ENTRIES } from './bootEntries.mjs'+import { AUTHENTICATED_SHELL } from './bootEntries.mjs'+import { chainTo, isAssetPath, readImportGraph, repoRoot, staticReach } from './importGraph.mjs'import { renderLayerGraphHtml } from './layerGraphHtml.mjs'import { findOpportunities } from './layerOpportunities.mjs'import { LAYERS, isUpward, layerOf } from './layers.mjs'-const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..')const baselinePath = path.join(repoRoot, 'frontend', 'bin', 'layer-baseline.txt')const BASELINE_HEADER = `# Static imports from a lower frontend layer into a higher one (see frontend/bin/layers.mjs).# Grandfathered debt: the check fails on an upward import that is NOT listed here.@@ -27,132 +24,11 @@ const BASELINE_HEADER = `# Static imports from a lower frontend layer into a hig# Fixed one? Run \`hogli lint:frontend-layers --prune-baseline\` to drop it.`-// Path aliases resolve through tsconfig; anything else that is not relative is a package, and packages-// are outside the layer map.-const ALIAS_PREFIXES = ['lib/', 'scenes/', '~/', 'products/', 'public/', '@posthog/', '@common/']-const ASSET_EXTENSIONS = [- '.css',- '.scss',- '.svg',- '.png',- '.jpg',- '.jpeg',- '.gif',- '.webp',- '.avif',- '.ico',- '.woff',- '.woff2',- '.ttf',- '.otf',- '.eot',- '.mp3',- '.mp4',- '.wav',- '.ogg',- '.lottie',- '.riv',- '.json',- '.md',- '.txt',- '.html',- '.yaml',- '.yml',- '.csv',- '.wasm',- '.bin',- '.gz',- '.zip',- '.glb',- '.gltf',-]--const externalizePackages = {- name: 'externalize-packages',- setup(build) {- build.onResolve({ filter: /\?[a-z]+$/ }, (args) => ({ path: args.path, external: true }))- build.onResolve({ filter: /^[^./]/ }, async (args) => {- if (args.pluginData?.resolvingAlias) {- return undefined- }- if (ALIAS_PREFIXES.some((prefix) => args.path.startsWith(prefix))) {- const resolved = await build.resolve(args.path, {- kind: args.kind,- resolveDir: args.resolveDir,- importer: args.importer,- pluginData: { resolvingAlias: true },- })- if (!resolved.errors.length && !resolved.path.includes('/node_modules/')) {- return resolved- }- }- return { path: args.path, external: true }- })- },-}--async function readImportGraph() {- const result = await esbuildBuild({- absWorkingDir: repoRoot,- entryPoints: BOOT_ENTRIES.map((entry) => `frontend/${entry}`),- tsconfig: path.join(repoRoot, 'tsconfig.json'),- bundle: true,- splitting: true,- format: 'esm',- jsx: 'automatic',- write: false,- metafile: true,- outdir: path.join(repoRoot, 'frontend', '.layer-check-out'),- logLevel: 'silent',- loader: Object.fromEntries(ASSET_EXTENSIONS.map((extension) => [extension, 'empty'])),- plugins: [externalizePackages],- })- const files = {}- for (const [file, input] of Object.entries(result.metafile.inputs)) {- files[file] = {- bytes: input.bytes,- staticImports: input.imports- .filter((i) => i.kind === 'import-statement' && !i.external && !isAssetPath(i.path))- .map((i) => i.path),- }- }- return files-}--// The `empty` loader keeps asset files out of the bundle, but esbuild still records the import edge-// in the metafile. An asset carries no feature code, so it must not count as an upward import.-function isAssetPath(importPath) {- return ASSET_EXTENSIONS.includes(path.extname(importPath).toLowerCase())-}--function staticReach(files, root) {- const parentOf = new Map([[root, null]])- const queue = [root]- while (queue.length) {- const file = queue.shift()- for (const target of files[file]?.staticImports ?? []) {- if (!parentOf.has(target)) {- parentOf.set(target, file)- queue.push(target)- }- }- }- return parentOf-}--function chainTo(parentOf, file) {- const chain = []- for (let current = file; current; current = parentOf.get(current)) {- chain.unshift(current)- }- return chain-}-function upwardImports(files) {const edges = []for (const [from, { staticImports }] of Object.entries(files)) {for (const to of staticImports) {- if (isUpward(from, to)) {+ if (!isAssetPath(to) && isUpward(from, to)) {edges.push(`${from} -> ${to}`)}}diff --git a/frontend/bin/css-coupling-baseline.txt b/frontend/bin/css-coupling-baseline.txtnew file mode 100644index 000000000000..bf28d4ff4e8a--- /dev/null+++ b/frontend/bin/css-coupling-baseline.txt@@ -0,0 +1,65 @@+# Components that use a stylesheet's block class without importing the stylesheet (see frontend/bin/cssCoupling.mjs).+# Grandfathered debt: the check fails on a coupling that is NOT listed here.+#+# DO NOT EDIT BY HAND. Mechanical output of `hogli lint:frontend-css-coupling --update-baseline`.+# Fixed one? Run `hogli lint:frontend-css-coupling --prune-baseline` to drop it.+frontend/src/layout/navigation-3000/components/SimpleLayoutFrame.tsx -> .Navigation3000+frontend/src/layout/navigation-3000/layout-modes/TodayFramedLayout.tsx -> .TodayAppLayout+frontend/src/layout/navigation-3000/layout-modes/TodayPhoneLayout.tsx -> .TodayAppLayout+frontend/src/layout/today/TodayAnalyticsSidebar.tsx -> .TodayPane+frontend/src/layout/today/TodayContextPanelContent.tsx -> .TodayContextPanelContent+frontend/src/layout/today/TodayContextPanelLauncher.tsx -> .TodayContextPanelButton+frontend/src/layout/today/TodayPaneRow.tsx -> .TodayIconBadge+frontend/src/layout/today/TodayPaneSearchList.tsx -> .TodayPaneSearchList+frontend/src/layout/today/TodayPhoneHeader.tsx -> .TodayPhoneHeader+frontend/src/layout/today/TodayProductHoverCard.tsx -> .TodayIconBadge+frontend/src/layout/today/TodayProductsSidebar.tsx -> .TodayPane+frontend/src/layout/today/TodaySettingsSidebar.tsx -> .TodayPane+frontend/src/layout/today/TodaySpacesSidebar.tsx -> .TodayPane+frontend/src/layout/today/TodayTabBar.tsx -> .TodayTabBar+frontend/src/layout/today/TodayTopBar.tsx -> .TodayTopBar+frontend/src/lib/components/TileDecorations/TileDecorations.tsx -> .LemonIcon+frontend/src/lib/lemon-ui/Spinner/Spinner.tsx -> .LemonIcon+frontend/src/lib/monaco/CodeEditorResizable.tsx -> .CodeEditorResizeable+frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx -> .InsightVizDisplay+frontend/src/scenes/dashboard/items/DashboardErrorTileItem.tsx -> .InsightCard+frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx -> .EditorScene+frontend/src/scenes/feature-flags/FeatureFlagVariantsForm.tsx -> .VariantFormList+frontend/src/scenes/feature-flags/PercentageInput.tsx -> .LemonInput+frontend/src/scenes/notebooks/Nodes/components/NotebookNodeTitle.tsx -> .NotebookNodeTitle+frontend/src/scenes/onboarding/productSelection/ProductSelection.tsx -> .OnboardingProductCard+frontend/src/scenes/project-homepage/today/TodayChange.tsx -> .TodayChange+frontend/src/scenes/project-homepage/today/TodayCodeExcerpt.tsx -> .TodayCodeExcerpt+frontend/src/scenes/project-homepage/today/TodayEvidenceDetail.tsx -> .TodayCodeExcerpt+frontend/src/scenes/project-homepage/today/TodayEvidenceDetail.tsx -> .TodayEvidenceDetail+frontend/src/scenes/project-homepage/today/TodayExplore.tsx -> .TodayJumpList+frontend/src/scenes/project-homepage/today/TodayExplore.tsx -> .TodayJumpRow+frontend/src/scenes/project-homepage/today/TodayFigureMark.tsx -> .TodayFigureMark+frontend/src/scenes/project-homepage/today/TodayForYou.tsx -> .TodayRow+frontend/src/scenes/project-homepage/today/TodayForYou.tsx -> .TodayRows+frontend/src/scenes/project-homepage/today/TodayHomePage.tsx -> .TodayHome+frontend/src/scenes/project-homepage/today/TodayHomePage.tsx -> .TodayPulse+frontend/src/scenes/project-homepage/today/TodayHoverMark.tsx -> .TodayHoverMark+frontend/src/scenes/project-homepage/today/TodayImplementMenu.tsx -> .TodayImplementMenu+frontend/src/scenes/project-homepage/today/TodayKeyClauseMark.tsx -> .TodayKeyClauseMark+frontend/src/scenes/project-homepage/today/TodayPulse.tsx -> .TodayPulse+frontend/src/scenes/project-homepage/today/TodayRecents.tsx -> .TodayJumpList+frontend/src/scenes/project-homepage/today/TodayRecents.tsx -> .TodayJumpRow+frontend/src/scenes/project-homepage/today/TodayReportBody.tsx -> .TodayReportArticle+frontend/src/scenes/project-homepage/today/TodayReportNav.tsx -> .TodayReportNav+frontend/src/scenes/project-homepage/today/TodayReportPage.tsx -> .TodayReport+frontend/src/scenes/session-recordings/player/controller/PlayerController.tsx -> .SkipToNextButton+frontend/src/scenes/session-recordings/player/controller/PlayerControllerTime.tsx -> .PlayerControlSeekIcon+frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarTicks.tsx -> .PlayerSeekbarTicks+frontend/src/scenes/session-recordings/playlist/SessionRecordingPreviewCompact.tsx -> .SessionRecordingPreview+frontend/src/scenes/session-recordings/playlist/SessionRecordingPreviewFeed.tsx -> .SessionRecordingPreview+frontend/src/scenes/surveys/SurveyDragHandle.tsx -> .SurveyQuestionDragHandle+products/business_intelligence/frontend/BIPivotTable.tsx -> .DataVisualizationTable+products/dashboards/frontend/components/ImageTile/DashboardImageTile.tsx -> .DashboardTileCard+products/product_analytics/frontend/insights/funnels/Funnel.tsx -> .FunnelInsight+products/product_analytics/frontend/insights/insightScene/InsightSkeleton.tsx -> .InsightVizDisplay+products/product_analytics/frontend/insights/insightScene/SqlInsightFilters.tsx -> .InsightVizDisplay+products/product_analytics/frontend/insights/retention/RetentionContainer.tsx -> .RetentionContainer+products/product_analytics/frontend/insights/trends/Trends.tsx -> .TrendsInsight+products/workflows/frontend/TemplateLibrary/MessageTemplateCard.tsx -> .MessageTemplateItem+products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasContent.tsx -> .TileCanvasdiff --git a/frontend/bin/cssCoupling.mjs b/frontend/bin/cssCoupling.mjsnew file mode 100644index 000000000000..1bf2da8874be--- /dev/null+++ b/frontend/bin/cssCoupling.mjs@@ -0,0 +1,211 @@+// Finds components that use a stylesheet's class without importing the stylesheet (see check-css-coupling.mjs).++// Only PascalCase block classes count, like `.PropertyFilters` or `.LemonButton`. Lower-case top-level+// classes in our stylesheets often share a name with a Tailwind utility (`.flex`, `.hidden`), and a match+// on those would flag every component that uses the utility.+const BLOCK_CLASS = /^[A-Z][A-Za-z0-9]*(?:-[A-Za-z0-9]+)*$/++function stripScssComments(source) {+ // A `//` after `(` or `:` is part of a value such as `url(//host/x.png)`, not a comment.+ return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[\s;{}])\/\/.*$/gm, '$1')+}++/** The block classes a stylesheet defines in its top-level selectors. */+export function rootClassesOf(scss) {+ const source = stripScssComments(scss)+ const classes = new Set()+ let depth = 0+ let prelude = ''+ for (let i = 0; i < source.length; i++) {+ const char = source[i]+ // `#{$var}` interpolation braces do not open a block.+ if (char === '#' && source[i + 1] === '{') {+ const close = source.indexOf('}', i)+ if (close === -1) {+ break+ }+ if (depth === 0) {+ prelude += source.slice(i, close + 1)+ }+ i = close+ continue+ }+ if (char === '{') {+ if (depth === 0) {+ for (const name of blockClassesInPrelude(prelude)) {+ classes.add(name)+ }+ }+ depth+++ prelude = ''+ } else if (char === '}') {+ depth = Math.max(0, depth - 1)+ prelude = ''+ } else if (char === ';') {+ prelude = ''+ } else if (depth === 0) {+ prelude += char+ }+ }+ return [...classes].sort()+}++function blockClassesInPrelude(prelude) {+ const trimmed = prelude.trim()+ if (trimmed.startsWith('@')) {+ return []+ }+ const names = []+ for (const selector of trimmed.split(',')) {+ const name = /^\.([\w-]+)/.exec(selector.trim())?.[1]+ if (name && BLOCK_CLASS.test(name) && !name.includes('__') && !name.includes('--')) {+ names.push(name)+ }+ }+ return names+}++// Reads a quoted string that starts at `start`. Returns its text and the index of the closing quote.+function readQuoted(source, start) {+ const quote = source[start]+ let text = ''+ let i = start + 1+ while (i < source.length && source[i] !== quote) {+ if (source[i] === '\\') {+ i+++ }+ text += source[i]+ i+++ }+ return { text, end: i }+}++// A placeholder for a `${...}` hole, so `Foo${suffix}` does not read as the class `Foo`.+const HOLE = '\u0000'++// Collects the string literals of a JS expression in braces that starts at `start`.+function readExpressionStrings(source, start, strings) {+ let depth = 0+ for (let i = start; i < source.length; i++) {+ const char = source[i]+ if (char === '/' && source[i + 1] === '/') {+ const end = source.indexOf('\n', i)+ if (end === -1) {+ return source.length+ }+ i = end+ } else if (char === '/' && source[i + 1] === '*') {+ const end = source.indexOf('*/', i + 2)+ i = end === -1 ? source.length - 1 : end + 1+ } else if (char === '"' || char === "'") {+ const { text, end } = readQuoted(source, i)+ strings.push(text)+ i = end+ } else if (char === '`') {+ let text = ''+ i+++ while (i < source.length && source[i] !== '`') {+ if (source[i] === '\\') {+ text += source[i + 1]+ i += 2+ } else if (source[i] === '$' && source[i + 1] === '{') {+ text += HOLE+ i = readExpressionStrings(source, i + 1, strings) + 1+ } else {+ text += source[i]+ i+++ }+ }+ strings.push(text)+ } else if (char === '{') {+ depth+++ } else if (char === '}') {+ depth--+ if (depth === 0) {+ return i+ }+ }+ }+ return source.length+}++/** The class names a component passes in string literals to `className` and `*ClassName` props. */+export function classNamesUsedIn(tsx) {+ const strings = []+ for (const match of tsx.matchAll(/\b(?:className|\w+ClassName)\s*=\s*/g)) {+ const start = match.index + match[0].length+ const char = tsx[start]+ if (char === '"' || char === "'") {+ strings.push(readQuoted(tsx, start).text)+ } else if (char === '{') {+ readExpressionStrings(tsx, start, strings)+ }+ }+ const names = new Set()+ for (const text of strings) {+ for (const token of text.split(/\s+/)) {+ if (token && !token.includes(HOLE)) {+ names.add(token)+ }+ }+ }+ return names+}++/** True when `file` or anything it statically imports, directly or transitively, is one of `targets`. */+export function reachesAny(files, file, targets) {+ const seen = new Set([file])+ const queue = [file]+ while (queue.length) {+ const current = queue.shift()+ if (targets.has(current)) {+ return true+ }+ for (const next of files[current]?.staticImports ?? []) {+ if (!seen.has(next)) {+ seen.add(next)+ queue.push(next)+ }+ }+ }+ return false+}++const isSource = (file) => !file.includes('node_modules/')++/**+ * Every component that uses a block class but does not statically reach a stylesheet that defines it.+ * `files` is the import graph from importGraph.mjs, and `readSource` returns a file's text.+ *+ * `stylesheetFiles` lists every stylesheet to index for block classes. It defaults to the stylesheets+ * already in `files`, but a stylesheet with no remaining importer drops out of that graph entirely, so a+ * caller checking a real build passes the full on-disk list instead.+ */+export function findCouplings(+ files,+ readSource,+ stylesheetFiles = Object.keys(files).filter((file) => isSource(file) && /\.s?css$/.test(file))+) {+ const sheetsByClass = new Map()+ for (const file of stylesheetFiles) {+ for (const name of rootClassesOf(readSource(file))) {+ sheetsByClass.set(name, [...(sheetsByClass.get(name) ?? []), file])+ }+ }+ const couplings = []+ for (const file of Object.keys(files)) {+ if (!isSource(file) || !file.endsWith('.tsx')) {+ continue+ }+ for (const name of classNamesUsedIn(readSource(file))) {+ const sheets = sheetsByClass.get(name)+ if (sheets && !reachesAny(files, file, new Set(sheets))) {+ couplings.push({ file, className: name, stylesheets: sheets.sort() })+ }+ }+ }+ return couplings.sort((a, b) => a.file.localeCompare(b.file) || a.className.localeCompare(b.className))+}++/** The baseline line for a coupling. */+export const couplingKey = ({ file, className }) => `${file} -> .${className}`diff --git a/frontend/bin/cssCoupling.test.ts b/frontend/bin/cssCoupling.test.tsnew file mode 100644index 000000000000..717d01379997--- /dev/null+++ b/frontend/bin/cssCoupling.test.ts@@ -0,0 +1,80 @@+import { classNamesUsedIn, findCouplings, rootClassesOf } from './cssCoupling.mjs'++describe('cssCoupling.mjs', () => {+ it.each([+ [+ 'a nested BEM block',+ '.PropertyFilters {\n display: flex;\n .PropertyFilters__content { gap: 1px; }\n}',+ ['PropertyFilters'],+ ],+ ['each selector in a list', '.Foo, .Bar:hover { color: red; }', ['Bar', 'Foo']],+ ['no element or modifier only selectors', '.Foo__row { a: b; }\n.Foo--active { a: b; }', []],+ ['no lower-case classes that shadow utilities', '.flex { display: flex; }', []],+ ['no global or attribute-scoped selectors', "body { a: b; }\n[theme='dark'] .Foo { a: b; }", []],+ ['no at-rules', '@media (min-width: 1px) { .Foo { a: b; } }\n@include thing;', []],+ ['no nested classes', '.Foo { .Bar { a: b; } }', ['Foo']],+ [+ 'past comments and interpolation',+ '// .Old { }\n/* .Older { } */\n.Foo-#{$x} { a: b; }\n.Bar { background: url(//x/y.png); }',+ ['Bar'],+ ],+ ])('rootClassesOf finds %s', (_, scss, expected) => {+ expect(rootClassesOf(scss)).toEqual(expected)+ })++ it.each([+ ['a plain attribute', '<div className="PropertyFilters flex-wrap" />', ['PropertyFilters', 'flex-wrap']],+ ['a clsx call', "<div className={clsx('Foo', active && 'Foo--active')} />", ['Foo', 'Foo--active']],+ ['a *ClassName prop', '<Popover overlayClassName="Bar" />', ['Bar']],+ ['template literal text, not a word cut by a hole', '<div className={`Foo ${size} Baz${x}`} />', ['Foo']],+ ['no strings outside className', "<div title='Foo' />", []],+ [+ 'a line comment with an apostrophe before the class',+ "<div className={\n // don't remove\n 'Foo'\n} />",+ ['Foo'],+ ],+ [+ 'a block comment with an apostrophe before the class',+ "<div className={/* don't remove */ 'Foo'} />",+ ['Foo'],+ ],+ ])('classNamesUsedIn reads %s', (_, tsx, expected) => {+ expect([...classNamesUsedIn(tsx)].sort()).toEqual(expected.sort())+ })++ const sources: Record<string, string> = {+ 'PropertyFilters.scss': '.PropertyFilters { display: flex; }',+ 'PropertyFilters.tsx': '<div className="PropertyFilters" />',+ 'PropertyFiltersDisplay.tsx': '<div className="PropertyFilters flex-wrap" />',+ 'Middle.ts': '',+ }+ it.each([+ ['no import route to the stylesheet', { 'PropertyFiltersDisplay.tsx': [] }, ['PropertyFiltersDisplay.tsx']],+ ['a direct import', { 'PropertyFiltersDisplay.tsx': ['PropertyFilters.scss'] }, []],+ [+ 'a transitive import',+ { 'PropertyFiltersDisplay.tsx': ['Middle.ts'], 'Middle.ts': ['PropertyFilters.tsx'] },+ [],+ ],+ ])('findCouplings flags PropertyFiltersDisplay with %s', (_, extraImports, expected) => {+ const imports: Record<string, string[]> = { 'PropertyFilters.tsx': ['PropertyFilters.scss'], ...extraImports }+ const files = Object.fromEntries(+ Object.keys(sources).map((file) => [file, { bytes: 0, staticImports: imports[file] ?? [] }])+ )+ expect(findCouplings(files, (file: string) => sources[file]).map((c: { file: string }) => c.file)).toEqual(+ expected+ )+ })++ it('findCouplings still flags a stylesheet with no remaining importer', () => {+ // Removing the sole import drops the stylesheet from the esbuild graph entirely, so it is not+ // a key of `files`. An explicit stylesheetFiles list is the only way to still index its classes.+ const files = {+ 'PropertyFiltersDisplay.tsx': { bytes: 0, staticImports: [] },+ }+ const stylesheetFiles = ['PropertyFilters.scss']+ expect(+ findCouplings(files, (file: string) => sources[file], stylesheetFiles).map((c: { file: string }) => c.file)+ ).toEqual(['PropertyFiltersDisplay.tsx'])+ })+})diff --git a/frontend/bin/importGraph.mjs b/frontend/bin/importGraph.mjsnew file mode 100644index 000000000000..a6157f0d2471--- /dev/null+++ b/frontend/bin/importGraph.mjs@@ -0,0 +1,129 @@+// The app's static import graph, read from an esbuild metafile. check-layers.mjs and check-css-coupling.mjs share it.+import path from 'node:path'+import { fileURLToPath } from 'node:url'++import { esbuildBuild } from '@posthog/esbuilder'++import { BOOT_ENTRIES } from './bootEntries.mjs'++export const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..')++// Path aliases resolve through tsconfig; anything else that is not relative is a package, and packages+// are outside the layer map.+const ALIAS_PREFIXES = ['lib/', 'scenes/', '~/', 'products/', 'public/', '@posthog/', '@common/']+const ASSET_EXTENSIONS = [+ '.css',+ '.scss',+ '.svg',+ '.png',+ '.jpg',+ '.jpeg',+ '.gif',+ '.webp',+ '.avif',+ '.ico',+ '.woff',+ '.woff2',+ '.ttf',+ '.otf',+ '.eot',+ '.mp3',+ '.mp4',+ '.wav',+ '.ogg',+ '.lottie',+ '.riv',+ '.json',+ '.md',+ '.txt',+ '.html',+ '.yaml',+ '.yml',+ '.csv',+ '.wasm',+ '.bin',+ '.gz',+ '.zip',+ '.glb',+ '.gltf',+]++const externalizePackages = {+ name: 'externalize-packages',+ setup(build) {+ build.onResolve({ filter: /\?[a-z]+$/ }, (args) => ({ path: args.path, external: true }))+ build.onResolve({ filter: /^[^./]/ }, async (args) => {+ if (args.pluginData?.resolvingAlias) {+ return undefined+ }+ if (ALIAS_PREFIXES.some((prefix) => args.path.startsWith(prefix))) {+ const resolved = await build.resolve(args.path, {+ kind: args.kind,+ resolveDir: args.resolveDir,+ importer: args.importer,+ pluginData: { resolvingAlias: true },+ })+ if (!resolved.errors.length && !resolved.path.includes('/node_modules/')) {+ return resolved+ }+ }+ return { path: args.path, external: true }+ })+ },+}++// The `empty` loader keeps asset files out of the bundle, but esbuild still records the import edge in the+// metafile. The graph keeps those edges, because the CSS coupling check needs stylesheet imports. An asset+// carries no feature code, so the layer check skips them.+export function isAssetPath(importPath) {+ return ASSET_EXTENSIONS.includes(path.extname(importPath).toLowerCase())+}++export async function readImportGraph() {+ const result = await esbuildBuild({+ absWorkingDir: repoRoot,+ entryPoints: BOOT_ENTRIES.map((entry) => `frontend/${entry}`),+ tsconfig: path.join(repoRoot, 'tsconfig.json'),+ bundle: true,+ splitting: true,+ format: 'esm',+ jsx: 'automatic',+ write: false,+ metafile: true,+ outdir: path.join(repoRoot, 'frontend', '.layer-check-out'),+ logLevel: 'silent',+ loader: Object.fromEntries(ASSET_EXTENSIONS.map((extension) => [extension, 'empty'])),+ plugins: [externalizePackages],+ })+ const files = {}+ for (const [file, input] of Object.entries(result.metafile.inputs)) {+ files[file] = {+ bytes: input.bytes,+ staticImports: input.imports.filter((i) => i.kind === 'import-statement' && !i.external).map((i) => i.path),+ }+ }+ return files+}++export function staticReach(files, root) {+ const parentOf = new Map([[root, null]])+ const queue = [root]+ while (queue.length) {+ const file = queue.shift()+ for (const target of files[file]?.staticImports ?? []) {+ if (!parentOf.has(target)) {+ parentOf.set(target, file)+ queue.push(target)+ }+ }+ }+ return parentOf+}++export function chainTo(parentOf, file) {+ const chain = []+ for (let current = file; current; current = parentOf.get(current)) {+ chain.unshift(current)+ }+ return chain+}diff --git a/hogli.yaml b/hogli.yamlindex 76ae7e5dc7c6..0df4afda78a6 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -901,6 +901,9 @@ quality:lint:frontend-layers:cmd: node frontend/bin/check-layers.mjs "$@"description: Block new static imports from a lower frontend layer into a higher one+ lint:frontend-css-coupling:+ cmd: node frontend/bin/check-css-coupling.mjs "$@"+ description: Block new components that use a stylesheet's class without importing the stylesheetlint:workflows:click: hogli_commands.workflow_lint.cli:cmd_lint_workflowsdescription: Lint .github/workflows/** for repo conventionsdiff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.pyindex 46edf60ff5d4..916e5838cfac 100644--- a/tools/hogli-commands/hogli_commands/ci_preflight.py+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py@@ -310,6 +310,21 @@ DIFF_CHECKS: list[DiffCheck] = [fix=["hogli", "lint:frontend-layers", "--prune-baseline"],requires=("node",),),+ DiffCheck(+ key="frontend-css-coupling",+ label="new component that uses a stylesheet's class without importing the stylesheet",+ triggers=[+ "frontend/src/*",+ "products/*/frontend/*",+ "frontend/bin/cssCoupling.mjs",+ "frontend/bin/css-coupling-baseline.txt",+ ],+ verify=["hogli", "lint:frontend-css-coupling"],+ # Prune, never update: --update-baseline would grandfather the coupling the+ # branch just added, which is the one thing the check exists to stop.+ fix=["hogli", "lint:frontend-css-coupling", "--prune-baseline"],+ requires=("node",),+ ),DiffCheck(key="workflow-lint",label="workflow-convention failure in .github/workflows",