screenshot/test_1

This commit is contained in:
ramkumarp
2025-03-27 11:21:02 +00:00
commit 616d466383
470 changed files with 144705 additions and 0 deletions

28
node_modules/playwright/lib/transform/babelBundle.js generated vendored Normal file
View File

@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.types = exports.traverse = exports.declare = exports.codeFrameColumns = exports.babelTransform = exports.babelParse = void 0;
/**
* 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.
*/
const codeFrameColumns = exports.codeFrameColumns = require('./babelBundleImpl').codeFrameColumns;
const declare = exports.declare = require('./babelBundleImpl').declare;
const types = exports.types = require('./babelBundleImpl').types;
const traverse = exports.traverse = require('./babelBundleImpl').traverse;
const babelTransform = exports.babelTransform = require('./babelBundleImpl').babelTransform;
const babelParse = exports.babelParse = require('./babelBundleImpl').babelParse;

2032
node_modules/playwright/lib/transform/babelBundleImpl.js generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,254 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.addToCompilationCache = addToCompilationCache;
exports.affectedTestFiles = affectedTestFiles;
exports.belongsToNodeModules = belongsToNodeModules;
exports.cacheDir = void 0;
exports.collectAffectedTestFiles = collectAffectedTestFiles;
exports.currentFileDepsCollector = currentFileDepsCollector;
exports.dependenciesForTestFile = dependenciesForTestFile;
exports.fileDependenciesForTest = fileDependenciesForTest;
exports.getFromCompilationCache = getFromCompilationCache;
exports.getUserData = getUserData;
exports.installSourceMapSupport = installSourceMapSupport;
exports.internalDependenciesForTestFile = internalDependenciesForTestFile;
exports.serializeCompilationCache = serializeCompilationCache;
exports.setExternalDependencies = setExternalDependencies;
exports.startCollectingFileDeps = startCollectingFileDeps;
exports.stopCollectingFileDeps = stopCollectingFileDeps;
var _fs = _interopRequireDefault(require("fs"));
var _os = _interopRequireDefault(require("os"));
var _path = _interopRequireDefault(require("path"));
var _globals = require("../common/globals");
var _utilsBundle = require("../utilsBundle");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
* 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.
*/
// Assumptions for the compilation cache:
// - Files in the temp directory we work with can disappear at any moment, either some of them or all together.
// - Multiple workers can be trying to read from the compilation cache at the same time.
// - There is a single invocation of the test runner at a time.
//
// Therefore, we implement the following logic:
// - Never assume that file is present, always try to read it to determine whether it's actually present.
// - Never write to the cache from worker processes to avoid "multiple writers" races.
// - Since we perform all static imports in the runner beforehand, most of the time
// workers should be able to read from the cache.
// - For workers-only dynamic imports or some cache problems, we will re-transpile files in
// each worker anew.
const cacheDir = exports.cacheDir = process.env.PWTEST_CACHE_DIR || ((_process$geteuid, _process) => {
if (process.platform === 'win32') return _path.default.join(_os.default.tmpdir(), `playwright-transform-cache`);
// Use `geteuid()` instead of more natural `os.userInfo().username`
// since `os.userInfo()` is not always available.
// Note: `process.geteuid()` is not available on windows.
// See https://github.com/microsoft/playwright/issues/22721
return _path.default.join(_os.default.tmpdir(), `playwright-transform-cache-` + ((_process$geteuid = (_process = process).geteuid) === null || _process$geteuid === void 0 ? void 0 : _process$geteuid.call(_process)));
})();
const sourceMaps = new Map();
const memoryCache = new Map();
// Dependencies resolved by the loader.
const fileDependencies = new Map();
// Dependencies resolved by the external bundler.
const externalDependencies = new Map();
function installSourceMapSupport() {
Error.stackTraceLimit = 200;
_utilsBundle.sourceMapSupport.install({
environment: 'node',
handleUncaughtExceptions: false,
retrieveSourceMap(source) {
if (!sourceMaps.has(source)) return null;
const sourceMapPath = sourceMaps.get(source);
try {
return {
map: JSON.parse(_fs.default.readFileSync(sourceMapPath, 'utf-8')),
url: source
};
} catch {
return null;
}
}
});
}
function _innerAddToCompilationCacheAndSerialize(filename, entry) {
sourceMaps.set(entry.moduleUrl || filename, entry.sourceMapPath);
memoryCache.set(filename, entry);
return {
sourceMaps: [[entry.moduleUrl || filename, entry.sourceMapPath]],
memoryCache: [[filename, entry]],
fileDependencies: [],
externalDependencies: []
};
}
function getFromCompilationCache(filename, hash, moduleUrl) {
// First check the memory cache by filename, this cache will always work in the worker,
// because we just compiled this file in the loader.
const cache = memoryCache.get(filename);
if (cache !== null && cache !== void 0 && cache.codePath) {
try {
return {
cachedCode: _fs.default.readFileSync(cache.codePath, 'utf-8')
};
} catch {
// Not able to read the file - fall through.
}
}
// Then do the disk cache, this cache works between the Playwright Test runs.
const cachePath = calculateCachePath(filename, hash);
const codePath = cachePath + '.js';
const sourceMapPath = cachePath + '.map';
const dataPath = cachePath + '.data';
try {
const cachedCode = _fs.default.readFileSync(codePath, 'utf8');
const serializedCache = _innerAddToCompilationCacheAndSerialize(filename, {
codePath,
sourceMapPath,
dataPath,
moduleUrl
});
return {
cachedCode,
serializedCache
};
} catch {}
return {
addToCache: (code, map, data) => {
if ((0, _globals.isWorkerProcess)()) return {};
_fs.default.mkdirSync(_path.default.dirname(cachePath), {
recursive: true
});
if (map) _fs.default.writeFileSync(sourceMapPath, JSON.stringify(map), 'utf8');
if (data.size) _fs.default.writeFileSync(dataPath, JSON.stringify(Object.fromEntries(data.entries()), undefined, 2), 'utf8');
_fs.default.writeFileSync(codePath, code, 'utf8');
const serializedCache = _innerAddToCompilationCacheAndSerialize(filename, {
codePath,
sourceMapPath,
dataPath,
moduleUrl
});
return {
serializedCache
};
}
};
}
function serializeCompilationCache() {
return {
sourceMaps: [...sourceMaps.entries()],
memoryCache: [...memoryCache.entries()],
fileDependencies: [...fileDependencies.entries()].map(([filename, deps]) => [filename, [...deps]]),
externalDependencies: [...externalDependencies.entries()].map(([filename, deps]) => [filename, [...deps]])
};
}
function addToCompilationCache(payload) {
for (const entry of payload.sourceMaps) sourceMaps.set(entry[0], entry[1]);
for (const entry of payload.memoryCache) memoryCache.set(entry[0], entry[1]);
for (const entry of payload.fileDependencies) {
const existing = fileDependencies.get(entry[0]) || [];
fileDependencies.set(entry[0], new Set([...entry[1], ...existing]));
}
for (const entry of payload.externalDependencies) {
const existing = externalDependencies.get(entry[0]) || [];
externalDependencies.set(entry[0], new Set([...entry[1], ...existing]));
}
}
function calculateCachePath(filePath, hash) {
const fileName = _path.default.basename(filePath, _path.default.extname(filePath)).replace(/\W/g, '') + '_' + hash;
return _path.default.join(cacheDir, hash[0] + hash[1], fileName);
}
// Since ESM and CJS collect dependencies differently,
// we go via the global state to collect them.
let depsCollector;
function startCollectingFileDeps() {
depsCollector = new Set();
}
function stopCollectingFileDeps(filename) {
if (!depsCollector) return;
depsCollector.delete(filename);
for (const dep of depsCollector) {
if (belongsToNodeModules(dep)) depsCollector.delete(dep);
}
fileDependencies.set(filename, depsCollector);
depsCollector = undefined;
}
function currentFileDepsCollector() {
return depsCollector;
}
function setExternalDependencies(filename, deps) {
const depsSet = new Set(deps.filter(dep => !belongsToNodeModules(dep) && dep !== filename));
externalDependencies.set(filename, depsSet);
}
function fileDependenciesForTest() {
return fileDependencies;
}
function collectAffectedTestFiles(changedFile, testFileCollector) {
const isTestFile = file => fileDependencies.has(file);
if (isTestFile(changedFile)) testFileCollector.add(changedFile);
for (const [testFile, deps] of fileDependencies) {
if (deps.has(changedFile)) testFileCollector.add(testFile);
}
for (const [importingFile, depsOfImportingFile] of externalDependencies) {
if (depsOfImportingFile.has(changedFile)) {
if (isTestFile(importingFile)) testFileCollector.add(importingFile);
for (const [testFile, depsOfTestFile] of fileDependencies) {
if (depsOfTestFile.has(importingFile)) testFileCollector.add(testFile);
}
}
}
}
function affectedTestFiles(changes) {
const result = new Set();
for (const change of changes) collectAffectedTestFiles(change, result);
return [...result];
}
function internalDependenciesForTestFile(filename) {
return fileDependencies.get(filename);
}
function dependenciesForTestFile(filename) {
const result = new Set();
for (const testDependency of fileDependencies.get(filename) || []) {
result.add(testDependency);
for (const externalDependency of externalDependencies.get(testDependency) || []) result.add(externalDependency);
}
for (const dep of externalDependencies.get(filename) || []) result.add(dep);
return result;
}
// This is only used in the dev mode, specifically excluding
// files from packages/playwright*. In production mode, node_modules covers
// that.
const kPlaywrightInternalPrefix = _path.default.resolve(__dirname, '../../../playwright');
function belongsToNodeModules(file) {
if (file.includes(`${_path.default.sep}node_modules${_path.default.sep}`)) return true;
if (file.startsWith(kPlaywrightInternalPrefix) && (file.endsWith('.js') || file.endsWith('.mjs'))) return true;
return false;
}
async function getUserData(pluginName) {
const result = new Map();
for (const [fileName, cache] of memoryCache) {
if (!cache.dataPath) continue;
if (!_fs.default.existsSync(cache.dataPath)) continue;
const data = JSON.parse(await _fs.default.promises.readFile(cache.dataPath, 'utf8'));
if (data[pluginName]) result.set(fileName, data[pluginName]);
}
return result;
}

117
node_modules/playwright/lib/transform/esmLoader.js generated vendored Normal file
View File

@@ -0,0 +1,117 @@
"use strict";
var _fs = _interopRequireDefault(require("fs"));
var _url = _interopRequireDefault(require("url"));
var _compilationCache = require("./compilationCache");
var _portTransport = require("./portTransport");
var _transform = require("./transform");
var _util = require("../util");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
* 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.
*/
// Node < 18.6: defaultResolve takes 3 arguments.
// Node >= 18.6: nextResolve from the chain takes 2 arguments.
async function resolve(specifier, context, defaultResolve) {
var _currentFileDepsColle;
if (context.parentURL && context.parentURL.startsWith('file://')) {
const filename = _url.default.fileURLToPath(context.parentURL);
const resolved = (0, _transform.resolveHook)(filename, specifier);
if (resolved !== undefined) specifier = _url.default.pathToFileURL(resolved).toString();
}
const result = await defaultResolve(specifier, context, defaultResolve);
// Note: we collect dependencies here that will be sent to the main thread
// (and optionally runner process) after the loading finishes.
if (result !== null && result !== void 0 && result.url && result.url.startsWith('file://')) (_currentFileDepsColle = (0, _compilationCache.currentFileDepsCollector)()) === null || _currentFileDepsColle === void 0 || _currentFileDepsColle.add(_url.default.fileURLToPath(result.url));
return result;
}
// Node < 18.6: defaultLoad takes 3 arguments.
// Node >= 18.6: nextLoad from the chain takes 2 arguments.
async function load(moduleUrl, context, defaultLoad) {
var _transport;
// Bail out for wasm, json, etc.
// non-js files have context.format === undefined
if (context.format !== 'commonjs' && context.format !== 'module' && context.format !== undefined) return defaultLoad(moduleUrl, context, defaultLoad);
// Bail for built-in modules.
if (!moduleUrl.startsWith('file://')) return defaultLoad(moduleUrl, context, defaultLoad);
const filename = _url.default.fileURLToPath(moduleUrl);
// Bail for node_modules.
if (!(0, _transform.shouldTransform)(filename)) return defaultLoad(moduleUrl, context, defaultLoad);
const code = _fs.default.readFileSync(filename, 'utf-8');
const transformed = (0, _transform.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 = transport) === null || _transport === void 0 ? void 0 : _transport.send('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: context.format || ((0, _util.fileIsModule)(filename) ? 'module' : 'commonjs'),
source: transformed.code,
shortCircuit: true
};
}
let transport;
// Node.js < 20
function globalPreload(context) {
transport = createTransport(context.port);
return `
globalThis.__esmLoaderPortPreV20 = port;
`;
}
// Node.js >= 20
function initialize(data) {
transport = createTransport(data === null || data === void 0 ? void 0 : data.port);
}
function createTransport(port) {
return new _portTransport.PortTransport(port, async (method, params) => {
if (method === 'setSingleTSConfig') {
(0, _transform.setSingleTSConfig)(params.tsconfig);
return;
}
if (method === 'setTransformConfig') {
(0, _transform.setTransformConfig)(params.config);
return;
}
if (method === 'addToCompilationCache') {
(0, _compilationCache.addToCompilationCache)(params.cache);
return;
}
if (method === 'getCompilationCache') return {
cache: (0, _compilationCache.serializeCompilationCache)()
};
if (method === 'startCollectingFileDeps') {
(0, _compilationCache.startCollectingFileDeps)();
return;
}
if (method === 'stopCollectingFileDeps') {
(0, _compilationCache.stopCollectingFileDeps)(params.file);
return;
}
});
}
module.exports = {
globalPreload,
initialize,
load,
resolve
};

32
node_modules/playwright/lib/transform/esmUtils.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.execArgvWithExperimentalLoaderOptions = execArgvWithExperimentalLoaderOptions;
exports.execArgvWithoutExperimentalLoaderOptions = execArgvWithoutExperimentalLoaderOptions;
var _url = _interopRequireDefault(require("url"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
* 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.
*/
const kExperimentalLoaderOptions = ['--no-warnings', `--experimental-loader=${_url.default.pathToFileURL(require.resolve('playwright/lib/transform/esmLoader')).toString()}`];
function execArgvWithExperimentalLoaderOptions() {
return [...process.execArgv, ...kExperimentalLoaderOptions];
}
function execArgvWithoutExperimentalLoaderOptions() {
return process.execArgv.filter(arg => !kExperimentalLoaderOptions.includes(arg));
}

81
node_modules/playwright/lib/transform/portTransport.js generated vendored Normal file
View File

@@ -0,0 +1,81 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PortTransport = void 0;
/**
* 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.
*/
class PortTransport {
constructor(port, handler) {
this._lastId = 0;
this._port = void 0;
this._callbacks = new Map();
this._port = port;
port.addEventListener('message', async event => {
const message = event.data;
const {
id,
ackId,
method,
params,
result
} = message;
if (id) {
const result = await handler(method, params);
this._port.postMessage({
ackId: id,
result
});
return;
}
if (ackId) {
const callback = this._callbacks.get(ackId);
this._callbacks.delete(ackId);
this._resetRef();
callback === null || callback === void 0 || callback(result);
return;
}
});
// Make sure to unref **after** adding a 'message' event listener.
// https://nodejs.org/api/worker_threads.html#portref
this._resetRef();
}
async send(method, params) {
return await new Promise(f => {
const id = ++this._lastId;
this._callbacks.set(id, f);
this._resetRef();
this._port.postMessage({
id,
method,
params
});
});
}
_resetRef() {
if (this._callbacks.size) {
// When we are waiting for a response, ref the port to prevent this process from exiting.
this._port.ref();
} else {
// When we are not waiting for a response, unref the port to prevent this process
// from hanging forever.
this._port.unref();
}
}
}
exports.PortTransport = PortTransport;

294
node_modules/playwright/lib/transform/transform.js generated vendored Normal file
View File

@@ -0,0 +1,294 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.requireOrImport = requireOrImport;
exports.resolveHook = resolveHook;
exports.setSingleTSConfig = setSingleTSConfig;
exports.setTransformConfig = setTransformConfig;
exports.setTransformData = setTransformData;
exports.shouldTransform = shouldTransform;
exports.singleTSConfig = singleTSConfig;
exports.transformConfig = transformConfig;
exports.transformHook = transformHook;
exports.wrapFunctionWithLocation = wrapFunctionWithLocation;
var _crypto = _interopRequireDefault(require("crypto"));
var _fs = _interopRequireDefault(require("fs"));
var _module = _interopRequireDefault(require("module"));
var _path = _interopRequireDefault(require("path"));
var _url = _interopRequireDefault(require("url"));
var _tsconfigLoader = require("../third_party/tsconfig-loader");
var _util = require("../util");
var _utilsBundle = require("../utilsBundle");
var _compilationCache = require("./compilationCache");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
* 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.
*/
const version = require('../../package.json').version;
const cachedTSConfigs = new Map();
let _transformConfig = {
babelPlugins: [],
external: []
};
let _externalMatcher = () => false;
function setTransformConfig(config) {
_transformConfig = config;
_externalMatcher = (0, _util.createFileMatcher)(_transformConfig.external);
}
function transformConfig() {
return _transformConfig;
}
let _singleTSConfigPath;
let _singleTSConfig;
function setSingleTSConfig(value) {
_singleTSConfigPath = value;
}
function singleTSConfig() {
return _singleTSConfigPath;
}
function validateTsConfig(tsconfig) {
var _tsconfig$absoluteBas, _tsconfig$paths, _tsconfig$paths2;
// When no explicit baseUrl is set, resolve paths relative to the tsconfig file.
// See https://www.typescriptlang.org/tsconfig#paths
const pathsBase = (_tsconfig$absoluteBas = tsconfig.absoluteBaseUrl) !== null && _tsconfig$absoluteBas !== void 0 ? _tsconfig$absoluteBas : (_tsconfig$paths = tsconfig.paths) === null || _tsconfig$paths === void 0 ? void 0 : _tsconfig$paths.pathsBasePath;
// Only add the catch-all mapping when baseUrl is specified
const pathsFallback = tsconfig.absoluteBaseUrl ? [{
key: '*',
values: ['*']
}] : [];
return {
allowJs: !!tsconfig.allowJs,
pathsBase,
paths: Object.entries(((_tsconfig$paths2 = tsconfig.paths) === null || _tsconfig$paths2 === void 0 ? void 0 : _tsconfig$paths2.mapping) || {}).map(([key, values]) => ({
key,
values
})).concat(pathsFallback)
};
}
function loadAndValidateTsconfigsForFile(file) {
if (_singleTSConfigPath && !_singleTSConfig) _singleTSConfig = (0, _tsconfigLoader.loadTsConfig)(_singleTSConfigPath).map(validateTsConfig);
if (_singleTSConfig) return _singleTSConfig;
return loadAndValidateTsconfigsForFolder(_path.default.dirname(file));
}
function loadAndValidateTsconfigsForFolder(folder) {
const foldersWithConfig = [];
let currentFolder = _path.default.resolve(folder);
let result;
while (true) {
const cached = cachedTSConfigs.get(currentFolder);
if (cached) {
result = cached;
break;
}
foldersWithConfig.push(currentFolder);
for (const name of ['tsconfig.json', 'jsconfig.json']) {
const configPath = _path.default.join(currentFolder, name);
if (_fs.default.existsSync(configPath)) {
const loaded = (0, _tsconfigLoader.loadTsConfig)(configPath);
result = loaded.map(validateTsConfig);
break;
}
}
if (result) break;
const parentFolder = _path.default.resolve(currentFolder, '../');
if (currentFolder === parentFolder) break;
currentFolder = parentFolder;
}
result = result || [];
for (const folder of foldersWithConfig) cachedTSConfigs.set(folder, result);
return result;
}
const pathSeparator = process.platform === 'win32' ? ';' : ':';
const builtins = new Set(_module.default.builtinModules);
function resolveHook(filename, specifier) {
if (specifier.startsWith('node:') || builtins.has(specifier)) return;
if (!shouldTransform(filename)) return;
if (isRelativeSpecifier(specifier)) return (0, _util.resolveImportSpecifierAfterMapping)(_path.default.resolve(_path.default.dirname(filename), specifier), false);
/**
* TypeScript discourages path-mapping into node_modules:
* https://www.typescriptlang.org/docs/handbook/modules/reference.html#paths-should-not-point-to-monorepo-packages-or-node_modules-packages
* However, if path-mapping doesn't yield a result, TypeScript falls back to the default resolution through node_modules.
*/
const isTypeScript = filename.endsWith('.ts') || filename.endsWith('.tsx');
const tsconfigs = loadAndValidateTsconfigsForFile(filename);
for (const tsconfig of tsconfigs) {
if (!isTypeScript && !tsconfig.allowJs) continue;
let longestPrefixLength = -1;
let pathMatchedByLongestPrefix;
for (const {
key,
values
} of tsconfig.paths) {
let matchedPartOfSpecifier = specifier;
const [keyPrefix, keySuffix] = key.split('*');
if (key.includes('*')) {
// * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
// * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
// * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
// https://github.com/microsoft/TypeScript/blob/f82d0cb3299c04093e3835bc7e29f5b40475f586/src/compiler/moduleNameResolver.ts#L1049
if (keyPrefix) {
if (!specifier.startsWith(keyPrefix)) continue;
matchedPartOfSpecifier = matchedPartOfSpecifier.substring(keyPrefix.length, matchedPartOfSpecifier.length);
}
if (keySuffix) {
if (!specifier.endsWith(keySuffix)) continue;
matchedPartOfSpecifier = matchedPartOfSpecifier.substring(0, matchedPartOfSpecifier.length - keySuffix.length);
}
} else {
if (specifier !== key) continue;
matchedPartOfSpecifier = specifier;
}
if (keyPrefix.length <= longestPrefixLength) continue;
for (const value of values) {
let candidate = value;
if (value.includes('*')) candidate = candidate.replace('*', matchedPartOfSpecifier);
candidate = _path.default.resolve(tsconfig.pathsBase, candidate);
const existing = (0, _util.resolveImportSpecifierAfterMapping)(candidate, true);
if (existing) {
longestPrefixLength = keyPrefix.length;
pathMatchedByLongestPrefix = existing;
}
}
}
if (pathMatchedByLongestPrefix) return pathMatchedByLongestPrefix;
}
if (_path.default.isAbsolute(specifier)) {
// Handle absolute file paths like `import '/path/to/file'`
// Do not handle module imports like `import 'fs'`
return (0, _util.resolveImportSpecifierAfterMapping)(specifier, false);
}
}
function shouldTransform(filename) {
if (_externalMatcher(filename)) return false;
return !(0, _compilationCache.belongsToNodeModules)(filename);
}
let transformData;
function setTransformData(pluginName, value) {
transformData.set(pluginName, value);
}
function transformHook(originalCode, filename, moduleUrl) {
const hasPreprocessor = 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));
const pluginsPrologue = _transformConfig.babelPlugins;
const pluginsEpilogue = hasPreprocessor ? [[process.env.PW_TEST_SOURCE_TRANSFORM]] : [];
const hash = calculateHash(originalCode, filename, !!moduleUrl, pluginsPrologue, pluginsEpilogue);
const {
cachedCode,
addToCache,
serializedCache
} = (0, _compilationCache.getFromCompilationCache)(filename, hash, moduleUrl);
if (cachedCode !== undefined) return {
code: cachedCode,
serializedCache
};
// We don't use any browserslist data, but babel checks it anyway.
// Silence the annoying warning.
process.env.BROWSERSLIST_IGNORE_OLD_DATA = 'true';
const {
babelTransform
} = require('./babelBundle');
transformData = new Map();
const babelResult = babelTransform(originalCode, filename, !!moduleUrl, pluginsPrologue, pluginsEpilogue);
if (!(babelResult !== null && babelResult !== void 0 && babelResult.code)) return {
code: originalCode,
serializedCache
};
const {
code,
map
} = babelResult;
const added = addToCache(code, map, transformData);
return {
code,
serializedCache: added.serializedCache
};
}
function calculateHash(content, filePath, isModule, pluginsPrologue, pluginsEpilogue) {
const hash = _crypto.default.createHash('sha1').update(isModule ? 'esm' : 'no_esm').update(content).update(filePath).update(version).update(pluginsPrologue.map(p => p[0]).join(',')).update(pluginsEpilogue.map(p => p[0]).join(',')).digest('hex');
return hash;
}
async function requireOrImport(file) {
installTransformIfNeeded();
const isModule = (0, _util.fileIsModule)(file);
const esmImport = () => eval(`import(${JSON.stringify(_url.default.pathToFileURL(file))})`);
if (isModule) return await esmImport();
const result = require(file);
const depsCollector = (0, _compilationCache.currentFileDepsCollector)();
if (depsCollector) {
const module = require.cache[file];
if (module) collectCJSDependencies(module, depsCollector);
}
return result;
}
let transformInstalled = false;
function installTransformIfNeeded() {
if (transformInstalled) return;
transformInstalled = true;
(0, _compilationCache.installSourceMapSupport)();
const originalResolveFilename = _module.default._resolveFilename;
function resolveFilename(specifier, parent, ...rest) {
if (parent) {
const resolved = resolveHook(parent.filename, specifier);
if (resolved !== undefined) specifier = resolved;
}
return originalResolveFilename.call(this, specifier, parent, ...rest);
}
_module.default._resolveFilename = resolveFilename;
_utilsBundle.pirates.addHook((code, filename) => {
if (!shouldTransform(filename)) return code;
return transformHook(code, filename).code;
}, {
exts: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.mts', '.cjs', '.cts']
});
}
const collectCJSDependencies = (module, dependencies) => {
module.children.forEach(child => {
if (!(0, _compilationCache.belongsToNodeModules)(child.filename) && !dependencies.has(child.filename)) {
dependencies.add(child.filename);
collectCJSDependencies(child, dependencies);
}
});
};
function wrapFunctionWithLocation(func) {
return (...args) => {
const oldPrepareStackTrace = Error.prepareStackTrace;
Error.prepareStackTrace = (error, stackFrames) => {
const frame = _utilsBundle.sourceMapSupport.wrapCallSite(stackFrames[1]);
const fileName = frame.getFileName();
// Node error stacks for modules use file:// urls instead of paths.
const file = fileName && fileName.startsWith('file://') ? _url.default.fileURLToPath(fileName) : fileName;
return {
file,
line: frame.getLineNumber(),
column: frame.getColumnNumber()
};
};
const oldStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 2;
const obj = {};
Error.captureStackTrace(obj);
const location = obj.stack;
Error.stackTraceLimit = oldStackTraceLimit;
Error.prepareStackTrace = oldPrepareStackTrace;
return func(location, ...args);
};
}
function isRelativeSpecifier(specifier) {
return specifier === '.' || specifier === '..' || specifier.startsWith('./') || specifier.startsWith('../');
}