import fs from 'fs-extra' ; import type { Plugin } from 'rollup' ; import { join } from 'path' ; import type { BuildOptions } from '../../utils/options' ; import { minify } from 'terser' ; param opts returns export function typescriptSourcePlugin ( opts ) { const tsPath = require . resolve ( 'typescript' ) ; return { name : 'typescriptSourcePlugin' , param id returns resolveId ( id ) { if ( id === 'typescript' ) { return tsPath ; } return null ; } , param id returns load ( id ) { if ( id === tsPath ) { return bundleTypeScriptSource ( tsPath , opts ) ; } return null ; } , } ; } param tsPath param opts returns async function bundleTypeScriptSource ( tsPath , opts ) { const fileName = `typescript-${ opts . typescriptVersion . replace ( /\./g , '_' ) }-bundle-cache${ opts . isProd ? '.min' : '' }.js` ; const cacheFile = join ( opts . scriptsBuildDir , fileName ) ; try { return await fs . readFile ( cacheFile , 'utf8' ) ; } catch ( e ) { } let code = await fs . readFile ( tsPath , 'utf8' ) ; code = removeFromSource ( code , `ts.getDefaultLibFilePath = getDefaultLibFilePath;` ) ; code = removeFromSource ( code , `enableCPUProfiler: enableCPUProfiler,` ) ; code = removeFromSource ( code , `disableCPUProfiler: disableCPUProfiler,` ) ; const tsEnding = `})(ts || (ts = {}));` ; if ( ! code . includes ( tsEnding ) ) { throw new Error ( `"${ tsEnding }" not found` ) ; } const lastEnding = code . lastIndexOf ( tsEnding ) ; code = code . substr ( 0 , lastEnding + tsEnding . length ) ; code = code . replace ( /var ts;/g , '' ) ; code = code . replace ( / \|\| \(ts \= \{\}\)/g , '' ) ; const o = [ ] ; o . push ( `// TypeScript ${ opts . typescriptVersion }` ) ; o . push ( `import { IS_NODE_ENV } from '@environment';` ) ; o . push ( `process.browser = !IS_NODE_ENV;` ) ; o . push ( `const ts = {};` ) ; o . push ( code ) ; o . push ( `export default ts;` ) ; code = o . join ( '\n' ) ; if ( opts . isProd ) { const minified = await minify ( code , { ecma : 2018 , module : true , compress : { ecma : 2018 , passes : 2 , } , format : { ecma : 2018 , comments : false , } , } ) ; code = minified . code ; } await fs . writeFile ( cacheFile , code ) ; return code ; } param srcCode param removeCode return function removeFromSource ( srcCode , removeCode ) { if ( ! srcCode . includes ( removeCode ) ) { throw new Error ( `"${ removeCode }" not found` ) ; } return srcCode . replace ( removeCode , `/* commented out: ${ removeCode } */` ) ; }