import { Project } from "../models" ; export class RewriteSourcesContext { project : Project ; processedFiles : any ; logLn : ( s : string ) => void ; createFile : ( content : ArrayBuffer | string , type : string ) => string ; constructor ( project ) { this . project = project ; this . processedFiles = Object . create ( null ) ; } } function expandURL ( path , base ) { return new URL ( path , "https://example.org/" + base ) . pathname . substr ( 1 ) ; } export function rewriteJS ( context , jsFileName ) { const file = context . project . getFile ( jsFileName ) ; if ( ! file ) { return null ; } const src = file . getData ( ) as string ; return src . replace ( /\bfrom\s+['"](.+?)['"](\s*[;\n])/g , ( all , path ? , sep ? ) => { const fullPath = expandURL ( path , jsFileName ) ; const blobUrl = processJSFile ( context , fullPath ) ; if ( ! blobUrl ) { ( void 0 , context . logLn ) ( `Cannot find file '${ path }' mentioned in ${ jsFileName }` ) ; return all ; } return `from "${ blobUrl }"${ sep }` ; } ) ; } export function processJSFile ( context , fullPath ) { if ( context . processedFiles [ fullPath ] ) { return context . processedFiles [ fullPath ] ; } const src = rewriteJS ( context , fullPath ) ; const resultUrl = context . createFile ( src , "application/javascript" ) ; context . processedFiles [ fullPath ] = resultUrl ; return resultUrl ; } export function rewriteHTML ( context , htmlFileName ) { const file = context . project . getFile ( htmlFileName ) ; if ( ! file ) { return null ; } const src = file . getData ( ) as string ; return src . replace ( /\bsrc\s*=\s*['"](.+?)['"]/g , ( all , path ? ) => { const fullPath = expandURL ( path , htmlFileName ) ; const blobUrl = processJSFile ( context , fullPath ) ; if ( ! blobUrl ) { ( void 0 , context . logLn ) ( `Cannot find file '${ path }' mentioned in ${ htmlFileName }` ) ; return all ; } return `src="${ blobUrl }"` ; } ) ; }