Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 9 additions & 27 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions packages/playwright/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,13 @@
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.65.0-next"
},
"peerDependencies": {
"esbuild": ">=0.21.5"
},
"peerDependenciesMeta": {
"esbuild": {
"optional": true
}
}
}
92 changes: 92 additions & 0 deletions packages/playwright/src/transform/esbuildTransform.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import path from 'path';

import { libPath } from '../package';

import type * as esbuild from 'esbuild';
import type { JsxOptions } from './babelBundle';

export type Esbuild = typeof esbuild;

export function loadEsbuild(): Esbuild {
try {
return require('esbuild');
} catch (error) {
throw new Error(`PLAYWRIGHT_EXPERIMENTAL_ESBUILD requires the "esbuild" package, install it with "npm install --save-dev esbuild"`, { cause: error });
}
}

export function esbuildTransform(esbuild: Esbuild, code: string, filename: string, isModule: boolean, useDefineForClassFields: boolean, jsx: JsxOptions | undefined): { code: string, map: any } {
const options = transformOptions(filename, isModule, useDefineForClassFields, jsx);
let result: esbuild.TransformResult;
try {
result = transformSync(esbuild, code, options);
} catch (error) {
throw toSyntaxError(error, code, filename);
}
return { code: result.code, map: JSON.parse(result.map) };
}

function transformOptions(filename: string, isModule: boolean, useDefineForClassFields: boolean, jsx: JsxOptions | undefined): esbuild.TransformOptions {
const ext = path.extname(filename);
const jsxMode = jsx?.jsx ?? 'react-jsx';
return {
sourcefile: filename,
loader: ext === '.tsx' ? 'tsx' : ['.ts', '.mts', '.cts'].includes(ext) ? 'ts' : 'jsx',
format: isModule ? 'esm' : 'cjs',
platform: 'node',
target: 'node' + process.versions.node.split('-')[0],
sourcemap: 'both',
jsx: jsxMode === 'react' ? 'transform' : 'automatic',
jsxDev: jsxMode === 'react-jsxdev',
jsxFactory: jsx?.jsxFactory,
jsxFragment: jsx?.jsxFragmentFactory,
jsxImportSource: jsx?.jsxImportSource,
tsconfigRaw: {
compilerOptions: {
useDefineForClassFields,
alwaysStrict: true,
},
},
logLevel: 'silent',
};
}

function transformSync(esbuild: Esbuild, code: string, options: esbuild.TransformOptions): esbuild.TransformResult {
try {
return esbuild.transformSync(code, options);
} catch (error) {
// Ctrl+C terminates esbuild's service process along with the whole process group.
if (!(error instanceof Error) || !/^The service (is no longer running|was stopped)/.test(error.message))
throw error;
void esbuild.stop();
return esbuild.transformSync(code, options);
}
}

function toSyntaxError(error: any, code: string, filename: string): Error {
const message: esbuild.Message | undefined = error?.errors?.[0];
if (!message?.location)
return error;
const { line, column } = message.location;
const { codeFrameColumns } = require(libPath('transform', 'babelBundle'));
const codeFrame = codeFrameColumns(code, { start: { line, column: column + 1 } });
const syntaxError = new SyntaxError(`${filename}: ${message.text} (${line}:${column})\n\n${codeFrame}`);
(syntaxError as any).loc = { line, column };
return syntaxError;
}
14 changes: 12 additions & 2 deletions packages/playwright/src/transform/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { loadTsConfig } from './tsconfig-loader';
import { libPath, packageJSON } from '../package';
import { createFileMatcher, debugTest, fileIsModule, resolveImportSpecifierAfterMapping } from '../util';
import * as cc from './compilationCache';
import { esbuildTransform, loadEsbuild } from './esbuildTransform';
import * as esmLoaderSync from './esmLoaderSync';
import { addHook } from './pirates';
import { PortTransport } from './portTransport';
Expand Down Expand Up @@ -230,7 +231,9 @@ export function shouldTransform(filename: string): boolean {
}

export function transformHook(originalCode: string, filename: string, moduleUrl?: string): { code: string, serializedCache?: any } {
const esbuild = process.env.PLAYWRIGHT_EXPERIMENTAL_ESBUILD ? loadEsbuild() : undefined;
const hasPreprocessor =
!esbuild &&
process.env.PW_TEST_SOURCE_TRANSFORM &&
process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE &&
process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE.split(pathSeparator).some(f => filename.startsWith(f));
Expand All @@ -239,11 +242,17 @@ export function transformHook(originalCode: string, filename: string, moduleUrl?
const jsx = tsconfigs.find(tsconfig => tsconfig.jsx)?.jsx;
// Without "target", tsc defaults to the latest one, which defines class fields.
const useDefineForClassFields = tsconfigs.find(tsconfig => tsconfig.useDefineForClassFields !== undefined)?.useDefineForClassFields ?? true;
const hash = calculateHash(originalCode, filename, !!moduleUrl, pluginsEpilogue, useDefineForClassFields, jsx);
const hash = calculateHash(originalCode, filename, !!moduleUrl, pluginsEpilogue, useDefineForClassFields, jsx, esbuild?.version);
const { cachedCode, addToCache, serializedCache } = cc.getFromCompilationCache(filename, hash, moduleUrl);
if (cachedCode !== undefined)
return { code: cachedCode, serializedCache };

if (esbuild) {
const { code, map } = esbuildTransform(esbuild, originalCode, filename, !!moduleUrl, useDefineForClassFields, jsx);
const added = addToCache!(code, map);
return { code, serializedCache: added.serializedCache };
}

// We don't use any browserslist data, but babel checks it anyway.
// Silence the annoying warning.
process.env.BROWSERSLIST_IGNORE_OLD_DATA = 'true';
Expand All @@ -257,7 +266,7 @@ export function transformHook(originalCode: string, filename: string, moduleUrl?
return { code, serializedCache: added.serializedCache };
}

function calculateHash(content: string, filePath: string, isModule: boolean, pluginsEpilogue: BabelPlugin[], useDefineForClassFields: boolean, jsx: JsxOptions | undefined): string {
function calculateHash(content: string, filePath: string, isModule: boolean, pluginsEpilogue: BabelPlugin[], useDefineForClassFields: boolean, jsx: JsxOptions | undefined, esbuildVersion: string | undefined): string {
const hash = crypto.createHash('sha1')
.update(isModule ? 'esm' : 'no_esm')
.update(content)
Expand All @@ -266,6 +275,7 @@ function calculateHash(content: string, filePath: string, isModule: boolean, plu
.update(pluginsEpilogue.map(p => p[0]).join(','))
.update(useDefineForClassFields ? 'define' : 'assign')
.update(jsx ? JSON.stringify(jsx) : '')
.update(esbuildVersion ? 'esbuild@' + esbuildVersion : '')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT: should this also include the node version (see the process.versions.node.split('-')[0] above) so that if the developer switches node without updating playwright we wont attempt to reuse the same code?

.digest('hex');
return hash;
}
Expand Down
Loading
Loading