import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';

// Babylon 9's @babylonjs/inspector module has circular imports that resolve
// to TDZ when collapsed into a single IIFE scope (regardless of minifier).
// Output ESM instead — module boundaries preserve the original import order
// so the inspector initializes cleanly. Consumers load via
// `<script type="module" src="adom-3d-viewer-babylon9.esm.js"></script>`.
export default defineConfig({
  plugins: [svelte({ compilerOptions: { css: 'injected' } })],
  // @babylonjs/inspector v9 pulls in React, which references the Node-only
  // `process.env.NODE_ENV` global at runtime. Vite injects this automatically
  // in `serve` and standard `build` modes but NOT in `lib` mode, so without
  // a define the inspector crashes with "process is not defined" the first
  // time the user opens it. Replacing the env lookup at bundle time strips
  // every `if (process.env.NODE_ENV !== 'production') warn(...)` branch
  // from React, which incidentally removes the only `process` references.
  define: {
    'process.env.NODE_ENV': JSON.stringify('production'),
  },
  build: {
    lib: {
      entry: 'standalone.ts',
      formats: ['es'],
      name: 'Adom3DViewerBabylon9',
      fileName: () => 'adom-3d-viewer-babylon9.esm.js',
    },
    rollupOptions: {
      external: [],
      output: {
        // Allow `await import(...)` to produce separate chunks. The inspector
        // lazy-import lands in its own scope and avoids the
        // "object is not extensible" error when collapsed into the main bundle.
        inlineDynamicImports: false,
        chunkFileNames: 'chunk-[hash].js',
      },
    },
    outDir: 'dist-standalone',
    minify: 'esbuild',
    sourcemap: false,
    chunkSizeWarningLimit: 50000,
    target: 'es2020',
  },
  resolve: {
    dedupe: ['svelte', '@babylonjs/core'],
  },
});
