From 938b2488662e8416d483a4f61a7b60e693f67a84 Mon Sep 17 00:00:00 2001 From: n4o847 <22975590+n4o847@users.noreply.github.com> Date: Tue, 8 Dec 2020 23:39:12 +0900 Subject: [PATCH] Don't create a temporary file --- src/index.ts | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/src/index.ts b/src/index.ts index 9ff3956..437faec 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,10 +1,7 @@ import * as ts from 'typescript'; -import { promises as fs } from 'fs'; import * as tmp from 'tmp-promise'; import * as path from 'path'; -tmp.setGracefulCleanup(); - interface RunOptions { input: Buffer; } @@ -14,19 +11,32 @@ interface RunResult { } export async function run(fileName: string, { input = Buffer.of() }: Partial = {}): Promise { - const { path: callerFileName, cleanup } = await tmp.file({ prefix: `compile-time-typescript`, postfix: `caller.ts` }); - await fs.writeFile(callerFileName, ` + const callerFileName = await tmp.tmpName({ prefix: `compile-time-typescript`, postfix: `caller.ts` }); + const callerSourceFile = ts.createSourceFile(callerFileName, ` import Main from ${JSON.stringify(path.resolve(fileName).replace(/\.ts$/, ''))}; type Input = ${JSON.stringify(input.toString('binary'))}; type Output = Main; - `); + `, ts.ScriptTarget.Latest); + + const defaultCompilerHost = ts.createCompilerHost({}); + const customCompilerHost: ts.CompilerHost = { + ...defaultCompilerHost, + getSourceFile(fileName: string, languageVersion: ts.ScriptTarget, onError?: ((message: string) => void), shouldCreateNewSourceFile?: boolean): ts.SourceFile | undefined { + if (fileName === callerFileName) { + return callerSourceFile; + } else { + return defaultCompilerHost.getSourceFile.call(this, fileName, languageVersion, onError, shouldCreateNewSourceFile); + } + }, + }; + const program = ts.createProgram({ rootNames: [callerFileName], options: { strict: true, }, + host: customCompilerHost, }); - const source = program.getSourceFile(callerFileName)!; const checker = program.getTypeChecker(); const outputList: Buffer[] = []; @@ -43,8 +53,8 @@ export async function run(fileName: string, { input = Buffer.of() }: Partial