Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
fix(esm): fix source maps in esm loader (#38584)
Pavel Feldmanad994617f26e
diff --git a/packages/playwright/src/transform/esmLoader.ts b/packages/playwright/src/transform/esmLoader.tsindex d32537be5e..2d8622bac8 100644--- a/packages/playwright/src/transform/esmLoader.ts+++ b/packages/playwright/src/transform/esmLoader.ts@@ -22,9 +22,14 @@ import { PortTransport } from './portTransport';import { resolveHook, setSingleTSConfig, setTransformConfig, shouldTransform, transformHook } from './transform';import { fileIsModule } from '../util';+// Before each import of the ESM module, a preflight request with the .esm.preflight extension is issued.+// When handled, it is resolved similarly to the reqular import, but loading it yields empty content.+const esmPreflightExtension = '.esm.preflight';+// Node < 18.6: defaultResolve takes 3 arguments.// Node >= 18.6: nextResolve from the chain takes 2 arguments.-async function resolve(specifier: string, context: { parentURL?: string }, defaultResolve: Function) {+async function resolve(originalSpecifier: string, context: { parentURL?: string }, defaultResolve: Function) {+ let specifier = originalSpecifier.replace(esmPreflightExtension, '');if (context.parentURL && context.parentURL.startsWith('file://')) {const filename = url.fileURLToPath(context.parentURL);const resolved = resolveHook(filename, specifier);@@ -37,6 +42,8 @@ async function resolve(specifier: string, context: { parentURL?: string }, defauif (result?.url && result.url.startsWith('file://'))currentFileDepsCollector()?.add(url.fileURLToPath(result.url));+ if (originalSpecifier.endsWith(esmPreflightExtension))+ result.url = result.url + esmPreflightExtension;return result;}@@ -54,7 +61,8 @@ const kSupportedFormats = new Map([// Node < 18.6: defaultLoad takes 3 arguments.// Node >= 18.6: nextLoad from the chain takes 2 arguments.-async function load(moduleUrl: string, context: { format?: string }, defaultLoad: Function) {+async function load(originalModuleUrl: string, context: { format?: string }, defaultLoad: Function) {+ const moduleUrl = originalModuleUrl.replace(esmPreflightExtension, '');// Bail out for wasm, json, etc.if (!kSupportedFormats.has(context.format))return defaultLoad(moduleUrl, context, defaultLoad);@@ -71,29 +79,23 @@ async function load(moduleUrl: string, context: { format?: string }, defaultLoadconst code = fs.readFileSync(filename, 'utf-8');const transformed = transformHook(code, filename, moduleUrl);- // Flush the source maps to the main thread, so that errors during import() are source-mapped.- if (transformed.serializedCache) {- if (legacyWaitForSourceMaps)- await transport?.send('pushToCompilationCache', { cache: transformed.serializedCache });- else- transport?.post('pushToCompilationCache', { cache: transformed.serializedCache });- }+ // Flush the source maps to the main thread, so that errors after import() are source-mapped.+ if (transformed.serializedCache)+ transport?.post('pushToCompilationCache', { cache: transformed.serializedCache });// Output format is required, so we determine it manually when unknown.// shortCircuit is required by Node >= 18.6 to designate no more loaders should be called.return {format: kSupportedFormats.get(context.format) || (fileIsModule(filename) ? 'module' : 'commonjs'),- source: transformed.code,+ source: originalModuleUrl.endsWith(esmPreflightExtension) ? `void 0;` : transformed.code,shortCircuit: true,};}let transport: PortTransport | undefined;-let legacyWaitForSourceMaps = false;function initialize(data: { port: MessagePort }) {transport = createTransport(data?.port);- legacyWaitForSourceMaps = !!process.env.PLAYWRIGHT_WAIT_FOR_SOURCE_MAPS;}function createTransport(port: MessagePort) {diff --git a/packages/playwright/src/transform/transform.ts b/packages/playwright/src/transform/transform.tsindex 18a99b2b24..0aa637572b 100644--- a/packages/playwright/src/transform/transform.ts+++ b/packages/playwright/src/transform/transform.ts@@ -260,16 +260,20 @@ function calculateHash(content: string, filePath: string, isModule: boolean, pluexport async function requireOrImport(file: string) {installTransformIfNeeded();const isModule = fileIsModule(file);- const esmImport = () => eval(`import(${JSON.stringify(url.pathToFileURL(file))})`);if (isModule) {- return await esmImport().finally(async () => {- // Compilation cache, which includes source maps, is populated in a post task.- // When importing a module results in an error, the very next access to `error.stack`- // will need source maps. To make sure source maps have arrived, we insert a task- // that will be processed after compilation cache and guarantee that- // source maps are available, before `error.stack` is accessed.- await new Promise(resolve => setTimeout(resolve, 0));- });+ const fileName = url.pathToFileURL(file);+ const esmImport = () => eval(`import(${JSON.stringify(fileName)})`);++ // For ESM imports, issue a preflight to populate the compilation cache with the+ // source maps. This allows inline test() calls to resolve wrapFunctionWithLocation.+ await eval(`import(${JSON.stringify(fileName + '.esm.preflight')})`).finally(nextTask);++ // Compilation cache, which includes source maps, is populated in a post task.+ // When importing a module results in an error, the very next access to `error.stack`+ // will need source maps. To make sure source maps have arrived, we insert a task+ // that will be processed after compilation cache and guarantee that+ // source maps are available, before `error.stack` is accessed.+ return await esmImport().finally(nextTask);}const result = require(file);const depsCollector = currentFileDepsCollector();@@ -344,3 +348,7 @@ export function wrapFunctionWithLocation<A extends any[], R>(func: (location: Lofunction isRelativeSpecifier(specifier: string) {return specifier === '.' || specifier === '..' || specifier.startsWith('./') || specifier.startsWith('../');}++async function nextTask() {+ return new Promise(resolve => setTimeout(resolve, 0));+}