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): dont bail for preflight requests (#39237)

Simon Knott23b2c1599085
diff --git a/packages/playwright/src/transform/esmLoader.ts b/packages/playwright/src/transform/esmLoader.ts
index 2d8622bac8..57e8ab6cbf 100644
--- a/packages/playwright/src/transform/esmLoader.ts
+++ b/packages/playwright/src/transform/esmLoader.ts
@@ -61,8 +61,7 @@ const kSupportedFormats = new Map([
// Node < 18.6: defaultLoad takes 3 arguments.
// Node >= 18.6: nextLoad from the chain takes 2 arguments.
-async function load(originalModuleUrl: string, context: { format?: string }, defaultLoad: Function) {
- const moduleUrl = originalModuleUrl.replace(esmPreflightExtension, '');
+async function load(moduleUrl: string, context: { format?: string }, defaultLoad: Function) {
// Bail out for wasm, json, etc.
if (!kSupportedFormats.has(context.format))
return defaultLoad(moduleUrl, context, defaultLoad);
@@ -72,12 +71,17 @@ async function load(originalModuleUrl: string, context: { format?: string }, def
return defaultLoad(moduleUrl, context, defaultLoad);
const filename = url.fileURLToPath(moduleUrl);
+ const isPreflight = moduleUrl.endsWith(esmPreflightExtension);
+
// Bail for node_modules.
if (!shouldTransform(filename))
return defaultLoad(moduleUrl, context, defaultLoad);
- const code = fs.readFileSync(filename, 'utf-8');
- const transformed = transformHook(code, filename, moduleUrl);
+ const originalModuleUrl = isPreflight ? moduleUrl.slice(0, -esmPreflightExtension.length) : moduleUrl;
+ const originalFilename = isPreflight ? url.fileURLToPath(originalModuleUrl) : filename;
+
+ const code = fs.readFileSync(originalFilename, 'utf-8');
+ const transformed = transformHook(code, originalFilename, originalModuleUrl);
// Flush the source maps to the main thread, so that errors after import() are source-mapped.
if (transformed.serializedCache)
@@ -86,8 +90,8 @@ async function load(originalModuleUrl: string, context: { format?: string }, def
// 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: originalModuleUrl.endsWith(esmPreflightExtension) ? `void 0;` : transformed.code,
+ format: kSupportedFormats.get(context.format) || (fileIsModule(originalFilename) ? 'module' : 'commonjs'),
+ source: isPreflight ? `void 0;` : transformed.code,
shortCircuit: true,
};
}
diff --git a/packages/playwright/src/transform/transform.ts b/packages/playwright/src/transform/transform.ts
index 862023cc5f..82fd4d86f7 100644
--- a/packages/playwright/src/transform/transform.ts
+++ b/packages/playwright/src/transform/transform.ts
@@ -22,7 +22,7 @@ import url from 'url';
import crypto from 'crypto';
import { loadTsConfig } from '../third_party/tsconfig-loader';
-import { createFileMatcher, fileIsModule, resolveImportSpecifierAfterMapping } from '../util';
+import { createFileMatcher, debugTest, fileIsModule, resolveImportSpecifierAfterMapping } from '../util';
import { sourceMapSupport } from '../utilsBundle';
import { belongsToNodeModules, currentFileDepsCollector, getFromCompilationCache, installSourceMapSupport } from './compilationCache';
import { addHook } from '../third_party/pirates';
@@ -276,7 +276,9 @@ export async function requireOrImport(file: string) {
// 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);
+ await eval(`import(${JSON.stringify(fileName + '.esm.preflight')})`)
+ .catch((error: any) => debugTest('Failed to load preflight for ' + file + ', source maps may be missing for errors thrown during loading.', error))
+ .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`
diff --git a/tests/playwright-test/loader.spec.ts b/tests/playwright-test/loader.spec.ts
index 4372b25245..fcc56e0c79 100644
--- a/tests/playwright-test/loader.spec.ts
+++ b/tests/playwright-test/loader.spec.ts
@@ -16,6 +16,7 @@
import { test, expect, playwrightCtConfigText } from './playwright-test-fixtures';
import path from 'path';
+import url from 'url';
test('should return the location of a syntax error', async ({ runInlineTest }) => {
const result = await runInlineTest({
@@ -1161,3 +1162,157 @@ test('should dynamically import re-exported cjs namespace', {
expect(result.exitCode).toBe(0);
expect(result.passed).toBe(1);
});
+
+test('should compose with a custom ESM loader before playwright', {
+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/39172' },
+}, async ({ runInlineTest }, testInfo) => {
+ const result = await runInlineTest({
+ 'package.json': JSON.stringify({ type: 'module' }),
+ 'custom-loader.mjs': `
+ export async function resolve(specifier, context, nextResolve) {
+ console.log('%% resolve ' + specifier);
+ return nextResolve(specifier, context);
+ }
+
+ export async function load(url, context, nextLoad) {
+ const result = await nextLoad(url, context);
+ console.log('%% load ' + url + ' source=' + result.source);
+ return result;
+ }
+ `,
+ 'playwright.config.ts': `
+ import { register } from 'node:module';
+ register('./custom-loader.mjs', import.meta.url);
+
+ import { defineConfig } from '@playwright/test';
+ export default defineConfig({
+ projects: [{ name: 'foo' }],
+ build: { external: ['*'] },
+ });
+ `,
+ 'a.test.js': `
+ import { test, expect } from '@playwright/test';
+ test('pass', () => {
+ expect(1 + 1).toBe(2);
+ });
+ `,
+ });
+
+ expect(result.exitCode).toBe(0);
+ expect(result.passed).toBe(1);
+ const testFile = url.pathToFileURL(testInfo.outputPath('a.test.js')).toString();
+ const expectedSequence = [
+ `resolve ${testFile}.esm.preflight`,
+ // no load for preflight, it falls through to the node default loader which cannot resolve it and thus errors out
+ `resolve ${testFile}`,
+ `load ${testFile} source=`,
+ `resolve @playwright/test`,
+ ];
+ expect(result.outputLines).toEqual([
+ ...expectedSequence, // test collection
+ ...expectedSequence, // worker
+ ]);
+});
+
+test('should compose with a custom ESM loader after playwright', {
+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/39172' },
+}, async ({ runInlineTest }, testInfo) => {
+ const result = await runInlineTest({
+ 'package.json': JSON.stringify({ type: 'module' }),
+ 'custom-loader.mjs': `
+ import fs from 'node:fs';
+ import { fileURLToPath } from 'url';
+ const outputDir = ${JSON.stringify(url.pathToFileURL(testInfo.outputDir).toString())};
+ export async function resolve(specifier, context, nextResolve) {
+ if (specifier.startsWith(outputDir)) {
+ console.log('%% resolve ' + specifier);
+ fs.readFileSync(fileURLToPath(specifier)); // throw if file does not exist
+ }
+ return nextResolve(specifier, context);
+ }
+
+ export async function load(url, context, nextLoad) {
+ const result = await nextLoad(url, context);
+ if (url.startsWith(outputDir)) {
+ console.log('%% load ' + url + ' source=' + result.source);
+ fs.readFileSync(fileURLToPath(url)); // throw if file does not exist
+ }
+ return result;
+ }
+ `,
+ 'register-loader.mjs': `
+ import { register } from 'node:module';
+ register('./custom-loader.mjs', import.meta.url);
+ `,
+ 'playwright.config.ts': `
+ import { defineConfig } from '@playwright/test';
+ export default defineConfig({
+ projects: [{ name: 'foo' }],
+ build: { external: ['*'] },
+ });
+ `,
+ 'a.test.js': `
+ import { test, expect } from '@playwright/test';
+ test('pass', () => {
+ expect(1 + 1).toBe(2);
+ });
+ `,
+ }, {}, {
+ NODE_OPTIONS: `--import ${url.pathToFileURL(testInfo.outputPath('register-loader.mjs')).toString()}`,
+ });
+
+ expect(result.exitCode).toBe(0);
+ expect(result.passed).toBe(1);
+ const outputDir = url.pathToFileURL(testInfo.outputDir).toString();
+ const expectedSequence = [
+ `resolve ${outputDir}/playwright.config.ts`,
+ `resolve ${outputDir}/playwright.config.ts`,
+ `resolve ${outputDir}/a.test.js`,
+ `resolve ${outputDir}/a.test.js`,
+ `load ${outputDir}/a.test.js source=`,
+ ];
+ expect(result.outputLines).toEqual([
+ ...expectedSequence, // test collection
+ ...expectedSequence, // worker
+ ]);
+});
+
+test('preflight should survive faulty ESM loader ahead of playwright', {
+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/39172' },
+}, async ({ runInlineTest }) => {
+ const result = await runInlineTest({
+ 'package.json': JSON.stringify({ type: 'module' }),
+ 'custom-loader.mjs': `
+ export async function resolve(specifier, context, nextResolve) {
+ if (specifier.endsWith('.esm.preflight'))
+ throw new Error('could not find file, what the heck is preflight?');
+ return nextResolve(specifier, context);
+ }
+
+ export async function load(url, context, nextLoad) {
+ return await nextLoad(url, context);
+ }
+ `,
+ 'playwright.config.ts': `
+ import { register } from 'node:module';
+ register('./custom-loader.mjs', import.meta.url);
+
+ import { defineConfig } from '@playwright/test';
+ export default defineConfig({
+ projects: [{ name: 'foo' }],
+ build: { external: ['*'] },
+ });
+ `,
+ 'a.test.js': `
+ import { test, expect } from '@playwright/test';
+ test('pass', () => {
+ expect(1 + 1).toBe(2);
+ });
+ `,
+ }, {}, { DEBUG: 'pw:test' });
+
+ expect(result.exitCode).toBe(0);
+ expect(result.passed).toBe(1);
+ expect(result.output).toContain('Failed to load preflight');
+ expect(result.output).toContain('what the heck is preflight');
+});