From 25fa8562ae110ca3b558893470568699fe14aa1d Mon Sep 17 00:00:00 2001 From: Yen-Chi Chen Date: Sun, 3 May 2020 11:36:17 +0200 Subject: [PATCH] async version of transform() --- .../jest-transform/src/ScriptTransformer.ts | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/packages/jest-transform/src/ScriptTransformer.ts b/packages/jest-transform/src/ScriptTransformer.ts index 6241b4255f73..57f573d9a601 100644 --- a/packages/jest-transform/src/ScriptTransformer.ts +++ b/packages/jest-transform/src/ScriptTransformer.ts @@ -630,6 +630,54 @@ export default class ScriptTransformer { } + private async _transformAndBuildScriptAsync( + filename: Config.Path, + options: Options, + instrument: boolean, + fileSource?: string, + ): Promise { + const { + isCoreModule, + isInternalModule, + supportsDynamicImport, + supportsStaticESM, + } = options; + const content = stripShebang( + fileSource || fs.readFileSync(filename, 'utf8'), + ); + + let code = content; + let sourceMapPath: string | null = null; + + const willTransform = + !isInternalModule && + !isCoreModule && + (this.shouldTransform(filename) || instrument); + + try { + if (willTransform) { + const transformedSource = await this.transformSourceAsync( + filename, + content, + instrument, + supportsDynamicImport, + supportsStaticESM, + ); + + code = transformedSource.code; + sourceMapPath = transformedSource.sourceMapPath; + } + + return { + code, + originalCode: content, + sourceMapPath, + }; + } catch (e) { + throw handlePotentialSyntaxError(e); + } + } + private _transformAndBuildScript( filename: Config.Path, options: Options, @@ -678,6 +726,40 @@ export default class ScriptTransformer { } } + + async transformAsync( + filename: Config.Path, + options: Options, + fileSource?: string, + ): Promise { + let scriptCacheKey = undefined; + let instrument = false; + + if (!options.isCoreModule) { + instrument = + options.coverageProvider === 'babel' && + shouldInstrument(filename, options, this._config); + scriptCacheKey = getScriptCacheKey(filename, instrument); + const result = this._cache.transformedFiles.get(scriptCacheKey); + if (result) { + return result; + } + } + + const result = await this._transformAndBuildScriptAsync( + filename, + options, + instrument, + fileSource, + ); + + if (scriptCacheKey) { + this._cache.transformedFiles.set(scriptCacheKey, result); + } + + return result; + } + transform( filename: Config.Path, options: Options,