All files / repo-tools/src/vite-plugins/bundle-vats bundle-vat.ts

0% Statements 0/8
0% Branches 0/6
0% Functions 0/2
0% Lines 0/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74                                                                                                                                                   
import { build } from 'vite';
import type { Rollup } from 'vite';
 
import { exportMetadataPlugin } from './export-metadata-plugin.ts';
import { stripCommentsPlugin } from './strip-comments-plugin.ts';
 
/**
 * A bundle produced by the vat bundler.
 *
 * Contains the bundled code as an IIFE that assigns exports to `__vatExports__`,
 * along with metadata about the bundle's exports and external dependencies.
 */
export type VatBundle = {
  moduleFormat: 'iife';
  code: string;
  exports: string[];
  external: string[];
};
 
/**
 * Bundle a vat source file using vite.
 *
 * Produces an IIFE bundle that assigns exports to a `__vatExports__` global,
 * along with metadata about the bundle's exports and external dependencies.
 *
 * @param sourcePath - Absolute path to the vat entry point.
 * @returns The bundle object containing code and metadata.
 */
export async function bundleVat(sourcePath: string): Promise<VatBundle> {
  const metadataPlugin = exportMetadataPlugin();
 
  const result = await build({
    configFile: false,
    logLevel: 'silent',
    // TODO: Remove this define block and add a process shim to VatSupervisor
    // workerEndowments instead. This injects into ALL bundles but is only needed
    // for libraries like immer that check process.env.NODE_ENV.
    define: {
      'process.env.NODE_ENV': JSON.stringify('production'),
    },
    build: {
      write: false,
      lib: {
        entry: sourcePath,
        formats: ['iife'],
        name: '__vatExports__',
      },
      rollupOptions: {
        output: {
          exports: 'named',
          inlineDynamicImports: true,
        },
        plugins: [stripCommentsPlugin(), metadataPlugin],
      },
      minify: false,
    },
  });
 
  const output = Array.isArray(result) ? result[0] : result;
  const chunk = (output as Rollup.RollupOutput).output.find(
    (item): item is Rollup.OutputChunk => item.type === 'chunk' && item.isEntry,
  );
 
  if (!chunk) {
    throw new Error(`Failed to produce bundle for ${sourcePath}`);
  }
 
  return {
    moduleFormat: 'iife',
    code: chunk.code,
    ...metadataPlugin.getMetadata(),
  };
}