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.

10.0 KB
Raw Blame
import tailwindcss from '@tailwindcss/vite'
import react from '@vitejs/plugin-react'
import { dirname, resolve } from 'node:path'
import { URL, fileURLToPath } from 'node:url'
import { defineConfig } from 'vite'

const __dirname = dirname(fileURLToPath(import.meta.url))

// import { toolbarDenylistPlugin } from './vite-toolbar-plugin'
import { htmlGenerationPlugin } from './plugins/vite-html-plugin'
import { posthogJsPlugin } from './plugins/vite-posthog-js-plugin'
import { publicAssetsPlugin } from './plugins/vite-public-assets-plugin'
import { zodJitlessPlugin } from './plugins/vite-zod-jitless-plugin'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
    const isDev = mode === 'development'
    // Opt-in because the plugin's server listens on all interfaces with no auth. Set DEV_CODE_INSPECTOR=1 in .env.local.
    const codeInspectorEnabled = ['1', 'true'].includes(process.env.DEV_CODE_INSPECTOR?.toLowerCase() ?? '')

    return {
        plugins: [
            // Dev server only: hold Option+Shift (Alt+Shift) and click an element to open its source in your editor.
            // The plugin must come before react(). CSPMiddleware admits port 5678 when DEV_CODE_INSPECTOR is set, so keep the two in sync.
            codeInspectorEnabled &&
                import('code-inspector-plugin').then(({ codeInspectorPlugin }) =>
                    codeInspectorPlugin({
                        bundler: 'vite',
                        port: 5678,
                        pathType: 'relative',
                        injectTo: resolve(__dirname, 'src/index.tsx'),
                    })
                ),
            react(),
            tailwindcss(),
            // We delete and copy the HTML files for development
            htmlGenerationPlugin(),
            // Copy public assets to src/assets for development
            publicAssetsPlugin(),
            // Copy posthog-js files from node_modules to dist for development
            posthogJsPlugin(),
            zodJitlessPlugin(),
            {
                name: 'startup-message',
                configureServer(server) {
                    server.httpServer?.once('listening', () => {
                        setTimeout(() => {
                            console.info(`
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――

   🚀 Visit http://localhost:8010 to see the app
   ⚠️  You may need to wait for the other services to start

――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
`)
                        }, 1000)
                    })
                },
            },
        ],
        resolve: {
            // Linked workspace packages (including Quill) must share the app's
            // React instance or hooks are dispatched through a second runtime.
            dedupe: ['react', 'react-dom', '@base-ui/react'],
            alias: {
                '@base-ui/react': resolve(__dirname, 'node_modules/@base-ui/react'),
                '~': fileURLToPath(new URL('./src', import.meta.url)),
                '@': fileURLToPath(new URL('./src', import.meta.url)),
                // Add direct mappings for PostHog's import structure from tsconfig.json
                lib: resolve(__dirname, 'src/lib'),
                scenes: resolve(__dirname, 'src/scenes'),
                queries: resolve(__dirname, 'src/queries'),
                layout: resolve(__dirname, 'src/layout'),
                toolbar: resolve(__dirname, 'src/toolbar'),
                taxonomy: resolve(__dirname, 'src/taxonomy'),
                models: resolve(__dirname, 'src/models'),
                mocks: resolve(__dirname, 'src/mocks'),
                exporter: resolve(__dirname, 'src/exporter'),
                types: resolve(__dirname, 'src/types.ts'),
                // @posthog/lemon-ui aliases
                '@posthog/lemon-ui': resolve(__dirname, '@posthog/lemon-ui/src/index'),
                '@posthog/lemon-ui/': resolve(__dirname, '@posthog/lemon-ui/src/'),
                // Other aliases from tsconfig.json
                storybook: resolve(__dirname, '../.storybook'),
                // Just for Vite: we copy public assets to src/assets, we need to alias it to the correct path
                public: resolve(__dirname, 'src/assets'),
                // Required for production builds — @posthog/icons is in the pnpm store, not node_modules root
                '@posthog/icons': resolve(__dirname, 'node_modules/@posthog/icons'),
                '@posthog/quill-charts': resolve(__dirname, 'node_modules/@posthog/quill-charts'),
                // Source-only workspace package (exports map points at src/*.ts) — Vite can't resolve
                // it by default when imported from products/*/frontend, like the @posthog/icons case above.
                // Alias each export explicitly, subpath first: a lone package-root alias would rewrite the
                // '@posthog/llm-normalizer/types' import to a nonexistent path instead of src/types.ts.
                '@posthog/llm-normalizer/types': resolve(
                    __dirname,
                    'node_modules/@posthog/llm-normalizer/src/types.ts'
                ),
                '@posthog/llm-normalizer': resolve(__dirname, 'node_modules/@posthog/llm-normalizer/src/index.ts'),
                '@posthog/agent-contracts': resolve(__dirname, '../packages/agent/packages/agent-contracts/src'),
                // These @tiptap packages live only in frontend/node_modules, which products/*/frontend
                // files can't reach by walking up from their own directory. Alias each package
                // individually: a blanket '@tiptap' prefix would also rewrite the imports *inside*
                // tiptap packages (e.g. starter-kit importing @tiptap/extension-code) to paths that
                // don't exist under frontend/node_modules.
                '@tiptap/core': resolve(__dirname, 'node_modules/@tiptap/core'),
                '@tiptap/react': resolve(__dirname, 'node_modules/@tiptap/react'),
                '@tiptap/pm': resolve(__dirname, 'node_modules/@tiptap/pm'),
                '@tiptap/extension-image': resolve(__dirname, 'node_modules/@tiptap/extension-image'),
                '@tiptap/extension-placeholder': resolve(__dirname, 'node_modules/@tiptap/extension-placeholder'),
                products: resolve(__dirname, '../products'),
                '@posthog/shared-onboarding': resolve(__dirname, '../docs/onboarding'),
                '@posthog/shared-onboarding/*': resolve(__dirname, '../docs/onboarding/*'),
                // Node.js polyfills for browser compatibility
                buffer: 'buffer',
            },
        },
        build: {
            // Generate manifest for backend integration
            manifest: true,
            outDir: 'dist',
            rollupOptions: {
                input: {
                    index: resolve(__dirname, 'src/index.tsx'),
                    exporter: resolve(__dirname, 'src/exporter/index.tsx'),
                    render_query: resolve(__dirname, 'src/render-query/index.tsx'),
                    toolbar: resolve(__dirname, 'src/toolbar/floating/index.tsx'),
                },
                output: {
                    entryFileNames: isDev ? '[name].js' : '[name]-[hash].js',
                    chunkFileNames: isDev ? 'chunk-[name].js' : 'chunk-[name]-[hash].js',
                    assetFileNames: isDev ? '~/assets/[name].[ext]' : '~/assets/[name]-[hash].[ext]',
                },
            },
            sourcemap: true,
        },
        worker: {
            format: 'es', // Use ES modules to support WASM imports
            plugins: () => [react(), zodJitlessPlugin()],
            rollupOptions: {
                output: {
                    entryFileNames: isDev ? '[name].js' : '[name]-[hash].js',
                },
            },
        },
        server: {
            port: 8234,
            // The rest of the stack hardcodes 8234, so falling back to another port serves a
            // broken app (the browser keeps talking to whatever squats 8234). Fail loudly instead;
            // bin/start-frontend reclaims the port from stale processes before launching.
            strictPort: true,
            host: process.argv.includes('--host') ? '0.0.0.0' : 'localhost',
            allowedHosts: process.env.VITE_ALLOWED_HOSTS?.split(',')
                .map((s) => s.trim())
                .filter(Boolean),
            // nosemgrep: trailofbits.javascript.apollo-graphql.v3-cors-audit.v3-potentially-bad-cors
            cors: true,
            // JS_URL overrides for sandbox environments where Vite is exposed on a different port.
            origin: process.env.JS_URL || 'http://localhost:8234',
            hmr: process.env.JS_URL ? { clientPort: parseInt(process.env.JS_URL.split(':').pop()!) } : undefined,
            proxy: {
                '/static': {
                    target: 'http://localhost:8000',
                    changeOrigin: true,
                },
            },
        },
        define: {
            global: 'globalThis',
            'process.env.NODE_ENV': isDev ? '"development"' : '"production"',
        },
        css: {
            devSourcemap: true,
        },
        optimizeDeps: {
            include: ['react', 'react-dom', 'buffer'],
            // snappy-wasm: don't pre-bundle so the WASM file stays with the JS.
            // @posthog/brand: its PNG stubs resolve assets via `new URL(..., import.meta.url)`,
            // which pre-bundling rewrites to .vite/deps/ where the images don't exist — hoggie
            // art silently 404s in dev serve (production builds are unaffected).
            exclude: ['snappy-wasm', '@posthog/brand'],
            // Pre-bundled deps skip the main plugin list, and zod is pre-bundled.
            rolldownOptions: {
                plugins: [zodJitlessPlugin()],
            },
        },
    }
})