: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: revert "feat(exporter): split exporter bundle with ESM code splitting and lazy scenes" (#57817)
Vasco de Krijger8cacb04aebf2
diff --git a/common/esbuilder/utils.mjs b/common/esbuilder/utils.mjsindex fdf6d7a29161..33905012ecbf 100644--- a/common/esbuilder/utils.mjs+++ b/common/esbuilder/utils.mjs@@ -279,8 +279,7 @@ function getChunks(result) {(i) => i.kind === 'import-statement' && i.path.startsWith('dist/chunk-'))const exports = output.exports.filter((e) => e !== 'default' && e !== 'scene')- const isRootEntry = output.entryPoint === 'src/index.tsx' || output.entryPoint === 'src/exporter/index.tsx'- if (importStatements.length > 0 && (exports.length > 0 || isRootEntry)) {+ if (importStatements.length > 0 && (exports.length > 0 || output.entryPoint === 'src/index.tsx')) {chunks[exports[0] || 'index'] = importStatements.map((i) =>i.path.replace('dist/chunk-', '').replace('.js', ''))@@ -357,42 +356,10 @@ export async function buildInParallel(configs, { onBuildStart, onBuildComplete }/** Get the main ".js" and ".css" files for a build */function getBuiltEntryPoints(config, result) {- // Normalise entryPoints: support both array form and object form { name: path }- const entryValues = Array.isArray(config.entryPoints) ? config.entryPoints : Object.values(config.entryPoints || {})-- // Primary: scan the metafile directly — works regardless of entryNames overrides.- // CSS outputs never have entryPoint set, so we find JS entries first, then locate- // each companion CSS by matching the same base name (hashes differ between JS and CSS).- const jsFiles = []- for (const [outputPath, output] of Object.entries(result.metafile?.outputs || {})) {- if (output.entryPoint && entryValues.includes(output.entryPoint) && outputPath.endsWith('.js')) {- jsFiles.push(path.resolve(process.cwd(), outputPath))- }- }- if (jsFiles.length > 0) {- const allFiles = [...jsFiles]- const allOutputPaths = Object.keys(result.metafile?.outputs || {})- for (const jsFile of jsFiles) {- // Strip optional hash suffix: "dist/exporter-HASH.js" -> "dist/exporter"- const baseName = jsFile.replace(/(-[A-Z0-9]+)?\.js$/, '')- for (const outputPath of allOutputPaths) {- if (!outputPath.endsWith('.css')) {- continue- }- const absoluteCss = path.resolve(process.cwd(), outputPath)- if (absoluteCss.startsWith(baseName + '-') || absoluteCss === baseName + '.css') {- allFiles.push(absoluteCss)- }- }- }- return allFiles- }-- // Fallback: path-based convention for configs where metafile scan yields nothinglet outfiles = []if (config.outdir) {// convert "src/index.tsx" --> /a/posthog/frontend/dist/index.js- outfiles = entryValues.map((file) =>+ outfiles = config.entryPoints.map((file) =>path.resolve(config.absWorkingDir, file).replace('/src/', '/dist/')@@ -402,21 +369,24 @@ function getBuiltEntryPoints(config, result) {outfiles = [path.resolve(config.absWorkingDir, config.outfile)]}- const fallbackFiles = []+ const builtFiles = []for (const outfile of outfiles) {+ // convert "/a/something.tsx" --> "/a/something-"const fileNoExt = outfile.replace(/\.[^/]+$/, '')- for (const file of Object.keys(result.metafile?.outputs || {})) {+ // find if we built a .js or .css file that matches+ for (const file of Object.keys(result.metafile.outputs)) {const absoluteFile = path.resolve(process.cwd(), file)if ((absoluteFile.startsWith(`${fileNoExt}-`) && (file.endsWith('.js') || file.endsWith('.css'))) ||absoluteFile === `${fileNoExt}.js` ||absoluteFile === `${fileNoExt}.css`) {- fallbackFiles.push(absoluteFile)+ builtFiles.push(absoluteFile)}}}- return fallbackFiles++ return builtFiles}let buildsInProgress = 0diff --git a/frontend/build.mjs b/frontend/build.mjsindex cd15e130b800..e44edbcb79aa 100755--- a/frontend/build.mjs+++ b/frontend/build.mjs@@ -79,10 +79,10 @@ await buildInParallel(},{name: 'Exporter',- entryPoints: { exporter: 'src/exporter/index.tsx' },- splitting: true,- format: 'esm',- outdir: path.resolve(__dirname, 'dist'),+ globalName: 'posthogExporter',+ entryPoints: ['src/exporter/index.tsx'],+ format: 'iife',+ outfile: path.resolve(__dirname, 'dist', 'exporter.js'),...common,},{diff --git a/frontend/src/exporter/Exporter.tsx b/frontend/src/exporter/Exporter.tsxindex 1e270bab1014..efede9ef06cb 100644--- a/frontend/src/exporter/Exporter.tsx+++ b/frontend/src/exporter/Exporter.tsx@@ -3,28 +3,35 @@ import './Exporter.scss'import clsx from 'clsx'import { BindLogic, useValues } from 'kea'-import { lazy, Suspense, useEffect } from 'react'+import { useCallback, useEffect } from 'react'import { Logo } from 'lib/brand/Logo'+import { HeatmapCanvas } from 'lib/components/heatmaps/HeatmapCanvas'+import { usePageVisibilityCb } from 'lib/hooks/usePageVisibility'import { useResizeObserver } from 'lib/hooks/useResizeObserver'import { useThemedHtml } from 'lib/hooks/useThemedHtml'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { Link } from 'lib/lemon-ui/Link'import { humanFriendlyDuration } from 'lib/utils'-import { AUTO_REFRESH_INITIAL_INTERVAL_SECONDS } from 'scenes/dashboard/dashboardConstants'+import { Dashboard } from 'scenes/dashboard/Dashboard'+import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'+import { Notebook } from 'scenes/notebooks/Notebook/Notebook'+import { SessionRecordingPlayer } from 'scenes/session-recordings/player/SessionRecordingPlayer'+import { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'import { teamLogic } from 'scenes/teamLogic'+import { ExportedInsight } from '~/exporter/ExportedInsight/ExportedInsight'import { ExporterLogin } from '~/exporter/ExporterLogin'import { ExportType, ExportedData } from '~/exporter/types'+import { getQueryBasedDashboard } from '~/queries/nodes/InsightViz/utils'+import {+ AUTO_REFRESH_INITIAL_INTERVAL_SECONDS,+ scheduleSharedDashboardStaleAutoForceIfEligible,+} from '~/scenes/dashboard/dashboardUtils'+import { DashboardPlacement } from '~/types'import { exporterViewLogic } from './exporterViewLogic'-const LazyDashboardScene = lazy(() => import('./scenes/ExporterDashboardScene'))-const LazyNotebookScene = lazy(() => import('./scenes/ExporterNotebookScene'))-const LazyRecordingScene = lazy(() => import('./scenes/ExporterRecordingScene'))-const LazyHeatmapScene = lazy(() => import('./scenes/ExporterHeatmapScene'))-const LazyInsightScene = lazy(() => import('./scenes/ExporterInsightScene'))-function resolveForcedTheme(theme?: 'light' | 'dark' | 'system'): 'light' | 'dark' | null {if (theme === 'light' || theme === 'dark') {return theme@@ -37,7 +44,89 @@ function resolveForcedTheme(theme?: 'light' | 'dark' | 'system'): 'light' | 'dar: 'light'}+function ExportHeatmap(): JSX.Element {+ const { exportedData, isLoading, screenshotUrl } = useValues(exporterViewLogic)+ const { exportToken } = exportedData+ const width = exportedData.heatmap_context?.width++ return (+ <div+ className="heatmap-exporter relative"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ width: width ? `${width}px` : '100%',+ minHeight: '100vh',+ overflow: 'hidden',+ }}+ >+ <HeatmapCanvas+ positioning="absolute"+ widthOverride={width ?? null}+ context="in-app"+ exportToken={exportToken}+ />+ {exportedData.heatmap_context?.heatmap_type === 'screenshot' ? (+ isLoading ? null : (+ <img+ src={screenshotUrl ?? ''}+ alt="Heatmap"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ width: '100%', height: 'auto', display: 'block' }}+ />+ )+ ) : (+ <iframe+ id="heatmap-iframe"+ ref={null}+ title="Heatmap export"+ className="bg-white"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ width: '100%', height: '100vh', display: 'block' }}+ src={exportedData.heatmap_url ?? ''}+ onLoad={() => {}}+ // these two sandbox values are necessary so that the site and toolbar can run+ // this is a very loose sandbox,+ // but we specify it so that at least other capabilities are denied+ sandbox="allow-scripts allow-same-origin"+ // we don't allow things such as camera access though+ allow=""+ />+ )}+ </div>+ )+}++function SharedDashboardAutoRefresh({ dashboardId }: { dashboardId: number }): JSX.Element | null {+ const logic = dashboardLogic({ id: dashboardId, placement: DashboardPlacement.Public })+ const { setAutoRefresh, setPageVisibility, triggerDashboardRefresh } = logic.actions++ // Tie auto-refresh to tab visibility AND fire a one-shot staleness check when the tab+ // regains focus — Chrome throttles background timers, so the periodic interval can drift+ // well past the staleness budget before the next tick. Reading `logic.values` inside the+ // callback gets the live `effectiveLastRefresh` rather than a stale closure value.+ const onVisibilityChange = useCallback(+ (visible: boolean) => {+ setPageVisibility(visible)+ if (visible) {+ scheduleSharedDashboardStaleAutoForceIfEligible({+ effectiveLastRefresh: logic.values.effectiveLastRefresh,+ triggerDashboardRefresh: () => void triggerDashboardRefresh(),+ })+ }+ },+ [setPageVisibility, triggerDashboardRefresh, logic]+ )+ usePageVisibilityCb(onVisibilityChange)++ useEffect(() => {+ setAutoRefresh(true, AUTO_REFRESH_INITIAL_INTERVAL_SECONDS)+ }, [setAutoRefresh])++ return null+}+export function Exporter(props: ExportedData): JSX.Element {+ // NOTE: Mounting the logic is important as it is used by sub-logicsconst {type,dashboard,@@ -149,37 +238,40 @@ export function Exporter(props: ExportedData): JSX.Element {</div></div>)}- <Suspense fallback={null}>- <LazyNotebookScene- notebook={notebook}- insights={insights}- inline_query_results={inlineQueryResults}- />- </Suspense>+ <Notebook+ shortId={notebook.short_id}+ editable={false}+ cachedNotebook={notebook}+ cachedInsightsByShortId={insights}+ cachedInlineQueryResultsByNodeId={inlineQueryResults}+ /></div>) : insight ? (- <Suspense fallback={null}>- <LazyInsightScene insight={insight} themes={themes!} exportOptions={exportOptions} />- </Suspense>+ <ExportedInsight insight={insight} themes={themes!} exportOptions={exportOptions} />) : dashboard ? (- <Suspense fallback={null}>- <LazyDashboardScene dashboard={dashboard} type={type} themes={themes} />- </Suspense>- ) : recording ? (- <Suspense fallback={null}>- <LazyRecordingScene- recording={recording}- mode={props.mode}- autoplay={props.autoplay}- noBorder={props.noBorder}- exportToken={exportToken}- showInspector={showInspector}+ <>+ {type !== ExportType.Image && <SharedDashboardAutoRefresh dashboardId={dashboard.id} />}+ <Dashboard+ id={String(dashboard.id)}+ dashboard={getQueryBasedDashboard(dashboard)!}+ placement={+ type === ExportType.Image ? DashboardPlacement.Export : DashboardPlacement.Public+ }+ themes={themes}/>- </Suspense>+ </>+ ) : recording ? (+ <SessionRecordingPlayer+ playerKey="exporter"+ sessionRecordingId={recording.id}+ mode={props.mode ?? SessionRecordingPlayerMode.Sharing}+ autoPlay={props.autoplay ?? false}+ withSidebar={showInspector}+ noBorder={props.noBorder ?? false}+ accessToken={exportToken}+ />) : type === ExportType.Heatmap ? (- <Suspense fallback={null}>- <LazyHeatmapScene />- </Suspense>+ <ExportHeatmap />) : (<h1 className="text-center p-4">Something went wrong...</h1>)}diff --git a/frontend/src/exporter/scenes/ExporterDashboardScene.tsx b/frontend/src/exporter/scenes/ExporterDashboardScene.tsxdeleted file mode 100644index c02e86db6cc0..000000000000--- a/frontend/src/exporter/scenes/ExporterDashboardScene.tsx+++ /dev/null@@ -1,60 +0,0 @@-import { useActions } from 'kea'-import { useCallback, useEffect } from 'react'--import { usePageVisibilityCb } from 'lib/hooks/usePageVisibility'-import { Dashboard } from 'scenes/dashboard/Dashboard'-import { AUTO_REFRESH_INITIAL_INTERVAL_SECONDS } from 'scenes/dashboard/dashboardConstants'-import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'-import { scheduleSharedDashboardStaleAutoForceIfEligible } from 'scenes/dashboard/dashboardUtils'--import { getQueryBasedDashboard } from '~/queries/nodes/InsightViz/utils'-import { DashboardPlacement } from '~/types'--import { ExportType, ExportedData } from '../types'--function SharedDashboardAutoRefresh({ dashboardId }: { dashboardId: number }): JSX.Element | null {- const logic = dashboardLogic({ id: dashboardId, placement: DashboardPlacement.Public })- const { setAutoRefresh, setPageVisibility, triggerDashboardRefresh } = useActions(logic)-- const onVisibilityChange = useCallback(- (visible: boolean) => {- setPageVisibility(visible)- if (visible) {- scheduleSharedDashboardStaleAutoForceIfEligible({- effectiveLastRefresh: logic.values.effectiveLastRefresh,- triggerDashboardRefresh: () => void triggerDashboardRefresh(),- })- }- },- [setPageVisibility, triggerDashboardRefresh, logic]- )- usePageVisibilityCb(onVisibilityChange)-- useEffect(() => {- setAutoRefresh(true, AUTO_REFRESH_INITIAL_INTERVAL_SECONDS)- }, [setAutoRefresh])-- return null-}--export default function ExporterDashboardScene({- dashboard,- type,- themes,-}: {- dashboard: NonNullable<ExportedData['dashboard']>- type: ExportedData['type']- themes: ExportedData['themes']-}): JSX.Element {- return (- <>- {type !== ExportType.Image && <SharedDashboardAutoRefresh dashboardId={dashboard.id} />}- <Dashboard- id={String(dashboard.id)}- dashboard={getQueryBasedDashboard(dashboard)!}- placement={type === ExportType.Image ? DashboardPlacement.Export : DashboardPlacement.Public}- themes={themes}- />- </>- )-}diff --git a/frontend/src/exporter/scenes/ExporterHeatmapScene.tsx b/frontend/src/exporter/scenes/ExporterHeatmapScene.tsxdeleted file mode 100644index 683ce532842e..000000000000--- a/frontend/src/exporter/scenes/ExporterHeatmapScene.tsx+++ /dev/null@@ -1,55 +0,0 @@-import { useValues } from 'kea'--import { HeatmapCanvas } from 'lib/components/heatmaps/HeatmapCanvas'--import { exporterViewLogic } from '../exporterViewLogic'--export default function ExporterHeatmapScene(): JSX.Element {- const { exportedData, isLoading, screenshotUrl } = useValues(exporterViewLogic)- const { exportToken } = exportedData- const width = exportedData.heatmap_context?.width-- return (- <div- className="heatmap-exporter relative"- // eslint-disable-next-line react/forbid-dom-props- style={{- width: width ? `${width}px` : '100%',- minHeight: '100vh',- overflow: 'hidden',- }}- >- <HeatmapCanvas- positioning="absolute"- widthOverride={width ?? null}- context="in-app"- exportToken={exportToken}- />- {exportedData.heatmap_context?.heatmap_type === 'screenshot' ? (- isLoading ? null : (- <img- src={screenshotUrl ?? ''}- alt="Heatmap"- // eslint-disable-next-line react/forbid-dom-props- style={{ width: '100%', height: 'auto', display: 'block' }}- />- )- ) : (- <iframe- id="heatmap-iframe"- title="Heatmap export"- className="bg-white"- // eslint-disable-next-line react/forbid-dom-props- style={{ width: '100%', height: '100vh', display: 'block' }}- src={exportedData.heatmap_url ?? ''}- // these two sandbox values are necessary so that the site and toolbar can run- // this is a very loose sandbox,- // but we specify it so that at least other capabilities are denied- sandbox="allow-scripts allow-same-origin"- // we don't allow things such as camera access though- allow=""- />- )}- </div>- )-}diff --git a/frontend/src/exporter/scenes/ExporterInsightScene.tsx b/frontend/src/exporter/scenes/ExporterInsightScene.tsxdeleted file mode 100644index e7e58c4b5ad4..000000000000--- a/frontend/src/exporter/scenes/ExporterInsightScene.tsx+++ /dev/null@@ -1,16 +0,0 @@-import { ExportedInsight } from '~/exporter/ExportedInsight/ExportedInsight'-import { SharingConfigurationSettings } from '~/queries/schema/schema-general'--import { ExportedData } from '../types'--export default function ExporterInsightScene({- insight,- themes,- exportOptions,-}: {- insight: NonNullable<ExportedData['insight']>- themes: NonNullable<ExportedData['themes']>- exportOptions: SharingConfigurationSettings-}): JSX.Element {- return <ExportedInsight insight={insight} themes={themes} exportOptions={exportOptions} />-}diff --git a/frontend/src/exporter/scenes/ExporterNotebookScene.tsx b/frontend/src/exporter/scenes/ExporterNotebookScene.tsxdeleted file mode 100644index 7d1a4acbca4d..000000000000--- a/frontend/src/exporter/scenes/ExporterNotebookScene.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { Notebook } from 'scenes/notebooks/Notebook/Notebook'--import { ExportedData } from '../types'--export default function ExporterNotebookScene({- notebook,- insights,- inline_query_results: inlineQueryResults,-}: {- notebook: NonNullable<ExportedData['notebook']>- insights: ExportedData['insights']- inline_query_results: ExportedData['inline_query_results']-}): JSX.Element {- return (- <Notebook- shortId={notebook.short_id}- editable={false}- cachedNotebook={notebook}- cachedInsightsByShortId={insights}- cachedInlineQueryResultsByNodeId={inlineQueryResults}- />- )-}diff --git a/frontend/src/exporter/scenes/ExporterRecordingScene.tsx b/frontend/src/exporter/scenes/ExporterRecordingScene.tsxdeleted file mode 100644index 21a2cbf35bde..000000000000--- a/frontend/src/exporter/scenes/ExporterRecordingScene.tsx+++ /dev/null@@ -1,32 +0,0 @@-import { SessionRecordingPlayer } from 'scenes/session-recordings/player/SessionRecordingPlayer'-import { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'--import { ExportedData } from '../types'--export default function ExporterRecordingScene({- recording,- mode,- autoplay,- noBorder,- exportToken,- showInspector,-}: {- recording: NonNullable<ExportedData['recording']>- mode: ExportedData['mode']- autoplay: ExportedData['autoplay']- noBorder: ExportedData['noBorder']- exportToken: ExportedData['exportToken']- showInspector: ExportedData['showInspector']-}): JSX.Element {- return (- <SessionRecordingPlayer- playerKey="exporter"- sessionRecordingId={recording.id}- mode={mode ?? SessionRecordingPlayerMode.Sharing}- autoPlay={autoplay ?? false}- withSidebar={showInspector ?? false}- noBorder={noBorder ?? false}- accessToken={exportToken}- />- )-}diff --git a/frontend/src/scenes/dashboard/dashboardConstants.ts b/frontend/src/scenes/dashboard/dashboardConstants.tsdeleted file mode 100644index fbdda8e7e1bd..000000000000--- a/frontend/src/scenes/dashboard/dashboardConstants.ts+++ /dev/null@@ -1,2 +0,0 @@-export const AUTO_REFRESH_INITIAL_INTERVAL_SECONDS = 1800-export const SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES = AUTO_REFRESH_INITIAL_INTERVAL_SECONDS / 60diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.tsindex 93729963e579..9f25b0185017 100644--- a/frontend/src/scenes/dashboard/dashboardUtils.ts+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts@@ -4,12 +4,6 @@ import { lemonToast } from '@posthog/lemon-ui'import api, { ApiMethodOptions, getJSONOrNull } from 'lib/api'import type { Dayjs } from 'lib/dayjs'--import {- AUTO_REFRESH_INITIAL_INTERVAL_SECONDS,- SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES,-} from './dashboardConstants'-export { AUTO_REFRESH_INITIAL_INTERVAL_SECONDS, SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES }import { currentSessionId } from 'lib/internalMetrics'import { objectClean, shouldCancelQuery, toParams } from 'lib/utils'import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'@@ -121,8 +115,16 @@ export const DEFAULT_AUTO_PREVIEW_TILE_LIMIT = 10const RATE_LIMIT_ERROR_MESSAGE = 'concurrency_limit_exceeded'+export const AUTO_REFRESH_INITIAL_INTERVAL_SECONDS = 1800export const QUICK_FILTER_DEBOUNCE_MS = 1500+/**+ * Cold-start one-shot threshold: if data is older than this when a shared dashboard loads,+ * trigger one immediate force_blocking refresh. Aligned with the periodic interval and the+ * backend throttle (`SHARED_FORCE_BLOCKING_MIN_AGE`).+ */+export const SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES = AUTO_REFRESH_INITIAL_INTERVAL_SECONDS / 60+function staleAgeMinutes(effectiveLastRefresh: Dayjs | null): number | null {if (!effectiveLastRefresh) {return null