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.

feat(toolbar): split the toolbar into a tiny loader plus a code-split ESM app (#69093)

Rafael Audibertcd4481ffc46e
diff --git a/.agents/toolbar-migration.md b/.agents/toolbar-migration.md
index 83a1c09906ee..7496a9f542af 100644
--- a/.agents/toolbar-migration.md
+++ b/.agents/toolbar-migration.md
@@ -4,10 +4,10 @@ This file is the committed source of truth for the toolbar bundle modernization
## Status
-- **Current step**: Step 2 is UNBLOCKED — `src/products.tsx` (and the whole app scene graph) is out of the toolbar bundle graph as of the shim-leak fix below. Next: unstash `toolbar-step2-loader-esm-wip` (expect conflicts in `toolbar-config.mjs` — the working tree's `createToolbarModulePlugin` gained relative/`~/` shim matching that MUST be preserved) and apply the known adjustments in the Step 2 section.
+- **Current step**: Step 2 (loader + ESM splitting) is implemented and in review on `rafa/toolbar-migration-4-loader-esm-splitting` — see its section for the remaining parity gates before ready-for-review. Next after that: Step 4 (`~/types` hygiene) and the remaining Step 5/6 edges.
- **Last updated**: 2026-07-07
-- **PRs**: Step 1 — `rafa/toolbar-migration-1-graph-guard` (#69045); Step 3 — `rafa/toolbar-migration-2-products-urls-split` (#69071, stacked on Step 1); chain cuts + shim-leak fix — `rafa/toolbar-migration-3-shim-leak-and-chain-cuts` (stacked on #69071)
-- **Reorder note (resolved)**: a trial Step 2 build emitted **487 dead chunks** — with `products.tsx` reachable, every product scene's dynamic import becomes a real chunk in `dist/toolbar/`. The gate was: flip the format only once `products.tsx` leaves the graph. That's now done via two moves in this PR. First, the remaining chains all funneled through one root cause: the kea shims only matched exact alias strings (`scenes/teamLogic`), so relative imports (`dataThemeLogic` → `./teamLogic`) and `~/`-prefixed imports pulled the REAL logics and their whole app graph — fixed with relative + `~/` matching in `createToolbarModulePlugin`, disconnecting `products.tsx`, `scenes.ts`, `teamLogic`, `PersonDisplay`, and `experimentsLogic` in one move. Second, `scenes/urls` itself (imported by lib components shared with the app) is shimmed to the toolbar's parity-tested `~/toolbar/urls` duplicate from Step 3, taking the last products-manifest path out. Bundle graph 8448 → ~1000 files (99 → ~13.5 MiB source), shipped `dist/toolbar.js` 9.95 MB → ~4 MB (was just under the 10 MB CloudFront cliff). Graph budget ratcheted 110 MB → 18 MB.
+- **PRs**: Step 1 — `rafa/toolbar-migration-1-graph-guard` (#69045); Step 3 — `rafa/toolbar-migration-2-products-urls-split` (#69071, stacked on Step 1); chain cuts + shim-leak fix — `rafa/toolbar-migration-3-shim-leak-and-chain-cuts` (#69088, stacked on #69071); Step 2 — `rafa/toolbar-migration-4-loader-esm-splitting` (stacked on #69088)
+- **Reorder note (resolved)**: a trial Step 2 build emitted **487 dead chunks** — with `products.tsx` reachable, every product scene's dynamic import becomes a real chunk in `dist/toolbar/`. The gate was: flip the format only once `products.tsx` leaves the graph. That's now done via two moves in the third PR. First, the remaining chains all funneled through one root cause: the kea shims only matched exact alias strings (`scenes/teamLogic`), so relative imports (`dataThemeLogic` → `./teamLogic`) and `~/`-prefixed imports pulled the REAL logics and their whole app graph — fixed with relative + `~/` matching in `createToolbarModulePlugin`, disconnecting `products.tsx`, `scenes.ts`, `teamLogic`, `PersonDisplay`, and `experimentsLogic` in one move. Second, `scenes/urls` itself (imported by lib components shared with the app) is shimmed to the toolbar's parity-tested `~/toolbar/urls` duplicate from Step 3, taking the last products-manifest path out. Bundle graph 8448 → ~1000 files (99 → ~13.5 MiB source), shipped `dist/toolbar.js` 9.95 MB → ~4 MB (was just under the 10 MB CloudFront cliff). Graph budget ratcheted 110 MB → 18 MB.
- **posthog-js prerequisite**: DONE — release pipeline is layout-agnostic and verified as a no-op against today's build. Nothing blocks any step. See Step 0 for the constraints it imposes on the build here.
## Why
@@ -57,23 +57,24 @@ Work one step per PR (Graphite stack via `gt`; keep the stack shallow — merge
Done when: CI runs the graph check green with the baseline allowlist.
-### Step 2 — loader + ESM code splitting (GATED: land after `src/products.tsx` leaves the toolbar graph, see reorder note in Status)
+### Step 2 — loader + ESM code splitting (in review: `rafa/toolbar-migration-4-loader-esm-splitting`)
-Implementation is done and stashed as `toolbar-step2-loader-esm-wip` (loader.ts, two-config build, esbuilder `esbuildBuild` re-export, globals.d.ts). Known adjustments still needed when unstashing: esbuild 0.25 DOES emit per-chunk CSS files — drop the single-CSS assertion in `finalizeToolbarBuild` and instead require the entry CSS (it holds all statically-reachable styles; chunk CSS is dead weight for lazy scenes, but toolbar features must keep their styles statically imported — recheck at Step 7); surface `finalizeToolbarBuild` errors (buildInParallel's catch swallows them silently).
+Landed layout: `dist/toolbar.js` (1.2KB classic loader) + `dist/toolbar/` (ESM entry `toolbar-app-<hash>.js`, hashless fallback `toolbar-app.js`, `chunk-*-<hash>.js`, per-chunk CSS, `toolbar-app.css` hashless entry CSS loaded into the shadow root, `assets/` fonts) + `dist/toolbar.css` (transition-window copy for stale-cached single-file toolbar.js only).
-Target layout: `dist/toolbar.js` (~1-2KB classic loader) + `dist/toolbar.css` (single file, esbuild doesn't split CSS) + `dist/toolbar/toolbar-app-<hash>.js` + `dist/toolbar/toolbar-app.js` (hashless fallback) + `dist/toolbar/chunk-*-<hash>.js`.
+- [x] `frontend/toolbar-config.mjs`: `getToolbarAppBuildConfig` (ESM, `splitting: true`, outdir `dist/toolbar`, per-file `var define = undefined;` banner) + `finalizeToolbarBuild` (hashless copies, CSS promotion, loader build with `__POSTHOG_TOOLBAR_APP_ENTRY__` baked in), wired into `frontend/build.mjs` and `frontend/bin/build-toolbar.mjs` (dev watch mode verified)
+- [x] **`publicPath` must stay unset on the app build** (explicit `publicPath: undefined` to override commonConfig's `/static`): esbuild bakes publicPath into chunk import specifiers as absolute URLs, which breaks serving the same artifacts from any region/self-hosted/CDN prefix. Chunk imports are relative; svgs inline as data URLs (a relative specifier string would resolve against the customer page URL); font url()s in the CSS are relative and resolve because the CSS is fetched from inside `dist/toolbar/` (`ToolbarApp.tsx` now loads `toolbar/toolbar-app.css`). Bonus: retires the hardcoded `us.posthog.com` asset URLs (EU used to load fonts from US)
+- [x] `frontend/src/toolbar/loader.ts`: classic-script contract kept (`ph_load_toolbar`/`ph_load_editor`/controller stub synchronously); import with retry/backoff; hashless `toolbar-app.js?t={5-min bucket}` fallback; degrade to no-toolbar with console.warn
+- [x] `frontend/src/toolbar/index.tsx`: `export loadToolbar` + controller; window assigns kept for back-compat
+- [x] `check-toolbar-size.mjs` rewrite: per-file 10MB CloudFront limit across all outputs, eager-set budget 3.3MB (measured 2.97MB), loader <20KB (measured 1,153 bytes). Shared metafile helpers in `bin/toolbar-metafile.mjs`
+- [x] `check-toolbar-csp-eval.mjs` rewrite: scoped counts — loader 0, eager closure 1 (toolbarLogic probe), total 5 (4 pixi in lazy hedgehog chunks)
+- [x] Per-chunk CSS accepted (esbuild 0.25 emits it): only the entry CSS is loaded into the shadow root, so toolbar features must keep styles statically imported — verified all chunk-CSS inputs also land in the entry CSS; recheck at Step 7
+- [x] `buildInParallel` now logs callback errors before exiting (previously swallowed silently)
+- [x] Playwright smoke test (throwaway, not committed): static server over dist/ + strict CSP (`script-src 'self'`, no unsafe-eval) + classic-script injection exactly like posthog-js + `ph_load_toolbar` call → entry + 6 eager chunks fetched relative to the loader origin, shadow root mounts, controller stub delegates (`isLoaded` flips true), zero page errors
+- [x] Real-SDK smoke test (throwaway): published posthog-js (1.398.2 from node_modules, untouched) drives the whole flow — parses `#__posthog` authorize state, injects `/static/toolbar.js?v=&t=`, loader import()s the split app, shadow root mounts, controller live, zero page errors
+- [x] Local-stack click-through (Playwright driving `hogli up` at localhost:8010, throwaway script): real workspace via `/api/setup_test/`, authorized URL added, `redirect_to_site` → host page → toolbar mounts unauthenticated → full OAuth authorize flow (Authenticate → confirm modal → OAuth grant → redirect back) → `isAuthenticated: true` → all six feature menus open with real seeded data (heatmaps, actions, flags, event debugger, web vitals, experiments) → clicking Hedgehog mode fetches 10 pixi/hedgehog chunks on demand → styled bar renders from shadow-root CSS. Note: `redirect_to_site` no longer issues a `temporaryToken` — toolbar auth is OAuth now, so the unauthenticated first mount is expected behavior, not a regression
+- [ ] `Toolbar.stories.tsx` green in CI (runs on the PR)
-- [ ] `frontend/toolbar-config.mjs` returns two configs, built sequentially in `frontend/build.mjs` + `frontend/bin/build-toolbar.mjs`:
- - Toolbar App: `entryPoints: { 'toolbar-app': 'src/toolbar/index.tsx' }`, `format: 'esm'`, `splitting: true`, `outdir: dist/toolbar`, `chunkNames: 'chunk-[name]-[hash]'`, `banner: { js: 'var define = undefined;' }` (applies per output file — AMD guard on every chunk), keep `__POSTHOG_TOOLBAR_PUBLIC_PATH__` define + `createToolbarModulePlugin`, `writeMetaFile: true`. Post-build: `createHashlessEntrypoints` for `toolbar-app.js`; copy entry CSS to `dist/toolbar.css`
- - Toolbar loader: `format: 'iife'`, `outfile: dist/toolbar.js`, define `__POSTHOG_TOOLBAR_APP_ENTRY__` = hashed entry basename from the app build's metafile. Verify esbuild leaves runtime-dynamic `import(url)` untouched in IIFE output
-- [ ] New `frontend/src/toolbar/loader.ts`: capture `document.currentScript.src` as base; synchronously define `ph_load_toolbar`/`ph_load_editor`/forwarding `posthogToolbarController` stub; on first call `import()` the entry with retry/backoff (copy the pattern from `frontend/src/lib/utils/retryImport.ts` — do NOT import app code); on failure fall back once to hashless `toolbar/toolbar-app.js?t={5-min bucket}`, then degrade to no-toolbar with `console.warn`
-- [ ] `frontend/src/toolbar/index.tsx`: `export async function loadToolbar(...)` + export controller (keep window assigns for back-compat); drop the IIFE `globalName`/banner-footer wrapper (`__posthogToolbarModule` is referenced by nothing)
-- [ ] Same PR (or CI reds) — `frontend/bin/check-toolbar-size.mjs`: per-file 10MB gzip limit across all toolbar outputs; **eager-set budget** (entry + transitive `kind: 'import-statement'` closure from the metafile, same traversal as `writePreloadManifest` in `build.mjs`; start ~10% above baseline); loader < ~20KB
-- [ ] Same PR — `frontend/bin/check-toolbar-csp-eval.mjs`: glob all toolbar JS outputs; assert loader = 0 `new Function`, eager closure = 1 (the `toolbarLogic.ts` CSP probe), total = 5 (4 pixi move into the hedgehog chunk)
-- [ ] Assert exactly one CSS output in the metafile
-- [ ] Parity gates: toolbar end-to-end on local app via `hogli start` (authorize flow, tabs, hedgehog chunk loads on demand, CSS in shadow root); Playwright page with strict CSP (`'nonce-…' 'strict-dynamic'`, and separately host-allowlist) + posthog-js loading `dist/toolbar.js` → shadow root mounts; pin an OLD posthog-js version against the new dist to prove the contract; `Toolbar.stories.tsx` green
-
-Done when: ~30% of the bundle is deferred with no source changes and all guards are green. Known-unsupported: exact-path CSP allowlists (`script-src .../toolbar.js`) — document in the PR.
+Result: 1.06MB (26%) of app JS deferred with zero source changes; every file far under the 10MB cliff (largest 1.77MB). Known-unsupported: exact-path CSP allowlists (`script-src .../toolbar.js`) — chunks need the directory allowed.
### Step 3 — toolbar-owned `urls` duplicate (landed before Step 2, see reorder note)
diff --git a/common/esbuilder/utils.mjs b/common/esbuilder/utils.mjs
index 3142fbce558e..ae02b05a214b 100644
--- a/common/esbuilder/utils.mjs
+++ b/common/esbuilder/utils.mjs
@@ -16,6 +16,12 @@ import postcss from 'postcss'
import postcssPresetEnv from 'postcss-preset-env'
import ts from 'typescript'
+// 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
+// wouldn't let them import 'esbuild' themselves.
+export { build as esbuildBuild } from 'esbuild'
+
const defaultHost = process.argv.includes('--host') && process.argv.includes('0.0.0.0') ? '0.0.0.0' : 'localhost'
const defaultPort = 8234
@@ -40,12 +46,14 @@ export function copySnappyWASMFile(absWorkingDir) {
}
}
-export function copyRRWebWorkerFiles(absWorkingDir) {
- // Mirror rrweb's image-bitmap worker sourcemap (shipped from posthog-js) into our dist/
- // so the sourceMappingURL baked into our bundled rrweb resolves under collectstatic.
+export function copyRRWebWorkerFiles(absWorkingDir, distSubdir = 'dist') {
+ // Mirror rrweb's image-bitmap worker sourcemap (shipped from posthog-js) into the output
+ // dir so the sourceMappingURL baked into our bundled rrweb resolves under collectstatic.
+ // ManifestStaticFilesStorage resolves the reference relative to the referencing file's
+ // directory, so every outdir that bundles rrweb needs its own copy.
try {
const rrwebSourceDir = path.resolve(absWorkingDir, 'node_modules/posthog-js/dist')
- const distDir = path.resolve(absWorkingDir, 'dist')
+ const distDir = path.resolve(absWorkingDir, distSubdir)
const files = fse.readdirSync(rrwebSourceDir)
const mapFiles = files.filter((f) => f.startsWith('image-bitmap-data-url-worker-') && f.endsWith('.js.map'))
mapFiles.forEach((file) => {
@@ -377,7 +385,10 @@ export async function buildInParallel(configs, { onBuildStart, onBuildComplete }
})
)
)
- } catch {
+ } catch (error) {
+ // esbuild already prints its own compile errors, but onBuildStart/onBuildComplete
+ // failures (e.g. finalizeToolbarBuild) would otherwise die silently here.
+ console.error(error)
if (!isDev) {
process.exit(1)
}
diff --git a/frontend/bin/build-toolbar.mjs b/frontend/bin/build-toolbar.mjs
index 91d00059f93b..5e939bdb83e0 100644
--- a/frontend/bin/build-toolbar.mjs
+++ b/frontend/bin/build-toolbar.mjs
@@ -12,7 +12,7 @@ import { fileURLToPath } from 'url'
import { buildInParallel } from '@posthog/esbuilder'
-import { getToolbarBuildConfig } from '../toolbar-config.mjs'
+import { finalizeToolbarBuild, getToolbarAppBuildConfig } from '../toolbar-config.mjs'
const __dirname = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
@@ -24,9 +24,13 @@ const common = {
await buildInParallel(
[
{
- ...getToolbarBuildConfig(__dirname),
+ ...getToolbarAppBuildConfig(__dirname),
...common,
},
],
- {}
+ {
+ async onBuildComplete(config, buildResponse) {
+ await finalizeToolbarBuild(__dirname, buildResponse)
+ },
+ }
)
diff --git a/frontend/bin/check-toolbar-csp-eval.mjs b/frontend/bin/check-toolbar-csp-eval.mjs
index cb710d5cab69..b7cc046843fb 100644
--- a/frontend/bin/check-toolbar-csp-eval.mjs
+++ b/frontend/bin/check-toolbar-csp-eval.mjs
@@ -3,7 +3,10 @@ import traverse from '@babel/traverse'
import fs from 'fs'
import path from 'path'
-// Parse dist/toolbar.js and check for anything that might trigger CSP script-src violations
+import { eagerOutputs, jsOutputs, readToolbarMetafile } from './toolbar-metafile.mjs'
+
+// Parse every shipped toolbar JS file (the dist/toolbar.js loader + the ESM app outputs in
+// dist/toolbar/) and check for anything that might trigger CSP script-src violations.
// The threat model here is:
// * We're not trying to protect against an attacker hiding an eval like window["ev" + "al"]("...").
@@ -15,21 +18,21 @@ import path from 'path'
const UNSAFE_TIMERS = new Set(['setTimeout', 'setInterval', 'setImmediate', 'execScript'])
const FUNCTION_CTORS = new Set(['Function', 'AsyncFunction', 'GeneratorFunction', 'AsyncGeneratorFunction'])
-// Known violations from vendored dependencies that we can't avoid.
-// Each entry records the expected count and which dependency causes it.
-// If the count changes (e.g. after a dependency version bump), update the count here.
+// Known violations from vendored dependencies that we can't avoid, scoped to where they're
+// allowed to live. If a count changes (e.g. after a dependency version bump), update it here.
+// The loader is held to zero: it runs on every customer page that enables the toolbar, before
+// the user interacts at all, so it must never show up in a CSP report.
const ALLOWED_VIOLATIONS = {
'new Function()': {
- count: 5,
- source: 'pixi.js via @posthog/hedgehog-mode (4) + toolbarLogic CSP probe (1)',
+ loader: 0,
+ eager: 1, // toolbarLogic's deliberate CSP support probe
+ total: 5, // + pixi.js via @posthog/hedgehog-mode (4), in the lazy hedgehog chunks
+ source: 'toolbarLogic CSP probe (1, eager) + pixi.js via @posthog/hedgehog-mode (4, lazy)',
},
}
-function main() {
- const filePath = 'dist/toolbar.js'
- const absPath = path.resolve(process.cwd(), filePath)
- const source = fs.readFileSync(absPath, 'utf-8')
-
+function scanFile(filePath) {
+ const source = fs.readFileSync(path.resolve(process.cwd(), filePath), 'utf-8')
const ast = parser.parse(source, {
sourceType: 'unambiguous',
})
@@ -91,37 +94,65 @@ function main() {
},
})
- // Group violations by type
- const countsByType = {}
- for (const { type } of evals) {
- countsByType[type] = (countsByType[type] || 0) + 1
+ return evals.map((v) => ({ ...v, file: filePath }))
+}
+
+function countByType(violations) {
+ const counts = {}
+ for (const { type } of violations) {
+ counts[type] = (counts[type] || 0) + 1
}
+ return counts
+}
- let hasUnexpected = false
-
- for (const [type, count] of Object.entries(countsByType)) {
- const allowed = ALLOWED_VIOLATIONS[type]
- if (allowed && count === allowed.count) {
- // All good, nothing to see here, move along
- continue
- } else if (allowed && count !== allowed.count) {
- console.error(
- `✗ ${type}: found ${count} occurrence(s), expected ${allowed.count} (${allowed.source}). Update ALLOWED_VIOLATIONS if this is intentional.`
- )
- hasUnexpected = true
- } else {
- console.error(`✗ ${type}: ${count} unexpected occurrence(s)`)
- hasUnexpected = true
+function main() {
+ const metafile = readToolbarMetafile()
+ const outputs = metafile.outputs
+
+ const loaderViolations = scanFile('dist/toolbar.js')
+ const eagerJs = [...eagerOutputs(outputs)].filter((o) => o.endsWith('.js'))
+ const appViolations = jsOutputs(outputs).flatMap((file) => scanFile(file))
+ const eagerViolations = appViolations.filter((v) => eagerJs.includes(v.file))
+
+ const scopes = [
+ { name: 'loader (dist/toolbar.js)', key: 'loader', counts: countByType(loaderViolations) },
+ { name: 'eager app closure', key: 'eager', counts: countByType(eagerViolations) },
+ {
+ name: 'all app outputs + loader',
+ key: 'total',
+ counts: countByType([...loaderViolations, ...appViolations]),
+ },
+ ]
+
+ const mismatchedTypes = new Set()
+
+ for (const { name, key, counts } of scopes) {
+ const typesToCheck = new Set([...Object.keys(counts), ...Object.keys(ALLOWED_VIOLATIONS)])
+ for (const type of typesToCheck) {
+ const found = counts[type] || 0
+ const expected = ALLOWED_VIOLATIONS[type]?.[key] ?? 0
+ if (found !== expected) {
+ const source = ALLOWED_VIOLATIONS[type]?.source
+ console.error(
+ `✗ ${type} in ${name}: found ${found}, expected ${expected}${source ? ` (${source})` : ''}. ` +
+ 'Update ALLOWED_VIOLATIONS if this is intentional.'
+ )
+ mismatchedTypes.add(type)
+ }
}
}
- if (hasUnexpected) {
- evals.forEach(({ type, start: { line, column } }) => {
- const allowed = ALLOWED_VIOLATIONS[type]
- if (!allowed || countsByType[type] !== allowed.count) {
- console.error(` ${type}: line ${line}:${column}`)
+ if (mismatchedTypes.size > 0) {
+ // Only dump the violation types whose count is off — the allowed ones would drown the
+ // offender. Every instance of a mismatched type prints (counts can't tell which
+ // occurrence is new), tagged by scope since an expected total can still fail a scope.
+ const eagerSet = new Set(eagerJs)
+ for (const { type, file, start } of [...loaderViolations, ...appViolations]) {
+ if (mismatchedTypes.has(type)) {
+ const scope = file === 'dist/toolbar.js' ? 'loader' : eagerSet.has(file) ? 'eager' : 'deferred'
+ console.error(` ${type} [${scope}]: ${file} line ${start.line}:${start.column}`)
}
- })
+ }
process.exit(1)
}
}
diff --git a/frontend/bin/check-toolbar-size.mjs b/frontend/bin/check-toolbar-size.mjs
index 0ae61e44ef5f..0e35e807820a 100644
--- a/frontend/bin/check-toolbar-size.mjs
+++ b/frontend/bin/check-toolbar-size.mjs
@@ -1,46 +1,96 @@
import fs from 'fs'
import path from 'path'
-// Fail the build if dist/toolbar.js grows past the size CloudFront will still gzip.
-//
-// CloudFront only compresses responses whose body is between 1,000 and 10,000,000 bytes
-// (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html).
-// Once the toolbar bundle crosses 10,000,000 bytes it is served uncompressed, so a bundle that
-// tips just over the line jumps from ~1.7 MB on the wire to its full ~10 MB. That cliff is
-// invisible in a size-delta comment, so guard it with a hard failure instead.
+import { eagerOutputs, jsOutputs, readToolbarMetafile } from './toolbar-metafile.mjs'
+
+// Size guards for the split toolbar build (dist/toolbar.js loader + dist/toolbar/ ESM app).
//
-// When this fails, shrink the bundle rather than raising the limit — see the deny-list in
-// frontend/toolbar-config.mjs for the mechanism (heavy libraries the toolbar never renders can
-// be cut at resolve time, since the IIFE bundle has no code-splitting to defer them).
-const MAX_BYTES = 10_000_000
+// 1. Per-file CloudFront gzip ceiling. CloudFront only compresses responses whose body is
+// between 1,000 and 10,000,000 bytes
+// (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html).
+// A file that tips over the line is served uncompressed — a ~6x jump on the wire that no
+// size-delta comment makes visible. Code splitting means no single file should ever get
+// close again; if one does, split it rather than raising the limit.
+const MAX_FILE_BYTES = 10_000_000
+
+// 2. Eager-set budget: the entry plus everything statically imported from it — the bytes every
+// toolbar load fetches before any feature runs. Ratchet policy: when a cut lands, lower the
+// budget to lock it in; raise it only as a conscious, reviewed decision in the PR that needs it.
+// 2026-07-07: 2,967,721 bytes measured when splitting landed; ~10% headroom.
+const MAX_EAGER_BYTES = 3_300_000
+
+// 3. The loader is injected on every customer page that enables the toolbar and must stay tiny.
+// 2026-07-07: 1,153 bytes minified.
+const MAX_LOADER_BYTES = 20_000
function humanBytes(bytes) {
return `${(bytes / 1_000_000).toFixed(2)} MB (${bytes.toLocaleString()} bytes)`
}
-function main() {
- const filePath = 'dist/toolbar.js'
- const absPath = path.resolve(process.cwd(), filePath)
+let failed = false
- let bytes
+function fail(message) {
+ console.error(`✗ ${message}`)
+ failed = true
+}
+
+function statBytes(filePath) {
try {
- bytes = fs.statSync(absPath).size
+ return fs.statSync(path.resolve(process.cwd(), filePath)).size
} catch {
- console.error(`✗ Could not read ${filePath} — build the toolbar before running this check.`)
- process.exit(1)
+ fail(`Could not read ${filePath} — build the toolbar before running this check.`)
+ return null
}
+}
- if (bytes > MAX_BYTES) {
- console.error(
- `✗ Toolbar bundle is ${humanBytes(bytes)}, over the ${humanBytes(MAX_BYTES)} CloudFront gzip limit.`
+function main() {
+ const metafile = readToolbarMetafile()
+ const outputs = metafile.outputs
+
+ // Loader: not in the metafile (separate build), stat it directly.
+ const loaderBytes = statBytes('dist/toolbar.js')
+ if (loaderBytes !== null && loaderBytes > MAX_LOADER_BYTES) {
+ fail(
+ `Loader dist/toolbar.js is ${humanBytes(loaderBytes)}, over its ${humanBytes(MAX_LOADER_BYTES)} budget. ` +
+ 'It ships on every toolbar load before anything runs — app code belongs in the ESM entry.'
)
- console.error(
- ' CloudFront serves files this large uncompressed. Shrink the bundle (see frontend/toolbar-config.mjs).'
+ }
+
+ // Per-file ceiling across every shipped artifact (app outputs + loader + copied CSS).
+ const shippedFiles = Object.keys(outputs).filter((o) => !o.endsWith('.map'))
+ for (const file of [...shippedFiles, 'dist/toolbar.css']) {
+ const bytes = outputs[file]?.bytes ?? statBytes(file)
+ if (bytes !== null && bytes > MAX_FILE_BYTES) {
+ fail(
+ `${file} is ${humanBytes(bytes)}, over the ${humanBytes(MAX_FILE_BYTES)} CloudFront gzip limit — ` +
+ 'CloudFront serves files this large uncompressed. Split it further.'
+ )
+ }
+ }
+
+ // Eager-set budget.
+ const eagerJs = [...eagerOutputs(outputs)].filter((o) => o.endsWith('.js'))
+ const eagerBytes = eagerJs.reduce((sum, o) => sum + outputs[o].bytes, 0)
+ const lazyJs = jsOutputs(outputs).filter((o) => !eagerJs.includes(o))
+ const lazyBytes = lazyJs.reduce((sum, o) => sum + outputs[o].bytes, 0)
+ if (eagerBytes > MAX_EAGER_BYTES) {
+ fail(
+ `Eager toolbar JS is ${humanBytes(eagerBytes)} across ${eagerJs.length} files, over the ` +
+ `${humanBytes(MAX_EAGER_BYTES)} budget. Something newly reachable through static imports — ` +
+ 'lazy-load it (import()) or cut the import edge. See .agents/toolbar-migration.md.'
)
+ }
+
+ if (failed) {
process.exit(1)
}
- console.info(`✓ Toolbar bundle is ${humanBytes(bytes)}, within the ${humanBytes(MAX_BYTES)} CloudFront gzip limit.`)
+ console.info(
+ `✓ Toolbar sizes OK: loader ${humanBytes(loaderBytes)} (max ${humanBytes(MAX_LOADER_BYTES)}), ` +
+ `eager JS ${humanBytes(eagerBytes)} in ${eagerJs.length} files (budget ${humanBytes(MAX_EAGER_BYTES)}), ` +
+ `deferred JS ${humanBytes(lazyBytes)} in ${lazyJs.length} files, ` +
+ `every file under the ${humanBytes(MAX_FILE_BYTES)} CloudFront gzip limit.`
+ )
}
main()
diff --git a/frontend/bin/toolbar-metafile.mjs b/frontend/bin/toolbar-metafile.mjs
new file mode 100644
index 000000000000..627cded43ede
--- /dev/null
+++ b/frontend/bin/toolbar-metafile.mjs
@@ -0,0 +1,55 @@
+import fs from 'fs'
+import path from 'path'
+
+// Shared helpers for the toolbar build checks (check-toolbar-size.mjs,
+// check-toolbar-csp-eval.mjs). The toolbar app build writes its metafile to
+// toolbar-esbuild-meta.json (config name 'Toolbar'); the loader (dist/toolbar.js)
+// is built separately and is not part of the metafile.
+
+export const TOOLBAR_ENTRY_POINT = 'src/toolbar/index.tsx'
+
+export function readToolbarMetafile() {
+ const metafilePath = path.resolve(process.cwd(), 'toolbar-esbuild-meta.json')
+ try {
+ return JSON.parse(fs.readFileSync(metafilePath, 'utf-8'))
+ } catch {
+ console.error('✗ Could not read toolbar-esbuild-meta.json — build the toolbar before running this check.')
+ process.exit(1)
+ }
+}
+
+export function findEntryOutput(outputs) {
+ const entry = Object.keys(outputs).find((o) => outputs[o].entryPoint === TOOLBAR_ENTRY_POINT)
+ if (!entry) {
+ console.error(`✗ No output with entryPoint ${TOOLBAR_ENTRY_POINT} in the toolbar metafile.`)
+ process.exit(1)
+ }
+ return entry
+}
+
+/**
+ * The eager set: the entry output plus everything reachable from it through static
+ * `import` statements — i.e. the files fetched before the toolbar can run at all.
+ * Dynamic-import edges are the split points; their targets load on demand.
+ */
+export function eagerOutputs(outputs) {
+ const entry = findEntryOutput(outputs)
+ const eager = new Set()
+ const walk = (output) => {
+ if (eager.has(output)) {
+ return
+ }
+ eager.add(output)
+ for (const imp of outputs[output].imports || []) {
+ if (!imp.external && imp.kind === 'import-statement') {
+ walk(imp.path)
+ }
+ }
+ }
+ walk(entry)
+ return eager
+}
+
+export function jsOutputs(outputs) {
+ return Object.keys(outputs).filter((o) => o.endsWith('.js'))
+}
diff --git a/frontend/build.mjs b/frontend/build.mjs
index ade89485f024..1ac2390eafc4 100755
--- a/frontend/build.mjs
+++ b/frontend/build.mjs
@@ -15,7 +15,7 @@ import {
startDevServer,
} from '@posthog/esbuilder'
-import { getToolbarBuildConfig } from './toolbar-config.mjs'
+import { finalizeToolbarBuild, getToolbarAppBuildConfig } from './toolbar-config.mjs'
export const __dirname = path.dirname(fileURLToPath(import.meta.url))
@@ -104,7 +104,7 @@ await buildInParallel(
...common,
},
{
- ...getToolbarBuildConfig(__dirname),
+ ...getToolbarAppBuildConfig(__dirname),
...common,
},
],
@@ -143,6 +143,10 @@ await buildInParallel(
writeRenderQueryHtml(chunks, entrypoints)
}
+ if (config.name === 'Toolbar') {
+ await finalizeToolbarBuild(__dirname, buildResponse)
+ }
+
createHashlessEntrypoints(__dirname, entrypoints)
},
}
diff --git a/frontend/src/globals.d.ts b/frontend/src/globals.d.ts
index c518d9f15664..b54c652fdbb0 100644
--- a/frontend/src/globals.d.ts
+++ b/frontend/src/globals.d.ts
@@ -21,6 +21,12 @@ declare global {
// sibling files (currently just toolbar.css) from the same versioned URL.
const __POSTHOG_TOOLBAR_PUBLIC_PATH__: string
+ // Build-time constant injected into the toolbar loader (frontend/src/toolbar/loader.ts):
+ // the basename of the toolbar app's ESM entry inside dist/toolbar/ — hashed in prod
+ // builds (e.g. `toolbar-app-ABC123.js`), plain `toolbar-app.js` in dev. See
+ // finalizeToolbarBuild in frontend/toolbar-config.mjs.
+ const __POSTHOG_TOOLBAR_APP_ENTRY__: string
+
interface Window {
JS_URL?: string
JS_POSTHOG_API_KEY?: string
diff --git a/frontend/src/toolbar/ToolbarApp.tsx b/frontend/src/toolbar/ToolbarApp.tsx
index 2a7977f8c0a9..8a57b3601e2d 100644
--- a/frontend/src/toolbar/ToolbarApp.tsx
+++ b/frontend/src/toolbar/ToolbarApp.tsx
@@ -39,21 +39,26 @@ export function ToolbarApp(props: ToolbarProps = {}): JSX.Element {
styleLink.rel = 'stylesheet'
styleLink.type = 'text/css'
+ // The stylesheet is the app entry's CSS, emitted as a hashless copy inside
+ // dist/toolbar/ next to the JS. It must be fetched from there — its url()
+ // references (fonts) are relative, so they only resolve alongside the
+ // toolbar/assets/ directory it was built with.
+ //
// When __POSTHOG_TOOLBAR_PUBLIC_PATH__ is baked in at build
// time (posthog-js versioned bundle), load the CSS from the
// same versioned URL as the JS bundle. The version is the
// cache key, so no cache-busting query param is needed.
//
// Otherwise (i.e. posthog/posthog's own deploys), fall back to
- // serving toolbar.css from the API host alongside toolbar.js,
- // with a 5-minute cache-buster on the unversioned URL.
+ // serving it from the API host alongside toolbar.js, with a
+ // 5-minute cache-buster on the unversioned URL.
if (__POSTHOG_TOOLBAR_PUBLIC_PATH__) {
- styleLink.href = `${__POSTHOG_TOOLBAR_PUBLIC_PATH__}toolbar.css`
+ styleLink.href = `${__POSTHOG_TOOLBAR_PUBLIC_PATH__}toolbar/toolbar-app.css`
} else {
const fiveMinutesInMillis = 5 * 60 * 1000
const timestampToNearestFiveMinutes =
Math.floor(Date.now() / fiveMinutesInMillis) * fiveMinutesInMillis
- styleLink.href = `${apiHost}/static/toolbar.css?t=${timestampToNearestFiveMinutes}`
+ styleLink.href = `${apiHost}/static/toolbar/toolbar-app.css?t=${timestampToNearestFiveMinutes}`
}
styleLink.onload = () => setDidLoadStyles(true)
diff --git a/frontend/src/toolbar/index.tsx b/frontend/src/toolbar/index.tsx
index a67210712340..f30af720f89f 100644
--- a/frontend/src/toolbar/index.tsx
+++ b/frontend/src/toolbar/index.tsx
@@ -82,9 +82,14 @@ const initKeaInToolbar = ({ routerHistory, routerLocation, beforePlugins }: Init
const win = window as any
win['posthogToolbarController'] = posthogToolbarController
-win['ph_load_toolbar'] = async function (toolbarParams: ToolbarParams, posthog?: PostHog) {
- // Store the start time so we can measure total load duration in initInstrumentation
- ;(window as any).__posthog_toolbar_load_start = performance.now()
+// Re-exported for the loader script (loader.ts), which forwards its controller stub here.
+export { posthogToolbarController }
+
+export async function loadToolbar(toolbarParams: ToolbarParams, posthog?: PostHog): Promise<void> {
+ // Store the start time so we can measure total load duration in initInstrumentation.
+ // The loader script already stamps this before fetching the app module, so the measured
+ // duration includes the chunk fetch — keep the earliest timestamp.
+ ;(window as any).__posthog_toolbar_load_start ??= performance.now()
// If posthog and toolbarFlagsKey is present, fetch the feature flags from the backend
if (posthog && toolbarParams.toolbarFlagsKey) {
@@ -154,5 +159,8 @@ win['ph_load_toolbar'] = async function (toolbarParams: ToolbarParams, posthog?:
setToolbarRefs(root, container)
}
+// Kept for direct consumers and back-compat: once this module evaluates, calls skip the loader.
+win['ph_load_toolbar'] = loadToolbar
+
/** @deprecated, use "ph_load_toolbar" instead */
-win['ph_load_editor'] = win['ph_load_toolbar']
+win['ph_load_editor'] = loadToolbar
diff --git a/frontend/src/toolbar/loader.ts b/frontend/src/toolbar/loader.ts
new file mode 100644
index 000000000000..f174dfff183c
--- /dev/null
+++ b/frontend/src/toolbar/loader.ts
@@ -0,0 +1,124 @@
+import type { PostHog } from 'posthog-js'
+
+import type { ToolbarParams } from '~/types'
+
+// The toolbar loader: a tiny classic script served as /static/toolbar.js. posthog-js (every
+// version, forever) injects it with a plain <script> tag and calls window.ph_load_toolbar on
+// the script's load event — that contract must never change. This file defines those globals
+// synchronously, then dynamic-import()s the real toolbar app (an ESM entry with code-split
+// chunks under ./toolbar/) the first time the toolbar actually loads.
+//
+// Rules for this file:
+// - No value imports (type imports are fine — they're erased). Anything bundled here ships on
+// every toolbar load before a single feature runs; app code belongs in the ESM entry.
+// check-toolbar-size.mjs caps this file's size to keep that honest.
+// - No eval / new Function — customer pages run strict CSPs; check-toolbar-csp-eval.mjs
+// asserts zero violations for this file.
+// - Resolve chunks relative to the script's own URL, never an absolute host: the same
+// artifacts are served from Django /static/ on any region or self-hosted instance, and from
+// the versioned, major-alias and compatibility prefixes on the posthog-js CDN.
+
+type ToolbarModule = typeof import('~/toolbar/index')
+
+// document.currentScript is only set during the initial synchronous evaluation, so capture it
+// at module scope. It is null when the loader is evaluated as a module (tests) — then the
+// build-time public path (set for posthog-js versioned CDN bundles) is the fallback.
+const scriptSrc = (document.currentScript as HTMLScriptElement | null)?.src
+
+function resolveAppUrl(fileName: string): string {
+ const base = scriptSrc || __POSTHOG_TOOLBAR_PUBLIC_PATH__
+ if (!base) {
+ throw new Error('PostHog toolbar loader could not determine its own URL')
+ }
+ return new URL(`toolbar/${fileName}`, base).href
+}
+
+async function importWithRetry(url: string, retries: number, delayMs: number): Promise<ToolbarModule> {
+ try {
+ return await import(url)
+ } catch (error) {
+ if (retries <= 0) {
+ throw error
+ }
+ await new Promise((resolve) => setTimeout(resolve, delayMs))
+ return importWithRetry(url, retries - 1, delayMs * 2)
+ }
+}
+
+let appPromise: Promise<ToolbarModule> | null = null
+
+function loadApp(): Promise<ToolbarModule> {
+ if (!appPromise) {
+ appPromise = importWithRetry(resolveAppUrl(__POSTHOG_TOOLBAR_APP_ENTRY__), 2, 300)
+ .catch(() => {
+ // Version-skew fallback: a cached loader can reference a hashed entry that no
+ // longer exists on the origin after a deploy. The hashless copy always points at
+ // the latest build, whose chunk references are self-consistent. Same 5-minute
+ // cache bucket as the toolbar.css loader.
+ const fiveMinutesInMillis = 5 * 60 * 1000
+ const cacheBuster = Math.floor(Date.now() / fiveMinutesInMillis) * fiveMinutesInMillis
+ // Retried too: reaching here doesn't mean the network is healthy — the primary
+ // import may have failed on a transient error rather than a version-skew 404.
+ return importWithRetry(resolveAppUrl(`toolbar-app.js?t=${cacheBuster}`), 2, 300)
+ })
+ .then((module) => {
+ controllerDelegate = module.posthogToolbarController
+ return module
+ })
+ .catch((error) => {
+ appPromise = null // a later ph_load_toolbar call gets a fresh attempt
+ throw error
+ })
+ }
+ return appPromise
+}
+
+// The app module exposes the real window.posthogToolbarController when it evaluates, but
+// third-party code may grab the global right after the loader script loads — give those early
+// consumers a stub that starts forwarding once the app is in.
+let controllerDelegate: ToolbarModule['posthogToolbarController'] | null = null
+const controllerStub = {
+ get isLoaded(): boolean {
+ return controllerDelegate ? controllerDelegate.isLoaded : false
+ },
+ get isVisible(): boolean {
+ return controllerDelegate ? controllerDelegate.isVisible : false
+ },
+ get isAuthenticated(): boolean {
+ return controllerDelegate ? controllerDelegate.isAuthenticated : false
+ },
+ show(): void {
+ controllerDelegate?.show()
+ },
+ hide(): void {
+ controllerDelegate?.hide()
+ },
+ authenticate(): void {
+ controllerDelegate?.authenticate()
+ },
+ destroy(): void {
+ controllerDelegate?.destroy()
+ },
+}
+
+const win = window as any
+
+win['posthogToolbarController'] = win['posthogToolbarController'] || controllerStub
+
+win['ph_load_toolbar'] = async function (toolbarParams: ToolbarParams, posthog?: PostHog): Promise<void> {
+ // Start the load-duration clock before the app module and its chunks are fetched — the
+ // fetch is part of what the user waits for. loadToolbar keeps the earliest timestamp.
+ win.__posthog_toolbar_load_start = performance.now()
+ let module: ToolbarModule
+ try {
+ module = await loadApp()
+ } catch (error) {
+ // Graceful degradation is "no toolbar", never a broken host page.
+ console.warn('[PostHog Toolbar] Failed to load the toolbar bundle', error)
+ return
+ }
+ await module.loadToolbar(toolbarParams, posthog)
+}
+
+/** @deprecated, use "ph_load_toolbar" instead */
+win['ph_load_editor'] = win['ph_load_toolbar']
diff --git a/frontend/toolbar-config.mjs b/frontend/toolbar-config.mjs
index 6ed0d8933ad5..f0483b72df74 100644
--- a/frontend/toolbar-config.mjs
+++ b/frontend/toolbar-config.mjs
@@ -1,6 +1,7 @@
+import * as fs from 'fs'
import * as path from 'path'
-import { commonConfig, isDev } from '@posthog/esbuilder'
+import { commonConfig, copyRRWebWorkerFiles, createHashlessEntrypoints, esbuildBuild, isDev } from '@posthog/esbuilder'
// `TOOLBAR_PUBLIC_PATH`, when set, overrides the default `publicPath` so the
// toolbar bundle and its assets can be hosted under a versioned, content-pinned
@@ -47,10 +48,10 @@ const deniedPaths = [
]
// Heavy third-party libraries the toolbar never renders, but which leak in transitively
-// through the shared scene graph (mostly via scenes/urls.ts -> products.tsx). Because the
-// toolbar is a single IIFE with no code-splitting, even lazily `import()`-ed libraries get
-// inlined, so these must be cut at resolve time. CloudFront won't gzip files over 10 MB, so
-// keeping the bundle small is what keeps it compressible.
+// through the shared scene graph (mostly via scenes/urls.ts -> products.tsx). Code splitting
+// would defer the lazily-`import()`-ed ones rather than inline them, but until their import
+// edges are cut at the source (.agents/toolbar-migration.md), denying them at resolve time
+// keeps them out of the artifact set entirely — bin/check-toolbar-graph.mjs asserts absence.
const deniedThirdPartyPackages = [
// mermaid diagram rendering (via LemonMarkdownWithMermaid). Denying the entry cascades to
// its exclusive deps: katex, cytoscape, @mermaid-js/parser, dagre-d3-es, layout/cose-base.
@@ -154,16 +155,47 @@ function createToolbarModulePlugin(dirname) {
}
}
-export function getToolbarBuildConfig(dirname) {
+// The toolbar ships as two artifacts (see .agents/toolbar-migration.md):
+//
+// dist/toolbar.js — a tiny classic-script loader (src/toolbar/loader.ts). posthog-js
+// injects it with a plain <script> tag on customer pages and calls
+// window.ph_load_toolbar on load; the loader then import()s the app.
+// dist/toolbar/ — the real app: an ESM entry (toolbar-app-<hash>.js, hashless copy
+// alongside as a version-skew fallback) plus code-split chunks, so
+// lazily-imported features are fetched on demand instead of inlined.
+// dist/toolbar/toolbar-app.css — the app entry's stylesheet (hashless copy); ToolbarApp.tsx
+// fetches it into the shadow root. It lives inside dist/toolbar/
+// so its relative font url()s resolve against toolbar/assets/.
+// dist/toolbar.css — copy at the old URL, only consumed by stale-cached single-file
+// toolbar.js builds during the unversioned-deploy transition window.
+//
+// The loader resolves the app relative to its own script URL, and chunk imports inside the app
+// are relative too, so the same artifacts work from Django /static/ on any instance and from
+// the versioned/major-alias/compatibility prefixes on the posthog-js CDN (whose release
+// pipeline publishes dist/toolbar/ recursively when present).
+
+export function getToolbarAppBuildConfig(dirname) {
return {
+ // Named 'Toolbar' so the metafile lands at toolbar-esbuild-meta.json, which
+ // bin/check-toolbar-graph.mjs and bin/check-toolbar-size.mjs read.
name: 'Toolbar',
- globalName: '__posthogToolbarModule',
- entryPoints: ['src/toolbar/index.tsx'],
- format: 'iife',
- outfile: path.resolve(dirname, 'dist', 'toolbar.js'),
- banner: { js: 'var __posthogToolbarModule = (function () { var define = undefined;' },
- footer: { js: 'return __posthogToolbarModule })();' },
- publicPath: isDev ? '/static/' : toolbarPublicPathOverride || 'https://us.posthog.com/static/',
+ entryPoints: { 'toolbar-app': 'src/toolbar/index.tsx' },
+ format: 'esm',
+ splitting: true,
+ outdir: path.resolve(dirname, 'dist', 'toolbar'),
+ chunkNames: 'chunk-[name]-[hash]',
+ // Shadow any AMD loader on the host page (module-scoped var, applied to every output
+ // file) so bundled UMD dependencies don't try to register with e.g. RequireJS.
+ banner: { js: 'var define = undefined;' },
+ // NO publicPath (explicitly overriding commonConfig's '/static'): esbuild would bake it
+ // into the chunk import specifiers as absolute URLs, but the same artifacts are served
+ // from Django /static/ on any region or self-hosted instance and from the posthog-js
+ // CDN prefixes — chunks must resolve relative to the importing module. Fonts stay
+ // file-loaded with relative url()s in the CSS (which is fetched from inside
+ // dist/toolbar/, so they resolve); svgs are imported from JS where a relative specifier
+ // string would resolve against the customer page's URL, so inline them instead.
+ publicPath: undefined,
+ loader: { ...commonConfig.loader, '.svg': 'dataurl' },
// Inject TOOLBAR_PUBLIC_PATH at build time as a bare global so runtime
// code (e.g. ToolbarApp.tsx's CSS loader) can construct URLs to sibling
// files in the same versioned bundle. The identifier is declared as
@@ -178,3 +210,59 @@ export function getToolbarBuildConfig(dirname) {
extraPlugins: [createToolbarModulePlugin(dirname)],
}
}
+
+/**
+ * Runs after the toolbar app build: emits the hashless entry copies, promotes the entry CSS to
+ * the stable dist/toolbar.css URL, and builds the loader with the hashed entry filename baked
+ * in. Called from build.mjs's onBuildComplete and bin/build-toolbar.mjs (including per rebuild
+ * in watch mode — the loader build is a single tiny file).
+ */
+export async function finalizeToolbarBuild(dirname, buildResponse) {
+ if (!buildResponse) {
+ return
+ }
+
+ const entrypoints = buildResponse.entrypoints || []
+ const entryJs = entrypoints.find((e) => e.endsWith('.js'))
+ const entryCss = entrypoints.find((e) => e.endsWith('.css'))
+ if (!entryJs || !entryCss) {
+ // Failing the build beats shipping a loader that points at nothing.
+ throw new Error(`Toolbar app build produced no entry ${!entryJs ? 'JS' : 'CSS'} output.`)
+ }
+
+ // esbuild emits per-chunk CSS: only the entry's stylesheet is loaded into the shadow root
+ // (as toolbar.css), so toolbar features must keep their styles statically imported. Chunk
+ // CSS files are dead weight from lazily-imported app scenes, not a correctness problem.
+
+ // toolbar-app-<hash>.js -> toolbar-app.js next to it: the loader's version-skew fallback.
+ createHashlessEntrypoints(dirname, entrypoints)
+ // The copy lives one directory up from the entry CSS, so point its sourceMappingURL back
+ // into dist/toolbar/ — collectstatic fails on a sourcemap reference it can't resolve.
+ const entryCssContent = fs
+ .readFileSync(entryCss, 'utf8')
+ .replace(/sourceMappingURL=([^\s*]+\.css\.map)/, 'sourceMappingURL=toolbar/$1')
+ fs.writeFileSync(path.resolve(dirname, 'dist', 'toolbar.css'), entryCssContent)
+
+ // The chunks bundle rrweb, whose inlined worker string carries a sourceMappingURL that
+ // collectstatic resolves relative to dist/toolbar/ — the map must exist there too.
+ copyRRWebWorkerFiles(dirname, 'dist/toolbar')
+
+ await esbuildBuild({
+ absWorkingDir: dirname,
+ entryPoints: ['src/toolbar/loader.ts'],
+ bundle: true,
+ // ESM output keeps the runtime-dynamic import() untouched; with no static
+ // imports/exports of its own, the file still parses as a classic script.
+ format: 'esm',
+ outfile: path.resolve(dirname, 'dist', 'toolbar.js'),
+ minify: !isDev,
+ sourcemap: true,
+ target: commonConfig.target,
+ tsconfig: commonConfig.tsconfig,
+ define: {
+ ...commonConfig.define,
+ __POSTHOG_TOOLBAR_PUBLIC_PATH__: JSON.stringify(toolbarPublicPathOverride),
+ __POSTHOG_TOOLBAR_APP_ENTRY__: JSON.stringify(path.basename(entryJs)),
+ },
+ })
+}