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.

fix(frontend): drop top-level await from stable lazy chunks (#107020)

Paul D'Ambra39b69adda4e6
diff --git a/common/esbuilder/cssLoader.mjs b/common/esbuilder/cssLoader.mjs
index 327f6ab6535f..d35990e71324 100644
--- a/common/esbuilder/cssLoader.mjs
+++ b/common/esbuilder/cssLoader.mjs
@@ -129,6 +129,8 @@ export function cssLoaderScript(cssFile, cssFileFallback) {
}
export const CSS_LOAD_GLOBAL = 'ESBUILD_LOAD_CSS'
+export const CHUNK_CSS_GLOBAL = 'ESBUILD_CHUNK_CSS'
+export const CHUNK_IMPORT_GLOBAL = 'ESBUILD_IMPORT'
/**
* Inline loader for the stable build's split stylesheets (see frontend/bin/stableCssPlan.mjs).
@@ -143,6 +145,12 @@ export const CSS_LOAD_GLOBAL = 'ESBUILD_LOAD_CSS'
* stylesheet, which holds every rule, with its whole retry and reporting ladder. A failure in the
* stable build therefore ends up where the default build starts. A load that fails for good
* resolves `false` and is forgotten, so the next attempt fetches again.
+ *
+ * `window.ESBUILD_IMPORT(specifier)` is how the stable build imports a lazy entry chunk. The chunk
+ * registers its stylesheets in `window.ESBUILD_CHUNK_CSS` as it evaluates, and the import resolves
+ * once they apply, so a scene never renders unstyled. The chunk cannot wait for them itself with
+ * top-level await: WebKit before Safari 27 resolves a second import() of a module that is paused
+ * at a top-level await straight away, before the module's body has run.
*/
export function stableCssLoaderScript(eagerFiles, fullCssFile, fullCssFileFallback) {
return `
@@ -239,6 +247,21 @@ export function stableCssLoaderScript(eagerFiles, fullCssFile, fullCssFileFallba
return (window.JS_URL || '') + '/static/' + file;
});
window.${CSS_READY_GLOBAL} = window.${CSS_LOAD_GLOBAL}(eager);
+
+ window.${CHUNK_CSS_GLOBAL} = {};
+ window.${CHUNK_IMPORT_GLOBAL} = function (specifier) {
+ return import(specifier).then(function (module) {
+ if (!(specifier in window.${CHUNK_CSS_GLOBAL})) {
+ return module;
+ }
+ return window.${CSS_LOAD_GLOBAL}(window.${CHUNK_CSS_GLOBAL}[specifier]).then(function (applied) {
+ if (!applied) {
+ throw Object.assign(new Error('Stylesheets for this chunk did not load'), { name: 'ChunkLoadError' });
+ }
+ return module;
+ });
+ });
+ };
})();
`
}
diff --git a/common/esbuilder/cssLoader.test.ts b/common/esbuilder/cssLoader.test.ts
index 73f88b84140e..87f646aebad8 100644
--- a/common/esbuilder/cssLoader.test.ts
+++ b/common/esbuilder/cssLoader.test.ts
@@ -281,4 +281,60 @@ describe('css loader script', () => {
await expect(secondRequest).resolves.toBe(true)
})
})
+
+ describe('stable chunk import', () => {
+ const MODULE = { scene: 'the scene' }
+
+ // A classic-script Function body cannot run import(), so the test supplies the module.
+ function stableImporter(): ReturnType<typeof runLoader> & {
+ importChunk: (specifier: string) => Promise<unknown>
+ } {
+ const loader = runLoader({
+ script: stableCssLoaderScript(['eager-1.css'], CSS_FILE, CSS_FALLBACK).replace(
+ 'import(specifier)',
+ 'window.importModule(specifier)'
+ ),
+ })
+ loader.win.importModule = () => Promise.resolve(MODULE)
+ return { ...loader, importChunk: (specifier) => loader.win.ESBUILD_IMPORT(specifier) }
+ }
+
+ it('resolves a chunk that registered no stylesheets without loading any', async () => {
+ const { links, importChunk } = stableImporter()
+
+ await expect(importChunk('@c/eNOCSS')).resolves.toBe(MODULE)
+ expect(links).toHaveLength(1)
+ })
+
+ it.each([
+ ['resolves to the module once its stylesheets apply', true],
+ ['rejects with a ChunkLoadError when its stylesheets do not apply', false],
+ ])('%s', async (_name, applies) => {
+ const { links, win, importChunk } = stableImporter()
+ const imported = importChunk('@c/eSCENE')
+ // The chunk registers its stylesheets as it evaluates, before the import settles.
+ win.ESBUILD_CHUNK_CSS['@c/eSCENE'] = [[`${STATIC}scene.css`, 5]]
+ let settled = false
+ void imported.then(
+ () => (settled = true),
+ () => (settled = true)
+ )
+ await Promise.resolve()
+ await Promise.resolve()
+
+ expect(settled).toBe(false)
+ const sceneLink = links.find((link) => link.href === `${STATIC}scene.css`)!
+ if (applies) {
+ applyStylesheet(sceneLink)
+ await expect(imported).resolves.toBe(MODULE)
+ } else {
+ sceneLink.dispatch('error')
+ for (let attempt = 2; attempt < 6; attempt++) {
+ await Promise.resolve()
+ links[attempt]?.dispatch('error')
+ }
+ await expect(imported).rejects.toMatchObject({ name: 'ChunkLoadError' })
+ }
+ })
+ })
})
diff --git a/frontend/bin/stableChunkNames.mjs b/frontend/bin/stableChunkNames.mjs
index c6641dbc3e11..c506929576af 100644
--- a/frontend/bin/stableChunkNames.mjs
+++ b/frontend/bin/stableChunkNames.mjs
@@ -2,6 +2,8 @@ import { createHash } from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
+import { CHUNK_IMPORT_GLOBAL } from '@posthog/esbuilder/cssLoader.mjs'
+
/**
* Stable chunk names.
*
@@ -48,13 +50,20 @@ export function chunkIdentity(output) {
// the import map. The same path passed to new URL(), fetch() or a Worker must stay a real URL.
const IMPORT_OF_PATH = /(\bfrom\s*|\bimport\s*\(?\s*)(["'])\/static\/([^"'\s]+?\.js)\2/g
-/** Replaces every import of a known chunk by path with an import of its identity specifier. */
-export function rewriteChunkSource(source, identityByFile) {
+const isDynamicImport = (keyword) => keyword.trimEnd().endsWith('(')
+
+/**
+ * Replaces every import of a known chunk by path with an import of its identity specifier. A
+ * dynamic import of a chunk in `cssChunkFiles` goes through `window.ESBUILD_IMPORT`, which waits
+ * for the stylesheets that chunk registers.
+ */
+export function rewriteChunkSource(source, identityByFile, cssChunkFiles = new Set()) {
return source.replace(SOURCE_MAP_COMMENT, '').replace(IMPORT_OF_PATH, (match, keyword, quote, file) => {
if (!identityByFile.has(file)) {
return match
}
- const replacement = `${keyword}${quote}${SPECIFIER_PREFIX}${identityByFile.get(file)}${quote}`
+ const importer = cssChunkFiles.has(file) && isDynamicImport(keyword) ? `${CHUNK_IMPORT_GLOBAL}(` : keyword
+ const replacement = `${importer}${quote}${SPECIFIER_PREFIX}${identityByFile.get(file)}${quote}`
// Pad to the original byte length so every other offset in the file is unchanged and the
// esbuild-emitted source map (which points at byte offsets) still lines up. `from"…"`,
// `import"…"` and `import("…")` all allow whitespace after the closing quote.
@@ -80,6 +89,8 @@ export function stableFileName(originalFile, rewrittenSource) {
* Plans the stable copy of a build. `outputs` is the esbuild metafile's `outputs`, and
* `readSource(outputPath)` returns an output file's contents. Pure apart from `readSource`.
*
+ * `preludes` maps an output path to a function of its specifier that returns the chunk's first line.
+ *
* Returns, per JS output, its identity, stable file name and rewritten source, plus the import
* map.
*/
@@ -103,19 +114,20 @@ export function planStableChunks(outputs, readSource, distPrefix = 'dist/', prel
identityByFile.set(fileOf(outputPath), identity)
}
+ const cssChunkFiles = new Set([...preludes.keys()].map(fileOf))
const plan = new Map()
const imports = {}
for (const [outputPath] of jsOutputs) {
const file = fileOf(outputPath)
const rawSource = readSource(outputPath)
- const source = rewriteChunkSource(rawSource, identityByFile)
- // Every replacement preserves length, except an identity collision with a short entry name
- // (see rewriteChunkSource). When that happens the map's byte offsets no longer line up.
+ const source = rewriteChunkSource(rawSource, identityByFile, cssChunkFiles)
+ // Every replacement preserves length, unless it outgrows a very short chunk name (an identity
+ // collision, or ESBUILD_IMPORT). When that happens the map's byte offsets no longer line up.
const mapValid = source.length === rawSource.replace(SOURCE_MAP_COMMENT, '').length
// A prelude goes on its own first line, so the map only needs to shift down one line.
- const prelude = preludes.get(outputPath) ?? null
- const finalSource = prelude ? `${prelude}\n${source}` : source
const identity = identityByFile.get(file)
+ const prelude = preludes.get(outputPath)?.(`${SPECIFIER_PREFIX}${identity}`) ?? null
+ const finalSource = prelude ? `${prelude}\n${source}` : source
const stableFile = stableFileName(file, finalSource)
plan.set(outputPath, { identity, file, stableFile, source: finalSource, mapValid, prelude })
imports[`${SPECIFIER_PREFIX}${identity}`] = `static/${stableFile}`
diff --git a/frontend/bin/stableChunkNames.test.ts b/frontend/bin/stableChunkNames.test.ts
index f5646c701e45..174af9779137 100644
--- a/frontend/bin/stableChunkNames.test.ts
+++ b/frontend/bin/stableChunkNames.test.ts
@@ -109,19 +109,40 @@ describe('planStableChunks', () => {
})
// The copied source map is shifted down exactly one line, so the prelude must be a line of its own.
- it('puts a prelude on its own first line and names the chunk by it', () => {
+ it('puts a prelude on its own first line, keyed by the chunk specifier, and names the chunk by it', () => {
const sources = entry('export const a=1')
const withPrelude = planStableChunks(
OUTPUTS,
(outputPath: string) => sources[outputPath],
'dist/',
- new Map([['dist/Scene-AAAA1111.js', 'await window.ESBUILD_LOAD_CSS([]);']])
+ new Map([['dist/Scene-AAAA1111.js', (specifier: string) => `register(${JSON.stringify(specifier)});`]])
).plan.get('dist/Scene-AAAA1111.js')!
- expect(withPrelude.source.split('\n')[0]).toBe('await window.ESBUILD_LOAD_CSS([]);')
+ expect(withPrelude.source.split('\n')[0]).toMatch(/^register\("@c\/e[0-9A-F]{10}"\);$/)
expect(withPrelude.stableFile).not.toBe(plan(sources).get('dist/Scene-AAAA1111.js')!.stableFile)
})
+ it('imports a chunk with a prelude dynamically through the stylesheet-aware loader, and statically as is', () => {
+ const outputs = {
+ ...OUTPUTS,
+ 'dist/Lazy-DDDD4444.js': { entryPoint: 'src/scenes/Lazy.tsx', inputs: { 'src/scenes/Lazy.tsx': {} } },
+ }
+ const importer =
+ 'import("/static/Lazy-DDDD4444.js");import("/static/chunk-BBBB2222.js");import"/static/Lazy-DDDD4444.js"'
+ const { plan: lazyPlan } = planStableChunks(
+ outputs,
+ (outputPath: string) => (outputPath === 'dist/Scene-AAAA1111.js' ? importer : ''),
+ 'dist/',
+ new Map([['dist/Lazy-DDDD4444.js', () => 'register();']])
+ )
+ const { source, mapValid } = lazyPlan.get('dist/Scene-AAAA1111.js')!
+
+ expect(source).toMatch(
+ /^ESBUILD_IMPORT\("@c\/e[0-9A-F]{10}" *\);import\("@c\/c[0-9A-F]{10}" *\);import"@c\/e[0-9A-F]{10}" *$/
+ )
+ expect(mapValid).toBe(true)
+ })
+
describe('writeStableChunks', () => {
const ENTRY_OUTPUTS = {
'dist/entry-AAAA1111.js': { entryPoint: 'src/entry.tsx', inputs: { 'src/entry.tsx': {} } },
@@ -144,7 +165,7 @@ describe('planStableChunks', () => {
chunks: {},
entrypoints: [],
preloadManifest: undefined,
- preludes: prelude ? new Map([['dist/entry-AAAA1111.js', prelude]]) : new Map(),
+ preludes: prelude ? new Map([['dist/entry-AAAA1111.js', () => prelude]]) : new Map(),
})
const stableMapFile = readdirSync(distDir).find(
@@ -158,7 +179,7 @@ describe('planStableChunks', () => {
// Pins the map shift so a regression here doesn't only show up as misattributed stack traces.
it.each([
- ['a prelude chunk', 'await window.ESBUILD_LOAD_CSS([]);', ';AAAA'],
+ ['a prelude chunk', 'register();', ';AAAA'],
['a chunk with no prelude', null, 'AAAA'],
])('shifts the written source map by one line for %s', (_name, prelude, expectedMappings) => {
expect(writeAndReadMap(prelude)).toBe(expectedMappings)
diff --git a/frontend/bin/stableCssPlan.mjs b/frontend/bin/stableCssPlan.mjs
index e008266067fe..0007b3be0127 100644
--- a/frontend/bin/stableCssPlan.mjs
+++ b/frontend/bin/stableCssPlan.mjs
@@ -1,4 +1,4 @@
-import { CSS_LOAD_GLOBAL } from '@posthog/esbuilder/cssLoader.mjs'
+import { CHUNK_CSS_GLOBAL } from '@posthog/esbuilder/cssLoader.mjs'
import { BOOT_ENTRIES, ENTRY } from './bootEntries.mjs'
import { alphanumericStem, chunkIdentity, shortHash } from './stableChunkNames.mjs'
@@ -13,7 +13,7 @@ import { alphanumericStem, chunkIdentity, shortHash } from './stableChunkNames.m
* - Eager layers hold the CSS that the boot chain (entry, App, bootApp, AuthenticatedShell) imports
* statically. The stable page links them in order before the first render.
* - Lazy groups hold the rest, grouped by the JS chunks whose modules import it. A lazy entry
- * chunk waits for the groups its static imports need before it runs (see `cssPrelude`).
+ * chunk registers the groups its static imports need, and its import waits for them (see `cssPrelude`).
*
* Groups keep today's rule order among themselves, because every group lists its files in the
* order of the entry stylesheet. Lazy groups load after the eager layers.
@@ -153,7 +153,6 @@ export function planCssGroups({ inputs, outputs }, bootEntries = BOOT_ENTRIES) {
}
const eager = EAGER_ORDER.filter((name) => groups.has(name))
- // A lazy prelude would call the undefined window.ESBUILD_LOAD_CSS if there's no eager layer to define it.
if (lazyGroupsByEntry.size > 0 && eager.length === 0) {
throw new Error('stable css: lazy chunks need split CSS but no eager layer would define the loader')
}
@@ -165,20 +164,13 @@ export function planCssGroups({ inputs, outputs }, bootEntries = BOOT_ENTRIES) {
}
/**
- * The line a lazy entry chunk starts with: it waits for its stylesheets before any of its code
- * runs, so the chunk never renders unstyled. `import.meta.resolve` reads each group's URL from the
- * import map, and the group's rank tells the loader where to insert it.
- *
- * A browser without `import.meta.resolve` (Chromium 89 to 104 has import maps but not this) gets
- * the full stylesheet instead. When even that fails, the chunk throws a ChunkLoadError, so the
- * app's chunk-load recovery runs, not an unstyled scene.
+ * The line a lazy entry chunk starts with: it registers the chunk's stylesheets for
+ * `window.ESBUILD_IMPORT` to wait on. Without `import.meta.resolve` (Chromium 89 to 104 has import
+ * maps but not this) it registers `null`, which asks for the full stylesheet instead.
*/
-export function cssPrelude(groupNames, rankOfGroup) {
+export function cssPrelude(specifier, groupNames, rankOfGroup) {
const entries = groupNames.map(
(name) => `[import.meta.resolve(${JSON.stringify(CSS_SPECIFIER_PREFIX + name)}),${rankOfGroup.get(name)}]`
)
- return (
- `if(!(await window.${CSS_LOAD_GLOBAL}(typeof import.meta.resolve=="function"?[${entries.join(',')}]:null)))` +
- `throw Object.assign(new Error("Stylesheets for this chunk did not load"),{name:"ChunkLoadError"});`
- )
+ return `window.${CHUNK_CSS_GLOBAL}[${JSON.stringify(specifier)}]=typeof import.meta.resolve=="function"?[${entries.join(',')}]:null;`
}
diff --git a/frontend/bin/stableCssPlan.test.ts b/frontend/bin/stableCssPlan.test.ts
index 8330ec9184d2..131b71bba3aa 100644
--- a/frontend/bin/stableCssPlan.test.ts
+++ b/frontend/bin/stableCssPlan.test.ts
@@ -1,4 +1,4 @@
-import { CSS_LOAD_GLOBAL } from '@posthog/esbuilder/cssLoader.mjs'
+import { CHUNK_CSS_GLOBAL } from '@posthog/esbuilder/cssLoader.mjs'
import { cssPrelude, planCssGroups } from './stableCssPlan.mjs'
@@ -153,75 +153,42 @@ describe('planCssGroups', () => {
})
describe('cssPrelude', () => {
- // A prelude that resolved a wrong URL, dropped a rank, or swapped the ternary branches would
- // still pass planCssGroups' own tests, since those never evaluate the generated string.
- async function runPrelude(
+ const SPECIFIER = '@c/eSCENE'
+
+ function runPrelude(
groupNames: string[],
rankOfGroup: Map<string, number>,
- {
- hasImportMetaResolve = true,
- loadCss,
- }: { hasImportMetaResolve?: boolean; loadCss: (entries: unknown) => Promise<boolean> }
- ): Promise<{ error?: Error }> {
- const win: Record<string, unknown> = { [CSS_LOAD_GLOBAL]: loadCss }
+ { hasImportMetaResolve = true } = {}
+ ): Record<string, unknown> {
+ const win: Record<string, Record<string, unknown>> = { [CHUNK_CSS_GLOBAL]: {} }
const importMeta = hasImportMetaResolve ? { resolve: (specifier: string) => `resolved:${specifier}` } : {}
- // `import.meta` is only valid inside a module, so a plain Function body can't reference it
- // directly: stub it in as a parameter instead. In production this prelude runs inside an
- // ES module chunk, loaded via dynamic import, which a plain Function body can't replicate.
- const body = cssPrelude(groupNames, rankOfGroup).replace(/import\.meta/g, 'importMeta')
- try {
- await new Function('window', 'importMeta', `return (async () => { ${body} })()`)(win, importMeta)
- return {}
- } catch (error) {
- return { error: error as Error }
- }
+ // `import.meta` is only valid inside a module, so stub it in as a parameter.
+ const body = cssPrelude(SPECIFIER, groupNames, rankOfGroup).replace(/import\.meta/g, 'importMeta')
+ new Function('window', 'importMeta', body)(win, importMeta)
+ return win[CHUNK_CSS_GLOBAL]
}
- it('resolves each group to its import-map URL and rank, in the order given', async () => {
+ it('registers each group under the chunk specifier with its import-map URL and rank, in the order given', () => {
const rankOfGroup = new Map([
['lazy-a', 3],
['lazy-b', 1],
])
- let seenEntries: unknown
- await runPrelude(['lazy-a', 'lazy-b'], rankOfGroup, {
- loadCss: (entries) => {
- seenEntries = entries
- return Promise.resolve(true)
- },
- })
- expect(seenEntries).toEqual([
- ['resolved:@css/lazy-a', 3],
- ['resolved:@css/lazy-b', 1],
- ])
+ expect(runPrelude(['lazy-a', 'lazy-b'], rankOfGroup)).toEqual({
+ [SPECIFIER]: [
+ ['resolved:@css/lazy-a', 3],
+ ['resolved:@css/lazy-b', 1],
+ ],
+ })
})
- it.each([
- { loadResult: true, expectedErrorName: undefined },
- { loadResult: false, expectedErrorName: 'ChunkLoadError' },
- ])(
- 'throws a ChunkLoadError only when the stylesheets fail to load (loadCss resolves $loadResult)',
- async ({ loadResult, expectedErrorName }) => {
- const { error } = await runPrelude(['lazy-a'], new Map([['lazy-a', 0]]), {
- loadCss: () => Promise.resolve(loadResult),
- })
-
- expect(error?.name).toBe(expectedErrorName)
- }
- )
-
- // A browser without import.meta.resolve cannot look up group URLs, so the prelude asks for the
- // full stylesheet instead of resolving anything.
- it('requests the full stylesheet instead when import.meta.resolve is unavailable', async () => {
- let seenEntries: unknown = 'not called'
- await runPrelude(['lazy-a'], new Map([['lazy-a', 0]]), {
- hasImportMetaResolve: false,
- loadCss: (entries) => {
- seenEntries = entries
- return Promise.resolve(true)
- },
+ it('registers the full stylesheet instead when import.meta.resolve is unavailable', () => {
+ expect(runPrelude(['lazy-a'], new Map([['lazy-a', 0]]), { hasImportMetaResolve: false })).toEqual({
+ [SPECIFIER]: null,
})
+ })
- expect(seenEntries).toBeNull()
+ it('never emits a top-level await', () => {
+ expect(cssPrelude(SPECIFIER, ['lazy-a'], new Map([['lazy-a', 0]]))).not.toMatch(/\bawait\b/)
})
})
diff --git a/frontend/build.mjs b/frontend/build.mjs
index 0be5dd40d2e4..e2d4a56d51fc 100755
--- a/frontend/build.mjs
+++ b/frontend/build.mjs
@@ -130,7 +130,7 @@ await buildInParallel(
preludes: new Map(
[...cssPlan.lazyGroupsByEntry].map(([file, groups]) => [
file,
- cssPrelude(groups, cssPlan.rankOfGroup),
+ (specifier) => cssPrelude(specifier, groups, cssPlan.rankOfGroup),
])
),
extraImports: Object.fromEntries(