import vm from "vm" ; import { AdditionalModules , Context , ProcessedModuleRule , ScriptBlueprint , ScriptRunner , ScriptRunnerResult , } from "@miniflare/shared" ; import { VMScriptRunnerError } from "./error" ; import { defineHasInstances } from "./instanceof" ; import { ModuleLinker } from "./linker" ; export * from "./error" ; export * from "./instanceof" ; export class VMScriptRunner implements ScriptRunner { constructor ( private context ? ) { } private runAsScript ( context , blueprint ) { const script = new vm . Script ( blueprint . code , { filename : blueprint . filePath , } ) ; script . runInContext ( context ) ; } private async runAsModule ( context , blueprint , linker ) { const module = new vm . SourceTextModule ( blueprint . code , { identifier : blueprint . filePath , context , } ) ; await module . link ( linker ) ; await module . evaluate ( ) ; return module . namespace ; } async run ( globalScope , blueprint , modulesRules ? , additionalModules ? ) { if ( modulesRules && ! ( "SourceTextModule" in vm ) ) { throw new VMScriptRunnerError ( "ERR_MODULE_DISABLED" , "Modules support requires the --experimental-vm-modules flag" ) ; } const linker = modulesRules && new ModuleLinker ( modulesRules , additionalModules ?? { } ) ; let context = this . context ; if ( context ) { Object . assign ( context , globalScope ) ; } else { context = vm . createContext ( globalScope , { codeGeneration : { strings : false , wasm : false } , } ) ; } defineHasInstances ( context ) ; let exports = { } ; let bundleSize = 0 ; bundleSize += Buffer . byteLength ( blueprint . code ) ; if ( linker ) { exports = await this . runAsModule ( context , blueprint , linker . linker ) ; } else { this . runAsScript ( context , blueprint ) ; } if ( linker ) bundleSize += linker . referencedPathsTotalSize ; const watch = linker && [ ... linker . referencedPaths ] ; return { exports , bundleSize , watch } ; } }