11import * as worker from "monaco-editor/esm/vs/editor/editor.worker" ;
22import { TypeScriptWorker } from "monaco-editor/esm/vs/language/typescript/tsWorker" ;
3+ import * as ts from "typescript" ;
34import * as tstl from "typescript-to-lua" ;
45
56// Mock unsupported in path-browserify@0.0.1 parse and format functions used for normalization in
@@ -18,13 +19,15 @@ const emitHost: tstl.EmitHost = {
1819
1920 return libContext ( `./${ featureName } .lua` ) . default ;
2021 } ,
22+ writeFile ( ) { } ,
2123} ;
2224
25+ const transpiler = new tstl . Transpiler ( { emitHost } ) ;
26+
2327export class CustomTypeScriptWorker extends TypeScriptWorker {
2428 public async getTranspileOutput ( fileName : string ) {
25- const { transpiledFiles } = this . transpileLua ( fileName ) ;
26- const [ file ] = transpiledFiles ;
27- return { lua : file . lua ! , ast : file . luaAst ! , sourceMap : file . sourceMap ! } ;
29+ const { ast, lua, sourceMap } = this . transpileLua ( fileName ) ;
30+ return { ast, lua, sourceMap } ;
2831 }
2932
3033 public async getSemanticDiagnostics ( fileName : string ) {
@@ -38,13 +41,43 @@ export class CustomTypeScriptWorker extends TypeScriptWorker {
3841
3942 private transpileLua ( fileName : string ) {
4043 const program = this . _languageService . getProgram ( ) ! ;
44+ const sourceFile = program . getSourceFile ( fileName ) ! ;
4145
4246 const compilerOptions : tstl . CompilerOptions = program . getCompilerOptions ( ) ;
4347 compilerOptions . rootDir = "inmemory://model/" ;
4448 compilerOptions . luaLibImport = tstl . LuaLibImportKind . Inline ;
4549 compilerOptions . luaTarget = tstl . LuaTarget . Lua53 ;
50+ compilerOptions . sourceMap = true ;
51+
52+ let ast ! : tstl . Block ;
53+ let lua ! : string ;
54+ let sourceMap ! : string ;
55+ const { diagnostics } = transpiler . emit ( {
56+ program,
57+ sourceFiles : [ sourceFile ] ,
58+ writeFile ( fileName , data , _writeBOM , _onError , sourceFiles = [ ] ) {
59+ if ( ! sourceFiles . includes ( sourceFile ) ) return ;
60+ if ( fileName . endsWith ( ".lua" ) ) lua = data ;
61+ if ( fileName . endsWith ( ".lua.map" ) ) sourceMap = data ;
62+ } ,
63+ plugins : [
64+ {
65+ visitors : {
66+ [ ts . SyntaxKind . SourceFile ] ( node , context ) {
67+ const [ file ] = context . superTransformNode ( node ) as [ tstl . Block ] ;
68+
69+ if ( node === sourceFile ) {
70+ ast = file ;
71+ }
72+
73+ return file ;
74+ } ,
75+ } ,
76+ } ,
77+ ] ,
78+ } ) ;
4679
47- return tstl . transpile ( { program , emitHost , sourceFiles : [ program . getSourceFile ( fileName ) ! ] } ) ;
80+ return { diagnostics , ast , lua , sourceMap } ;
4881 }
4982}
5083
0 commit comments