Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

fix(esm): prevent ESM loading deadlock in certain import chains (#35933)

Adam Gastineaue4f0d9503b50
diff --git a/packages/playwright/src/transform/esmLoader.ts b/packages/playwright/src/transform/esmLoader.ts
index a74b20110d..f12e054cf2 100644
--- a/packages/playwright/src/transform/esmLoader.ts
+++ b/packages/playwright/src/transform/esmLoader.ts
@@ -17,10 +17,16 @@
import fs from 'fs';
import url from 'url';
+import { monotonicTime, raceAgainstDeadline } from 'playwright-core/lib/utils';
+
import { addToCompilationCache, currentFileDepsCollector, serializeCompilationCache, startCollectingFileDeps, stopCollectingFileDeps } from './compilationCache';
import { PortTransport } from './portTransport';
import { resolveHook, setSingleTSConfig, setTransformConfig, shouldTransform, transformHook } from './transform';
-import { fileIsModule } from '../util';
+import { debugTest, fileIsModule } from '../util';
+
+// See note on pushToCompilationCache()
+// Once we enter a deadlock scenario, we will fallback to unawaited IPC
+let workerShouldFallbackCompilationCache = false;
// Node < 18.6: defaultResolve takes 3 arguments.
// Node >= 18.6: nextResolve from the chain takes 2 arguments.
@@ -72,8 +78,8 @@ async function load(moduleUrl: string, context: { format?: string }, defaultLoad
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)
- await transport?.send('pushToCompilationCache', { cache: transformed.serializedCache });
+ if (transformed.serializedCache && transport)
+ await pushToCompilationCache(transport, 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.
@@ -84,6 +90,23 @@ async function load(moduleUrl: string, context: { format?: string }, defaultLoad
};
}
+// Under certain conditions with ESM -> CJS -> any imports, we can enter deadlock awaiting the
+// MessagePort transfer simultaneously with the Node.js worker thread that is performing the load().
+// Attempt to await the IPC transfer, and if it takes too long, fallback to a non-awaiting transfer
+async function pushToCompilationCache(transport: PortTransport, cache: any) {
+ if (workerShouldFallbackCompilationCache) {
+ transport.send('pushToCompilationCache', { cache })
+ .catch(e => debugTest('Failed to push compilation cache', e));
+ return;
+ }
+
+ const { timedOut } = await raceAgainstDeadline(() => transport.send('pushToCompilationCache', { cache }), monotonicTime() + 1000);
+ if (timedOut) {
+ debugTest('Falling back to unawaited compilation cache');
+ workerShouldFallbackCompilationCache = true;
+ }
+}
+
let transport: PortTransport | undefined;
function initialize(data: { port: MessagePort }) {
diff --git a/tests/playwright-test/esm.spec.ts b/tests/playwright-test/esm.spec.ts
index 9f567b0f44..dcf2467b40 100644
--- a/tests/playwright-test/esm.spec.ts
+++ b/tests/playwright-test/esm.spec.ts
@@ -35,6 +35,35 @@ test('should load nested as esm when package.json has type module', async ({ run
expect(result.passed).toBe(1);
});
+test('should load esm -> cjs -> cjs require tree', async ({ runInlineTest }) => {
+ test.setTimeout(10000);
+ const result = await runInlineTest({
+ 'playwright.config.js': `
+ export default { projects: [{name: 'foo'}] };
+ `,
+ 'package.json': JSON.stringify({ type: 'module' }),
+ 'a.esm.test.js': `
+ import { test, expect } from '@playwright/test';
+ import * as root from './nested/root_require.js';
+ test('check project name', ({}, testInfo) => {
+ console.log('root', root);
+ expect(testInfo.project.name).toBe('foo');
+ });
+ `,
+ 'nested/package.json': JSON.stringify({ type: 'commonjs' }),
+ 'nested/root_require.js': `
+ const nested = require('./nested_require.js');
+ console.log(nested);
+ `,
+ 'nested/nested_require.js': `
+ console.log('nested require');
+ `,
+ });
+
+ expect(result.exitCode).toBe(0);
+ expect(result.passed).toBe(1);
+});
+
test('should support import attributes', async ({ runInlineTest }) => {
const result = await runInlineTest({
'playwright.config.ts': `