import { testInlineExpects } from './inline-expectation' ; import { Stylable , StylableConfig , StylableResults } from '@stylable/core' ; import { createMemoryFs } from '@file-services/memory' ; import type { IDirectoryContents , IFileSystem } from '@file-services/types' ; import { isAbsolute } from 'path' ; export interface TestOptions { entries : string [ ] ; stylableConfig : TestStylableConfig ; } export type TestStylableConfig = Omit < StylableConfig , 'fileSystem' | `projectRoot` | `resolveNamespace` > & { filesystem ? : IFileSystem ; projectRoot ? : StylableConfig [ 'projectRoot' ] ; resolveNamespace ? : StylableConfig [ 'resolveNamespace' ] ; } ; param input export function testStylableCore ( input , options = { } ) { const fs = options . stylableConfig ?. filesystem || createMemoryFs ( typeof input === `string` ? { '/entry.st.css' : input } : input ) ; const stylable = Stylable . create ( { fileSystem : fs , projectRoot : '/' , resolveNamespace : ( ns ) => ns , requireModule : createJavascriptRequireModule ( fs ) , ... ( options . stylableConfig || { } ) , } ) ; const allSheets = fs . findFilesSync ( `/` , { filterFile : ( { path } ) => path . endsWith ( `.st.css` ) } ) ; const entries = options . entries || allSheets ; const sheets = { } ; for ( const path of entries ) { if ( ! isAbsolute ( path || '' ) ) { throw new Error ( testStylableCore . errors . absoluteEntry ( path ) ) ; } const meta = stylable . process ( path ) ; const { exports } = stylable . transform ( meta ) ; sheets [ path ] = { meta , exports } ; } for ( const path of allSheets ) { const meta = stylable . process ( path ) ; if ( ! meta . outputAst ) { stylable . transform ( meta ) ; } testInlineExpects ( { meta } ) ; } return { sheets , stylable , fs } ; } testStylableCore . errors = { absoluteEntry : ( entry ) => `entry must be absolute path got: ${ entry }` , } ; function createJavascriptRequireModule ( fs ) { const requireModule = ( id ) : any => { const _module = { id , exports : { } , } ; try { if ( ! id . match ( /\.js$/ ) ) { id += '.js' ; } const fn = new Function ( 'module' , 'exports' , 'require' , fs . readFileSync ( id , { encoding : 'utf8' , flag : 'r' } ) ) ; fn ( _module , _module . exports , requireModule ) ; } catch ( e ) { throw new Error ( 'Cannot require file: ' + id ) ; } return _module . exports ; } ; return requireModule ; }