: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
perf(frontend): serve the esbuild chunk map as a static file instead of inlining it (#94059)
Paul D'Ambraa3ec19fabd73
diff --git a/common/esbuilder/chunkLoader.mjs b/common/esbuilder/chunkLoader.mjsnew file mode 100644index 000000000000..d15a9cef702d--- /dev/null+++ b/common/esbuilder/chunkLoader.mjs@@ -0,0 +1,78 @@+import { createHash } from 'node:crypto'++/**+ * Esbuild splits a scene into many chunks, and each chunk only declares its own imports, so the+ * browser discovers a scene's files level by level. The chunk map lists every chunk per lazy entry+ * so the scene loader can request them all at once. The map is ~0.5 MB of hashes for the whole+ * app and changes on every deploy, so it is served as its own hashed, immutable static file rather+ * than inlined into the HTML document that every page load has to download and parse first.+ *+ * Only the `index` entry list stays inline: the app entry needs it synchronously at boot, and it+ * is a handful of chunks.+ */+export const CHUNK_MAP_GLOBAL = 'ESBUILD_CHUNK_MAP'++// Hashes the exact bytes chunkMapFileContents emits, not just the chunk metadata, so a change+// to the wrapper it writes also gets a new URL. Otherwise a deploy that only touches the wrapper+// would reuse the old immutable URL while serving different bytes, letting caches keep the stale+// wrapper.+export function chunkMapFileName(entry, chunks) {+ const hash = createHash('sha256').update(chunkMapFileContents(chunks)).digest('hex').slice(0, 8).toUpperCase()+ return `chunk-map-${entry}-${hash}.js`+}++/** Contents of the external map file: merges the full map into the inline global. */+export function chunkMapFileContents(chunks) {+ return `window.${CHUNK_MAP_GLOBAL} = Object.assign(window.${CHUNK_MAP_GLOBAL} || {}, ${JSON.stringify(chunks)});\n`+}++/**+ * Inline loader script. `chunkMapFile` is the hashed external file, or null to inline the whole+ * map (dev builds serve no map at all and pass `{}`).+ *+ * Scenes requested before the external map arrives are queued and flushed when it loads. The map+ * is a prefetch optimization only: `import()` of the scene module resolves its graph regardless,+ * so a missing or failed map file costs latency, never correctness.+ */+export function chunkLoaderScript(chunks, chunkMapFile) {+ const inlineMap = chunkMapFile ? { index: chunks.index || [] } : chunks+ const loadExternal = chunkMapFile+ ? `+ (function () {+ var pending = [];+ window.ESBUILD_PENDING_CHUNK_SCENES = pending;+ var script = document.createElement('script');+ script.async = true;+ if (document.currentScript && document.currentScript.nonce) {+ script.nonce = document.currentScript.nonce;+ }+ script.src = (window.JS_URL || '') + '/static/' + ${JSON.stringify(chunkMapFile)};+ script.onload = function () {+ window.ESBUILD_PENDING_CHUNK_SCENES = null;+ pending.forEach(function (name) { window.ESBUILD_LOAD_CHUNKS(name); });+ };+ script.onerror = function () {+ window.ESBUILD_PENDING_CHUNK_SCENES = null;+ };+ document.head.appendChild(script);+ })();`+ : ''+ return `+ window.ESBUILD_LOADED_CHUNKS = new Set();+ window.${CHUNK_MAP_GLOBAL} = Object.assign(window.${CHUNK_MAP_GLOBAL} || {}, ${JSON.stringify(inlineMap)});+ window.ESBUILD_LOAD_CHUNKS = function(name) {+ var chunks = window.${CHUNK_MAP_GLOBAL}[name];+ if (!chunks && window.ESBUILD_PENDING_CHUNK_SCENES) {+ window.ESBUILD_PENDING_CHUNK_SCENES.push(name);+ return;+ }+ for (const chunk of chunks || []) {+ if (!window.ESBUILD_LOADED_CHUNKS.has(chunk)) {+ window.ESBUILD_LOAD_SCRIPT('chunk-'+chunk+'.js');+ window.ESBUILD_LOADED_CHUNKS.add(chunk);+ }+ }+ }+ window.ESBUILD_LOAD_CHUNKS('index');${loadExternal}+ `+}diff --git a/common/esbuilder/chunkLoader.test.ts b/common/esbuilder/chunkLoader.test.tsnew file mode 100644index 000000000000..fa611afad98c--- /dev/null+++ b/common/esbuilder/chunkLoader.test.ts@@ -0,0 +1,93 @@+import { createHash } from 'node:crypto'++import { chunkLoaderScript, chunkMapFileContents, chunkMapFileName } from './chunkLoader.mjs'++const CHUNKS = {+ index: ['AAAA1111', 'BBBB2222'],+ Dashboard: ['BBBB2222', 'CCCC3333'],+ PersonScene: ['DDDD4444'],+}++type FakeScript = { async?: boolean; nonce?: string; src?: string; onload?: () => void; onerror?: () => void }++function runLoader(chunkMapFile: string | null): {+ win: Record<string, any>+ loaded: string[]+ scripts: FakeScript[]+} {+ const loaded: string[] = []+ const scripts: FakeScript[] = []+ const win: Record<string, any> = {+ JS_URL: 'https://cdn.example.com',+ ESBUILD_LOAD_SCRIPT: (file: string) => loaded.push(file),+ }+ const doc = {+ currentScript: { nonce: 'n0nce' },+ createElement: (): FakeScript => ({}),+ head: { appendChild: (s: FakeScript) => scripts.push(s) },+ }+ // The inline loader runs in the page as a classic script: `window` and `document` are globals.+ new Function('window', 'document', chunkLoaderScript(CHUNKS, chunkMapFile))(win, doc)+ return { win, loaded, scripts }+}++describe('chunk loader script', () => {+ it('loads the index chunks synchronously at boot', () => {+ const { loaded } = runLoader('chunk-map-index-ABCD1234.js')+ expect(loaded).toEqual(['chunk-AAAA1111.js', 'chunk-BBBB2222.js'])+ })++ it('fetches the external map with the page nonce and CDN base', () => {+ const { scripts } = runLoader('chunk-map-index-ABCD1234.js')+ expect(scripts).toHaveLength(1)+ expect(scripts[0].src).toBe('https://cdn.example.com/static/chunk-map-index-ABCD1234.js')+ expect(scripts[0].async).toBe(true)+ expect(scripts[0].nonce).toBe('n0nce')+ })++ it('queues scenes requested before the map arrives and flushes them on load, skipping loaded chunks', () => {+ const { win, loaded, scripts } = runLoader('chunk-map-index-ABCD1234.js')+ win.ESBUILD_LOAD_CHUNKS('Dashboard')+ expect(loaded).toEqual(['chunk-AAAA1111.js', 'chunk-BBBB2222.js'])++ // The external file merges the full map into the same global, then the queue drains.+ new Function('window', chunkMapFileContents(CHUNKS))(win)+ scripts[0].onload?.()++ expect(loaded).toEqual(['chunk-AAAA1111.js', 'chunk-BBBB2222.js', 'chunk-CCCC3333.js'])+ win.ESBUILD_LOAD_CHUNKS('PersonScene')+ expect(loaded).toContain('chunk-DDDD4444.js')+ })++ it('gives up queueing when the map fails to load, so later requests are plain no-ops', () => {+ const { win, loaded, scripts } = runLoader('chunk-map-index-ABCD1234.js')+ scripts[0].onerror?.()+ win.ESBUILD_LOAD_CHUNKS('Dashboard')+ expect(loaded).toEqual(['chunk-AAAA1111.js', 'chunk-BBBB2222.js'])+ expect(win.ESBUILD_PENDING_CHUNK_SCENES).toBeNull()+ })++ it('inlines the whole map and fetches nothing when no external file is given', () => {+ const { win, loaded, scripts } = runLoader(null)+ win.ESBUILD_LOAD_CHUNKS('Dashboard')+ expect(scripts).toHaveLength(0)+ expect(loaded).toEqual(['chunk-AAAA1111.js', 'chunk-BBBB2222.js', 'chunk-CCCC3333.js'])+ })++ it('names the map file by content so a changed map gets a new URL', () => {+ const a = chunkMapFileName('index', CHUNKS)+ const b = chunkMapFileName('index', { ...CHUNKS, Dashboard: ['EEEE5555'] })+ expect(a).toMatch(/^chunk-map-index-[0-9A-F]{8}\.js$/)+ expect(a).not.toBe(b)++ // The hash covers the exact bytes chunkMapFileContents writes to disk, wrapper included,+ // not just the chunk metadata. A future change to the wrapper also gets a new URL.+ const hash = a.match(/^chunk-map-index-([0-9A-F]{8})\.js$/)?.[1]+ const contentHash = createHash('sha256')+ .update(chunkMapFileContents(CHUNKS))+ .digest('hex')+ .slice(0, 8)+ .toUpperCase()+ expect(hash).toBe(contentHash)+ })+})diff --git a/common/esbuilder/utils.mjs b/common/esbuilder/utils.mjsindex cf627d16316e..6ccd964f071d 100644--- a/common/esbuilder/utils.mjs+++ b/common/esbuilder/utils.mjs@@ -16,6 +16,8 @@ import postcss from 'postcss'import postcssPresetEnv from 'postcss-preset-env'import ts from 'typescript'+import { chunkLoaderScript, chunkMapFileContents, chunkMapFileName } from './chunkLoader.mjs'+// Re-exported for one-shot builds outside buildInParallel (e.g. the toolbar loader, which is// built after the toolbar app build so it can embed the hashed entry filename). Consumers// depend on @posthog/esbuilder, not on esbuild directly, so pnpm's strict node_modules@@ -107,23 +109,19 @@ export function copyIndexHtml(// Esbuild "chunks" a scene into possibly hundreds of tiny files. When we load the first few files,// they tell us which other files to load. This cascading loading is slow. That's why we cache// the list of chunks per scene, and load them all in parallel when a scene is loaded.+ //+ // The full map is written to its own content-hashed file in dist and fetched by the inline+ // loader, instead of being inlined into the HTML: the map is hundreds of KB that changed on+ // every deploy and had to be downloaded and parsed before the app could boot, on every page.// Don't use chunks in dev mode.// Django caches the generated index.html, and we'll end up loading the wrong chunks after one change.const chunksToServe = isDev ? {} : chunks- const chunkCode = `- window.ESBUILD_LOADED_CHUNKS = new Set();- window.ESBUILD_LOAD_CHUNKS = function(name) {- const chunks = ${JSON.stringify(chunksToServe)}[name] || [];- for (const chunk of chunks) {- if (!window.ESBUILD_LOADED_CHUNKS.has(chunk)) {- window.ESBUILD_LOAD_SCRIPT('chunk-'+chunk+'.js');- window.ESBUILD_LOADED_CHUNKS.add(chunk);- }- }- }- window.ESBUILD_LOAD_CHUNKS('index');- `+ const chunkMapFile = Object.keys(chunksToServe).length > 0 ? chunkMapFileName(entry, chunksToServe) : null+ if (chunkMapFile) {+ fse.writeFileSync(path.resolve(absWorkingDir, 'dist', chunkMapFile), chunkMapFileContents(chunksToServe))+ }+ const chunkCode = Object.keys(chunks).length > 0 ? chunkLoaderScript(chunksToServe, chunkMapFile) : ''// Fallback to non-hashed CSS (with cache-busting build ID) when the hashed// version fails to load (e.g. CDN returns 403). Mirrors the JS fallback above.@@ -173,7 +171,7 @@ export function copyIndexHtml(// adding elements to the DOM${cssFile ? cssLoader : ''}${scriptCode}- ${Object.keys(chunks).length > 0 ? chunkCode : ''}+ ${chunkCode}</script></head>`)diff --git a/frontend/jest.config.ts b/frontend/jest.config.tsindex 6596d2e6a444..85cf75a40d20 100644--- a/frontend/jest.config.ts+++ b/frontend/jest.config.ts@@ -90,6 +90,7 @@ function rootDirectories(): string[] {'<rootDir>/../packages/quill/packages/charts/src','<rootDir>/../packages/quill/packages/components/src','<rootDir>/../packages/llm-normalizer/src',+ '<rootDir>/../common/esbuilder',]}diff --git a/frontend/src/globals.d.ts b/frontend/src/globals.d.tsindex 48cf28478f0d..99f955d8b499 100644--- a/frontend/src/globals.d.ts+++ b/frontend/src/globals.d.ts@@ -43,6 +43,10 @@ declare global {ESBUILD_LOADED_CHUNKS: Set<string>/** Set by the HTML loader script: resolves when the boot stylesheet has loaded (true) or failed (false). */ESBUILD_CSS_READY?: Promise<boolean>+ /** Chunk hashes per lazy entry; the full map arrives from a hashed static file after boot. */+ ESBUILD_CHUNK_MAP: Record<string, string[]>+ /** Scenes requested before the chunk map loaded; null once it has loaded or failed. */+ ESBUILD_PENDING_CHUNK_SCENES: string[] | nullPOSTHOG_EXPORTED_DATA: ExportedDataPOSTHOG_USER_IDENTITY_WITH_FLAGS?: {distinctID: string