import * as fs from 'fs' ; import * as path from 'path' ; import { transformIframeHtml } from './transform-iframe-html' ; import { generateIframeScriptCode } from './codegen-iframe-script' ; import { generateModernIframeScriptCode } from './codegen-modern-iframe-script' ; import { generateImportFnScriptCode } from './codegen-importfn-script' ; import type { Plugin } from 'vite' ; import type { ExtendedOptions } from './types' ; export function codeGeneratorPlugin ( options ) { const virtualFileId = '/virtual:/@storybook/builder-vite/vite-app.js' ; const virtualStoriesFile = '/virtual:/@storybook/builder-vite/storybook-stories.js' ; const iframePath = path . resolve ( __dirname , '..' , 'input' , 'iframe.html' ) ; let iframeId ; return { name : 'storybook-vite-code-generator-plugin' , enforce : 'pre' , configureServer ( server ) { server . watcher . on ( 'change' , ( _e ) => { const { moduleGraph } = server ; const appModule = moduleGraph . getModuleById ( virtualFileId ) ; if ( appModule ) { server . moduleGraph . invalidateModule ( appModule ) ; } const storiesModule = moduleGraph . getModuleById ( virtualStoriesFile ) ; if ( storiesModule ) { server . moduleGraph . invalidateModule ( storiesModule ) ; } } ) ; } , config ( config , { command } ) { if ( command === 'build' ) { if ( ! config . build ) { config . build = { } ; } config . build . rollupOptions = { input : iframePath , } ; } } , configResolved ( config ) { iframeId = `${ config . root }/iframe.html` ; } , resolveId ( source ) { if ( source === virtualFileId ) { return virtualFileId ; } else if ( source === iframePath ) { return iframeId ; } else if ( source === virtualStoriesFile ) { return virtualStoriesFile ; } } , async load ( id ) { if ( id === virtualStoriesFile ) { return generateImportFnScriptCode ( options ) ; } if ( id === virtualFileId ) { if ( options . features && options . features . storyStoreV7 ) { return generateModernIframeScriptCode ( options , { storiesFilename : virtualStoriesFile } ) ; } else { return generateIframeScriptCode ( options ) ; } } if ( id === iframeId ) { return fs . readFileSync ( path . resolve ( __dirname , '..' , 'input' , 'iframe.html' ) , 'utf-8' ) ; } } , async transformIndexHtml ( html , ctx ) { if ( ctx . path !== '/iframe.html' ) { return ; } return transformIframeHtml ( html , options ) ; } , } ; }