import { defineConfig } from 'vite';
import { resolve } from 'path';

function annotateGltfViewerMikktspaceFallback()
{
  const OriginalFallbackExpression =
    "new URL('mikktspace_bg.wasm', import.meta.url)";
  const AnnotatedFallbackExpression =
    "new URL(/* @vite-ignore */ 'mikktspace_bg.wasm', import.meta.url)";

  return {
    name: 'annotate-gltf-viewer-mikktspace-fallback',
    transform(Code: string, Id: string)
    {
      if (!Id.includes('@khronosgroup/gltf-viewer/dist/gltf-viewer.module.js'))
      {
        return null;
      }

      if (!Code.includes(OriginalFallbackExpression))
      {
        return null;
      }

      return {
        code: Code.replaceAll(
          OriginalFallbackExpression,
          AnnotatedFallbackExpression
        ),
        map: null
      };
    }
  };
}

export default defineConfig({
  plugins: [
    annotateGltfViewerMikktspaceFallback()
  ],
  build: {
    outDir: 'dist',
    emptyOutDir: true,
    sourcemap: true,
    lib: {
      entry: resolve(__dirname, 'src/browser-spatial-runtime.ts'),
      formats: ['es'],
      fileName: () => 'browser-spatial-runtime.js'
    },
    rollupOptions: {
      onwarn(warning, warn) {
        if (warning.code === 'MODULE_LEVEL_DIRECTIVE' && warning.message.includes('"use client"'))
        {
          return;
        }

        warn(warning);
      },
      output: {
        assetFileNames: 'assets/[name][extname]',
        chunkFileNames: 'assets/[name].js'
      }
    }
  },
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  }
});
