Skip to content

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

chore: export coreBundle (#40057)

Pavel Feldman72310c757282
diff --git a/packages/playwright-browser-chromium/install.js b/packages/playwright-browser-chromium/install.js
index 5f725bb2c9..8e42a18b24 100644
--- a/packages/playwright-browser-chromium/install.js
+++ b/packages/playwright-browser-chromium/install.js
@@ -17,8 +17,8 @@
let install;
try {
- if (!require('playwright-core/lib/utils').isLikelyNpxGlobal())
- install = require('playwright-core/lib/server').installBrowsersForNpmInstall;
+ if (!require('playwright-core/lib/coreBundle').serverUtils.isLikelyNpxGlobal())
+ install = require('playwright-core/lib/coreBundle').sever.installBrowsersForNpmInstall;
} catch (e) {
// Dev build, don't install browsers by default.
}
diff --git a/packages/playwright-browser-firefox/install.js b/packages/playwright-browser-firefox/install.js
index a917664fc0..561032d644 100644
--- a/packages/playwright-browser-firefox/install.js
+++ b/packages/playwright-browser-firefox/install.js
@@ -17,8 +17,8 @@
let install;
try {
- if (!require('playwright-core/lib/utils').isLikelyNpxGlobal())
- install = require('playwright-core/lib/server').installBrowsersForNpmInstall;
+ if (!require('playwright-core/lib/coreBundle').serverUtils.isLikelyNpxGlobal())
+ install = require('playwright-core/lib/coreBundle').sever.installBrowsersForNpmInstall;
} catch (e) {
// Dev build, don't install browsers by default.
}
diff --git a/packages/playwright-browser-webkit/install.js b/packages/playwright-browser-webkit/install.js
index 237ee38d63..dbb98b90eb 100644
--- a/packages/playwright-browser-webkit/install.js
+++ b/packages/playwright-browser-webkit/install.js
@@ -17,8 +17,8 @@
let install;
try {
- if (!require('playwright-core/lib/utils').isLikelyNpxGlobal())
- install = require('playwright-core/lib/server').installBrowsersForNpmInstall;
+ if (!require('playwright-core/lib/coreBundle').serverUtils.isLikelyNpxGlobal())
+ install = require('playwright-core/lib/coreBundle').sever.installBrowsersForNpmInstall;
} catch (e) {
// Dev build, don't install browsers by default.
}
diff --git a/packages/playwright-chromium/cli.js b/packages/playwright-chromium/cli.js
index f46d8b409e..1ab7f499d7 100755
--- a/packages/playwright-chromium/cli.js
+++ b/packages/playwright-chromium/cli.js
@@ -15,5 +15,7 @@
* limitations under the License.
*/
-const { program } = require('playwright-core/lib/cli/program');
+const { program } = require('playwright-core/lib/utilsBundle');
+const { libCli } = require('playwright-core/lib/coreBundle');
+libCli.decorateProgram(program);
program.parse(process.argv);
diff --git a/packages/playwright-chromium/install.js b/packages/playwright-chromium/install.js
index 5f725bb2c9..8e42a18b24 100644
--- a/packages/playwright-chromium/install.js
+++ b/packages/playwright-chromium/install.js
@@ -17,8 +17,8 @@
let install;
try {
- if (!require('playwright-core/lib/utils').isLikelyNpxGlobal())
- install = require('playwright-core/lib/server').installBrowsersForNpmInstall;
+ if (!require('playwright-core/lib/coreBundle').serverUtils.isLikelyNpxGlobal())
+ install = require('playwright-core/lib/coreBundle').sever.installBrowsersForNpmInstall;
} catch (e) {
// Dev build, don't install browsers by default.
}
diff --git a/packages/playwright-cli-stub/playwright-cli-stub.js b/packages/playwright-cli-stub/playwright-cli-stub.js
index 59772a7ce8..d33211f9be 100755
--- a/packages/playwright-cli-stub/playwright-cli-stub.js
+++ b/packages/playwright-cli-stub/playwright-cli-stub.js
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-const { program } = require('playwright-core/lib/tools/cli-client/program');
+const { program } = require('playwright-core/lib/coreBundle').cli;
program().catch(e => {
console.error(e.message);
diff --git a/packages/playwright-core/cli.js b/packages/playwright-core/cli.js
index fb309ead0a..f275a03346 100755
--- a/packages/playwright-core/cli.js
+++ b/packages/playwright-core/cli.js
@@ -14,5 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-const { program } = require('./lib/cli/programWithTestStub');
+const { libCli, libCliTestStub } = require('./lib/coreBundle');
+const { program } = require('./lib/utilsBundle');
+libCli.decorateProgram(program);
+libCliTestStub.decorateProgram(program);
program.parse(process.argv);
diff --git a/packages/playwright-core/index.js b/packages/playwright-core/index.js
index d4991d0ed2..e845cfae9f 100644
--- a/packages/playwright-core/index.js
+++ b/packages/playwright-core/index.js
@@ -29,4 +29,4 @@ if (major < minimumMajorNodeVersion) {
process.exit(1);
}
-module.exports = require('./lib/inprocess');
+module.exports = require('./lib/coreBundle').inprocess.playwright;
diff --git a/packages/playwright-core/package.json b/packages/playwright-core/package.json
index 930db2f908..8bdc261a4b 100644
--- a/packages/playwright-core/package.json
+++ b/packages/playwright-core/package.json
@@ -23,23 +23,11 @@
},
"./package.json": "./package.json",
"./lib/bootstrap": "./lib/bootstrap.js",
- "./lib/outofprocess": "./lib/outofprocess.js",
- "./lib/cli/program": "./lib/cli/program.js",
- "./lib/tools/cli-client/program": "./lib/tools/cli-client/program.js",
- "./lib/tools/mcp/program": "./lib/tools/mcp/program.js",
+ "./lib/coreBundle": "./lib/coreBundle.js",
"./lib/mcpBundle": "./lib/mcpBundle.js",
- "./lib/zodBundle": "./lib/zodBundle.js",
- "./lib/tools/exports": "./lib/tools/exports.js",
- "./lib/remote/playwrightServer": "./lib/remote/playwrightServer.js",
- "./lib/server": "./lib/server/index.js",
- "./lib/server/utils/image_tools/stats": "./lib/server/utils/image_tools/stats.js",
- "./lib/server/utils/image_tools/compare": "./lib/server/utils/image_tools/compare.js",
- "./lib/server/utils/image_tools/imageChannel": "./lib/server/utils/image_tools/imageChannel.js",
- "./lib/server/utils/image_tools/colorUtils": "./lib/server/utils/image_tools/colorUtils.js",
- "./lib/server/registry/index": "./lib/server/registry/index.js",
- "./lib/utils": "./lib/utils.js",
"./lib/utilsBundle": "./lib/utilsBundle.js",
- "./lib/zipBundle": "./lib/zipBundle.js"
+ "./lib/zipBundle": "./lib/zipBundle.js",
+ "./lib/zodBundle": "./lib/zodBundle.js"
},
"bin": {
"playwright-core": "cli.js"
diff --git a/packages/playwright-core/src/DEPS.list b/packages/playwright-core/src/DEPS.list
index 292d724854..d962b703a6 100644
--- a/packages/playwright-core/src/DEPS.list
+++ b/packages/playwright-core/src/DEPS.list
@@ -18,8 +18,7 @@ utilsBundle.ts
**
[inprocess.ts]
-utils/
-server/utils
+**
[outofprocess.ts]
client/
@@ -28,5 +27,9 @@ utils/
utils/isomorphic
server/utils
+[package.ts]
+"strict"
+
[serverRegistry.ts]
"strict"
+package.ts
diff --git a/packages/playwright-core/src/cli/DEPS.list b/packages/playwright-core/src/cli/DEPS.list
index 7bc1c0cdf0..5ed8f9dfb4 100644
--- a/packages/playwright-core/src/cli/DEPS.list
+++ b/packages/playwright-core/src/cli/DEPS.list
@@ -1,5 +1,5 @@
[*]
-../..
+../inprocess.ts
../server/
../server/utils/
../remote/
diff --git a/packages/playwright-core/src/cli/browserActions.ts b/packages/playwright-core/src/cli/browserActions.ts
index cbefe7ddd4..31d53c8a3f 100644
--- a/packages/playwright-core/src/cli/browserActions.ts
+++ b/packages/playwright-core/src/cli/browserActions.ts
@@ -20,7 +20,7 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
-import * as playwright from '../..';
+import { playwright } from '../inprocess';
import { gracefullyProcessExitDoNotHang, ManualPromise } from '../utils';
import { dotenv, program } from '../utilsBundle';
diff --git a/packages/playwright-core/src/cli/driver.ts b/packages/playwright-core/src/cli/driver.ts
index 0485f45e0e..356b677c13 100644
--- a/packages/playwright-core/src/cli/driver.ts
+++ b/packages/playwright-core/src/cli/driver.ts
@@ -18,7 +18,7 @@
import fs from 'fs';
-import * as playwright from '../..';
+import { playwright } from '../inprocess';
import { PipeTransport } from '../server/utils/pipeTransport';
import { PlaywrightServer } from '../remote/playwrightServer';
import { DispatcherConnection, PlaywrightDispatcher, RootDispatcher, createPlaywright } from '../server';
diff --git a/packages/playwright-core/src/cli/program.ts b/packages/playwright-core/src/cli/program.ts
index e47b9c4159..988ee101ba 100644
--- a/packages/playwright-core/src/cli/program.ts
+++ b/packages/playwright-core/src/cli/program.ts
@@ -24,233 +24,233 @@ import { program } from '../utilsBundle';
import type { TraceViewerServerOptions } from '../server/trace/viewer/traceViewer';
import type { Command } from '../utilsBundle';
-export { program } from '../utilsBundle';
-
-const packageJSON = require('../../package.json');
-
-program
- .version('Version ' + (process.env.PW_CLI_DISPLAY_VERSION || packageJSON.version))
- .name(buildBasePlaywrightCLICommand(process.env.PW_LANG_NAME));
-
-program
- .command('mark-docker-image [dockerImageNameTemplate]', { hidden: true })
- .description('mark docker image')
- .allowUnknownOption(true)
- .action(async function(dockerImageNameTemplate) {
- const { markDockerImage } = await import('./installActions');
- markDockerImage(dockerImageNameTemplate).catch(logErrorAndExit);
- });
-
-commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', [])
- .action(async function(url, options) {
- const { open } = await import('./browserActions');
- open(options, url).catch(logErrorAndExit);
- })
- .addHelpText('afterAll', `
-Examples:
-
- $ open
- $ open -b webkit https://example.com`);
-
-commandWithOpenOptions('codegen [url]', 'open page and generate code for user actions',
- [
- ['-o, --output <file name>', 'saves the generated script to a file'],
- ['--target <language>', `language to generate, one of javascript, playwright-test, python, python-async, python-pytest, csharp, csharp-mstest, csharp-nunit, java, java-junit`, codegenId()],
- ['--test-id-attribute <attributeName>', 'use the specified attribute to generate data test ID selectors'],
- ]).action(async function(url, options) {
- const { codegen } = await import('./browserActions');
- await codegen(options, url);
-}).addHelpText('afterAll', `
-Examples:
-
- $ codegen
- $ codegen --target=python
- $ codegen -b webkit https://example.com`);
-
-program
- .command('install [browser...]')
- .description('ensure browsers necessary for this version of Playwright are installed')
- .option('--with-deps', 'install system dependencies for browsers')
- .option('--dry-run', 'do not execute installation, only print information')
- .option('--list', 'prints list of browsers from all playwright installations')
- .option('--force', 'force reinstall of already installed browsers')
- .option('--only-shell', 'only install headless shell when installing chromium')
- .option('--no-shell', 'do not install chromium headless shell')
- .action(async function(args: string[], options: { withDeps?: boolean, force?: boolean, dryRun?: boolean, list?: boolean, shell?: boolean, noShell?: boolean, onlyShell?: boolean }) {
- try {
- const { installBrowsers } = await import('./installActions');
- await installBrowsers(args, options);
- } catch (e) {
- console.log(`Failed to install browsers\n${e}`);
- gracefullyProcessExitDoNotHang(1);
- }
- }).addHelpText('afterAll', `
-
-Examples:
- - $ install
- Install default browsers.
-
- - $ install chrome firefox
- Install custom browsers, supports chromium, firefox, webkit, chromium-headless-shell.`);
-
-program
- .command('uninstall')
- .description('Removes browsers used by this installation of Playwright from the system (chromium, firefox, webkit, ffmpeg). This does not include branded channels.')
- .option('--all', 'Removes all browsers used by any Playwright installation from the system.')
- .action(async (options: { all?: boolean }) => {
- const { uninstallBrowsers } = await import('./installActions');
- uninstallBrowsers(options).catch(logErrorAndExit);
- });
-
-program
- .command('install-deps [browser...]')
- .description('install dependencies necessary to run browsers (will ask for sudo permissions)')
- .option('--dry-run', 'Do not execute installation commands, only print them')
- .action(async function(args: string[], options: { dryRun?: boolean }) {
- try {
- const { installDeps } = await import('./installActions');
- await installDeps(args, options);
- } catch (e) {
- console.log(`Failed to install browser dependencies\n${e}`);
- gracefullyProcessExitDoNotHang(1);
- }
- }).addHelpText('afterAll', `
-Examples:
- - $ install-deps
- Install dependencies for default browsers.
-
- - $ install-deps chrome firefox
- Install dependencies for specific browsers, supports chromium, firefox, webkit, chromium-headless-shell.`);
-
-const browsers = [
- { alias: 'cr', name: 'Chromium', type: 'chromium' },
- { alias: 'ff', name: 'Firefox', type: 'firefox' },
- { alias: 'wk', name: 'WebKit', type: 'webkit' },
-];
-
-for (const { alias, name, type } of browsers) {
- commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, [])
+export function decorateProgram(program: Command) {
+ const packageJSON = require('../../package.json');
+
+ program
+ .version('Version ' + (process.env.PW_CLI_DISPLAY_VERSION || packageJSON.version))
+ .name(buildBasePlaywrightCLICommand(process.env.PW_LANG_NAME));
+
+ program
+ .command('mark-docker-image [dockerImageNameTemplate]', { hidden: true })
+ .description('mark docker image')
+ .allowUnknownOption(true)
+ .action(async function(dockerImageNameTemplate) {
+ const { markDockerImage } = await import('./installActions');
+ markDockerImage(dockerImageNameTemplate).catch(logErrorAndExit);
+ });
+
+ commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', [])
.action(async function(url, options) {
const { open } = await import('./browserActions');
- open({ ...options, browser: type }, url).catch(logErrorAndExit);
+ open(options, url).catch(logErrorAndExit);
+ })
+ .addHelpText('afterAll', `
+ Examples:
+
+ $ open
+ $ open -b webkit https://example.com`);
+
+ commandWithOpenOptions('codegen [url]', 'open page and generate code for user actions',
+ [
+ ['-o, --output <file name>', 'saves the generated script to a file'],
+ ['--target <language>', `language to generate, one of javascript, playwright-test, python, python-async, python-pytest, csharp, csharp-mstest, csharp-nunit, java, java-junit`, codegenId()],
+ ['--test-id-attribute <attributeName>', 'use the specified attribute to generate data test ID selectors'],
+ ]).action(async function(url, options) {
+ const { codegen } = await import('./browserActions');
+ await codegen(options, url);
+ }).addHelpText('afterAll', `
+ Examples:
+
+ $ codegen
+ $ codegen --target=python
+ $ codegen -b webkit https://example.com`);
+
+ program
+ .command('install [browser...]')
+ .description('ensure browsers necessary for this version of Playwright are installed')
+ .option('--with-deps', 'install system dependencies for browsers')
+ .option('--dry-run', 'do not execute installation, only print information')
+ .option('--list', 'prints list of browsers from all playwright installations')
+ .option('--force', 'force reinstall of already installed browsers')
+ .option('--only-shell', 'only install headless shell when installing chromium')
+ .option('--no-shell', 'do not install chromium headless shell')
+ .action(async function(args: string[], options: { withDeps?: boolean, force?: boolean, dryRun?: boolean, list?: boolean, shell?: boolean, noShell?: boolean, onlyShell?: boolean }) {
+ try {
+ const { installBrowsers } = await import('./installActions');
+ await installBrowsers(args, options);
+ } catch (e) {
+ console.log(`Failed to install browsers\n${e}`);
+ gracefullyProcessExitDoNotHang(1);
+ }
}).addHelpText('afterAll', `
-Examples:
- $ ${alias} https://example.com`);
-}
+ Examples:
+ - $ install
+ Install default browsers.
+
+ - $ install chrome firefox
+ Install custom browsers, supports chromium, firefox, webkit, chromium-headless-shell.`);
+
+ program
+ .command('uninstall')
+ .description('Removes browsers used by this installation of Playwright from the system (chromium, firefox, webkit, ffmpeg). This does not include branded channels.')
+ .option('--all', 'Removes all browsers used by any Playwright installation from the system.')
+ .action(async (options: { all?: boolean }) => {
+ const { uninstallBrowsers } = await import('./installActions');
+ uninstallBrowsers(options).catch(logErrorAndExit);
+ });
+
+ program
+ .command('install-deps [browser...]')
+ .description('install dependencies necessary to run browsers (will ask for sudo permissions)')
+ .option('--dry-run', 'Do not execute installation commands, only print them')
+ .action(async function(args: string[], options: { dryRun?: boolean }) {
+ try {
+ const { installDeps } = await import('./installActions');
+ await installDeps(args, options);
+ } catch (e) {
+ console.log(`Failed to install browser dependencies\n${e}`);
+ gracefullyProcessExitDoNotHang(1);
+ }
+ }).addHelpText('afterAll', `
+ Examples:
+ - $ install-deps
+ Install dependencies for default browsers.
+
+ - $ install-deps chrome firefox
+ Install dependencies for specific browsers, supports chromium, firefox, webkit, chromium-headless-shell.`);
+
+ const browsers = [
+ { alias: 'cr', name: 'Chromium', type: 'chromium' },
+ { alias: 'ff', name: 'Firefox', type: 'firefox' },
+ { alias: 'wk', name: 'WebKit', type: 'webkit' },
+ ];
+
+ for (const { alias, name, type } of browsers) {
+ commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, [])
+ .action(async function(url, options) {
+ const { open } = await import('./browserActions');
+ open({ ...options, browser: type }, url).catch(logErrorAndExit);
+ }).addHelpText('afterAll', `
+ Examples:
+
+ $ ${alias} https://example.com`);
+ }
-commandWithOpenOptions('screenshot <url> <filename>', 'capture a page screenshot',
- [
- ['--wait-for-selector <selector>', 'wait for selector before taking a screenshot'],
- ['--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot'],
- ['--full-page', 'whether to take a full page screenshot (entire scrollable area)'],
- ]).action(async function(url, filename, command) {
- const { screenshot } = await import('./browserActions');
- screenshot(command, command, url, filename).catch(logErrorAndExit);
-}).addHelpText('afterAll', `
-Examples:
-
- $ screenshot -b webkit https://example.com example.png`);
-
-commandWithOpenOptions('pdf <url> <filename>', 'save page as pdf',
- [
- ['--paper-format <format>', 'paper format: Letter, Legal, Tabloid, Ledger, A0, A1, A2, A3, A4, A5, A6'],
- ['--wait-for-selector <selector>', 'wait for given selector before saving as pdf'],
- ['--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf'],
- ]).action(async function(url, filename, options) {
- const { pdf } = await import('./browserActions');
- pdf(options, options, url, filename).catch(logErrorAndExit);
-}).addHelpText('afterAll', `
-Examples:
-
- $ pdf https://example.com example.pdf`);
-
-program
- .command('run-driver', { hidden: true })
- .action(async function(options) {
- const { runDriver } = await import('./driver');
- runDriver();
- });
-
-program
- .command('run-server', { hidden: true })
- .option('--port <port>', 'Server port')
- .option('--host <host>', 'Server host')
- .option('--path <path>', 'Endpoint Path', '/')
- .option('--max-clients <maxClients>', 'Maximum clients')
- .option('--mode <mode>', 'Server mode, either "default" or "extension"')
- .option('--artifacts-dir <artifactsDir>', 'Artifacts directory')
- .action(async function(options) {
- const { runServer } = await import('./driver');
- runServer({
- port: options.port ? +options.port : undefined,
- host: options.host,
- path: options.path,
- maxConnections: options.maxClients ? +options.maxClients : Infinity,
- extension: options.mode === 'extension' || !!process.env.PW_EXTENSION_MODE,
- artifactsDir: options.artifactsDir,
- }).catch(logErrorAndExit);
- });
-
-program
- .command('print-api-json', { hidden: true })
- .action(async function(options) {
- const { printApiJson } = await import('./driver');
- printApiJson();
- });
-
-program
- .command('launch-server', { hidden: true })
- .requiredOption('--browser <browserName>', 'Browser name, one of "chromium", "firefox" or "webkit"')
- .option('--config <path-to-config-file>', 'JSON file with launchServer options')
- .action(async function(options) {
- const { launchBrowserServer } = await import('./driver');
- launchBrowserServer(options.browser, options.config);
- });
-
-program
- .command('show-trace [trace]')
- .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium')
- .option('-h, --host <host>', 'Host to serve trace on; specifying this option opens trace in a browser tab')
- .option('-p, --port <port>', 'Port to serve trace on, 0 for any free port; specifying this option opens trace in a browser tab')
- .option('--stdin', 'Accept trace URLs over stdin to update the viewer')
- .description('show trace viewer')
- .action(async function(trace, options) {
- if (options.browser === 'cr')
- options.browser = 'chromium';
- if (options.browser === 'ff')
- options.browser = 'firefox';
- if (options.browser === 'wk')
- options.browser = 'webkit';
-
- const openOptions: TraceViewerServerOptions = {
- host: options.host,
- port: +options.port,
- isServer: !!options.stdin,
- };
-
- const { runTraceInBrowser, runTraceViewerApp } = await import('../server/trace/viewer/traceViewer');
- if (options.port !== undefined || options.host !== undefined)
- runTraceInBrowser(trace, openOptions).catch(logErrorAndExit);
- else
- runTraceViewerApp(trace, options.browser, openOptions).catch(logErrorAndExit);
- }).addHelpText('afterAll', `
-Examples:
-
- $ show-trace
- $ show-trace https://example.com/trace.zip`);
-
-addTraceCommands(program, logErrorAndExit);
-
-program
- .command('cli', { hidden: true })
- .allowExcessArguments(true)
- .allowUnknownOption(true)
- .action(async options => {
- const { program: cliProgram } = await import('../tools/cli-client/program');
- process.argv.splice(process.argv.indexOf('cli'), 1);
- cliProgram().catch(logErrorAndExit);
- });
+ commandWithOpenOptions('screenshot <url> <filename>', 'capture a page screenshot',
+ [
+ ['--wait-for-selector <selector>', 'wait for selector before taking a screenshot'],
+ ['--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot'],
+ ['--full-page', 'whether to take a full page screenshot (entire scrollable area)'],
+ ]).action(async function(url, filename, command) {
+ const { screenshot } = await import('./browserActions');
+ screenshot(command, command, url, filename).catch(logErrorAndExit);
+ }).addHelpText('afterAll', `
+ Examples:
+
+ $ screenshot -b webkit https://example.com example.png`);
+
+ commandWithOpenOptions('pdf <url> <filename>', 'save page as pdf',
+ [
+ ['--paper-format <format>', 'paper format: Letter, Legal, Tabloid, Ledger, A0, A1, A2, A3, A4, A5, A6'],
+ ['--wait-for-selector <selector>', 'wait for given selector before saving as pdf'],
+ ['--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf'],
+ ]).action(async function(url, filename, options) {
+ const { pdf } = await import('./browserActions');
+ pdf(options, options, url, filename).catch(logErrorAndExit);
+ }).addHelpText('afterAll', `
+ Examples:
+
+ $ pdf https://example.com example.pdf`);
+
+ program
+ .command('run-driver', { hidden: true })
+ .action(async function(options) {
+ const { runDriver } = await import('./driver');
+ runDriver();
+ });
+
+ program
+ .command('run-server', { hidden: true })
+ .option('--port <port>', 'Server port')
+ .option('--host <host>', 'Server host')
+ .option('--path <path>', 'Endpoint Path', '/')
+ .option('--max-clients <maxClients>', 'Maximum clients')
+ .option('--mode <mode>', 'Server mode, either "default" or "extension"')
+ .option('--artifacts-dir <artifactsDir>', 'Artifacts directory')
+ .action(async function(options) {
+ const { runServer } = await import('./driver');
+ runServer({
+ port: options.port ? +options.port : undefined,
+ host: options.host,
+ path: options.path,
+ maxConnections: options.maxClients ? +options.maxClients : Infinity,
+ extension: options.mode === 'extension' || !!process.env.PW_EXTENSION_MODE,
+ artifactsDir: options.artifactsDir,
+ }).catch(logErrorAndExit);
+ });
+
+ program
+ .command('print-api-json', { hidden: true })
+ .action(async function(options) {
+ const { printApiJson } = await import('./driver');
+ printApiJson();
+ });
+
+ program
+ .command('launch-server', { hidden: true })
+ .requiredOption('--browser <browserName>', 'Browser name, one of "chromium", "firefox" or "webkit"')
+ .option('--config <path-to-config-file>', 'JSON file with launchServer options')
+ .action(async function(options) {
+ const { launchBrowserServer } = await import('./driver');
+ launchBrowserServer(options.browser, options.config);
+ });
+
+ program
+ .command('show-trace [trace]')
+ .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium')
+ .option('-h, --host <host>', 'Host to serve trace on; specifying this option opens trace in a browser tab')
+ .option('-p, --port <port>', 'Port to serve trace on, 0 for any free port; specifying this option opens trace in a browser tab')
+ .option('--stdin', 'Accept trace URLs over stdin to update the viewer')
+ .description('show trace viewer')
+ .action(async function(trace, options) {
+ if (options.browser === 'cr')
+ options.browser = 'chromium';
+ if (options.browser === 'ff')
+ options.browser = 'firefox';
+ if (options.browser === 'wk')
+ options.browser = 'webkit';
+
+ const openOptions: TraceViewerServerOptions = {
+ host: options.host,
+ port: +options.port,
+ isServer: !!options.stdin,
+ };
+
+ const { runTraceInBrowser, runTraceViewerApp } = await import('../server/trace/viewer/traceViewer');
+ if (options.port !== undefined || options.host !== undefined)
+ runTraceInBrowser(trace, openOptions).catch(logErrorAndExit);
+ else
+ runTraceViewerApp(trace, options.browser, openOptions).catch(logErrorAndExit);
+ }).addHelpText('afterAll', `
+ Examples:
+
+ $ show-trace
+ $ show-trace https://example.com/trace.zip`);
+
+ addTraceCommands(program, logErrorAndExit);
+
+ program
+ .command('cli', { hidden: true })
+ .allowExcessArguments(true)
+ .allowUnknownOption(true)
+ .action(async options => {
+ const { program: cliProgram } = await import('../tools/cli-client/program');
+ process.argv.splice(process.argv.indexOf('cli'), 1);
+ cliProgram().catch(logErrorAndExit);
+ });
+}
function logErrorAndExit(e: Error) {
if (process.env.PWDEBUGIMPL)
diff --git a/packages/playwright-core/src/cli/programWithTestStub.ts b/packages/playwright-core/src/cli/programWithTestStub.ts
index e7c4257526..0664610cf1 100644
--- a/packages/playwright-core/src/cli/programWithTestStub.ts
+++ b/packages/playwright-core/src/cli/programWithTestStub.ts
@@ -18,8 +18,8 @@
import { gracefullyProcessExitDoNotHang } from '../server/utils/processLauncher';
import { getPackageManager } from '../utils';
-import { program } from './program';
-export { program } from './program';
+
+import type { Command } from '../utilsBundle';
function printPlaywrightTestError(command: string) {
const packages: string[] = [];
@@ -53,7 +53,8 @@ const kExternalPlaywrightTestCommands = [
['show-report', 'Show Playwright Test HTML report.'],
['merge-reports', 'Merge Playwright Test Blob reports'],
];
-function addExternalPlaywrightTestCommands() {
+
+function addExternalPlaywrightTestCommands(program: Command) {
for (const [command, description] of kExternalPlaywrightTestCommands) {
const playwrightTest = program.command(command)
.allowUnknownOption(true)
@@ -66,5 +67,7 @@ function addExternalPlaywrightTestCommands() {
}
}
-if (!process.env.PW_LANG_NAME)
- addExternalPlaywrightTestCommands();
+export function decorateProgram(program: Command) {
+ if (!process.env.PW_LANG_NAME)
+ addExternalPlaywrightTestCommands(program);
+}
diff --git a/packages/playwright-core/src/coreBundle.ts b/packages/playwright-core/src/coreBundle.ts
new file mode 100644
index 0000000000..b11112515c
--- /dev/null
+++ b/packages/playwright-core/src/coreBundle.ts
@@ -0,0 +1,28 @@
+/**
+ * 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.
+ */
+
+export * as iso from './utils/isomorphic';
+export * as serverUtils from './server/utils';
+export * as tools from './tools';
+export * as libCli from './cli/program';
+export * as libCliTestStub from './cli/programWithTestStub';
+export * as inprocess from './inprocess';
+export * as oop from './outofprocess';
+export * as remote from './remote/playwrightServer';
+export * as mcp from './tools/mcp/program';
+export * as cli from './tools/cli-client/program';
+export * as registry from './server/registry/index';
+export * as sever from './server/index';
diff --git a/packages/playwright-core/src/inProcessFactory.ts b/packages/playwright-core/src/inProcessFactory.ts
deleted file mode 100644
index 8e9de3413d..0000000000
--- a/packages/playwright-core/src/inProcessFactory.ts
+++ /dev/null
@@ -1,58 +0,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.
- */
-
-import { AndroidServerLauncherImpl } from './androidServerImpl';
-import { BrowserServerLauncherImpl } from './browserServerImpl';
-import { DispatcherConnection, PlaywrightDispatcher, RootDispatcher, createPlaywright } from './server';
-import { nodePlatform } from './server/utils/nodePlatform';
-import { Connection } from './client/connection';
-
-import type { Playwright as PlaywrightAPI } from './client/playwright';
-import type { Language } from './utils';
-
-export function createInProcessPlaywright(): PlaywrightAPI {
- const playwright = createPlaywright({ sdkLanguage: (process.env.PW_LANG_NAME as Language | undefined) || 'javascript' });
- const clientConnection = new Connection(nodePlatform);
- clientConnection.useRawBuffers();
- const dispatcherConnection = new DispatcherConnection(true /* local */);
-
- // Dispatch synchronously at first.
- dispatcherConnection.onmessage = message => clientConnection.dispatch(message);
- clientConnection.onmessage = message => dispatcherConnection.dispatch(message);
-
- const rootScope = new RootDispatcher(dispatcherConnection);
-
- // Initialize Playwright channel.
- new PlaywrightDispatcher(rootScope, playwright);
- const playwrightAPI = clientConnection.getObjectWithKnownName('Playwright') as PlaywrightAPI;
- playwrightAPI.chromium._serverLauncher = new BrowserServerLauncherImpl('chromium');
- playwrightAPI.firefox._serverLauncher = new BrowserServerLauncherImpl('firefox');
- playwrightAPI.webkit._serverLauncher = new BrowserServerLauncherImpl('webkit');
- playwrightAPI._android._serverLauncher = new AndroidServerLauncherImpl();
-
- // Switch to async dispatch after we got Playwright object.
- dispatcherConnection.onmessage = message => setImmediate(() => clientConnection.dispatch(message));
- clientConnection.onmessage = message => setImmediate(() => dispatcherConnection.dispatch(message));
-
- clientConnection.toImpl = x => {
- if (x instanceof Connection)
- return x === clientConnection ? dispatcherConnection : undefined;
- if (!x)
- return dispatcherConnection._dispatcherByGuid.get('');
- return dispatcherConnection._dispatcherByGuid.get(x._guid)!._object;
- };
- return playwrightAPI;
-}
diff --git a/packages/playwright-core/src/inprocess.ts b/packages/playwright-core/src/inprocess.ts
index bd3590115d..26c36b93b1 100644
--- a/packages/playwright-core/src/inprocess.ts
+++ b/packages/playwright-core/src/inprocess.ts
@@ -14,6 +14,47 @@
* limitations under the License.
*/
-import { createInProcessPlaywright } from './inProcessFactory';
+import { AndroidServerLauncherImpl } from './androidServerImpl';
+import { BrowserServerLauncherImpl } from './browserServerImpl';
+import { DispatcherConnection, PlaywrightDispatcher, RootDispatcher, createPlaywright } from './server';
+import { nodePlatform } from './server/utils/nodePlatform';
+import { Connection } from './client/connection';
-module.exports = createInProcessPlaywright();
+import type { Playwright as PlaywrightAPI } from './client/playwright';
+import type { Language } from './utils';
+
+function createInProcessPlaywright(): PlaywrightAPI {
+ const playwright = createPlaywright({ sdkLanguage: (process.env.PW_LANG_NAME as Language | undefined) || 'javascript' });
+ const clientConnection = new Connection(nodePlatform);
+ clientConnection.useRawBuffers();
+ const dispatcherConnection = new DispatcherConnection(true /* local */);
+
+ // Dispatch synchronously at first.
+ dispatcherConnection.onmessage = message => clientConnection.dispatch(message);
+ clientConnection.onmessage = message => dispatcherConnection.dispatch(message);
+
+ const rootScope = new RootDispatcher(dispatcherConnection);
+
+ // Initialize Playwright channel.
+ new PlaywrightDispatcher(rootScope, playwright);
+ const playwrightAPI = clientConnection.getObjectWithKnownName('Playwright') as PlaywrightAPI;
+ playwrightAPI.chromium._serverLauncher = new BrowserServerLauncherImpl('chromium');
+ playwrightAPI.firefox._serverLauncher = new BrowserServerLauncherImpl('firefox');
+ playwrightAPI.webkit._serverLauncher = new BrowserServerLauncherImpl('webkit');
+ playwrightAPI._android._serverLauncher = new AndroidServerLauncherImpl();
+
+ // Switch to async dispatch after we got Playwright object.
+ dispatcherConnection.onmessage = message => setImmediate(() => clientConnection.dispatch(message));
+ clientConnection.onmessage = message => setImmediate(() => dispatcherConnection.dispatch(message));
+
+ clientConnection.toImpl = x => {
+ if (x instanceof Connection)
+ return x === clientConnection ? dispatcherConnection : undefined;
+ if (!x)
+ return dispatcherConnection._dispatcherByGuid.get('');
+ return dispatcherConnection._dispatcherByGuid.get(x._guid)!._object;
+ };
+ return playwrightAPI;
+}
+
+export const playwright = createInProcessPlaywright();
diff --git a/packages/playwright-core/src/package.ts b/packages/playwright-core/src/package.ts
new file mode 100644
index 0000000000..47bff2d85d
--- /dev/null
+++ b/packages/playwright-core/src/package.ts
@@ -0,0 +1,21 @@
+/**
+ * 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';
+
+export const packageJSON = require('../package.json');
+export const packageRoot = path.dirname(require.resolve('../package.json'));
+export const binPath = path.join(packageRoot, 'bin');
diff --git a/packages/playwright-core/src/server/DEPS.list b/packages/playwright-core/src/server/DEPS.list
index c991d24035..4dfd5fe933 100644
--- a/packages/playwright-core/src/server/DEPS.list
+++ b/packages/playwright-core/src/server/DEPS.list
@@ -1,5 +1,6 @@
[*]
../generated/
+../package.ts
../protocol/
../utils
../utils/isomorphic/**
diff --git a/packages/playwright-core/src/server/index.ts b/packages/playwright-core/src/server/index.ts
index 8232c8c0ea..1513c16b81 100644
--- a/packages/playwright-core/src/server/index.ts
+++ b/packages/playwright-core/src/server/index.ts
@@ -28,4 +28,5 @@ export { createPlaywright } from './playwright';
export type { DispatcherScope } from './dispatchers/dispatcher';
export type { Playwright } from './playwright';
+export type { TraceViewerRedirectOptions, TraceViewerServerOptions } from './trace/viewer/traceViewer';
export { installRootRedirect, openTraceInBrowser, openTraceViewerApp, startTraceViewerServer, runTraceViewerApp } from './trace/viewer/traceViewer';
diff --git a/packages/playwright-core/src/server/registry/dependencies.ts b/packages/playwright-core/src/server/registry/dependencies.ts
index 2b97d02d20..69cd5195c6 100644
--- a/packages/playwright-core/src/server/registry/dependencies.ts
+++ b/packages/playwright-core/src/server/registry/dependencies.ts
@@ -25,10 +25,10 @@ import { hostPlatform, isOfficiallySupportedPlatform } from '../utils/hostPlatfo
import { spawnAsync } from '../utils/spawnAsync';
import { getPlaywrightVersion } from '../utils/userAgent';
+import { packageJSON, binPath } from '../../package';
import { buildPlaywrightCLICommand, registry } from '.';
-const BIN_DIRECTORY = path.join(__dirname, '..', '..', '..', 'bin');
-const languageBindingVersion = process.env.PW_CLI_DISPLAY_VERSION || require('../../../package.json').version;
+const languageBindingVersion = process.env.PW_CLI_DISPLAY_VERSION || packageJSON.version;
const dockerVersionFilePath = '/ms-playwright/.docker-info';
export async function writeDockerVersion(dockerImageNameTemplate: string) {
@@ -78,12 +78,12 @@ export type DependencyGroup = 'chromium' | 'firefox' | 'webkit' | 'tools';
export async function installDependenciesWindows(targets: Set<DependencyGroup>, dryRun: boolean): Promise<void> {
if (targets.has('chromium')) {
const command = 'powershell.exe';
- const args = ['-ExecutionPolicy', 'Bypass', '-File', path.join(BIN_DIRECTORY, 'install_media_pack.ps1')];
+ const args = ['-ExecutionPolicy', 'Bypass', '-File', path.join(binPath, 'install_media_pack.ps1')];
if (dryRun) {
console.log(`${command} ${quoteProcessArgs(args).join(' ')}`); // eslint-disable-line no-console
return;
}
- const { code } = await spawnAsync(command, args, { cwd: BIN_DIRECTORY, stdio: 'inherit' });
+ const { code } = await spawnAsync(command, args, { cwd: binPath, stdio: 'inherit' });
if (code !== 0)
throw new Error('Failed to install windows dependencies!');
}
diff --git a/packages/playwright-core/src/server/registry/index.ts b/packages/playwright-core/src/server/registry/index.ts
index d9e3dab66f..ad5bde97e0 100644
--- a/packages/playwright-core/src/server/registry/index.ts
+++ b/packages/playwright-core/src/server/registry/index.ts
@@ -32,14 +32,15 @@ import { spawnAsync } from '../utils/spawnAsync';
import { getEmbedderName } from '../utils/userAgent';
import { lockfile } from '../../utilsBundle';
import { canAccessFile, existsAsync, removeFolders } from '../utils/fileUtils';
+import { packageRoot, binPath } from '../../package';
import type { DependencyGroup } from './dependencies';
import type { HostPlatform } from '../utils/hostPlatform';
export { writeDockerVersion } from './dependencies';
-const PACKAGE_PATH = path.join(__dirname, '..', '..', '..');
-const BIN_PATH = path.join(__dirname, '..', '..', '..', 'bin');
+const PACKAGE_PATH = packageRoot;
+const BIN_PATH = binPath;
const PLAYWRIGHT_CDN_MIRRORS = [
'https://cdn.playwright.dev/dbazure/download/playwright', // ESRP CDN
@@ -469,7 +470,7 @@ export const registryDirectory = (() => {
const envDefined = getFromENV('PLAYWRIGHT_BROWSERS_PATH');
if (envDefined === '0')
- result = path.join(__dirname, '..', '..', '..', '.local-browsers');
+ result = path.join(packageRoot, '.local-browsers');
else if (envDefined)
result = envDefined;
else
diff --git a/packages/playwright-core/src/server/utils/DEPS.list b/packages/playwright-core/src/server/utils/DEPS.list
index 3e42d76c2c..b601e7f24d 100644
--- a/packages/playwright-core/src/server/utils/DEPS.list
+++ b/packages/playwright-core/src/server/utils/DEPS.list
@@ -1,6 +1,7 @@
[*]
../../mcpBundle.ts
../../zodBundle.ts
+../../package.ts
../../utils
../../utils/isomorphic
../../utilsBundle.ts
diff --git a/packages/playwright-core/src/server/utils/index.ts b/packages/playwright-core/src/server/utils/index.ts
new file mode 100644
index 0000000000..8d72df26ca
--- /dev/null
+++ b/packages/playwright-core/src/server/utils/index.ts
@@ -0,0 +1,38 @@
+/**
+ * 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.
+ */
+
+export * from './ascii';
+export * from './comparators';
+export * from './crypto';
+export * from './debug';
+export * from './debugLogger';
+export * from './env';
+export * from './eventsHelper';
+export * from './expectUtils';
+export * from './fileUtils';
+export * from './hostPlatform';
+export * from './httpServer';
+export * from './network';
+export * from './nodePlatform';
+export * from './processLauncher';
+export * from './profiler';
+export * from './socksProxy';
+export * from './spawnAsync';
+export * from './task';
+export * from './userAgent';
+export * from './wsServer';
+export * from './zipFile';
+export * from './zones';
diff --git a/packages/playwright-core/src/server/utils/nodePlatform.ts b/packages/playwright-core/src/server/utils/nodePlatform.ts
index 84eb0e4015..c033e59d4e 100644
--- a/packages/playwright-core/src/server/utils/nodePlatform.ts
+++ b/packages/playwright-core/src/server/utils/nodePlatform.ts
@@ -25,6 +25,7 @@ import { colors } from '../../utilsBundle';
import { debugLogger } from './debugLogger';
import { currentZone, emptyZone } from './zones';
import { debugMode, isUnderTest } from './debug';
+import { packageRoot as coreDir } from '../../package';
import type { Platform, Zone } from '../../client/platform';
import type { Zone as ZoneImpl } from './zones';
@@ -61,8 +62,6 @@ export function setBoxedStackPrefixes(prefixes: string[]) {
boxedStackPrefixes = prefixes;
}
-const coreDir = path.dirname(require.resolve('../../../package.json'));
-
export const nodePlatform: Platform = {
name: 'node',
diff --git a/packages/playwright-core/src/server/utils/processLauncher.ts b/packages/playwright-core/src/server/utils/processLauncher.ts
index 6c491d0f48..9c77c7a0ce 100644
--- a/packages/playwright-core/src/server/utils/processLauncher.ts
+++ b/packages/playwright-core/src/server/utils/processLauncher.ts
@@ -20,7 +20,7 @@ import fs from 'fs';
import * as readline from 'readline';
import { removeFolders } from './fileUtils';
-import { isUnderTest } from '../../utils';
+import { isUnderTest } from './debug';
export type LaunchProcessOptions = {
command: string,
diff --git a/packages/playwright-core/src/serverRegistry.ts b/packages/playwright-core/src/serverRegistry.ts
index 08cb2612f2..e6160c775d 100644
--- a/packages/playwright-core/src/serverRegistry.ts
+++ b/packages/playwright-core/src/serverRegistry.ts
@@ -19,10 +19,12 @@ import net from 'net';
import path from 'path';
import os from 'os';
+import { packageJSON, packageRoot } from './package';
+
// Only client depenencies with backward compatibility guarantees should be imported here.
import type { LaunchOptions } from '../types/types';
-const packageVersion = require('../package.json').version;
+const packageVersion = packageJSON.version;
export type BrowserInfo = {
guid: string;
@@ -90,7 +92,7 @@ class ServerRegistry {
await fs.promises.mkdir(this._browsersDir(), { recursive: true });
const descriptor: BrowserDescriptor = {
playwrightVersion: packageVersion,
- playwrightLib: require.resolve('..'),
+ playwrightLib: packageRoot,
title: endpoint.title,
browser,
endpoint: endpoint.endpoint,
diff --git a/packages/playwright-core/src/tools/backend/context.ts b/packages/playwright-core/src/tools/backend/context.ts
index 91eee5813f..ca2fe4d9b3 100644
--- a/packages/playwright-core/src/tools/backend/context.ts
+++ b/packages/playwright-core/src/tools/backend/context.ts
@@ -19,13 +19,13 @@ import path from 'path';
import { debug } from '../../utilsBundle';
import { escapeWithQuotes } from '../../utils/isomorphic/stringUtils';
-import { selectors } from '../../..';
+import { playwright } from '../../inprocess';
import { Tab } from './tab';
import { disposeAll } from '../../server/utils/disposable';
import { eventsHelper } from '../../server/utils/eventsHelper';
-import type * as playwright from '../../..';
+import type * as playwrightTypes from '../../..';
import type { SessionLog } from './sessionLog';
import type { Disposable } from '../../server/utils/disposable';
import type { ToolCapability } from './tool';
@@ -76,7 +76,7 @@ export type RouteEntry = {
contentType?: string;
addHeaders?: Record<string, string>;
removeHeaders?: string[];
- handler: (route: playwright.Route) => Promise<void>;
+ handler: (route: playwrightTypes.Route) => Promise<void>;
};
export type FilenameTemplate = {
@@ -92,8 +92,8 @@ export class Context {
readonly config: ContextConfig;
readonly sessionLog: SessionLog | undefined;
readonly options: ContextOptions;
- private _rawBrowserContext: playwright.BrowserContext;
- private _browserContextPromise: Promise<playwright.BrowserContext> | undefined;
+ private _rawBrowserContext: playwrightTypes.BrowserContext;
+ private _browserContextPromise: Promise<playwrightTypes.BrowserContext> | undefined;
private _tabs: Tab[] = [];
private _currentTab: Tab | undefined;
private _routes: RouteEntry[] = [];
@@ -106,7 +106,7 @@ export class Context {
private _runningToolName: string | undefined;
- constructor(browserContext: playwright.BrowserContext, options: ContextOptions) {
+ constructor(browserContext: playwrightTypes.BrowserContext, options: ContextOptions) {
this.config = options.config;
this.sessionLog = options.sessionLog;
this.options = options;
@@ -201,7 +201,7 @@ export class Context {
return [...video.fileNames];
}
- private async _startPageVideo(page: playwright.Page) {
+ private async _startPageVideo(page: playwrightTypes.Page) {
if (!this._video)
return;
const suffix = this._video.fileNames.length ? `-${this._video.fileNames.length}` : '';
@@ -214,7 +214,7 @@ export class Context {
await page.screencast.start({ path: fileName, ...this._video.params });
}
- private _onPageCreated(page: playwright.Page) {
+ private _onPageCreated(page: playwrightTypes.Page) {
const tab = new Tab(this, page, tab => this._onPageClosed(tab));
this._tabs.push(tab);
if (!this._currentTab)
@@ -268,7 +268,7 @@ export class Context {
this._runningToolName = name;
}
- private async _setupRequestInterception(context: playwright.BrowserContext) {
+ private async _setupRequestInterception(context: playwrightTypes.BrowserContext) {
if (this.config.network?.allowedOrigins?.length) {
this._disposables.push(await context.route('**', route => route.abort('blockedbyclient')));
@@ -284,7 +284,7 @@ export class Context {
}
}
- async ensureBrowserContext(): Promise<playwright.BrowserContext> {
+ async ensureBrowserContext(): Promise<playwrightTypes.BrowserContext> {
if (this._browserContextPromise)
return this._browserContextPromise;
this._browserContextPromise = this._initializeBrowserContext();
@@ -293,7 +293,7 @@ export class Context {
private async _initializeBrowserContext() {
if (this.config.testIdAttribute)
- selectors.setTestIdAttribute(this.config.testIdAttribute);
+ playwright.selectors.setTestIdAttribute(this.config.testIdAttribute);
const browserContext = this._rawBrowserContext;
await this._setupRequestInterception(browserContext);
diff --git a/packages/playwright-core/src/tools/cli-client/DEPS.list b/packages/playwright-core/src/tools/cli-client/DEPS.list
index 7901dac129..c0159feef2 100644
--- a/packages/playwright-core/src/tools/cli-client/DEPS.list
+++ b/packages/playwright-core/src/tools/cli-client/DEPS.list
@@ -16,6 +16,7 @@
[registry.ts]
"strict"
+../../package.ts
[minimist.ts]
"strict"
diff --git a/packages/playwright-core/src/tools/cli-client/program.ts b/packages/playwright-core/src/tools/cli-client/program.ts
index 5626f0e618..2a55cb8fbb 100644
--- a/packages/playwright-core/src/tools/cli-client/program.ts
+++ b/packages/playwright-core/src/tools/cli-client/program.ts
@@ -236,8 +236,11 @@ async function runInitWorkspace(args: MinimistArgs) {
}
async function installBrowser() {
- const { program } = require('../../cli/program');
const argv = process.argv.map(arg => arg === 'install-browser' ? 'install' : arg);
+ const { libCli } = await import('../../coreBundle');
+ const { program } = await import('../../utilsBundle');
+ if (!program.version())
+ libCli.decorateProgram(program);
program.parse(argv);
}
diff --git a/packages/playwright-core/src/tools/cli-client/registry.ts b/packages/playwright-core/src/tools/cli-client/registry.ts
index 5fce84a0d7..ded5543cad 100644
--- a/packages/playwright-core/src/tools/cli-client/registry.ts
+++ b/packages/playwright-core/src/tools/cli-client/registry.ts
@@ -19,6 +19,8 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
+import { packageRoot, packageJSON } from '../../package';
+
import type * as playwright from '../../..';
export type ClientInfo = {
@@ -155,13 +157,11 @@ export const baseDaemonDir = (() => {
})();
export function createClientInfo(): ClientInfo {
- const packageLocation = require.resolve('../../../package.json');
- const packageJSON = require(packageLocation);
const workspaceDir = findWorkspaceDir(process.cwd());
const version = process.env.PLAYWRIGHT_CLI_VERSION_FOR_TEST || packageJSON.version;
const hash = crypto.createHash('sha1');
- hash.update(workspaceDir || packageLocation);
+ hash.update(workspaceDir || packageRoot);
const workspaceDirHash = hash.digest('hex').substring(0, 16);
return {
diff --git a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts b/packages/playwright-core/src/tools/dashboard/dashboardApp.ts
index 1ea5a736e5..8b998821cd 100644
--- a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts
+++ b/packages/playwright-core/src/tools/dashboard/dashboardApp.ts
@@ -19,7 +19,8 @@ import path from 'path';
import net from 'net';
import http from 'http';
-import { chromium } from '../../..';
+import { playwright } from '../../inprocess';
+import { packageRoot } from '../../package';
import { HttpServer } from '../../server/utils/httpServer';
import { makeSocketPath } from '../../server/utils/fileUtils';
import { gracefullyProcessExitDoNotHang } from '../../server/utils/processLauncher';
@@ -128,8 +129,7 @@ async function handleApiRequest(httpServer: HttpServer, request: http.IncomingMe
async function openDashboardApp(): Promise<api.Page> {
const httpServer = new HttpServer();
- const libDir = require.resolve('playwright-core/package.json');
- const dashboardDir = path.join(path.dirname(libDir), 'lib/vite/dashboard');
+ const dashboardDir = path.join(packageRoot, 'lib/vite/dashboard');
httpServer.routePrefix('/api/', (request: http.IncomingMessage, response: http.ServerResponse) => {
handleApiRequest(httpServer, request, response).catch(e => {
@@ -183,7 +183,7 @@ async function openDashboardApp(): Promise<api.Page> {
async function launchApp(appName: string) {
const channel = findChromiumChannelBestEffort('javascript');
const debugPort = parseInt(process.env.PLAYWRIGHT_DASHBOARD_DEBUG_PORT!, 10) || undefined;
- const context = await chromium.launchPersistentContext('', {
+ const context = await playwright.chromium.launchPersistentContext('', {
ignoreDefaultArgs: ['--enable-automation'],
channel,
headless: debugPort !== undefined,
diff --git a/packages/playwright-core/src/tools/exports.ts b/packages/playwright-core/src/tools/index.ts
similarity index 83%
rename from packages/playwright-core/src/tools/exports.ts
rename to packages/playwright-core/src/tools/index.ts
index 546db6eb37..5b98d33f06 100644
--- a/packages/playwright-core/src/tools/exports.ts
+++ b/packages/playwright-core/src/tools/index.ts
@@ -21,6 +21,11 @@ export { parseResponse } from './backend/response';
export { Tab } from './backend/tab';
export { browserTools, filteredTools } from './backend/tools';
export { start } from './utils/mcp/server';
+export { createConnection } from './mcp/index';
+export { resolveCLIConfigForCLI, resolveCLIConfigForMCP } from './mcp/config';
+export { isProfileLocked } from './mcp/browserFactory';
+export { compareSemver } from './utils/socketConnection';
+export { extractTrace, DirTraceLoaderBackend } from './trace/traceParser';
export type { ContextConfig } from './backend/context';
export type { CallToolRequest, CallToolResult, Tool } from './backend/tool';
@@ -29,4 +34,3 @@ export type { FullConfig } from './mcp/config';
export type { ServerBackend } from './utils/mcp/server';
export type { ToolSchema } from './utils/mcp/tool';
export type { ServerBackendFactory } from './utils/mcp/server';
-export { createConnection } from './mcp/index';
diff --git a/packages/playwright-core/src/tools/mcp/browserFactory.ts b/packages/playwright-core/src/tools/mcp/browserFactory.ts
index 9de21d157c..00354462a9 100644
--- a/packages/playwright-core/src/tools/mcp/browserFactory.ts
+++ b/packages/playwright-core/src/tools/mcp/browserFactory.ts
@@ -19,7 +19,7 @@ import fs from 'fs';
import net from 'net';
import path from 'path';
-import * as playwright from '../../..';
+import { playwright } from '../../inprocess';
import { registryDirectory } from '../../server/registry/index';
import { testDebug } from './log';
import { outputDir } from '../backend/context';
@@ -33,15 +33,16 @@ import type { FullConfig } from './config';
import type { ClientInfo } from '../utils/mcp/server';
// eslint-disable-next-line no-restricted-imports
import type { Playwright } from '../../client/playwright';
+import type * as playwrightTypes from '../../..';
import type { BrowserInfo } from '../../serverRegistry';
type BrowserWithInfo = {
- browser: playwright.Browser,
+ browser: playwrightTypes.Browser,
browserInfo: BrowserInfo,
canBind: boolean,
};
-export async function createBrowser(config: FullConfig, clientInfo: ClientInfo): Promise<playwright.Browser> {
+export async function createBrowser(config: FullConfig, clientInfo: ClientInfo): Promise<playwrightTypes.Browser> {
const { browser } = await createBrowserWithInfo(config, clientInfo);
return browser;
}
@@ -50,7 +51,7 @@ export async function createBrowserWithInfo(config: FullConfig, clientInfo: Clie
if (config.browser.remoteEndpoint)
return await createRemoteBrowser(config);
- let browser: playwright.Browser;
+ let browser: playwrightTypes.Browser;
let canBind = false;
if (config.browser.cdpEndpoint) {
browser = await createCDPBrowser(config);
@@ -69,11 +70,11 @@ export async function createBrowserWithInfo(config: FullConfig, clientInfo: Clie
}
export interface BrowserContextFactory {
- contexts(clientInfo: ClientInfo): Promise<playwright.BrowserContext[]>;
- createContext(clientInfo: ClientInfo): Promise<playwright.BrowserContext>;
+ contexts(clientInfo: ClientInfo): Promise<playwrightTypes.BrowserContext[]>;
+ createContext(clientInfo: ClientInfo): Promise<playwrightTypes.BrowserContext>;
}
-function browserInfo(browser: playwright.Browser, config: FullConfig): BrowserInfo {
+function browserInfo(browser: playwrightTypes.Browser, config: FullConfig): BrowserInfo {
return {
// eslint-disable-next-line no-restricted-syntax
guid: (browser as any)._guid,
@@ -83,7 +84,7 @@ function browserInfo(browser: playwright.Browser, config: FullConfig): BrowserIn
};
}
-async function createIsolatedBrowser(config: FullConfig, clientInfo: ClientInfo): Promise<playwright.Browser> {
+async function createIsolatedBrowser(config: FullConfig, clientInfo: ClientInfo): Promise<playwrightTypes.Browser> {
testDebug('create browser (isolated)');
await injectCdpPort(config.browser);
const browserType = playwright[config.browser.browserName];
@@ -101,7 +102,7 @@ async function createIsolatedBrowser(config: FullConfig, clientInfo: ClientInfo)
return browser;
}
-async function createCDPBrowser(config: FullConfig): Promise<playwright.Browser> {
+async function createCDPBrowser(config: FullConfig): Promise<playwrightTypes.Browser> {
testDebug('create browser (cdp)');
const browser = await playwright.chromium.connectOverCDP(config.browser.cdpEndpoint!, {
headers: config.browser.cdpHeaders,
@@ -135,7 +136,7 @@ async function createRemoteBrowser(config: FullConfig): Promise<BrowserWithInfo>
return { browser, browserInfo: browserInfo(browser, config), canBind: false };
}
-async function createPersistentBrowser(config: FullConfig, clientInfo: ClientInfo): Promise<playwright.Browser> {
+async function createPersistentBrowser(config: FullConfig, clientInfo: ClientInfo): Promise<playwrightTypes.Browser> {
testDebug('create browser (persistent)');
await injectCdpPort(config.browser);
const userDataDir = config.browser.userDataDir ?? await createUserDataDir(config, clientInfo);
@@ -146,7 +147,7 @@ async function createPersistentBrowser(config: FullConfig, clientInfo: ClientInf
const browserType = playwright[config.browser.browserName];
const configIgnoreDefaultArgs = config.browser.launchOptions?.ignoreDefaultArgs;
- const launchOptions: playwright.LaunchOptions & playwright.BrowserContextOptions = {
+ const launchOptions: playwrightTypes.LaunchOptions & playwrightTypes.BrowserContextOptions = {
tracesDir,
...config.browser.launchOptions,
...config.browser.contextOptions,
diff --git a/packages/playwright-core/src/tools/mcp/config.ts b/packages/playwright-core/src/tools/mcp/config.ts
index c199bbfbec..76ff160319 100644
--- a/packages/playwright-core/src/tools/mcp/config.ts
+++ b/packages/playwright-core/src/tools/mcp/config.ts
@@ -18,12 +18,12 @@ import fs from 'fs';
import path from 'path';
import os from 'os';
-import { devices } from '../../..';
+import { playwright } from '../../inprocess';
import { dotenv } from '../../utilsBundle';
import { configFromIniFile } from './configIni';
-import type * as playwright from '../../..';
+import type * as playwrightTypes from '../../..';
import type { Config, ToolCapability } from './config.d';
async function fileExistsAsync(resolved: string) {
@@ -247,7 +247,7 @@ function configFromCLIOptions(cliOptions: CLIOptions): Config & { configFile?: s
}
// Launch options
- const launchOptions: playwright.LaunchOptions = {
+ const launchOptions: playwrightTypes.LaunchOptions = {
channel,
executablePath: cliOptions.executablePath,
headless: cliOptions.headless,
@@ -270,7 +270,7 @@ function configFromCLIOptions(cliOptions: CLIOptions): Config & { configFile?: s
throw new Error('Device emulation is not supported with cdpEndpoint.');
// Context options
- const contextOptions: playwright.BrowserContextOptions = cliOptions.device ? devices[cliOptions.device] : {};
+ const contextOptions: playwrightTypes.BrowserContextOptions = cliOptions.device ? playwright.devices[cliOptions.device] : {};
if (cliOptions.storageState)
contextOptions.storageState = cliOptions.storageState;
diff --git a/packages/playwright-core/src/tools/mcp/extensionContextFactory.ts b/packages/playwright-core/src/tools/mcp/extensionContextFactory.ts
index 66210044a7..942b71cb49 100644
--- a/packages/playwright-core/src/tools/mcp/extensionContextFactory.ts
+++ b/packages/playwright-core/src/tools/mcp/extensionContextFactory.ts
@@ -14,16 +14,17 @@
* limitations under the License.
*/
-import * as playwright from '../../..';
+import { playwright } from '../../inprocess';
import { debug } from '../../utilsBundle';
import { createHttpServer, startHttpServer } from '../../server/utils/network';
import { CDPRelayServer } from './cdpRelay';
+import type * as playwrightTypes from '../../..';
import type { FullConfig } from './config';
const debugLogger = debug('pw:mcp:relay');
-export async function createExtensionBrowser(config: FullConfig, clientName: string): Promise<playwright.Browser> {
+export async function createExtensionBrowser(config: FullConfig, clientName: string): Promise<playwrightTypes.Browser> {
const httpServer = createHttpServer();
await startHttpServer(httpServer, {});
const relay = new CDPRelayServer(
diff --git a/packages/playwright-core/src/tools/trace/DEPS.list b/packages/playwright-core/src/tools/trace/DEPS.list
index b510c2bac9..9aa231b27c 100644
--- a/packages/playwright-core/src/tools/trace/DEPS.list
+++ b/packages/playwright-core/src/tools/trace/DEPS.list
@@ -4,7 +4,7 @@
./*.ts
[traceSnapshot.ts]
-../../..
+../../inprocess.ts
../../utils
../backend/browserBackend.ts
../backend/tools.ts
diff --git a/packages/playwright-core/src/tools/trace/traceSnapshot.ts b/packages/playwright-core/src/tools/trace/traceSnapshot.ts
index f3342c64b8..2805c905d3 100644
--- a/packages/playwright-core/src/tools/trace/traceSnapshot.ts
+++ b/packages/playwright-core/src/tools/trace/traceSnapshot.ts
@@ -19,7 +19,7 @@
import { TraceLoader } from '../../utils/isomorphic/trace/traceLoader';
import { BrowserBackend } from '../backend/browserBackend';
import { browserTools } from '../backend/tools';
-import * as playwright from '../../..';
+import { playwright } from '../../inprocess';
import { gracefullyCloseAll } from '../../utils';
import { parseCommand } from '../cli-daemon/command';
import { minimist } from '../cli-client/minimist';
diff --git a/packages/playwright-core/src/utils.ts b/packages/playwright-core/src/utils.ts
index bdc4d7679d..2bdb8dc009 100644
--- a/packages/playwright-core/src/utils.ts
+++ b/packages/playwright-core/src/utils.ts
@@ -14,49 +14,7 @@
* limitations under the License.
*/
-export * from './utils/isomorphic/ariaSnapshot';
-export * from './utils/isomorphic/assert';
-export * from './utils/isomorphic/colors';
-export * from './utils/isomorphic/headers';
-export * from './utils/isomorphic/imageUtils';
-export * from './utils/isomorphic/jsonSchema';
-export * from './utils/isomorphic/locatorGenerators';
-export * from './utils/isomorphic/manualPromise';
-export * from './utils/isomorphic/mimeType';
-export * from './utils/isomorphic/multimap';
-export * from './utils/isomorphic/protocolFormatter';
-export * from './utils/isomorphic/protocolMetainfo';
-export * from './utils/isomorphic/rtti';
-export * from './utils/isomorphic/semaphore';
-export * from './utils/isomorphic/stackTrace';
-export * from './utils/isomorphic/stringUtils';
-export * from './utils/isomorphic/formatUtils';
-export * from './utils/isomorphic/time';
-export * from './utils/isomorphic/timeoutRunner';
-export * from './utils/isomorphic/urlMatch';
-export * from './utils/isomorphic/yaml';
-
-export * from './server/utils/ascii';
-export * from './server/utils/comparators';
-export * from './server/utils/crypto';
-export * from './server/utils/debug';
-export * from './server/utils/debugLogger';
-export * from './server/utils/env';
-export * from './server/utils/eventsHelper';
-export * from './server/utils/expectUtils';
-export * from './server/utils/fileUtils';
-export * from './server/utils/hostPlatform';
-export * from './server/utils/httpServer';
-export * from './server/utils/network';
-export * from './server/utils/nodePlatform';
-export * from './server/utils/processLauncher';
-export * from './server/utils/profiler';
-export * from './server/utils/socksProxy';
-export * from './server/utils/spawnAsync';
-export * from './server/utils/task';
-export * from './server/utils/userAgent';
-export * from './server/utils/wsServer';
-export * from './server/utils/zipFile';
-export * from './server/utils/zones';
+export * from './utils/isomorphic';
+export * from './server/utils';
export { colors } from './utilsBundle';
diff --git a/packages/playwright-core/src/utils/isomorphic/index.ts b/packages/playwright-core/src/utils/isomorphic/index.ts
new file mode 100644
index 0000000000..ada2af9bee
--- /dev/null
+++ b/packages/playwright-core/src/utils/isomorphic/index.ts
@@ -0,0 +1,37 @@
+/**
+ * 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.
+ */
+
+export * from './ariaSnapshot';
+export * from './assert';
+export * from './colors';
+export * from './headers';
+export * from './imageUtils';
+export * from './jsonSchema';
+export * from './locatorGenerators';
+export * from './manualPromise';
+export * from './mimeType';
+export * from './multimap';
+export * from './protocolFormatter';
+export * from './protocolMetainfo';
+export * from './rtti';
+export * from './semaphore';
+export * from './stackTrace';
+export * from './stringUtils';
+export * from './formatUtils';
+export * from './time';
+export * from './timeoutRunner';
+export * from './urlMatch';
+export * from './yaml';
diff --git a/packages/playwright-ct-core/src/vitePlugin.ts b/packages/playwright-ct-core/src/vitePlugin.ts
index ad9cd4adc9..9a8912b75c 100644
--- a/packages/playwright-ct-core/src/vitePlugin.ts
+++ b/packages/playwright-ct-core/src/vitePlugin.ts
@@ -17,7 +17,7 @@
import fs from 'fs';
import path from 'path';
-import { assert, calculateSha1, getPlaywrightVersion, isURLAvailable } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { colors, debug } from 'playwright-core/lib/utilsBundle';
import { setExternalDependencies } from 'playwright/lib/transform/compilationCache';
import { resolveHook } from 'playwright/lib/transform/transform';
@@ -41,7 +41,7 @@ import type { ComponentRegistry } from './viteUtils';
const log = debug('pw:vite');
let stoppableServer: any;
-const playwrightVersion = getPlaywrightVersion();
+const playwrightVersion = serverUtils.getPlaywrightVersion();
export function createPlugin(): TestRunnerPlugin {
let configDir: string;
@@ -115,7 +115,7 @@ export async function buildBundle(config: FullConfig, configDir: string): Promis
const endpoint = resolveEndpoint(config);
const protocol = endpoint.https ? 'https:' : 'http:';
const url = new URL(`${protocol}//${endpoint.host}:${endpoint.port}`);
- if (await isURLAvailable(url, true)) {
+ if (await serverUtils.isURLAvailable(url, true)) {
// eslint-disable-next-line no-console
console.log(`Dev Server is already running at ${url.toString()}, using it.\n`);
process.env.PLAYWRIGHT_TEST_BASE_URL = url.toString();
@@ -136,15 +136,15 @@ export async function buildBundle(config: FullConfig, configDir: string): Promis
let buildInfo: BuildInfo;
const registerSource = injectedSource + '\n' + await fs.promises.readFile(registerSourceFile, 'utf-8');
- const registerSourceHash = calculateSha1(registerSource);
+ const registerSourceHash = serverUtils.calculateSha1(registerSource);
const { version: viteVersion, build, mergeConfig } = await import('vite');
try {
buildInfo = JSON.parse(await fs.promises.readFile(buildInfoFile, 'utf-8')) as BuildInfo;
- assert(buildInfo.version === playwrightVersion);
- assert(buildInfo.viteVersion === viteVersion);
- assert(buildInfo.registerSourceHash === registerSourceHash);
+ iso.assert(buildInfo.version === playwrightVersion);
+ iso.assert(buildInfo.viteVersion === viteVersion);
+ iso.assert(buildInfo.registerSourceHash === registerSourceHash);
buildExists = true;
} catch (e) {
buildInfo = {
diff --git a/packages/playwright-firefox/cli.js b/packages/playwright-firefox/cli.js
index f46d8b409e..1ab7f499d7 100755
--- a/packages/playwright-firefox/cli.js
+++ b/packages/playwright-firefox/cli.js
@@ -15,5 +15,7 @@
* limitations under the License.
*/
-const { program } = require('playwright-core/lib/cli/program');
+const { program } = require('playwright-core/lib/utilsBundle');
+const { libCli } = require('playwright-core/lib/coreBundle');
+libCli.decorateProgram(program);
program.parse(process.argv);
diff --git a/packages/playwright-firefox/install.js b/packages/playwright-firefox/install.js
index a917664fc0..561032d644 100644
--- a/packages/playwright-firefox/install.js
+++ b/packages/playwright-firefox/install.js
@@ -17,8 +17,8 @@
let install;
try {
- if (!require('playwright-core/lib/utils').isLikelyNpxGlobal())
- install = require('playwright-core/lib/server').installBrowsersForNpmInstall;
+ if (!require('playwright-core/lib/coreBundle').serverUtils.isLikelyNpxGlobal())
+ install = require('playwright-core/lib/coreBundle').sever.installBrowsersForNpmInstall;
} catch (e) {
// Dev build, don't install browsers by default.
}
diff --git a/packages/playwright-webkit/cli.js b/packages/playwright-webkit/cli.js
index f46d8b409e..1ab7f499d7 100755
--- a/packages/playwright-webkit/cli.js
+++ b/packages/playwright-webkit/cli.js
@@ -15,5 +15,7 @@
* limitations under the License.
*/
-const { program } = require('playwright-core/lib/cli/program');
+const { program } = require('playwright-core/lib/utilsBundle');
+const { libCli } = require('playwright-core/lib/coreBundle');
+libCli.decorateProgram(program);
program.parse(process.argv);
diff --git a/packages/playwright-webkit/install.js b/packages/playwright-webkit/install.js
index 237ee38d63..dbb98b90eb 100644
--- a/packages/playwright-webkit/install.js
+++ b/packages/playwright-webkit/install.js
@@ -17,8 +17,8 @@
let install;
try {
- if (!require('playwright-core/lib/utils').isLikelyNpxGlobal())
- install = require('playwright-core/lib/server').installBrowsersForNpmInstall;
+ if (!require('playwright-core/lib/coreBundle').serverUtils.isLikelyNpxGlobal())
+ install = require('playwright-core/lib/coreBundle').sever.installBrowsersForNpmInstall;
} catch (e) {
// Dev build, don't install browsers by default.
}
diff --git a/packages/playwright/src/agents/generateAgents.ts b/packages/playwright/src/agents/generateAgents.ts
index 1ae032914e..e4095fbda2 100644
--- a/packages/playwright/src/agents/generateAgents.ts
+++ b/packages/playwright/src/agents/generateAgents.ts
@@ -18,8 +18,7 @@ import fs from 'fs';
import path from 'path';
import { colors, yaml } from 'playwright-core/lib/utilsBundle';
-import { mkdirIfNeeded } from 'playwright-core/lib/utils';
-
+import { serverUtils } from 'playwright-core/lib/coreBundle';
import { FullConfigInternal } from '../common/config';
import { defaultSeedFile, findSeedFile, seedFileContent, seedProject } from '../mcp/test/seed';
import { parseAgentSpec } from './agentParser';
@@ -318,7 +317,7 @@ export class VSCodeGenerator {
async function writeFile(filePath: string, content: string, icon: string, description: string) {
console.log(` ${icon} ${path.relative(process.cwd(), filePath)} ${colors.dim('- ' + description)}`);
- await mkdirIfNeeded(filePath);
+ await serverUtils.mkdirIfNeeded(filePath);
await fs.promises.writeFile(filePath, content, 'utf-8');
}
diff --git a/packages/playwright/src/common/configLoader.ts b/packages/playwright/src/common/configLoader.ts
index 4d35f4087a..d35d82dc6c 100644
--- a/packages/playwright/src/common/configLoader.ts
+++ b/packages/playwright/src/common/configLoader.ts
@@ -17,8 +17,7 @@
import fs from 'fs';
import path from 'path';
-import { isRegExp } from 'playwright-core/lib/utils';
-
+import { iso } from 'playwright-core/lib/coreBundle';
import { requireOrImport, setSingleTSConfig, setTransformConfig } from '../transform/transform';
import { errorWithFile, fileIsModule } from '../util';
import { FullConfigInternal } from './config';
@@ -29,6 +28,8 @@ import type { ConfigLocation } from './config';
import type { ConfigCLIOverrides, SerializedConfig } from './ipc';
import type { Config, Project } from '../../types/test';
+const { isRegExp } = iso;
+
const kDefineConfigWasUsed = Symbol('defineConfigWasUsed');
export const defineConfig = (...configs: any[]) => {
let result = configs[0];
diff --git a/packages/playwright/src/common/process.ts b/packages/playwright/src/common/process.ts
index 727c1d9968..5ce8b0dec0 100644
--- a/packages/playwright/src/common/process.ts
+++ b/packages/playwright/src/common/process.ts
@@ -15,12 +15,13 @@
*/
import 'playwright-core/lib/bootstrap';
-import { ManualPromise, setTimeOrigin, startProfiling, stopProfiling } from 'playwright-core/lib/utils';
-
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { serializeError } from '../util';
import type { EnvProducedPayload, ProcessInitParams, TestInfoErrorImpl } from './ipc';
+type ManualPromise<T = void> = iso.ManualPromise<T>;
+
export type ProtocolRequest = {
id: number;
method: string;
@@ -68,8 +69,8 @@ const startingEnv = { ...process.env };
process.on('message', async (message: any) => {
if (message.method === '__init__') {
const { processParams, runnerParams, runnerScript } = message.params as { processParams: ProcessInitParams, runnerParams: any, runnerScript: string };
- void startProfiling();
- setTimeOrigin(processParams.timeOrigin);
+ void serverUtils.startProfiling();
+ iso.setTimeOrigin(processParams.timeOrigin);
const { create } = require(runnerScript);
processRunner = create(runnerParams) as ProcessRunner;
processName = processParams.processName;
@@ -111,7 +112,7 @@ async function gracefullyCloseAndExit(forceExit: boolean) {
// Meanwhile, try to gracefully shutdown.
await processRunner?.gracefullyClose().catch(() => {});
if (processName)
- await stopProfiling(processName).catch(() => {});
+ await serverUtils.stopProfiling(processName).catch(() => {});
// eslint-disable-next-line no-restricted-properties
process.exit(0);
}
@@ -138,7 +139,7 @@ const requestCallbacks = new Map<number, ManualPromise<any>>();
async function sendRequestToParent(method: string, params?: any): Promise<any> {
const id = ++lastId;
sendMessageToParent({ method: '__request__', params: { id, method, params } });
- const promise = new ManualPromise<any>();
+ const promise = new iso.ManualPromise<any>();
requestCallbacks.set(id, promise);
return promise;
}
diff --git a/packages/playwright/src/common/suiteUtils.ts b/packages/playwright/src/common/suiteUtils.ts
index 61389b1076..49050c85c1 100644
--- a/packages/playwright/src/common/suiteUtils.ts
+++ b/packages/playwright/src/common/suiteUtils.ts
@@ -16,7 +16,7 @@
import path from 'path';
-import { calculateSha1, toPosixPath } from 'playwright-core/lib/utils';
+import { serverUtils } from 'playwright-core/lib/coreBundle';
import { createFileMatcher, forceRegExp, parseLocationArg } from '../util';
import type { FullProjectInternal } from './config';
@@ -33,7 +33,7 @@ export function filterTestsRemoveEmptySuites(suite: Suite, filter: TestCaseFilte
export function bindFileSuiteToProject(project: FullProjectInternal, suite: Suite): Suite {
const relativeFile = path.relative(project.project.testDir, suite.location!.file);
- const fileId = calculateSha1(toPosixPath(relativeFile)).slice(0, 20);
+ const fileId = serverUtils.calculateSha1(serverUtils.toPosixPath(relativeFile)).slice(0, 20);
// Clone suite.
const result = suite._deepClone();
@@ -44,8 +44,8 @@ export function bindFileSuiteToProject(project: FullProjectInternal, suite: Suit
suite._fileId = fileId;
// At the point of the query, suite is not yet attached to the project, so we only get file, describe and test titles.
const [file, ...titles] = test.titlePath();
- const testIdExpression = `[project=${project.id}]${toPosixPath(file)}\x1e${titles.join('\x1e')}`;
- const testId = fileId + '-' + calculateSha1(testIdExpression).slice(0, 20);
+ const testIdExpression = `[project=${project.id}]${serverUtils.toPosixPath(file)}\x1e${titles.join('\x1e')}`;
+ const testId = fileId + '-' + serverUtils.calculateSha1(testIdExpression).slice(0, 20);
test.id = testId;
test._projectId = project.id;
@@ -80,8 +80,8 @@ export function applyRepeatEachIndex(project: FullProjectInternal, fileSuite: Su
fileSuite.forEachTest((test, suite) => {
if (repeatEachIndex) {
const [file, ...titles] = test.titlePath();
- const testIdExpression = `[project=${project.id}]${toPosixPath(file)}\x1e${titles.join('\x1e')} (repeat:${repeatEachIndex})`;
- const testId = suite._fileId + '-' + calculateSha1(testIdExpression).slice(0, 20);
+ const testIdExpression = `[project=${project.id}]${serverUtils.toPosixPath(file)}\x1e${titles.join('\x1e')} (repeat:${repeatEachIndex})`;
+ const testId = suite._fileId + '-' + serverUtils.calculateSha1(testIdExpression).slice(0, 20);
test.id = testId;
test.repeatEachIndex = repeatEachIndex;
diff --git a/packages/playwright/src/common/testType.ts b/packages/playwright/src/common/testType.ts
index a6b1c3be6f..3d91e74152 100644
--- a/packages/playwright/src/common/testType.ts
+++ b/packages/playwright/src/common/testType.ts
@@ -15,8 +15,7 @@
*/
import { errors } from 'playwright-core';
-import { getPackageManagerExecCommand, monotonicTime, raceAgainstDeadline, currentZone } from 'playwright-core/lib/utils';
-
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { currentTestInfo, currentlyLoadingFileSuite, setCurrentlyLoadingFileSuite } from './globals';
import { Suite, TestCase } from './test';
import { expect } from '../matchers/expect';
@@ -267,10 +266,10 @@ export class TestTypeImpl {
throw new Error(`test.step() can only be called from a test`);
await testInfo._onUserStepBegin?.(title);
const step = testInfo._addStep({ category: 'test.step', title, location: options.location, box: options.box });
- return await currentZone().with('stepZone', step).run(async () => {
+ return await serverUtils.currentZone().with('stepZone', step).run(async () => {
try {
- let result: Awaited<ReturnType<typeof raceAgainstDeadline<T>>> | undefined = undefined;
- result = await raceAgainstDeadline(async () => {
+ let result: Awaited<ReturnType<typeof iso.raceAgainstDeadline<T>>> | undefined = undefined;
+ result = await iso.raceAgainstDeadline(async () => {
try {
return await step.info._runStepBody(expectation === 'skip', body, step.location);
} catch (e) {
@@ -280,7 +279,7 @@ export class TestTypeImpl {
testInfo._failWithError(e);
throw e;
}
- }, options.timeout ? monotonicTime() + options.timeout : 0);
+ }, options.timeout ? iso.monotonicTime() + options.timeout : 0);
if (result.timedOut)
throw new errors.TimeoutError(`Step timeout of ${options.timeout}ms exceeded.`);
step.complete({});
@@ -304,7 +303,7 @@ export class TestTypeImpl {
function throwIfRunningInsideJest() {
if (process.env.JEST_WORKER_ID) {
- const packageManagerCommand = getPackageManagerExecCommand();
+ const packageManagerCommand = serverUtils.getPackageManagerExecCommand();
throw new Error(
`Playwright Test needs to be invoked via '${packageManagerCommand} playwright test' and excluded from Jest test runs.\n` +
`Creating one directory for Playwright tests and one for Jest is the recommended way of doing it.\n` +
diff --git a/packages/playwright/src/common/validators.ts b/packages/playwright/src/common/validators.ts
index 5ab1bd803a..25474f50a4 100644
--- a/packages/playwright/src/common/validators.ts
+++ b/packages/playwright/src/common/validators.ts
@@ -14,11 +14,11 @@
* limitations under the License.
*/
-import { validate } from 'playwright-core/lib/utils';
-
+import { iso } from 'playwright-core/lib/coreBundle';
import type { TestDetailsAnnotation } from '../../types/test';
import type { Location } from '../../types/testReporter';
-import type { JsonSchema } from 'playwright-core/lib/utils';
+
+type JsonSchema = iso.JsonSchema;
const testAnnotationSchema: JsonSchema = {
type: 'object',
@@ -54,7 +54,7 @@ type ValidTestDetails = {
};
export function validateTestDetails(details: unknown, location: Location): ValidTestDetails {
- const errors = validate(details, testDetailsSchema, 'details');
+ const errors = iso.validate(details, testDetailsSchema, 'details');
if (errors.length)
throw new Error(errors.join('\n'));
diff --git a/packages/playwright/src/errorContext.ts b/packages/playwright/src/errorContext.ts
index a5ab393a82..3c86c4f56f 100644
--- a/packages/playwright/src/errorContext.ts
+++ b/packages/playwright/src/errorContext.ts
@@ -17,8 +17,7 @@
import fs from 'fs';
import path from 'path';
-import { parseErrorStack, stripAnsiEscapes } from 'playwright-core/lib/utils';
-
+import { iso } from 'playwright-core/lib/coreBundle';
import { relativeFilePath } from './util';
import type { TestInfoError } from '../types/test';
@@ -58,7 +57,7 @@ export function buildErrorContext(options: {
lines.push(
'',
'```',
- stripAnsiEscapes(error.message || ''),
+ iso.stripAnsiEscapes(error.message || ''),
'```',
);
}
@@ -96,7 +95,7 @@ function buildCodeFrame(error: TestInfoError, testLocation: { file: string; line
if (!stack)
return undefined;
- const parsed = parseErrorStack(stack, path.sep);
+ const parsed = iso.parseErrorStack(stack, path.sep);
const errorLocation = parsed.location;
if (!errorLocation)
return undefined;
@@ -115,7 +114,7 @@ function buildCodeFrame(error: TestInfoError, testLocation: { file: string; line
const end = Math.min(sourceLines.length, errorLocation.line + linesBelow);
const scope = sourceLines.slice(start, end);
const lineNumberWidth = String(end).length;
- const message = stripAnsiEscapes(error.message || '').split('\n')[0] || undefined;
+ const message = iso.stripAnsiEscapes(error.message || '').split('\n')[0] || undefined;
const frame = scope.map((line, index) => `${(start + index + 1) === errorLocation.line ? '> ' : ' '}${(start + index + 1).toString().padEnd(lineNumberWidth, ' ')} | ${line}`);
if (message)
frame.splice(errorLocation.line - start, 0, `${' '.repeat(lineNumberWidth + 2)} | ${' '.repeat(Math.max(0, errorLocation.column - 2))} ^ ${message}`);
diff --git a/packages/playwright/src/index.ts b/packages/playwright/src/index.ts
index 0f61235bc7..f47cc7bcf2 100644
--- a/packages/playwright/src/index.ts
+++ b/packages/playwright/src/index.ts
@@ -18,7 +18,7 @@ import fs from 'fs';
import path from 'path';
import * as playwrightLibrary from 'playwright-core';
-import { setBoxedStackPrefixes, createGuid, currentZone, debugMode, jsonStringifyForceASCII, asLocatorDescription, renderTitleForCall, getActionGroup, escapeHTML } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { buildErrorContext } from './errorContext';
import { currentTestInfo } from './common/globals';
import { rootTestType } from './common/testType';
@@ -39,7 +39,7 @@ import type { BrowserContext, BrowserContextOptions, LaunchOptions, Page, Tracin
export { expect } from './matchers/expect';
export const _baseTest: TestType<{}, {}> = rootTestType.test;
-setBoxedStackPrefixes([path.dirname(require.resolve('../package.json'))]);
+serverUtils.setBoxedStackPrefixes([path.dirname(require.resolve('../package.json'))]);
if ((process as any)['__pw_initiator__']) {
const originalStackTraceLimit = Error.stackTraceLimit;
@@ -111,7 +111,7 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
exposeNetwork: connectOptions.exposeNetwork,
headers: {
// HTTP headers are ASCII only (not UTF-8).
- 'x-playwright-launch-options': jsonStringifyForceASCII(_browserOptions),
+ 'x-playwright-launch-options': serverUtils.jsonStringifyForceASCII(_browserOptions),
...connectOptions.headers,
},
});
@@ -238,7 +238,7 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
playwrightLibrary.selectors.setTestIdAttribute(testIdAttribute);
testInfo.snapshotSuffix = process.platform;
testInfo._onCustomMessageCallback = () => Promise.reject(new Error('Only tests that use default Playwright context or page fixture support test_debug'));
- if (debugMode() === 'inspector')
+ if (serverUtils.debugMode() === 'inspector')
(testInfo as TestInfoImpl)._setIgnoreTimeouts(true);
playwright._defaultContextTimeout = actionTimeout || 0;
@@ -265,7 +265,7 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
// Some special calls do not get into steps.
if (!testInfo || data.apiName.includes('setTestIdAttribute') || data.apiName === 'tracing.groupEnd')
return;
- const zone = currentZone().data<TestStepInternal>('stepZone');
+ const zone = serverUtils.currentZone().data<TestStepInternal>('stepZone');
const isExpectCall = data.apiName === 'locator._expect' || data.apiName === 'frame._expect' || data.apiName === 'page._expectScreenshot';
if (zone && zone.category === 'expect' && isExpectCall) {
// Display the internal locator._expect call under the name of the enclosing expect call,
@@ -285,7 +285,7 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
title: renderTitle(channel.type, channel.method, channel.params, data.title),
apiName: data.apiName,
params: channel.params,
- group: getActionGroup({ type: channel.type, method: channel.method }),
+ group: iso.getActionGroup({ type: channel.type, method: channel.method }),
}, tracingGroupSteps[tracingGroupSteps.length - 1]);
data.userData = step;
data.stepId = step.stepId;
@@ -642,7 +642,7 @@ class SnapshotRecorder {
return;
(page as any)[this.testInfo._uniqueSymbol] = true;
try {
- const path = temporary ? this._createTemporaryArtifact(createGuid() + this._extension) : this._createAttachmentPath();
+ const path = temporary ? this._createTemporaryArtifact(serverUtils.createGuid() + this._extension) : this._createAttachmentPath();
await this._doSnapshot(page, path);
if (temporary)
this._temporary.push(path);
@@ -850,15 +850,15 @@ function createTestOverlay(parts: string[], position: string, fontSize: number)
};
const posStyle = positionStyles[position] ?? positionStyles['top-left'];
return `<div style="white-space: nowrap; font-size: ${fontSize}px; padding: 3px 6px; background: rgba(0,0,0,0.5); color: white; border-radius: 4px; position: absolute; ${posStyle}">
- ${parts.map(p => `<div>${escapeHTML(p)}</div>`).join('')}
+ ${parts.map(p => `<div>${iso.escapeHTML(p)}</div>`).join('')}
</div>`;
}
function renderTitle(type: string, method: string, params: Record<string, string> | undefined, title?: string) {
- const prefix = renderTitleForCall({ title, type, method, params });
+ const prefix = iso.renderTitleForCall({ title, type, method, params });
let selector;
if (params?.['selector'] && typeof params.selector === 'string')
- selector = asLocatorDescription('javascript', params.selector);
+ selector = iso.asLocatorDescription('javascript', params.selector);
return prefix + (selector ? ` ${selector}` : '');
}
diff --git a/packages/playwright/src/matchers/expect.ts b/packages/playwright/src/matchers/expect.ts
index 02d2da2f0c..48e92f4500 100644
--- a/packages/playwright/src/matchers/expect.ts
+++ b/packages/playwright/src/matchers/expect.ts
@@ -14,13 +14,7 @@
* limitations under the License.
*/
-import {
- captureRawStack,
- createGuid,
- currentZone,
- escapeWithQuotes,
- isString,
- pollAgainstDeadline } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { ExpectError, isJestError } from './matcherHint';
import {
@@ -84,7 +78,7 @@ function createExpect(info: ExpectMetaInfo, prefix: string[], userMatchers: Reco
const expectInstance: Expect<{}> = new Proxy(expectLibrary, {
apply: function(target: any, thisArg: any, argumentsList: [unknown, ExpectMessage?]) {
const [actual, messageOrOptions] = argumentsList;
- const message = isString(messageOrOptions) ? messageOrOptions : messageOrOptions?.message || info.message;
+ const message = iso.isString(messageOrOptions) ? messageOrOptions : messageOrOptions?.message || info.message;
const newInfo = { ...info, message };
if (newInfo.poll) {
if (typeof actual !== 'function')
@@ -100,7 +94,7 @@ function createExpect(info: ExpectMetaInfo, prefix: string[], userMatchers: Reco
if (property === 'extend') {
return (matchers: any) => {
- const qualifier = [...prefix, createGuid()];
+ const qualifier = [...prefix, serverUtils.createGuid()];
const wrappedMatchers: any = {};
for (const [name, matcher] of Object.entries(matchers)) {
@@ -125,7 +119,7 @@ function createExpect(info: ExpectMetaInfo, prefix: string[], userMatchers: Reco
if (property === 'poll') {
return (actual: unknown, messageOrOptions?: ExpectMessage & { timeout?: number, intervals?: number[] }) => {
- const poll = isString(messageOrOptions) ? {} : messageOrOptions || {};
+ const poll = iso.isString(messageOrOptions) ? {} : messageOrOptions || {};
return configure({ _poll: poll })(actual, messageOrOptions) as any;
};
}
@@ -305,13 +299,13 @@ class ExpectMetaInfoProxyHandler implements ProxyHandler<any> {
const customMessage = this._info.message || '';
const suffixes = computeMatcherTitleSuffix(matcherName, this._actual, args);
const defaultTitle = `${this._info.poll ? 'poll ' : ''}${this._info.isSoft ? 'soft ' : ''}${this._info.isNot ? 'not ' : ''}${matcherName}${suffixes.short || ''}`;
- const shortTitle = customMessage || `Expect ${escapeWithQuotes(defaultTitle, '"')}`;
+ const shortTitle = customMessage || `Expect ${iso.escapeWithQuotes(defaultTitle, '"')}`;
const longTitle = shortTitle + (suffixes.long || '');
const apiName = `expect${this._info.poll ? '.poll ' : ''}${this._info.isSoft ? '.soft ' : ''}${this._info.isNot ? '.not' : ''}.${matcherName}${suffixes.short || ''}`;
// This looks like it is unnecessary, but it isn't - we need to filter
// out all the frames that belong to the test runner from caught runtime errors.
- const stackFrames = filteredStackTrace(captureRawStack());
+ const stackFrames = filteredStackTrace(iso.captureRawStack());
// toPass and poll matchers can contain other steps, expects and API calls,
// so they behave like a retriable step.
@@ -352,7 +346,7 @@ class ExpectMetaInfoProxyHandler implements ProxyHandler<any> {
try {
setMatcherCallContext({ expectInfo: this._info, testInfo, step: step.info });
const callback = () => matcher.call(target, ...args);
- const result = currentZone().with('stepZone', step).run(callback);
+ const result = serverUtils.currentZone().with('stepZone', step).run(callback);
if (result instanceof Promise)
return result.then(finalizer).catch(reportStepError);
finalizer();
@@ -370,7 +364,7 @@ async function pollMatcher(qualifiedMatcherName: string, info: ExpectMetaInfo, p
const timeout = poll.timeout ?? info.timeout ?? testInfo?._projectInternal?.expect?.timeout ?? defaultExpectTimeout;
const { deadline, timeoutMessage } = testInfo ? testInfo._deadlineForMatcher(timeout) : TestInfoImpl._defaultDeadlineForMatcher(timeout);
- const result = await pollAgainstDeadline<Error|undefined>(async () => {
+ const result = await iso.pollAgainstDeadline<Error|undefined>(async () => {
if (testInfo && currentTestInfo() !== testInfo)
return { continuePolling: false, result: undefined };
diff --git a/packages/playwright/src/matchers/matcherHint.ts b/packages/playwright/src/matchers/matcherHint.ts
index bc7e846bab..63016189b8 100644
--- a/packages/playwright/src/matchers/matcherHint.ts
+++ b/packages/playwright/src/matchers/matcherHint.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { stringifyStackFrames } from 'playwright-core/lib/utils';
+import { iso } from 'playwright-core/lib/coreBundle';
import type { StackFrame } from '@protocol/channels';
@@ -49,7 +49,7 @@ export class ExpectError extends Error {
if (customMessage)
this.message = customMessage + '\n\n' + this.message;
- this.stack = this.name + ': ' + this.message + '\n' + stringifyStackFrames(stackFrames).join('\n');
+ this.stack = this.name + ': ' + this.message + '\n' + iso.stringifyStackFrames(stackFrames).join('\n');
}
}
diff --git a/packages/playwright/src/matchers/matchers.ts b/packages/playwright/src/matchers/matchers.ts
index 826b3a6c94..0c6825b2d4 100644
--- a/packages/playwright/src/matchers/matchers.ts
+++ b/packages/playwright/src/matchers/matchers.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { asLocatorDescription, constructURLBasedOnBaseURL, isRegExp, isString, isTextualMimeType, isURLPattern, pollAgainstDeadline, serializeExpectedTextValues, formatMatcherMessage } from 'playwright-core/lib/utils';
-import { colors } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { colors } from 'playwright-core/lib/utilsBundle';
import { expectTypes } from '../util';
import { toBeTruthy } from './toBeTruthy';
@@ -33,7 +33,9 @@ import type { TestStepInfoImpl } from '../worker/testInfo';
import type { APIResponse, Locator, Frame, Page } from 'playwright-core';
import type { FrameExpectParams } from 'playwright-core/lib/client/types';
import type { ExpectMatcherUtils } from '../../types/test';
-import type { InternalMatcherUtils, URLPattern } from 'playwright-core/lib/utils';
+type InternalMatcherUtils = serverUtils.InternalMatcherUtils;
+type URLPattern = iso.URLPattern;
+const { serializeExpectedTextValues } = serverUtils;
export type ExpectMatcherStateInternal = Omit<ExpectMatcherState, 'utils'> & {
_stepInfo?: TestStepInfoImpl;
@@ -244,7 +246,7 @@ export function toHaveAttribute(
) {
if (!options) {
// Update params for the case toHaveAttribute(name, options);
- if (typeof expected === 'object' && !isRegExp(expected)) {
+ if (typeof expected === 'object' && !iso.isRegExp(expected)) {
options = expected;
expected = undefined;
}
@@ -286,14 +288,14 @@ export function toContainClass(
options?: { timeout?: number },
) {
if (Array.isArray(expected)) {
- if (expected.some(e => isRegExp(e)))
+ if (expected.some(e => iso.isRegExp(e)))
throw new Error(`"expected" argument in toContainClass cannot contain RegExp values`);
return toEqual.call(this, 'toContainClass', locator, 'Locator', async (isNot, timeout) => {
const expectedText = serializeExpectedTextValues(expected);
return await locator._expect('to.contain.class.array', { expectedText, isNot, timeout });
}, expected, options);
} else {
- if (isRegExp(expected))
+ if (iso.isRegExp(expected))
throw new Error(`"expected" argument in toContainClass cannot be a RegExp value`);
return toMatchText.call(this, 'toContainClass', locator, 'Locator', async (isNot, timeout) => {
const expectedText = serializeExpectedTextValues([expected]);
@@ -357,7 +359,7 @@ export function toHaveRole(
expected: string,
options?: { timeout?: number, ignoreCase?: boolean },
) {
- if (!isString(expected))
+ if (!iso.isString(expected))
throw new Error(`"role" argument in toHaveRole must be a string`);
return toMatchText.call(this, 'toHaveRole', locator, 'Locator', async (isNot, timeout) => {
const expectedText = serializeExpectedTextValues([expected]);
@@ -426,7 +428,7 @@ export function toHaveURL(
expected: string | RegExp | URLPattern | ((url: URL) => boolean),
options?: { ignoreCase?: boolean; timeout?: number },
) {
- if (isURLPattern(expected))
+ if (iso.isURLPattern(expected))
return toHaveURLWithPredicate.call(this, page, url => (expected as URLPattern).test(url.href), options);
// Ports don't support predicates. Keep separate server and client codepaths
@@ -434,7 +436,7 @@ export function toHaveURL(
return toHaveURLWithPredicate.call(this, page, expected, options);
const baseURL = (page.context() as any)._options.baseURL;
- expected = typeof expected === 'string' ? constructURLBasedOnBaseURL(baseURL, expected) : expected;
+ expected = typeof expected === 'string' ? iso.constructURLBasedOnBaseURL(baseURL, expected) : expected;
return toMatchText.call(this, 'toHaveURL', page, 'Page', async (isNot, timeout) => {
const expectedText = serializeExpectedTextValues([expected], { ignoreCase: options?.ignoreCase });
return await (page.mainFrame() as FrameEx)._expect('to.have.url', { expectedText, isNot, timeout });
@@ -449,13 +451,13 @@ export async function toBeOK(
expectTypes(response, ['APIResponse'], matcherName);
const contentType = response.headers()['content-type'];
- const isTextEncoding = contentType && isTextualMimeType(contentType);
+ const isTextEncoding = contentType && iso.isTextualMimeType(contentType);
const [log, text] = (this.isNot === response.ok()) ? await Promise.all([
response._fetchLog(),
isTextEncoding ? response.text() : null
]) : [];
- const message = () => formatMatcherMessage(this.utils, {
+ const message = () => serverUtils.formatMatcherMessage(this.utils, {
isNot: this.isNot,
promise: this.promise,
matcherName,
@@ -481,7 +483,7 @@ export async function toPass(
const intervals = takeFirst(options.intervals, testInfo?._projectInternal.expect?.toPass?.intervals, [100, 250, 500, 1000]);
const { deadline, timeoutMessage } = testInfo ? testInfo._deadlineForMatcher(timeout) : TestInfoImpl._defaultDeadlineForMatcher(timeout);
- const result = await pollAgainstDeadline<Error|undefined>(async () => {
+ const result = await iso.pollAgainstDeadline<Error|undefined>(async () => {
if (testInfo && currentTestInfo() !== testInfo)
return { continuePolling: false, result: undefined };
try {
@@ -511,7 +513,7 @@ export function computeMatcherTitleSuffix(matcherName: string, receiver: any, ar
}
if (receiver && typeof receiver === 'object' && receiver.constructor?.name === 'Locator') {
try {
- return { long: ' ' + asLocatorDescription('javascript', (receiver as LocatorEx)._selector) };
+ return { long: ' ' + iso.asLocatorDescription('javascript', (receiver as LocatorEx)._selector) };
} catch {
}
}
diff --git a/packages/playwright/src/matchers/toBeTruthy.ts b/packages/playwright/src/matchers/toBeTruthy.ts
index 3f4dc9c71e..d92a3a92e7 100644
--- a/packages/playwright/src/matchers/toBeTruthy.ts
+++ b/packages/playwright/src/matchers/toBeTruthy.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { formatMatcherMessage } from 'playwright-core/lib/utils';
+import { serverUtils } from 'playwright-core/lib/coreBundle';
import { expectTypes } from '../util';
@@ -57,7 +57,7 @@ export async function toBeTruthy(
printedReceived = errorMessage ? '' : `Received: ${received}`;
}
const message = () => {
- return formatMatcherMessage(this.utils, {
+ return serverUtils.formatMatcherMessage(this.utils, {
isNot: this.isNot,
promise: this.promise,
matcherName,
diff --git a/packages/playwright/src/matchers/toEqual.ts b/packages/playwright/src/matchers/toEqual.ts
index e158f61802..e60260dbc9 100644
--- a/packages/playwright/src/matchers/toEqual.ts
+++ b/packages/playwright/src/matchers/toEqual.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { formatMatcherMessage, isRegExp } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { expectTypes } from '../util';
@@ -61,7 +61,7 @@ export async function toEqual<T>(
} else if (Array.isArray(expected) && Array.isArray(received)) {
const normalizedExpected = expected.map((exp, index) => {
const rec = received[index];
- if (isRegExp(exp))
+ if (iso.isRegExp(exp))
return exp.test(rec) ? rec : exp;
return exp;
@@ -83,7 +83,7 @@ export async function toEqual<T>(
);
}
const message = () => {
- return formatMatcherMessage(this.utils, {
+ return serverUtils.formatMatcherMessage(this.utils, {
isNot: this.isNot,
promise: this.promise,
matcherName,
diff --git a/packages/playwright/src/matchers/toHaveURL.ts b/packages/playwright/src/matchers/toHaveURL.ts
index 959eca13c1..8d6667ad82 100644
--- a/packages/playwright/src/matchers/toHaveURL.ts
+++ b/packages/playwright/src/matchers/toHaveURL.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { formatMatcherMessage, printReceivedStringContainExpectedResult, urlMatches } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import type { MatcherResult } from './matcherHint';
import type { Page } from 'playwright-core';
@@ -39,7 +39,7 @@ export async function toHaveURLWithPredicate(
if (options?.ignoreCase) {
return (
!this.isNot ===
- urlMatches(
+ iso.urlMatches(
baseURL?.toLocaleLowerCase(),
lastCheckedURLString.toLocaleLowerCase(),
expected,
@@ -48,7 +48,7 @@ export async function toHaveURLWithPredicate(
}
return (
- !this.isNot === urlMatches(baseURL, lastCheckedURLString, expected)
+ !this.isNot === iso.urlMatches(baseURL, lastCheckedURLString, expected)
);
},
{ timeout },
@@ -100,7 +100,7 @@ function toHaveURLMessage(
} else {
if (pass) {
printedExpected = `Expected pattern: not ${state.utils.printExpected(expected)}`;
- const formattedReceived = printReceivedStringContainExpectedResult(state.utils, receivedString, null);
+ const formattedReceived = serverUtils.printReceivedStringContainExpectedResult(state.utils, receivedString, null);
printedReceived = `Received string: ${formattedReceived}`;
} else {
const labelExpected = `Expected ${typeof expected === 'string' ? 'string' : 'pattern'}`;
@@ -108,7 +108,7 @@ function toHaveURLMessage(
}
}
- return formatMatcherMessage(state.utils, {
+ return serverUtils.formatMatcherMessage(state.utils, {
isNot: state.isNot,
promise: state.promise,
matcherName,
diff --git a/packages/playwright/src/matchers/toMatchAriaSnapshot.ts b/packages/playwright/src/matchers/toMatchAriaSnapshot.ts
index f1959cf644..a63a645684 100644
--- a/packages/playwright/src/matchers/toMatchAriaSnapshot.ts
+++ b/packages/playwright/src/matchers/toMatchAriaSnapshot.ts
@@ -18,7 +18,7 @@
import fs from 'fs';
import path from 'path';
-import { formatMatcherMessage, escapeTemplateString, isString, printReceivedStringContainExpectedSubstring } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { expectTypes, fileExistsAsync } from '../util';
import { currentTestInfo } from '../common/globals';
@@ -57,7 +57,7 @@ export async function toMatchAriaSnapshot(
let expected: string;
let timeout: number;
let expectedPath: string | undefined;
- if (isString(expectedParam)) {
+ if (iso.isString(expectedParam)) {
expected = expectedParam;
timeout = options.timeout ?? this.timeout;
} else {
@@ -101,13 +101,13 @@ export async function toMatchAriaSnapshot(
if (errorMessage) {
printedExpected = `Expected: ${this.isNot ? 'not ' : ''}${this.utils.printExpected(expected)}`;
} else if (pass) {
- const receivedString = printReceivedStringContainExpectedSubstring(this.utils, typedReceived.raw, typedReceived.raw.indexOf(expected), expected.length);
+ const receivedString = serverUtils.printReceivedStringContainExpectedSubstring(this.utils, typedReceived.raw, typedReceived.raw.indexOf(expected), expected.length);
printedExpected = `Expected: not ${this.utils.printExpected(expected)}`;
printedReceived = `Received: ${receivedString}`;
} else {
printedDiff = this.utils.printDiffOrStringify(expected, typedReceived.raw, 'Expected', 'Received', false);
}
- return formatMatcherMessage(this.utils, {
+ return serverUtils.formatMatcherMessage(this.utils, {
isNot: this.isNot,
promise: this.promise,
matcherName,
@@ -145,7 +145,7 @@ export async function toMatchAriaSnapshot(
}
return { pass: true, message: () => '', name: 'toMatchAriaSnapshot' };
} else {
- const suggestedRebaseline = `\`\n${escapeTemplateString(indent(typedReceived.regex, '{indent} '))}\n{indent}\``;
+ const suggestedRebaseline = `\`\n${iso.escapeTemplateString(indent(typedReceived.regex, '{indent} '))}\n{indent}\``;
if (updateSnapshots === 'missing') {
const message = 'A snapshot is not provided, generating new baseline.';
testInfo._hasNonRetriableError = true;
diff --git a/packages/playwright/src/matchers/toMatchSnapshot.ts b/packages/playwright/src/matchers/toMatchSnapshot.ts
index 37a5777d2b..169f26f1a2 100644
--- a/packages/playwright/src/matchers/toMatchSnapshot.ts
+++ b/packages/playwright/src/matchers/toMatchSnapshot.ts
@@ -17,8 +17,8 @@
import fs from 'fs';
import path from 'path';
-import { callLogText, formatMatcherMessage, compareBuffersOrStrings, getComparator, isString } from 'playwright-core/lib/utils';
-import { colors } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { colors } from 'playwright-core/lib/utilsBundle';
import { mime } from 'playwright-core/lib/utilsBundle';
import { addSuffixToFilePath, expectTypes } from '../util';
@@ -30,7 +30,8 @@ import type { FullProjectInternal } from '../common/config';
import type { TestInfoImpl, TestStepInfoImpl } from '../worker/testInfo';
import type { Locator, Page } from 'playwright-core';
import type { ExpectScreenshotOptions, Page as PageEx } from 'playwright-core/lib/client/page';
-import type { Comparator, ImageComparatorOptions } from 'playwright-core/lib/utils';
+type Comparator = serverUtils.Comparator;
+type ImageComparatorOptions = serverUtils.ImageComparatorOptions;
type NameOrSegments = string | string[];
@@ -139,7 +140,7 @@ class SnapshotHelper {
this.updateSnapshots = testInfo.config.updateSnapshots;
this.mimeType = mime.getType(path.basename(this.expectedPath)) ?? 'application/octet-stream';
- this.comparator = getComparator(this.mimeType);
+ this.comparator = serverUtils.getComparator(this.mimeType);
this.testInfo = testInfo;
this.state = state;
@@ -236,7 +237,7 @@ class SnapshotHelper {
}
if (log?.length)
- output.push(callLogText(this.state.utils, log));
+ output.push(serverUtils.callLogText(this.state.utils, log));
else
output.push('');
@@ -281,7 +282,7 @@ export function toMatchSnapshot(
const expected = fs.readFileSync(helper.expectedPath);
if (helper.updateSnapshots === 'all') {
- if (!compareBuffersOrStrings(received, expected))
+ if (!serverUtils.compareBuffersOrStrings(received, expected))
return helper.handleMatching();
writeFileSync(helper.expectedPath, received);
/* eslint-disable no-console */
@@ -303,7 +304,7 @@ export function toMatchSnapshot(
if (!result)
return helper.handleMatching();
- const header = formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toMatchSnapshot', receiver: isString(received) ? 'string' : 'Buffer', expectation: 'expected' });
+ const header = serverUtils.formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toMatchSnapshot', receiver: iso.isString(received) ? 'string' : 'Buffer', expectation: 'expected' });
return helper.handleDifferent(received, expected, undefined, result.diff, header, result.errorMessage, undefined, this._stepInfo);
}
@@ -388,7 +389,7 @@ export async function toHaveScreenshot(
// We tried re-generating new snapshot but failed.
// This can be due to e.g. spinning animation, so we want to show it as a diff.
if (errorMessage) {
- const header = formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });
+ const header = serverUtils.formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });
return helper.handleDifferent(actual, undefined, previous, diff, header, errorMessage, log, this._stepInfo);
}
@@ -413,7 +414,7 @@ export async function toHaveScreenshot(
if (!errorMessage) {
// Screenshot is matching, but is not necessarily the same as the expected.
- if (helper.updateSnapshots === 'all' && actual && compareBuffersOrStrings(actual, expected)) {
+ if (helper.updateSnapshots === 'all' && actual && serverUtils.compareBuffersOrStrings(actual, expected)) {
console.log(helper.expectedPath + ' is re-generated, writing actual.');
return writeFiles(actual);
}
@@ -423,12 +424,12 @@ export async function toHaveScreenshot(
if (helper.updateSnapshots === 'changed' || helper.updateSnapshots === 'all') {
if (actual)
return writeFiles(actual);
- let header = formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });
+ let header = serverUtils.formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });
header += ' Failed to re-generate expected.\n';
return helper.handleDifferent(actual, expectScreenshotOptions.expected, previous, diff, header, errorMessage, log, this._stepInfo);
}
- const header = formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });
+ const header = serverUtils.formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });
return helper.handleDifferent(actual, expectScreenshotOptions.expected, previous, diff, header, errorMessage, log, this._stepInfo);
} finally {
await page.screencast.showOverlays();
diff --git a/packages/playwright/src/matchers/toMatchText.ts b/packages/playwright/src/matchers/toMatchText.ts
index 85410d734b..c1b1634174 100644
--- a/packages/playwright/src/matchers/toMatchText.ts
+++ b/packages/playwright/src/matchers/toMatchText.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { formatMatcherMessage, printReceivedStringContainExpectedResult, printReceivedStringContainExpectedSubstring } from 'playwright-core/lib/utils';
+import { serverUtils } from 'playwright-core/lib/coreBundle';
import { expectTypes } from '../util';
@@ -39,7 +39,7 @@ export async function toMatchText(
!(expected && typeof expected.test === 'function')
) {
const errorMessage = `Error: ${this.utils.EXPECTED_COLOR('expected')} value must be a string or regular expression\n${this.utils.printWithType('Expected', expected, this.utils.printExpected)}`;
- throw new Error(formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, locator: locator?.toString(), matcherName, expectation: 'expected', errorMessage }));
+ throw new Error(serverUtils.formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, locator: locator?.toString(), matcherName, expectation: 'expected', errorMessage }));
}
const timeout = options.timeout ?? this.timeout;
@@ -65,13 +65,13 @@ export async function toMatchText(
if (typeof expected === 'string') {
printedExpected = `Expected${expectedSuffix}: not ${this.utils.printExpected(expected)}`;
if (!errorMessage) {
- const formattedReceived = printReceivedStringContainExpectedSubstring(this.utils, receivedString, receivedString.indexOf(expected), expected.length);
+ const formattedReceived = serverUtils.printReceivedStringContainExpectedSubstring(this.utils, receivedString, receivedString.indexOf(expected), expected.length);
printedReceived = `Received${receivedSuffix}: ${formattedReceived}`;
}
} else {
printedExpected = `Expected${expectedSuffix}: not ${this.utils.printExpected(expected)}`;
if (!errorMessage) {
- const formattedReceived = printReceivedStringContainExpectedResult(this.utils, receivedString, typeof expected.exec === 'function' ? expected.exec(receivedString) : null);
+ const formattedReceived = serverUtils.printReceivedStringContainExpectedResult(this.utils, receivedString, typeof expected.exec === 'function' ? expected.exec(receivedString) : null);
printedReceived = `Received${receivedSuffix}: ${formattedReceived}`;
}
}
@@ -83,7 +83,7 @@ export async function toMatchText(
}
const message = () => {
- return formatMatcherMessage(this.utils, {
+ return serverUtils.formatMatcherMessage(this.utils, {
promise: this.promise,
isNot: this.isNot,
matcherName,
diff --git a/packages/playwright/src/mcp/test/browserBackend.ts b/packages/playwright/src/mcp/test/browserBackend.ts
index 668fcc6bd0..fa2ba1a15d 100644
--- a/packages/playwright/src/mcp/test/browserBackend.ts
+++ b/packages/playwright/src/mcp/test/browserBackend.ts
@@ -15,9 +15,9 @@
*/
import crypto from 'crypto';
-import { stripAnsiEscapes } from 'playwright-core/lib/utils';
+import { iso } from 'playwright-core/lib/coreBundle';
-import type * as tools from 'playwright-core/lib/tools/exports';
+import type { tools } from 'playwright-core/lib/coreBundle';
import type * as playwright from '../../../index';
import type { TestInfoImpl } from '../../worker/testInfo';
@@ -37,11 +37,11 @@ export type BrowserMCPResponse = {
export function createCustomMessageHandler(testInfo: TestInfoImpl, context: playwright.BrowserContext) {
let backend: tools.BrowserBackend | undefined;
const config: tools.ContextConfig = { capabilities: ['testing'] };
- let tools: typeof import('playwright-core/lib/tools/exports') | undefined;
+ let tools: typeof import('playwright-core/lib/coreBundle').tools | undefined;
return async (data: BrowserMCPRequest): Promise<BrowserMCPResponse> => {
if (!tools)
- tools = await import('playwright-core/lib/tools/exports');
+ ({ tools } = await import('playwright-core/lib/coreBundle'));
const toolList = tools.filteredTools(config);
if (data.initialize) {
if (backend)
@@ -68,13 +68,13 @@ export function createCustomMessageHandler(testInfo: TestInfoImpl, context: play
};
}
-async function generatePausedMessage(tools: typeof import('playwright-core/lib/tools/exports'), testInfo: TestInfoImpl, context: playwright.BrowserContext) {
+async function generatePausedMessage(tools: typeof import('playwright-core/lib/coreBundle').tools, testInfo: TestInfoImpl, context: playwright.BrowserContext) {
const lines: string[] = [];
if (testInfo.errors.length) {
lines.push(`### Paused on error:`);
for (const error of testInfo.errors)
- lines.push(stripAnsiEscapes(error.message || ''));
+ lines.push(iso.stripAnsiEscapes(error.message || ''));
} else {
lines.push(`### Paused at end of test. ready for interaction`);
}
diff --git a/packages/playwright/src/mcp/test/seed.ts b/packages/playwright/src/mcp/test/seed.ts
index 04ebd74b8b..09ea5370ac 100644
--- a/packages/playwright/src/mcp/test/seed.ts
+++ b/packages/playwright/src/mcp/test/seed.ts
@@ -17,7 +17,8 @@
import fs from 'fs';
import path from 'path';
-import { mkdirIfNeeded } from 'playwright-core/lib/utils';
+import { serverUtils } from 'playwright-core/lib/coreBundle';
+
import { collectFilesForProject, findTopLevelProjects } from '../../runner/projectUtils';
import type { FullConfigInternal, FullProjectInternal } from '../../common/config';
@@ -46,7 +47,7 @@ export async function ensureSeedFile(project: FullProjectInternal) {
if (seedFile)
return seedFile;
const seedFilePath = defaultSeedFile(project);
- await mkdirIfNeeded(seedFilePath);
+ await serverUtils.mkdirIfNeeded(seedFilePath);
await fs.promises.writeFile(seedFilePath, seedFileContent);
return seedFilePath;
}
diff --git a/packages/playwright/src/mcp/test/testBackend.ts b/packages/playwright/src/mcp/test/testBackend.ts
index d554068f02..40494d8af5 100644
--- a/packages/playwright/src/mcp/test/testBackend.ts
+++ b/packages/playwright/src/mcp/test/testBackend.ts
@@ -17,8 +17,7 @@
import EventEmitter from 'events';
import { z as zod } from 'playwright-core/lib/zodBundle';
-import * as mcp from 'playwright-core/lib/tools/exports';
-import { browserTools } from 'playwright-core/lib/tools/exports';
+import { tools } from 'playwright-core/lib/coreBundle';
import { TestContext } from './testContext';
import * as testTools from './testTools.js';
@@ -26,7 +25,6 @@ import * as generatorTools from './generatorTools.js';
import * as plannerTools from './plannerTools.js';
import type { TestTool } from './testTool';
-import type { Tool } from 'playwright-core/lib/tools/exports';
const typesWithIntent = ['action', 'assertion', 'input'];
@@ -40,10 +38,10 @@ export const testServerBackendTools: TestTool<any>[] = [
testTools.listTests,
testTools.runTests,
testTools.debugTest,
- ...browserTools.map(tool => wrapBrowserTool(tool)),
+ ...tools.browserTools.map(tool => wrapBrowserTool(tool)),
];
-export class TestServerBackend extends EventEmitter implements mcp.ServerBackend {
+export class TestServerBackend extends EventEmitter implements tools.ServerBackend {
readonly name = 'Playwright';
readonly version = '0.0.1';
private _options: { muteConsole?: boolean, headless?: boolean };
@@ -56,11 +54,11 @@ export class TestServerBackend extends EventEmitter implements mcp.ServerBackend
this._configPath = configPath;
}
- async initialize(clientInfo: mcp.ClientInfo): Promise<void> {
+ async initialize(clientInfo: tools.ClientInfo): Promise<void> {
this._context = new TestContext(clientInfo, this._configPath, this._options);
}
- async callTool(name: string, args: mcp.CallToolRequest['params']['arguments']): Promise<mcp.CallToolResult> {
+ async callTool(name: string, args: tools.CallToolRequest['params']['arguments']): Promise<tools.CallToolResult> {
const tool = testServerBackendTools.find(tool => tool.schema.name === name);
if (!tool)
throw new Error(`Tool not found: ${name}. Available tools: ${testServerBackendTools.map(tool => tool.schema.name).join(', ')}`);
@@ -76,7 +74,7 @@ export class TestServerBackend extends EventEmitter implements mcp.ServerBackend
}
}
-function wrapBrowserTool(tool: Tool): TestTool {
+function wrapBrowserTool(tool: tools.Tool): TestTool {
const inputSchema = typesWithIntent.includes(tool.schema.type) ? (tool.schema.inputSchema as any).extend({
intent: zod.string().describe('The intent of the call, for example the test step description plan idea')
}) : tool.schema.inputSchema;
diff --git a/packages/playwright/src/mcp/test/testContext.ts b/packages/playwright/src/mcp/test/testContext.ts
index a886e77d92..d33a3419c7 100644
--- a/packages/playwright/src/mcp/test/testContext.ts
+++ b/packages/playwright/src/mcp/test/testContext.ts
@@ -18,8 +18,7 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
-import { noColors, escapeRegExp, ManualPromise, toPosixPath } from 'playwright-core/lib/utils';
-import { parseResponse } from 'playwright-core/lib/tools/exports';
+import { iso, serverUtils, tools } from 'playwright-core/lib/coreBundle';
import { debug } from 'playwright-core/lib/utilsBundle';
import { terminalScreen } from '../../reporters/base';
@@ -33,7 +32,6 @@ import { resolveConfigLocation } from '../../common/configLoader';
import type { TerminalScreen } from '../../reporters/base';
import type { FullResultStatus, RunTestsParams } from '../../runner/testRunner';
import type { ConfigLocation } from '../../common/config';
-import type { ClientInfo } from 'playwright-core/lib/tools/exports';
import type { BrowserMCPRequest, BrowserMCPResponse } from './browserBackend';
export type SeedFile = {
@@ -63,7 +61,7 @@ export class GeneratorJournal {
const result: string[] = [];
result.push(`# Plan`);
result.push(this._plan);
- result.push(`# Seed file: ${toPosixPath(path.relative(this._rootPath, this._seed.file))}`);
+ result.push(`# Seed file: ${serverUtils.toPosixPath(path.relative(this._rootPath, this._seed.file))}`);
result.push('```ts');
result.push(this._seed.content);
result.push('```');
@@ -88,14 +86,14 @@ type TestRunnerAndScreen = {
};
export class TestContext {
- private _clientInfo: ClientInfo;
+ private _clientInfo: tools.ClientInfo;
private _testRunnerAndScreen: TestRunnerAndScreen | undefined;
readonly computedHeaded: boolean;
private readonly _configLocation: ConfigLocation;
readonly rootPath: string;
generatorJournal: GeneratorJournal | undefined;
- constructor(clientInfo: ClientInfo, configPath: string | undefined, options?: { muteConsole?: boolean, headless?: boolean }) {
+ constructor(clientInfo: tools.ClientInfo, configPath: string | undefined, options?: { muteConsole?: boolean, headless?: boolean }) {
this._clientInfo = clientInfo;
this._configLocation = resolveConfigLocation(configPath || clientInfo.cwd);
@@ -129,7 +127,7 @@ export class TestContext {
const testRunner = new TestRunner(this._configLocation, {});
await testRunner.initialize({});
- const testPaused = new ManualPromise<void>();
+ const testPaused = new iso.ManualPromise<void>();
const testRunnerAndScreen: TestRunnerAndScreen = {
...createScreen(),
testRunner,
@@ -181,7 +179,7 @@ export class TestContext {
async runSeedTest(seedFile: string, projectName: string): Promise<{ output: string, status: FullResultStatus | 'paused' }> {
const result = await this.runTestsWithGlobalSetupAndPossiblePause({
headed: this.computedHeaded,
- locations: ['/' + escapeRegExp(seedFile) + '/'],
+ locations: ['/' + iso.escapeRegExp(seedFile) + '/'],
projects: [projectName],
timeout: 0,
workers: 1,
@@ -261,7 +259,7 @@ export class TestContext {
if (result.error)
throw new Error(result.error.message);
if (typeof request?.callTool?.arguments?.['intent'] === 'string') {
- const response = parseResponse(result.response.callTool!);
+ const response = tools.parseResponse(result.response.callTool!);
if (response && !response.isError && response.code)
this.generatorJournal?.logStep(request.callTool.arguments['intent'], response.code);
}
@@ -277,7 +275,7 @@ export function createScreen() {
const screen = {
...terminalScreen,
isTTY: false,
- colors: noColors,
+ colors: iso.noColors,
stdout: stdout as unknown as NodeJS.WriteStream,
stderr: stderr as unknown as NodeJS.WriteStream,
};
diff --git a/packages/playwright/src/mcp/test/testTool.ts b/packages/playwright/src/mcp/test/testTool.ts
index cbffb5ab07..a1d80b47b0 100644
--- a/packages/playwright/src/mcp/test/testTool.ts
+++ b/packages/playwright/src/mcp/test/testTool.ts
@@ -17,10 +17,10 @@
import type { z } from 'zod';
import type { TestContext } from './testContext.js';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
-import type { ToolSchema } from 'playwright-core/lib/tools/exports.js';
+import type { tools } from 'playwright-core/lib/coreBundle';
export type TestTool<Input extends z.Schema = z.Schema> = {
- schema: ToolSchema<Input>;
+ schema: tools.ToolSchema<Input>;
handle: (context: TestContext, params: z.output<Input>) => Promise<CallToolResult>;
};
diff --git a/packages/playwright/src/plugins/gitCommitInfoPlugin.ts b/packages/playwright/src/plugins/gitCommitInfoPlugin.ts
index 06a67f41ee..82ddc77539 100644
--- a/packages/playwright/src/plugins/gitCommitInfoPlugin.ts
+++ b/packages/playwright/src/plugins/gitCommitInfoPlugin.ts
@@ -16,7 +16,7 @@
import * as fs from 'fs';
-import { monotonicTime, spawnAsync } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import type { TestRunnerPlugin } from './';
import type { FullConfig } from '../../types/testReporter';
@@ -179,13 +179,13 @@ async function gitDiff(gitDir: string, ci?: CIInfo): Promise<string | undefined>
async function runGit(command: string, cwd: string): Promise<string | undefined> {
debug(`running "${command}"`);
- const start = monotonicTime();
- const result = await spawnAsync(
+ const start = iso.monotonicTime();
+ const result = await serverUtils.spawnAsync(
command,
[],
{ stdio: 'pipe', cwd, timeout: GIT_OPERATIONS_TIMEOUT_MS, shell: true }
);
- if (monotonicTime() - start > GIT_OPERATIONS_TIMEOUT_MS) {
+ if (iso.monotonicTime() - start > GIT_OPERATIONS_TIMEOUT_MS) {
print(`timeout of ${GIT_OPERATIONS_TIMEOUT_MS}ms exceeded while running "${command}"`);
return;
}
diff --git a/packages/playwright/src/plugins/webServerPlugin.ts b/packages/playwright/src/plugins/webServerPlugin.ts
index 7788746836..633fec4b29 100644
--- a/packages/playwright/src/plugins/webServerPlugin.ts
+++ b/packages/playwright/src/plugins/webServerPlugin.ts
@@ -16,8 +16,8 @@
import net from 'net';
import path from 'path';
-import { launchProcess, isURLAvailable, monotonicTime, raceAgainstDeadline, ManualPromise } from 'playwright-core/lib/utils';
-import { colors } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { colors } from 'playwright-core/lib/utilsBundle';
import { debug } from 'playwright-core/lib/utilsBundle';
import type { TestRunnerPlugin } from '.';
@@ -55,7 +55,7 @@ export class WebServerPlugin implements TestRunnerPlugin {
private _options: WebServerPluginOptions;
private _checkPortOnly: boolean;
private _reporter?: ReporterV2;
- private _waitForStdioPromise: ManualPromise | undefined;
+ private _waitForStdioPromise: iso.ManualPromise | undefined;
name = 'playwright:webserver';
@@ -101,7 +101,7 @@ export class WebServerPlugin implements TestRunnerPlugin {
throw new Error('config.webServer.command cannot be empty');
debugWebServer(`Starting WebServer process ${this._options.command}...`);
- const { launchedProcess, gracefullyClose } = await launchProcess({
+ const { launchedProcess, gracefullyClose } = await serverUtils.launchProcess({
command: this._options.command,
env: {
...DEFAULT_ENVIRONMENT_VARIABLES,
@@ -142,7 +142,7 @@ export class WebServerPlugin implements TestRunnerPlugin {
debugWebServer(`Process started`);
if (this._options.wait?.stdout || this._options.wait?.stderr)
- this._waitForStdioPromise = new ManualPromise();
+ this._waitForStdioPromise = new iso.ManualPromise();
const stdioWaitCollectors = {
stdout: this._options.wait?.stdout ? '' : undefined,
stderr: this._options.wait?.stderr ? '' : undefined,
@@ -189,13 +189,13 @@ export class WebServerPlugin implements TestRunnerPlugin {
debugWebServer(`Waiting for availability...`);
const launchTimeout = this._options.timeout || 60 * 1000;
const cancellationToken = { canceled: false };
- const deadline = monotonicTime() + launchTimeout;
+ const deadline = iso.monotonicTime() + launchTimeout;
const racingPromises = [this._processExitedPromise];
if (this._isAvailableCallback)
- racingPromises.push(raceAgainstDeadline(() => waitFor(this._isAvailableCallback!, cancellationToken), deadline));
+ racingPromises.push(iso.raceAgainstDeadline(() => waitFor(this._isAvailableCallback!, cancellationToken), deadline));
if (this._waitForStdioPromise)
- racingPromises.push(raceAgainstDeadline(() => this._waitForStdioPromise!, deadline));
+ racingPromises.push(iso.raceAgainstDeadline(() => this._waitForStdioPromise!, deadline));
const { timedOut } = await Promise.race(racingPromises);
cancellationToken.canceled = true;
@@ -235,7 +235,7 @@ async function waitFor(waitFn: () => Promise<boolean>, cancellationToken: { canc
function getIsAvailableFunction(url: string, checkPortOnly: boolean, ignoreHTTPSErrors: boolean, onStdErr: ReporterV2['onStdErr']) {
const urlObject = new URL(url);
if (!checkPortOnly)
- return () => isURLAvailable(urlObject, ignoreHTTPSErrors, debugWebServer, onStdErr);
+ return () => serverUtils.isURLAvailable(urlObject, ignoreHTTPSErrors, debugWebServer, onStdErr);
const port = urlObject.port;
return () => isPortUsed(+port);
}
diff --git a/packages/playwright/src/program.ts b/packages/playwright/src/program.ts
index 6951be727f..78da782bfc 100644
--- a/packages/playwright/src/program.ts
+++ b/packages/playwright/src/program.ts
@@ -17,19 +17,20 @@
/* eslint-disable no-console */
import 'playwright-core/lib/bootstrap';
-import { gracefullyProcessExitDoNotHang } from 'playwright-core/lib/utils';
-
-import { program } from 'playwright-core/lib/cli/program';
+import { libCli, serverUtils } from 'playwright-core/lib/coreBundle';
+import { program } from 'playwright-core/lib/utilsBundle';
import { builtInReporters, defaultReporter, defaultTimeout } from './common/config';
-export { program } from 'playwright-core/lib/cli/program';
+export { program };
-import type { ServerBackendFactory } from 'playwright-core/lib/tools/exports';
+import type { tools } from 'playwright-core/lib/coreBundle';
import type { TraceMode } from '../types/test';
import type { Command } from 'playwright-core/lib/utilsBundle';
const packageJSON = require('../package.json');
+libCli.decorateProgram(program);
+
function addTestCommand(program: Command) {
const command = program.command('test [test-filter...]');
command.description('run tests with Playwright Test');
@@ -51,7 +52,7 @@ function addTestCommand(program: Command) {
await runTests(args, opts);
} catch (e) {
console.error(e);
- gracefullyProcessExitDoNotHang(1);
+ serverUtils.gracefullyProcessExitDoNotHang(1);
}
});
command.addHelpText('afterAll', `
@@ -124,7 +125,7 @@ function addMergeReportsCommand(program: Command) {
await mergeReports(dir, options);
} catch (e) {
console.error(e);
- gracefullyProcessExitDoNotHang(1);
+ serverUtils.gracefullyProcessExitDoNotHang(1);
}
});
command.option('-c, --config <file>', `Configuration file. Can be used to specify additional configuration for the output report.`);
@@ -145,10 +146,10 @@ function addTestMCPServerCommand(program: Command) {
command.option('--host <host>', 'host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.');
command.option('--port <port>', 'port to listen on for SSE transport.');
command.action(async options => {
- const { start, setupExitWatchdog } = await import('playwright-core/lib/tools/exports');
+ const { tools } = await import('playwright-core/lib/coreBundle');
const { TestServerBackend, testServerBackendTools } = await import('./mcp/test/testBackend');
- setupExitWatchdog();
- const factory: ServerBackendFactory = {
+ tools.setupExitWatchdog();
+ const factory: tools.ServerBackendFactory = {
name: 'Playwright Test Runner',
nameInConfig: 'playwright-test-runner',
version: packageJSON.version,
@@ -157,7 +158,7 @@ function addTestMCPServerCommand(program: Command) {
disposed: async () => { }
};
// TODO: add all options from mcp.startHttpServer.
- await start(factory, { port: options.port === undefined ? undefined : +options.port, host: options.host });
+ await tools.start(factory, { port: options.port === undefined ? undefined : +options.port, host: options.host });
});
}
diff --git a/packages/playwright/src/reportActions.ts b/packages/playwright/src/reportActions.ts
index c49b5004a4..ef5962d016 100644
--- a/packages/playwright/src/reportActions.ts
+++ b/packages/playwright/src/reportActions.ts
@@ -17,8 +17,7 @@
import fs from 'fs';
import path from 'path';
-import { gracefullyProcessExitDoNotHang } from 'playwright-core/lib/utils';
-
+import { serverUtils } from 'playwright-core/lib/coreBundle';
import { builtInReporters, defaultReporter } from './common/config';
import { loadConfigFromFile, loadEmptyConfigForMergeReports } from './common/configLoader';
import { showHTMLReport } from './reporters/html';
@@ -47,7 +46,7 @@ export async function mergeReports(reportDir: string | undefined, opts: { [key:
reporterDescriptions = [[defaultReporter]];
const rootDirOverride = configFile ? config.config.rootDir : undefined;
await createMergedReport(config, dir, reporterDescriptions!, rootDirOverride);
- gracefullyProcessExitDoNotHang(0);
+ serverUtils.gracefullyProcessExitDoNotHang(0);
}
function resolveReporterOption(reporter?: string): ReporterDescription[] | undefined {
diff --git a/packages/playwright/src/reporters/base.ts b/packages/playwright/src/reporters/base.ts
index f00437c477..75c11e65b8 100644
--- a/packages/playwright/src/reporters/base.ts
+++ b/packages/playwright/src/reporters/base.ts
@@ -16,8 +16,8 @@
import path from 'path';
-import { getPackageManagerExecCommand, msToString as milliseconds, parseErrorStack } from 'playwright-core/lib/utils';
-import { colors as realColors, noColors } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { colors as realColors } from 'playwright-core/lib/utilsBundle';
import { ansiRegex, resolveReporterOutputPath, stripAnsiEscapes } from '../util';
import { getEastAsianWidth } from '../utilsBundle';
@@ -110,7 +110,7 @@ export const terminalScreen: TerminalScreen = (() => {
else if (process.env.DEBUG_COLORS || process.env.FORCE_COLOR)
useColors = true;
- const colors = useColors ? realColors : noColors;
+ const colors = useColors ? realColors : iso.noColors;
return {
resolveFiles: 'cwd',
isTTY,
@@ -259,7 +259,7 @@ export class TerminalReporter implements ReporterV2 {
if (didNotRun)
tokens.push(this.screen.colors.yellow(` ${didNotRun} did not run`));
if (expected)
- tokens.push(this.screen.colors.green(` ${expected} passed`) + this.screen.colors.dim(` (${milliseconds(this.result.duration)})`));
+ tokens.push(this.screen.colors.green(` ${expected} passed`) + this.screen.colors.dim(` (${iso.msToString(this.result.duration)})`));
if (fatalErrors.length && expected + unexpected.length + interrupted.length + flaky.length > 0)
tokens.push(this.screen.colors.red(` ${fatalErrors.length === 1 ? '1 error was not a part of any test' : fatalErrors.length + ' errors were not a part of any test'}, see above for details`));
@@ -327,7 +327,7 @@ export class TerminalReporter implements ReporterV2 {
private _printSlowTests() {
const slowTests = this.getSlowTests();
slowTests.forEach(([file, duration]) => {
- this.writeLine(this.screen.colors.yellow(' Slow test file: ') + file + this.screen.colors.yellow(` (${milliseconds(duration)})`));
+ this.writeLine(this.screen.colors.yellow(' Slow test file: ') + file + this.screen.colors.yellow(` (${iso.msToString(duration)})`));
});
if (slowTests.length)
this.writeLine(this.screen.colors.yellow(' Consider running tests from slow files in parallel. See: https://playwright.dev/docs/test-parallel'));
@@ -436,7 +436,7 @@ export function formatFailure(screen: Screen, config: FullConfig, test: TestCase
resultLines.push(screen.colors.dim(` ${relativePath}`));
// Make this extensible
if (attachment.name === 'trace') {
- const packageManagerCommand = getPackageManagerExecCommand();
+ const packageManagerCommand = serverUtils.getPackageManagerExecCommand();
resultLines.push(screen.colors.dim(` Usage:`));
resultLines.push('');
resultLines.push(screen.colors.dim(` ${packageManagerCommand} playwright show-trace ${quotePathIfNeeded(relativePath)}`));
@@ -612,7 +612,7 @@ export function prepareErrorStack(stack: string): {
stackLines: string[];
location?: Location;
} {
- return parseErrorStack(stack, path.sep, !!process.env.PWDEBUGIMPL);
+ return iso.parseErrorStack(stack, path.sep, !!process.env.PWDEBUGIMPL);
}
function characterWidth(c: string) {
diff --git a/packages/playwright/src/reporters/blob.ts b/packages/playwright/src/reporters/blob.ts
index 844d14b292..1bfc25189b 100644
--- a/packages/playwright/src/reporters/blob.ts
+++ b/packages/playwright/src/reporters/blob.ts
@@ -18,8 +18,8 @@ import fs from 'fs';
import path from 'path';
import { Readable } from 'stream';
-import { removeFolders, sanitizeForFilePath } from 'playwright-core/lib/utils';
-import { ManualPromise, calculateSha1, createGuid, getUserAgent } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+
import { mime } from 'playwright-core/lib/utilsBundle';
import { resolveOutputFile, CommonReporterOptions } from './base';
@@ -44,13 +44,13 @@ export class BlobReporter extends TeleReporterEmitter {
this._options = options;
if (this._options.fileName && !this._options.fileName.endsWith('.zip'))
throw new Error(`Blob report file name must end with .zip extension: ${this._options.fileName}`);
- this._salt = createGuid();
+ this._salt = serverUtils.createGuid();
}
override onConfigure(config: FullConfig) {
const metadata: BlobReportMetadata = {
version: currentBlobReportVersion,
- userAgent: getUserAgent(),
+ userAgent: serverUtils.getUserAgent(),
// TODO: remove after some time, recommend config.tag instead.
name: process.env.PWTEST_BOT_NAME,
shard: config.shard ?? undefined,
@@ -77,7 +77,7 @@ export class BlobReporter extends TeleReporterEmitter {
const { yazl } = await import('playwright-core/lib/zipBundle');
const zipFile = new yazl.ZipFile();
- const zipFinishPromise = new ManualPromise<undefined>();
+ const zipFinishPromise = new iso.ManualPromise<undefined>();
const finishPromise = zipFinishPromise.catch(e => {
throw new Error(`Failed to write report ${zipFileName}: ` + e.message);
});
@@ -110,7 +110,7 @@ export class BlobReporter extends TeleReporterEmitter {
}
})!;
if (!process.env.PWTEST_BLOB_DO_NOT_REMOVE)
- await removeFolders([outputDir!]);
+ await serverUtils.removeFolders([outputDir!]);
await fs.promises.mkdir(path.dirname(outputFile), { recursive: true });
return outputFile;
}
@@ -118,7 +118,7 @@ export class BlobReporter extends TeleReporterEmitter {
private _defaultReportName(config: FullConfig) {
let reportName = 'report';
if (this._options._commandHash)
- reportName += '-' + sanitizeForFilePath(this._options._commandHash);
+ reportName += '-' + serverUtils.sanitizeForFilePath(this._options._commandHash);
if (config.shard) {
const paddedNumber = `${config.shard.current}`.padStart(`${config.shard.total}`.length, '0');
reportName = `${reportName}-${paddedNumber}`;
@@ -131,7 +131,7 @@ export class BlobReporter extends TeleReporterEmitter {
if (!attachment.path)
return attachment;
// Add run guid to avoid clashes between shards.
- const sha1 = calculateSha1(attachment.path + this._salt);
+ const sha1 = serverUtils.calculateSha1(attachment.path + this._salt);
const extension = mime.getExtension(attachment.contentType) || 'dat';
const newPath = `resources/${sha1}.${extension}`;
this._attachments.push({ originalPath: attachment.path, zipEntryPath: newPath });
diff --git a/packages/playwright/src/reporters/github.ts b/packages/playwright/src/reporters/github.ts
index c19c7ab621..6be25b9087 100644
--- a/packages/playwright/src/reporters/github.ts
+++ b/packages/playwright/src/reporters/github.ts
@@ -16,7 +16,7 @@
import path from 'path';
-import { msToString as milliseconds, noColors } from 'playwright-core/lib/utils';
+import { iso } from 'playwright-core/lib/coreBundle';
import { TerminalReporter, formatResultFailure, formatRetry } from './base';
import { stripAnsiEscapes } from '../util';
@@ -66,7 +66,7 @@ export class GitHubReporter extends TerminalReporter {
constructor(options: { omitFailures?: boolean } = {}) {
super(options);
- this.screen = { ...this.screen, colors: noColors };
+ this.screen = { ...this.screen, colors: iso.noColors };
}
printsToStdio() {
@@ -95,7 +95,7 @@ export class GitHubReporter extends TerminalReporter {
private _printSlowTestAnnotations() {
this.getSlowTests().forEach(([file, duration]) => {
const filePath = workspaceRelativePath(path.join(process.cwd(), file));
- this.githubLogger.warning(`${filePath} took ${milliseconds(duration)}`, {
+ this.githubLogger.warning(`${filePath} took ${iso.msToString(duration)}`, {
title: 'Slow Test',
file: filePath,
});
diff --git a/packages/playwright/src/reporters/html.ts b/packages/playwright/src/reporters/html.ts
index cff686e038..8212d9b9f7 100644
--- a/packages/playwright/src/reporters/html.ts
+++ b/packages/playwright/src/reporters/html.ts
@@ -18,8 +18,9 @@ import fs from 'fs';
import path from 'path';
import { Transform } from 'stream';
-import { HttpServer, MultiMap, assert, calculateSha1, getPackageManagerExecCommand, copyFileAndMakeWritable, gracefullyProcessExitDoNotHang, removeFolders, sanitizeForFilePath, toPosixPath } from 'playwright-core/lib/utils';
-import { colors } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { colors } from 'playwright-core/lib/utilsBundle';
+
import { open } from 'playwright-core/lib/utilsBundle';
import { mime } from 'playwright-core/lib/utilsBundle';
@@ -140,7 +141,7 @@ class HtmlReporter implements ReporterV2 {
async onEnd(result: api.FullResult) {
const projectSuites = this.suite.suites;
- await removeFolders([this._outputFolder]);
+ await serverUtils.removeFolders([this._outputFolder]);
const noSnippets = parseBooleanEnvVar('PLAYWRIGHT_HTML_NO_SNIPPETS') ?? this._options.noSnippets;
const noCopyPrompt = parseBooleanEnvVar('PLAYWRIGHT_HTML_NO_COPY_PROMPT') ?? this._options.noCopyPrompt;
const doNotInlineAssets = parseBooleanEnvVar('PLAYWRIGHT_HTML_DO_NOT_INLINE_ASSETS') ?? this._options.doNotInlineAssets ?? false;
@@ -163,7 +164,7 @@ class HtmlReporter implements ReporterV2 {
if (shouldOpen) {
await showHTMLReport(this._outputFolder, this._host, this._port, singleTestId);
} else if (this._options._mode === 'test' && !!process.stdin.isTTY) {
- const packageManagerCommand = getPackageManagerExecCommand();
+ const packageManagerCommand = serverUtils.getPackageManagerExecCommand();
const relativeReportPath = this._outputFolder === standaloneDefaultFolder() ? '' : ' ' + path.relative(process.cwd(), this._outputFolder);
const hostArg = this._host ? ` --host ${this._host}` : '';
const portArg = this._port ? ` --port ${this._port}` : '';
@@ -210,10 +211,10 @@ function standaloneDefaultFolder(): string {
export async function showHTMLReport(reportFolder: string | undefined, host: string = 'localhost', port?: number, testId?: string) {
const folder = reportFolder ?? standaloneDefaultFolder();
try {
- assert(fs.statSync(folder).isDirectory());
+ iso.assert(fs.statSync(folder).isDirectory());
} catch (e) {
writeLine(colors.red(`No report found at "${folder}"`));
- gracefullyProcessExitDoNotHang(1);
+ serverUtils.gracefullyProcessExitDoNotHang(1);
return;
}
const server = startHtmlReportServer(folder);
@@ -228,8 +229,8 @@ export async function showHTMLReport(reportFolder: string | undefined, host: str
await new Promise(() => {});
}
-export function startHtmlReportServer(folder: string): HttpServer {
- const server = new HttpServer();
+export function startHtmlReportServer(folder: string): serverUtils.HttpServer {
+ const server = new serverUtils.HttpServer();
server.routePrefix('/', (request, response) => {
let relativePath = new URL('http://localhost' + request.url).pathname;
if (relativePath.startsWith('/trace/file')) {
@@ -253,7 +254,7 @@ type DataMap = Map<string, { testFile: TestFile, testFileSummary: TestFileSummar
class HtmlBuilder {
private _config: api.FullConfig;
private _reportFolder: string;
- private _stepsInFile = new MultiMap<string, TestStep>();
+ private _stepsInFile = new iso.MultiMap<string, TestStep>();
private _dataZipFile: ZipFile;
private _hasTraces = false;
private _attachmentsBaseURL: string;
@@ -350,12 +351,12 @@ class HtmlBuilder {
for (const file of fs.readdirSync(traceViewerFolder)) {
if (file.endsWith('.map') || file.includes('watch') || file.includes('assets'))
continue;
- await copyFileAndMakeWritable(path.join(traceViewerFolder, file), path.join(traceViewerTargetFolder, file));
+ await serverUtils.copyFileAndMakeWritable(path.join(traceViewerFolder, file), path.join(traceViewerTargetFolder, file));
}
for (const file of fs.readdirSync(path.join(traceViewerFolder, 'assets'))) {
if (file.endsWith('.map') || file.includes('xtermModule'))
continue;
- await copyFileAndMakeWritable(path.join(traceViewerFolder, 'assets', file), path.join(traceViewerAssetsTargetFolder, file));
+ await serverUtils.copyFileAndMakeWritable(path.join(traceViewerFolder, 'assets', file), path.join(traceViewerAssetsTargetFolder, file));
}
}
@@ -404,7 +405,7 @@ class HtmlBuilder {
}
private _createEntryForSuite(data: DataMap, projectName: string, suite: api.Suite, fileName: string, deep: boolean) {
- const fileId = calculateSha1(fileName).slice(0, 20);
+ const fileId = serverUtils.calculateSha1(fileName).slice(0, 20);
let fileEntry = data.get(fileId);
if (!fileEntry) {
fileEntry = {
@@ -499,7 +500,7 @@ class HtmlBuilder {
let fileName = a.path;
try {
const buffer = fs.readFileSync(a.path);
- const sha1 = calculateSha1(buffer) + path.extname(a.path);
+ const sha1 = serverUtils.calculateSha1(buffer) + path.extname(a.path);
fileName = this._attachmentsBaseURL + sha1;
fs.mkdirSync(path.join(this._reportFolder, 'data'), { recursive: true });
fs.writeFileSync(path.join(this._reportFolder, 'data', sha1), buffer);
@@ -530,8 +531,8 @@ class HtmlBuilder {
}
fs.mkdirSync(path.join(this._reportFolder, 'data'), { recursive: true });
- const extension = sanitizeForFilePath(path.extname(a.name).replace(/^\./, '')) || mime.getExtension(a.contentType) || 'dat';
- const sha1 = calculateSha1(a.body) + '.' + extension;
+ const extension = serverUtils.sanitizeForFilePath(path.extname(a.name).replace(/^\./, '')) || mime.getExtension(a.contentType) || 'dat';
+ const sha1 = serverUtils.calculateSha1(a.body) + '.' + extension;
fs.writeFileSync(path.join(this._reportFolder, 'data', sha1), a.body);
return {
name: a.name,
@@ -614,7 +615,7 @@ class HtmlBuilder {
private _relativeLocation(location: api.Location | undefined): api.Location | undefined {
if (!location)
return undefined;
- const file = toPosixPath(path.relative(this._config.rootDir, location.file));
+ const file = serverUtils.toPosixPath(path.relative(this._config.rootDir, location.file));
return {
file,
line: location.line,
@@ -710,7 +711,7 @@ function dedupeSteps(steps: api.TestStep[]) {
return result;
}
-function createSnippets(stepsInFile: MultiMap<string, TestStep>) {
+function createSnippets(stepsInFile: iso.MultiMap<string, TestStep>) {
for (const file of stepsInFile.keys()) {
let source: string;
try {
diff --git a/packages/playwright/src/reporters/internalReporter.ts b/packages/playwright/src/reporters/internalReporter.ts
index 7b0ac95b82..c1a8ffc518 100644
--- a/packages/playwright/src/reporters/internalReporter.ts
+++ b/packages/playwright/src/reporters/internalReporter.ts
@@ -16,7 +16,7 @@
import fs from 'fs';
-import { monotonicTime } from 'playwright-core/lib/utils';
+import { iso } from 'playwright-core/lib/coreBundle';
import { internalScreen, prepareErrorStack, relativeFilePath } from './base';
import { Multiplexer } from './multiplexer';
@@ -46,7 +46,7 @@ export class InternalReporter implements ReporterV2 {
onConfigure(config: FullConfig) {
this._config = config;
this._startTime = new Date();
- this._monotonicStartTime = monotonicTime();
+ this._monotonicStartTime = iso.monotonicTime();
this._reporter.onConfigure?.(config);
}
@@ -85,7 +85,7 @@ export class InternalReporter implements ReporterV2 {
return await this._reporter.onEnd?.({
...result,
startTime: this._startTime!,
- duration: monotonicTime() - this._monotonicStartTime!,
+ duration: iso.monotonicTime() - this._monotonicStartTime!,
});
}
diff --git a/packages/playwright/src/reporters/json.ts b/packages/playwright/src/reporters/json.ts
index 5823746e50..0da65f4f9d 100644
--- a/packages/playwright/src/reporters/json.ts
+++ b/packages/playwright/src/reporters/json.ts
@@ -17,7 +17,7 @@
import fs from 'fs';
import path from 'path';
-import { toPosixPath, MultiMap } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { formatError, nonTerminalScreen, prepareErrorStack, resolveOutputFile, CommonReporterOptions } from './base';
import { getProjectId } from '../common/config';
@@ -26,6 +26,8 @@ import type { ReporterV2 } from './reporterV2';
import type { JsonReporterOptions } from '../../types/test';
import type { FullConfig, FullResult, JSONReport, JSONReportError, JSONReportSpec, JSONReportSuite, JSONReportTest, JSONReportTestResult, JSONReportTestStep, Location, Suite, TestCase, TestError, TestResult, TestStep } from '../../types/testReporter';
+const { toPosixPath } = serverUtils;
+
class JSONReporter implements ReporterV2 {
config!: FullConfig;
suite!: Suite;
@@ -97,7 +99,7 @@ class JSONReporter implements ReporterV2 {
}
private _mergeSuites(suites: Suite[]): JSONReportSuite[] {
- const fileSuites = new MultiMap<string, JSONReportSuite>();
+ const fileSuites = new iso.MultiMap<string, JSONReportSuite>();
for (const projectSuite of suites) {
const projectId = getProjectId(projectSuite.project()!);
const projectName = projectSuite.project()!.name;
diff --git a/packages/playwright/src/reporters/junit.ts b/packages/playwright/src/reporters/junit.ts
index c4a9b23bb7..f23d6b23eb 100644
--- a/packages/playwright/src/reporters/junit.ts
+++ b/packages/playwright/src/reporters/junit.ts
@@ -17,7 +17,7 @@
import fs from 'fs';
import path from 'path';
-import { getAsBooleanFromENV } from 'playwright-core/lib/utils';
+import { serverUtils } from 'playwright-core/lib/coreBundle';
import { CommonReporterOptions, formatFailure, nonTerminalScreen, resolveOutputFile } from './base';
import { stripAnsiEscapes } from '../util';
@@ -41,9 +41,9 @@ class JUnitReporter implements ReporterV2 {
private includeRetries = false;
constructor(options: JUnitReporterOptions & CommonReporterOptions) {
- this.stripANSIControlSequences = getAsBooleanFromENV('PLAYWRIGHT_JUNIT_STRIP_ANSI', !!options.stripANSIControlSequences);
- this.includeProjectInTestName = getAsBooleanFromENV('PLAYWRIGHT_JUNIT_INCLUDE_PROJECT_IN_TEST_NAME', !!options.includeProjectInTestName);
- this.includeRetries = getAsBooleanFromENV('PLAYWRIGHT_JUNIT_INCLUDE_RETRIES', !!options.includeRetries);
+ this.stripANSIControlSequences = serverUtils.getAsBooleanFromENV('PLAYWRIGHT_JUNIT_STRIP_ANSI', !!options.stripANSIControlSequences);
+ this.includeProjectInTestName = serverUtils.getAsBooleanFromENV('PLAYWRIGHT_JUNIT_INCLUDE_PROJECT_IN_TEST_NAME', !!options.includeProjectInTestName);
+ this.includeRetries = serverUtils.getAsBooleanFromENV('PLAYWRIGHT_JUNIT_INCLUDE_RETRIES', !!options.includeRetries);
this.configDir = options.configDir;
this.resolvedOutputFile = resolveOutputFile('JUNIT', options)?.outputFile;
}
diff --git a/packages/playwright/src/reporters/list.ts b/packages/playwright/src/reporters/list.ts
index 26216edaba..eac307695a 100644
--- a/packages/playwright/src/reporters/list.ts
+++ b/packages/playwright/src/reporters/list.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { getAsBooleanFromENV, msToString as milliseconds } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { markErrorsAsReported, TerminalReporter, stepSuffix } from './base';
import { stripAnsiEscapes } from '../util';
@@ -41,7 +41,7 @@ class ListReporter extends TerminalReporter {
constructor(options?: ListReporterOptions & CommonReporterOptions & TerminalReporterOptions) {
super(options);
- this._printSteps = getAsBooleanFromENV('PLAYWRIGHT_LIST_PRINT_STEPS', options?.printSteps);
+ this._printSteps = serverUtils.getAsBooleanFromENV('PLAYWRIGHT_LIST_PRINT_STEPS', options?.printSteps);
}
override onBegin(suite: Suite) {
@@ -125,7 +125,7 @@ class ListReporter extends TerminalReporter {
text = this.screen.colors.red(title);
else
text = title;
- text += this.screen.colors.dim(` (${milliseconds(step.duration)})`);
+ text += this.screen.colors.dim(` (${iso.msToString(step.duration)})`);
this._updateOrAppendLine(this._stepRows, step, text, prefix);
}
@@ -218,7 +218,7 @@ class ListReporter extends TerminalReporter {
prefix = this._testPrefix(index, this.screen.colors.red(statusMark));
text = this.screen.colors.red(title);
}
- text += this._retrySuffix(result) + this.screen.colors.dim(` (${milliseconds(result.duration)})`);
+ text += this._retrySuffix(result) + this.screen.colors.dim(` (${iso.msToString(result.duration)})`);
}
this._updateOrAppendLine(this._testRows, test, text, prefix);
diff --git a/packages/playwright/src/reporters/merge.ts b/packages/playwright/src/reporters/merge.ts
index e8a7945396..2d9bfe74bd 100644
--- a/packages/playwright/src/reporters/merge.ts
+++ b/packages/playwright/src/reporters/merge.ts
@@ -17,7 +17,7 @@
import fs from 'fs';
import path from 'path';
-import { ZipFile } from 'playwright-core/lib/utils';
+import { serverUtils } from 'playwright-core/lib/coreBundle';
import { currentBlobReportVersion } from './blob';
import { Multiplexer } from './multiplexer';
@@ -155,7 +155,7 @@ async function extractAndParseReports(dir: string, shardFiles: string[], interna
for (const file of shardFiles) {
const absolutePath = path.join(dir, file);
printStatus(`extracting: ${relativeFilePath(absolutePath)}`);
- const zipFile = new ZipFile(absolutePath);
+ const zipFile = new serverUtils.ZipFile(absolutePath);
const entryNames = await zipFile.entries();
for (const entryName of entryNames.sort()) {
let reportFile = path.join(dir, entryName);
diff --git a/packages/playwright/src/reporters/teleEmitter.ts b/packages/playwright/src/reporters/teleEmitter.ts
index 7b70d15f34..86550a5a59 100644
--- a/packages/playwright/src/reporters/teleEmitter.ts
+++ b/packages/playwright/src/reporters/teleEmitter.ts
@@ -16,7 +16,7 @@
import path from 'path';
-import { createGuid } from 'playwright-core/lib/utils';
+import { serverUtils } from 'playwright-core/lib/coreBundle';
import { serializeRegexPatterns } from '../isomorphic/teleReceiver';
@@ -62,7 +62,7 @@ export class TeleReporterEmitter implements ReporterV2 {
}
onTestBegin(test: reporterTypes.TestCase, result: reporterTypes.TestResult): void {
- (result as any)[this._idSymbol] = createGuid();
+ (result as any)[this._idSymbol] = serverUtils.createGuid();
this._messageSink({
method: 'onTestBegin',
params: {
@@ -109,7 +109,7 @@ export class TeleReporterEmitter implements ReporterV2 {
}
onStepBegin(test: reporterTypes.TestCase, result: reporterTypes.TestResult, step: reporterTypes.TestStep): void {
- (step as any)[this._idSymbol] = createGuid();
+ (step as any)[this._idSymbol] = serverUtils.createGuid();
this._messageSink({
method: 'onStepBegin',
params: {
diff --git a/packages/playwright/src/runner/dispatcher.ts b/packages/playwright/src/runner/dispatcher.ts
index ff4660213f..eabf903bd2 100644
--- a/packages/playwright/src/runner/dispatcher.ts
+++ b/packages/playwright/src/runner/dispatcher.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { ManualPromise, eventsHelper } from 'playwright-core/lib/utils';
-import { colors } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { colors } from 'playwright-core/lib/utilsBundle';
import { addSuggestedRebaseline } from './rebase';
import { WorkerHost } from './workerHost';
@@ -32,7 +32,8 @@ import type { AttachmentPayload, DonePayload, RunPayload, SerializedConfig, Step
import type { Suite } from '../common/test';
import type { TestCase } from '../common/test';
import type { ReporterV2 } from '../reporters/reporterV2';
-import type { RegisteredListener } from 'playwright-core/lib/utils';
+
+const { eventsHelper } = serverUtils;
export type EnvByProjectId = Map<string, Record<string, string | undefined>>;
@@ -43,7 +44,7 @@ export class Dispatcher {
private _queue: TestGroup[] = [];
private _workerLimitPerProjectId = new Map<string, number>();
private _queuedOrRunningHashCount = new Map<string, number>();
- private _finished = new ManualPromise<void>();
+ private _finished = new iso.ManualPromise<void>();
private _isStopped = true;
private _config: FullConfigInternal;
@@ -276,14 +277,14 @@ export class Dispatcher {
}
class JobDispatcher {
- jobResult = new ManualPromise<{ newJob?: TestGroup, didFail: boolean }>();
+ jobResult = new iso.ManualPromise<{ newJob?: TestGroup, didFail: boolean }>();
readonly job: TestGroup;
private _config: FullConfigInternal;
private _reporter: ReporterV2;
private _failureTracker: FailureTracker;
private _stopCallback: () => void;
- private _listeners: RegisteredListener[] = [];
+ private _listeners: serverUtils.RegisteredListener[] = [];
private _failedTests = new Set<TestCase>();
private _failedWithNonRetriableError = new Set<TestCase|Suite>();
private _remainingByTestId = new Map<string, TestCase>();
diff --git a/packages/playwright/src/runner/loadUtils.ts b/packages/playwright/src/runner/loadUtils.ts
index 07979c2d8f..163c3e8e16 100644
--- a/packages/playwright/src/runner/loadUtils.ts
+++ b/packages/playwright/src/runner/loadUtils.ts
@@ -16,7 +16,7 @@
import path from 'path';
import fs from 'fs';
-import { toPosixPath } from 'playwright-core/lib/utils';
+import { serverUtils } from 'playwright-core/lib/coreBundle';
import { InProcessLoaderHost, OutOfProcessLoaderHost } from './loaderHost';
import { createTitleMatcher, errorWithFile, parseLocationArg } from '../util';
@@ -351,20 +351,20 @@ export async function loadTestList(config: FullConfigInternal, filePath: string)
project = tokens[0].substring(1, tokens[0].length - 1);
tokens.shift();
}
- return { project, file: toPosixPath(parseLocationArg(tokens[0]).file), titlePath: tokens.slice(1) };
+ return { project, file: serverUtils.toPosixPath(parseLocationArg(tokens[0]).file), titlePath: tokens.slice(1) };
});
const testFilter = (test: TestCase) => descriptions.some(d => {
// Note: there is no root yet at the time of filtering.
const [projectName, , ...titles] = test.titlePath();
if (d.project !== undefined && d.project !== projectName)
return false;
- const relativeFile = toPosixPath(path.relative(config.config.rootDir, test.location.file));
+ const relativeFile = serverUtils.toPosixPath(path.relative(config.config.rootDir, test.location.file));
if (relativeFile !== d.file)
return false;
return d.titlePath.length <= titles.length && d.titlePath.every((_, index) => titles[index] === d.titlePath[index]);
});
const fileFilter = (file: string) => {
- const relativeFile = toPosixPath(path.relative(config.config.rootDir, file));
+ const relativeFile = serverUtils.toPosixPath(path.relative(config.config.rootDir, file));
return descriptions.some(d => d.file === relativeFile);
};
return { testFilter, fileFilter };
diff --git a/packages/playwright/src/runner/processHost.ts b/packages/playwright/src/runner/processHost.ts
index e3d77633b2..9b06b15d44 100644
--- a/packages/playwright/src/runner/processHost.ts
+++ b/packages/playwright/src/runner/processHost.ts
@@ -17,7 +17,7 @@
import child_process from 'child_process';
import { EventEmitter } from 'events';
-import { assert, timeOrigin } from 'playwright-core/lib/utils';
+import { iso } from 'playwright-core/lib/coreBundle';
import { debug } from 'playwright-core/lib/utilsBundle';
import type { EnvProducedPayload, ProcessInitParams } from '../common/ipc';
@@ -50,7 +50,7 @@ export class ProcessHost extends EventEmitter {
}
async startRunner(runnerParams: any, options: { onStdOut?: (chunk: Buffer | string) => void, onStdErr?: (chunk: Buffer | string) => void } = {}): Promise<ProcessExitData | undefined> {
- assert(!this.process, 'Internal error: starting the same process twice');
+ iso.assert(!this.process, 'Internal error: starting the same process twice');
this.process = child_process.fork(require.resolve('../common/process'), {
// Note: we pass detached:false, so that workers are in the same process group.
// This way Ctrl+C or a kill command can shutdown all workers in case they misbehave.
@@ -127,7 +127,7 @@ export class ProcessHost extends EventEmitter {
const processParams: ProcessInitParams = {
processName: this._processName,
- timeOrigin: timeOrigin(),
+ timeOrigin: iso.timeOrigin(),
};
this.send({
diff --git a/packages/playwright/src/runner/projectUtils.ts b/packages/playwright/src/runner/projectUtils.ts
index 3ad639a995..d96717927d 100644
--- a/packages/playwright/src/runner/projectUtils.ts
+++ b/packages/playwright/src/runner/projectUtils.ts
@@ -18,7 +18,7 @@ import fs from 'fs';
import path from 'path';
import { promisify } from 'util';
-import { escapeRegExp } from 'playwright-core/lib/utils';
+import { iso } from 'playwright-core/lib/coreBundle';
import { minimatch } from 'playwright-core/lib/utilsBundle';
import { createFileMatcher } from '../util';
@@ -30,7 +30,7 @@ const readFileAsync = promisify(fs.readFile);
const readDirAsync = promisify(fs.readdir);
function wildcardPatternToRegExp(pattern: string): RegExp {
- return new RegExp('^' + pattern.split('*').map(escapeRegExp).join('.*') + '$', 'ig');
+ return new RegExp('^' + pattern.split('*').map(iso.escapeRegExp).join('.*') + '$', 'ig');
}
export function filterProjects(projects: FullProjectInternal[], projectNames?: string[]): FullProjectInternal[] {
diff --git a/packages/playwright/src/runner/rebase.ts b/packages/playwright/src/runner/rebase.ts
index 79dd3fa998..d01a752d15 100644
--- a/packages/playwright/src/runner/rebase.ts
+++ b/packages/playwright/src/runner/rebase.ts
@@ -18,8 +18,8 @@ import fs from 'fs';
import path from 'path';
-import { MultiMap } from 'playwright-core/lib/utils';
-import { colors } from 'playwright-core/lib/utils';
+import { iso } from 'playwright-core/lib/coreBundle';
+import { colors } from 'playwright-core/lib/utilsBundle';
import { diff } from 'playwright-core/lib/utilsBundle';
import { filterProjects } from './projectUtils';
@@ -42,7 +42,7 @@ type Replacement = {
code: string;
};
-const suggestedRebaselines = new MultiMap<string, Replacement>();
+const suggestedRebaselines = new iso.MultiMap<string, Replacement>();
export function addSuggestedRebaseline(location: Location, suggestedRebaseline: string) {
suggestedRebaselines.set(location.file, { location, code: suggestedRebaseline });
diff --git a/packages/playwright/src/runner/reporters.ts b/packages/playwright/src/runner/reporters.ts
index d3324a5383..dc9926d2d2 100644
--- a/packages/playwright/src/runner/reporters.ts
+++ b/packages/playwright/src/runner/reporters.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
import fs from 'fs';
-import { calculateSha1 } from 'playwright-core/lib/utils';
+import { serverUtils } from 'playwright-core/lib/coreBundle';
import { loadReporter } from './loadUtils';
import { formatError } from '../reporters/base';
@@ -128,10 +128,10 @@ function computeCommandHash(config: FullConfigInternal) {
if (config.config.tags.length)
command.tags = config.config.tags.join(' ');
if (config.cliTestList)
- command.cliTestList = calculateSha1(fs.readFileSync(config.cliTestList));
+ command.cliTestList = serverUtils.calculateSha1(fs.readFileSync(config.cliTestList));
if (config.cliTestListInvert)
- command.cliTestListInvert = calculateSha1(fs.readFileSync(config.cliTestListInvert));
+ command.cliTestListInvert = serverUtils.calculateSha1(fs.readFileSync(config.cliTestListInvert));
if (Object.keys(command).length)
- parts.push(calculateSha1(JSON.stringify(command)).substring(0, 7));
+ parts.push(serverUtils.calculateSha1(JSON.stringify(command)).substring(0, 7));
return parts.join('-');
}
diff --git a/packages/playwright/src/runner/taskRunner.ts b/packages/playwright/src/runner/taskRunner.ts
index ea0561faaa..f6719c5c24 100644
--- a/packages/playwright/src/runner/taskRunner.ts
+++ b/packages/playwright/src/runner/taskRunner.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { ManualPromise, monotonicTime } from 'playwright-core/lib/utils';
-import { colors } from 'playwright-core/lib/utils';
+import { iso } from 'playwright-core/lib/coreBundle';
+import { colors } from 'playwright-core/lib/utilsBundle';
import { debug } from 'playwright-core/lib/utilsBundle';
@@ -45,13 +45,13 @@ export class TaskRunner<Context> {
this._tasks.push(task);
}
- async run(context: Context, deadline: number, cancelPromise?: ManualPromise<void>): Promise<FullResult['status']> {
+ async run(context: Context, deadline: number, cancelPromise?: iso.ManualPromise<void>): Promise<FullResult['status']> {
const { status, cleanup } = await this.runDeferCleanup(context, deadline, cancelPromise);
const teardownStatus = await cleanup();
return status === 'passed' ? teardownStatus : status;
}
- async runDeferCleanup(context: Context, deadline: number, cancelPromise = new ManualPromise<void>()): Promise<{ status: FullResult['status'], cleanup: () => Promise<FullResult['status']> }> {
+ async runDeferCleanup(context: Context, deadline: number, cancelPromise = new iso.ManualPromise<void>()): Promise<{ status: FullResult['status'], cleanup: () => Promise<FullResult['status']> }> {
const sigintWatcher = new SigIntWatcher();
const timeoutWatcher = new TimeoutWatcher(deadline);
const teardownRunner = new TaskRunner<Context>(this._reporter, this._globalTimeoutForError);
@@ -118,14 +118,14 @@ export class TaskRunner<Context> {
class TimeoutWatcher {
private _timedOut = false;
- readonly promise = new ManualPromise();
+ readonly promise = new iso.ManualPromise();
private _timer: NodeJS.Timeout | undefined;
constructor(deadline: number) {
if (!deadline)
return;
- if (deadline - monotonicTime() <= 0) {
+ if (deadline - iso.monotonicTime() <= 0) {
this._timedOut = true;
this.promise.resolve();
return;
@@ -133,7 +133,7 @@ class TimeoutWatcher {
this._timer = setTimeout(() => {
this._timedOut = true;
this.promise.resolve();
- }, deadline - monotonicTime());
+ }, deadline - iso.monotonicTime());
}
timedOut(): boolean {
diff --git a/packages/playwright/src/runner/tasks.ts b/packages/playwright/src/runner/tasks.ts
index 15bd7b2784..0447f781ff 100644
--- a/packages/playwright/src/runner/tasks.ts
+++ b/packages/playwright/src/runner/tasks.ts
@@ -18,7 +18,7 @@ import fs from 'fs';
import path from 'path';
import { promisify } from 'util';
-import { monotonicTime, removeFolders } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { debug } from 'playwright-core/lib/utilsBundle';
import { Dispatcher } from './dispatcher';
@@ -41,7 +41,6 @@ import type { Task } from './taskRunner';
import type { FullResult } from '../../types/testReporter';
import type { FullConfigInternal, FullProjectInternal } from '../common/config';
import type { InternalReporter } from '../reporters/internalReporter';
-import type { ManualPromise } from 'playwright-core/lib/utils';
const readDirAsync = promisify(fs.readdir);
@@ -73,8 +72,8 @@ export class TestRun {
}
}
-export async function runTasks(testRun: TestRun, tasks: Task<TestRun>[], globalTimeout?: number, cancelPromise?: ManualPromise<void>) {
- const deadline = globalTimeout ? monotonicTime() + globalTimeout : 0;
+export async function runTasks(testRun: TestRun, tasks: Task<TestRun>[], globalTimeout?: number, cancelPromise?: iso.ManualPromise<void>) {
+ const deadline = globalTimeout ? iso.monotonicTime() + globalTimeout : 0;
const taskRunner = new TaskRunner<TestRun>(testRun.reporter, globalTimeout || 0);
for (const task of tasks)
taskRunner.addTask(task);
@@ -213,7 +212,7 @@ function createRemoveOutputDirsTask(): Task<TestRun> {
const projects = filterProjects(config.projects, config.cliProjectFilter);
projects.forEach(p => outputDirs.add(p.project.outputDir));
- await Promise.all(Array.from(outputDirs).map(outputDir => removeFolders([outputDir]).then(async ([error]) => {
+ await Promise.all(Array.from(outputDirs).map(outputDir => serverUtils.removeFolders([outputDir]).then(async ([error]) => {
if (!error)
return;
if ((error as any).code === 'EBUSY') {
@@ -221,7 +220,7 @@ function createRemoveOutputDirsTask(): Task<TestRun> {
// https://github.com/microsoft/playwright/issues/12106
// Do a best-effort to remove all files inside of it instead.
const entries = await readDirAsync(outputDir).catch(e => []);
- await Promise.all(entries.map(entry => removeFolders([path.join(outputDir, entry)])));
+ await Promise.all(entries.map(entry => serverUtils.removeFolders([path.join(outputDir, entry)])));
} else {
throw error;
}
diff --git a/packages/playwright/src/runner/testRunner.ts b/packages/playwright/src/runner/testRunner.ts
index 514e1e184b..e260551653 100644
--- a/packages/playwright/src/runner/testRunner.ts
+++ b/packages/playwright/src/runner/testRunner.ts
@@ -18,8 +18,7 @@ import EventEmitter from 'events';
import fs from 'fs';
import path from 'path';
-import { registry } from 'playwright-core/lib/server';
-import { ManualPromise, gracefullyProcessExitDoNotHang, setPlaywrightTestProcessEnv } from 'playwright-core/lib/utils';
+import { iso, serverUtils, sever } from 'playwright-core/lib/coreBundle';
import { loadConfig } from '../common/configLoader';
import { Watcher } from '../fsWatcher';
@@ -94,7 +93,7 @@ export class TestRunner extends EventEmitter<TestRunnerEventMap> {
private _ignoredProjectOutputs = new Set<string>();
private _watchedTestDependencies = new Set<string>();
- private _testRun: { run: Promise<reporterTypes.FullResult['status']>, stop: ManualPromise<void> } | undefined;
+ private _testRun: { run: Promise<reporterTypes.FullResult['status']>, stop: iso.ManualPromise<void> } | undefined;
private _queue = Promise.resolve();
private _globalSetup: { cleanup: () => Promise<any> } | undefined;
private _devServer: { cleanup: () => Promise<any> } | undefined;
@@ -118,7 +117,7 @@ export class TestRunner extends EventEmitter<TestRunnerEventMap> {
watchTestDirs?: boolean;
populateDependenciesOnList?: boolean;
}) {
- setPlaywrightTestProcessEnv();
+ serverUtils.setPlaywrightTestProcessEnv();
this._watchTestDirs = !!params.watchTestDirs;
this._populateDependenciesOnList = !!params.populateDependenciesOnList;
this._startingEnv = { ...process.env };
@@ -136,7 +135,7 @@ export class TestRunner extends EventEmitter<TestRunnerEventMap> {
hasSomeBrowsers(): boolean {
for (const browserName of ['chromium', 'webkit', 'firefox']) {
try {
- registry.findExecutable(browserName)!.executablePathOrDie('javascript');
+ sever.registry.findExecutable(browserName)!.executablePathOrDie('javascript');
return true;
} catch {
}
@@ -145,8 +144,8 @@ export class TestRunner extends EventEmitter<TestRunnerEventMap> {
}
async installBrowsers() {
- const executables = registry.defaultExecutables();
- await registry.install(executables);
+ const executables = sever.registry.defaultExecutables();
+ await sever.registry.install(executables);
}
async loadConfig() {
@@ -354,7 +353,7 @@ export class TestRunner extends EventEmitter<TestRunnerEventMap> {
const configReporters = params.disableConfigReporters ? [] : await createReporters(config, 'test');
const reporter = new InternalReporter([...configReporters, userReporter]);
- const stop = new ManualPromise();
+ const stop = new iso.ManualPromise();
const tasks = [
createApplyRebaselinesTask(),
createLoadTask('out-of-process', { filterOnly: true, failOnLoadErrors: !!params.failOnLoadErrors, doNotRunDepsOutsideProjectFilter: params.doNotRunDepsOutsideProjectFilter }),
@@ -400,7 +399,7 @@ export class TestRunner extends EventEmitter<TestRunnerEventMap> {
}
async closeGracefully() {
- gracefullyProcessExitDoNotHang(0);
+ serverUtils.gracefullyProcessExitDoNotHang(0);
}
async stop() {
@@ -457,7 +456,7 @@ async function resolveCtDirs(config: FullConfigInternal) {
}
export async function runAllTestsWithConfig(config: FullConfigInternal): Promise<FullResultStatus> {
- setPlaywrightTestProcessEnv();
+ serverUtils.setPlaywrightTestProcessEnv();
const listOnly = config.cliListOnly;
diff --git a/packages/playwright/src/runner/testServer.ts b/packages/playwright/src/runner/testServer.ts
index 627e4f7a25..4315b2413f 100644
--- a/packages/playwright/src/runner/testServer.ts
+++ b/packages/playwright/src/runner/testServer.ts
@@ -16,8 +16,7 @@
import util from 'util';
-import { installRootRedirect, openTraceInBrowser, openTraceViewerApp, startTraceViewerServer } from 'playwright-core/lib/server';
-import { ManualPromise, gracefullyProcessExitDoNotHang, isUnderTest } from 'playwright-core/lib/utils';
+import { iso, serverUtils, sever } from 'playwright-core/lib/coreBundle';
import { debug, open } from 'playwright-core/lib/utilsBundle';
import { loadConfig, resolveConfigLocation } from '../common/configLoader';
@@ -26,14 +25,15 @@ import { createReporterForTestServer } from './reporters';
import { SigIntWatcher } from './sigIntWatcher';
import { TestRunner, TestRunnerEvent } from './testRunner';
-import type { TraceViewerRedirectOptions, TraceViewerServerOptions } from 'playwright-core/lib/server/trace/viewer/traceViewer';
-import type { HttpServer, Transport } from 'playwright-core/lib/utils';
import type * as reporterTypes from '../../types/testReporter';
import type { ConfigLocation } from '../common/config';
import type { ConfigCLIOverrides } from '../common/ipc';
import type { ReportEntry, TestServerInterface, TestServerInterfaceEventEmitters } from '../isomorphic/testServerInterface';
import type { ReporterV2 } from '../reporters/reporterV2';
+type TraceViewerRedirectOptions = sever.TraceViewerRedirectOptions;
+type TraceViewerServerOptions = sever.TraceViewerServerOptions;
+
const originalDebugLog = debug.log;
// eslint-disable-next-line no-restricted-properties
const originalStdoutWrite = process.stdout.write;
@@ -52,9 +52,9 @@ class TestServer {
this._configCLIOverrides = configCLIOverrides;
}
- async start(options: { host?: string, port?: number }): Promise<HttpServer> {
+ async start(options: { host?: string, port?: number }): Promise<serverUtils.HttpServer> {
this._dispatcher = new TestServerDispatcher(this._configLocation, this._configCLIOverrides);
- return await startTraceViewerServer({ ...options, transport: this._dispatcher.transport });
+ return await sever.startTraceViewerServer({ ...options, transport: this._dispatcher.transport });
}
async stop() {
@@ -87,7 +87,7 @@ export type RunTestsParams = {
};
export class TestServerDispatcher implements TestServerInterface {
- readonly transport: Transport;
+ readonly transport: serverUtils.Transport;
private _serializer = require.resolve('./uiModeReporter');
private _closeOnDisconnect = false;
private _testRunner: TestRunner;
@@ -102,7 +102,7 @@ export class TestServerDispatcher implements TestServerInterface {
dispatch: (method, params) => (this as any)[method](params),
onclose: () => {
if (this._closeOnDisconnect)
- gracefullyProcessExitDoNotHang(0);
+ serverUtils.gracefullyProcessExitDoNotHang(0);
},
};
@@ -136,7 +136,7 @@ export class TestServerDispatcher implements TestServerInterface {
async ping() {}
async open(params: Parameters<TestServerInterface['open']>[0]): ReturnType<TestServerInterface['open']> {
- if (isUnderTest())
+ if (serverUtils.isUnderTest())
return;
// eslint-disable-next-line no-console
open('vscode://file/' + params.location.file + ':' + params.location.line).catch(e => console.error(e));
@@ -271,14 +271,14 @@ export class TestServerDispatcher implements TestServerInterface {
export async function runUIMode(configFile: string | undefined, configCLIOverrides: ConfigCLIOverrides, options: TraceViewerServerOptions & TraceViewerRedirectOptions): Promise<reporterTypes.FullResult['status']> {
const configLocation = resolveConfigLocation(configFile);
- return await innerRunTestServer(configLocation, configCLIOverrides, options, async (server: HttpServer, cancelPromise: ManualPromise<void>) => {
- await installRootRedirect(server, undefined, { ...options, webApp: 'uiMode.html' });
+ return await innerRunTestServer(configLocation, configCLIOverrides, options, async (server: serverUtils.HttpServer, cancelPromise: iso.ManualPromise<void>) => {
+ await sever.installRootRedirect(server, undefined, { ...options, webApp: 'uiMode.html' });
if (options.host !== undefined || options.port !== undefined) {
- await openTraceInBrowser(server.urlPrefix('human-readable'));
+ await sever.openTraceInBrowser(server.urlPrefix('human-readable'));
} else {
const channel = await installedChromiumChannelForUI(configLocation, configCLIOverrides);
- const page = await openTraceViewerApp(server.urlPrefix('precise'), 'chromium', {
- headless: isUnderTest() && process.env.PWTEST_HEADED_FOR_TEST !== '1',
+ const page = await sever.openTraceViewerApp(server.urlPrefix('precise'), 'chromium', {
+ headless: serverUtils.isUnderTest() && process.env.PWTEST_HEADED_FOR_TEST !== '1',
persistentContextOptions: {
handleSIGINT: false,
channel,
@@ -311,11 +311,11 @@ export async function runTestServer(configFile: string | undefined, configCLIOve
});
}
-async function innerRunTestServer(configLocation: ConfigLocation, configCLIOverrides: ConfigCLIOverrides, options: { host?: string, port?: number }, openUI: (server: HttpServer, cancelPromise: ManualPromise<void>) => Promise<void>): Promise<reporterTypes.FullResult['status']> {
+async function innerRunTestServer(configLocation: ConfigLocation, configCLIOverrides: ConfigCLIOverrides, options: { host?: string, port?: number }, openUI: (server: serverUtils.HttpServer, cancelPromise: iso.ManualPromise<void>) => Promise<void>): Promise<reporterTypes.FullResult['status']> {
const testServer = new TestServer(configLocation, configCLIOverrides);
- const cancelPromise = new ManualPromise<void>();
+ const cancelPromise = new iso.ManualPromise<void>();
const sigintWatcher = new SigIntWatcher();
- process.stdin.on('close', () => gracefullyProcessExitDoNotHang(0));
+ process.stdin.on('close', () => serverUtils.gracefullyProcessExitDoNotHang(0));
void sigintWatcher.promise().then(() => cancelPromise.resolve());
try {
const server = await testServer.start(options);
diff --git a/packages/playwright/src/runner/watchMode.ts b/packages/playwright/src/runner/watchMode.ts
index e63cf174b9..f7e50eebc4 100644
--- a/packages/playwright/src/runner/watchMode.ts
+++ b/packages/playwright/src/runner/watchMode.ts
@@ -18,9 +18,8 @@ import path from 'path';
import readline from 'readline';
import { EventEmitter } from 'stream';
-import { PlaywrightServer } from 'playwright-core/lib/remote/playwrightServer';
-import { ManualPromise, createGuid, eventsHelper, getPackageManagerExecCommand } from 'playwright-core/lib/utils';
-import { colors } from 'playwright-core/lib/utils';
+import { iso, remote, serverUtils } from 'playwright-core/lib/coreBundle';
+import { colors } from 'playwright-core/lib/utilsBundle';
import { separator, terminalScreen } from '../reporters/base';
import { enquirer } from '../utilsBundle';
@@ -99,7 +98,7 @@ export async function runWatchModeLoop(configLocation: ConfigLocation, initialOp
const dirtyTestFiles = new Set<string>();
const dirtyTestIds = new Set<string>();
- let onDirtyTests = new ManualPromise<'changed'>();
+ let onDirtyTests = new iso.ManualPromise<'changed'>();
let queue = Promise.resolve();
const changedFiles = new Set<string>();
@@ -123,7 +122,7 @@ export async function runWatchModeLoop(configLocation: ConfigLocation, initialOp
if (dirtyTestIds.size > 0) {
onDirtyTests.resolve('changed');
- onDirtyTests = new ManualPromise();
+ onDirtyTests = new iso.ManualPromise();
}
});
});
@@ -273,21 +272,21 @@ export async function runWatchModeLoop(configLocation: ConfigLocation, initialOp
}
function readKeyPress<T extends string>(handler: (text: string, key: any) => T | undefined): { dispose(): void; result: Promise<T> } {
- const promise = new ManualPromise<T>();
+ const promise = new iso.ManualPromise<T>();
const rl = readline.createInterface({ input: process.stdin, escapeCodeTimeout: 50 });
readline.emitKeypressEvents(process.stdin, rl);
if (process.stdin.isTTY)
process.stdin.setRawMode(true);
- const listener = eventsHelper.addEventListener(process.stdin, 'keypress', (text: string, key: any) => {
+ const listener = serverUtils.eventsHelper.addEventListener(process.stdin, 'keypress', (text: string, key: any) => {
const result = handler(text, key);
if (result)
promise.resolve(result);
});
const dispose = () => {
- eventsHelper.removeEventListeners([listener]);
+ serverUtils.eventsHelper.removeEventListeners([listener]);
rl.close();
if (process.stdin.isTTY)
process.stdin.setRawMode(false);
@@ -368,12 +367,12 @@ Change settings
});
}
-let showBrowserServer: PlaywrightServer | undefined;
+let showBrowserServer: remote.PlaywrightServer | undefined;
let connectWsEndpoint: string | undefined = undefined;
let seq = 1;
function printConfiguration(options: WatchModeOptions, title?: string) {
- const packageManagerCommand = getPackageManagerExecCommand();
+ const packageManagerCommand = serverUtils.getPackageManagerExecCommand();
const tokens: string[] = [];
tokens.push(`${packageManagerCommand} playwright test`);
if (options.projects)
@@ -419,7 +418,7 @@ ${colors.dim('Waiting for file changes. Press')} ${colors.bold('enter')} ${color
async function toggleShowBrowser() {
if (!showBrowserServer) {
- showBrowserServer = new PlaywrightServer({ mode: 'extension', path: '/' + createGuid(), maxConnections: 1 });
+ showBrowserServer = new remote.PlaywrightServer({ mode: 'extension', path: '/' + serverUtils.createGuid(), maxConnections: 1 });
connectWsEndpoint = await showBrowserServer.listen();
process.stdout.write(`${colors.dim('Show & reuse browser:')} ${colors.bold('on')}\n`);
} else {
diff --git a/packages/playwright/src/runner/workerHost.ts b/packages/playwright/src/runner/workerHost.ts
index bd8dcc7563..4c0fc00984 100644
--- a/packages/playwright/src/runner/workerHost.ts
+++ b/packages/playwright/src/runner/workerHost.ts
@@ -17,7 +17,7 @@
import fs from 'fs';
import path from 'path';
-import { removeFolders } from 'playwright-core/lib/utils';
+import { serverUtils } from 'playwright-core/lib/coreBundle';
import { ProcessHost } from './processHost';
import { stdioChunkToParams } from '../common/ipc';
@@ -77,7 +77,7 @@ export class WorkerHost extends ProcessHost {
}
override async onExit() {
- await removeFolders([this._params.artifactsDir]);
+ await serverUtils.removeFolders([this._params.artifactsDir]);
}
override async stop(didFail?: boolean) {
diff --git a/packages/playwright/src/testActions.ts b/packages/playwright/src/testActions.ts
index c50bff6f1a..7282044e35 100644
--- a/packages/playwright/src/testActions.ts
+++ b/packages/playwright/src/testActions.ts
@@ -17,9 +17,10 @@
import fs from 'fs';
import path from 'path';
-import { gracefullyProcessExitDoNotHang, startProfiling, stopProfiling } from 'playwright-core/lib/utils';
-
+import { serverUtils } from 'playwright-core/lib/coreBundle';
import { builtInReporters } from './common/config';
+
+const { gracefullyProcessExitDoNotHang } = serverUtils;
import { loadConfigFromFile, resolveConfigLocation } from './common/configLoader';
import { terminalScreen } from './reporters/base';
import { filterProjects } from './runner/projectUtils';
@@ -32,7 +33,7 @@ import type { ConfigCLIOverrides } from './common/ipc';
import type { ReporterDescription } from '../types/test';
export async function runTests(args: string[], opts: { [key: string]: any }) {
- await startProfiling();
+ await serverUtils.startProfiling();
const cliOverrides = overridesFromOptions(opts);
const config = await loadConfigFromFile(opts.config, cliOverrides, opts.deps === false);
@@ -63,7 +64,7 @@ export async function runTests(args: string[], opts: { [key: string]: any }) {
project: opts.project || undefined,
reporter: Array.isArray(opts.reporter) ? opts.reporter : opts.reporter ? [opts.reporter] : undefined,
});
- await stopProfiling('runner');
+ await serverUtils.stopProfiling('runner');
const exitCode = status === 'interrupted' ? 130 : (status === 'passed' ? 0 : 1);
gracefullyProcessExitDoNotHang(exitCode);
return;
@@ -81,14 +82,14 @@ export async function runTests(args: string[], opts: { [key: string]: any }) {
grep: opts.grep
}
);
- await stopProfiling('runner');
+ await serverUtils.stopProfiling('runner');
const exitCode = status === 'interrupted' ? 130 : (status === 'passed' ? 0 : 1);
gracefullyProcessExitDoNotHang(exitCode);
return;
}
const status = await runAllTestsWithConfig(config);
- await stopProfiling('runner');
+ await serverUtils.stopProfiling('runner');
const exitCode = status === 'interrupted' ? 130 : (status === 'passed' ? 0 : 1);
gracefullyProcessExitDoNotHang(exitCode);
}
diff --git a/packages/playwright/src/transform/compilationCache.ts b/packages/playwright/src/transform/compilationCache.ts
index d132f5f50d..1e81d9c70c 100644
--- a/packages/playwright/src/transform/compilationCache.ts
+++ b/packages/playwright/src/transform/compilationCache.ts
@@ -18,7 +18,7 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
-import { calculateSha1 } from 'playwright-core/lib/utils';
+import { serverUtils } from 'playwright-core/lib/coreBundle';
import { isWorkerProcess } from '../common/globals';
import { sourceMapSupport } from '../utilsBundle';
@@ -176,7 +176,7 @@ export function addToCompilationCache(payload: SerializedCompilationCache) {
function calculateFilePathHash(filePath: string): string {
// Larger file path hash allows for fewer collisions compared to content, as we only check file path collision for deleting files
- return calculateSha1(filePath).substring(0, 10);
+ return serverUtils.calculateSha1(filePath).substring(0, 10);
}
function calculateCachePath(filePath: string, cacheFolderName: string, hashPrefix: string): string {
diff --git a/packages/playwright/src/util.ts b/packages/playwright/src/util.ts
index 3da87f30c8..e441cb7a3c 100644
--- a/packages/playwright/src/util.ts
+++ b/packages/playwright/src/util.ts
@@ -19,15 +19,16 @@ import path from 'path';
import url from 'url';
import util from 'util';
-import { parseStackFrame, sanitizeForFilePath, calculateSha1, isRegExp, isString, stringifyStackFrames } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { debug, mime, minimatch } from 'playwright-core/lib/utilsBundle';
import type { Location } from './../types/testReporter';
import type { TestInfoErrorImpl } from './common/ipc';
import type { StackFrame } from '@protocol/channels';
-import type { RawStack } from 'playwright-core/lib/utils';
import type { TestCase } from './common/test';
+type RawStack = iso.RawStack;
+
const PLAYWRIGHT_TEST_PATH = path.join(__dirname, '..');
const PLAYWRIGHT_CORE_PATH = path.dirname(require.resolve('playwright-core/package.json'));
@@ -37,7 +38,7 @@ export function filterStackTrace(e: Error): { message: string, stack: string, ca
if (process.env.PWDEBUGIMPL)
return { message: name + e.message, stack: e.stack || '', cause };
- const stackLines = stringifyStackFrames(filteredStackTrace(e.stack?.split('\n') || []));
+ const stackLines = iso.stringifyStackFrames(filteredStackTrace(e.stack?.split('\n') || []));
return {
message: name + e.message,
stack: `${name}${e.message}${stackLines.map(line => '\n' + line).join('')}`,
@@ -56,7 +57,7 @@ export function filterStackFile(file: string) {
export function filteredStackTrace(rawStack: RawStack): StackFrame[] {
const frames: StackFrame[] = [];
for (const line of rawStack) {
- const frame = parseStackFrame(line, path.sep, !!process.env.PWDEBUGIMPL);
+ const frame = iso.parseStackFrame(line, path.sep, !!process.env.PWDEBUGIMPL);
if (!frame || !frame.file)
continue;
if (!filterStackFile(frame.file))
@@ -90,7 +91,7 @@ export function createFileMatcher(patterns: string | RegExp | (string | RegExp)[
const reList: RegExp[] = [];
const filePatterns: string[] = [];
for (const pattern of Array.isArray(patterns) ? patterns : [patterns]) {
- if (isRegExp(pattern)) {
+ if (iso.isRegExp(pattern)) {
reList.push(pattern);
} else {
if (!pattern.startsWith('**/'))
@@ -181,7 +182,7 @@ export const windowsFilesystemFriendlyLength = 60;
export function trimLongString(s: string, length = 100) {
if (s.length <= length)
return s;
- const hash = calculateSha1(s);
+ const hash = serverUtils.calculateSha1(s);
const middle = `-${hash.substring(0, 5)}-`;
const start = Math.floor((length - middle.length) / 2);
const end = length - middle.length - start;
@@ -197,7 +198,7 @@ export function addSuffixToFilePath(filePath: string, suffix: string): string {
export function sanitizeFilePathBeforeExtension(filePath: string, ext?: string): string {
ext ??= path.extname(filePath);
const base = filePath.substring(0, filePath.length - ext.length);
- return sanitizeForFilePath(base) + ext;
+ return serverUtils.sanitizeForFilePath(base) + ext;
}
/**
@@ -250,12 +251,12 @@ export async function normalizeAndSaveAttachment(outputPath: string, name: strin
if ((options.path !== undefined ? 1 : 0) + (options.body !== undefined ? 1 : 0) !== 1)
throw new Error(`Exactly one of "path" and "body" must be specified`);
if (options.path !== undefined) {
- const hash = calculateSha1(options.path);
+ const hash = serverUtils.calculateSha1(options.path);
- if (!isString(name))
+ if (!iso.isString(name))
throw new Error('"name" should be string.');
- const sanitizedNamePrefix = sanitizeForFilePath(name) + '-';
+ const sanitizedNamePrefix = serverUtils.sanitizeForFilePath(name) + '-';
const dest = path.join(outputPath, 'attachments', sanitizedNamePrefix + hash + path.extname(options.path));
await fs.promises.mkdir(path.dirname(dest), { recursive: true });
await fs.promises.copyFile(options.path, dest);
@@ -394,4 +395,4 @@ export async function removeDirAndLogToConsole(dir: string) {
}
}
-export { ansiRegex, stripAnsiEscapes } from 'playwright-core/lib/utils';
+export const { ansiRegex, stripAnsiEscapes } = iso;
diff --git a/packages/playwright/src/worker/fixtureRunner.ts b/packages/playwright/src/worker/fixtureRunner.ts
index c00b9fe626..105f187124 100644
--- a/packages/playwright/src/worker/fixtureRunner.ts
+++ b/packages/playwright/src/worker/fixtureRunner.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { escapeWithQuotes, ManualPromise } from 'playwright-core/lib/utils';
+import { iso } from 'playwright-core/lib/coreBundle';
import { fixtureParameterNames } from '../common/fixtures';
import { filterStackFile, formatLocation } from '../util';
@@ -31,7 +31,7 @@ class Fixture {
value: any;
failed = false;
- private _useFuncFinished: ManualPromise<void> | undefined;
+ private _useFuncFinished: iso.ManualPromise<void> | undefined;
private _selfTeardownComplete: Promise<void> | undefined;
private _setupDescription: FixtureDescription;
private _teardownDescription: FixtureDescription;
@@ -46,7 +46,7 @@ class Fixture {
const isUserFixture = this.registration.location && filterStackFile(this.registration.location.file);
const title = this.registration.customTitle || this.registration.name;
const location = isUserFixture ? this.registration.location : undefined;
- this._stepInfo = { title: `Fixture ${escapeWithQuotes(title, '"')}`, category: 'fixture', location };
+ this._stepInfo = { title: `Fixture ${iso.escapeWithQuotes(title, '"')}`, category: 'fixture', location };
if (this.registration.box === 'self')
this._stepInfo = undefined;
else if (this.registration.box)
@@ -104,13 +104,13 @@ class Fixture {
}
let called = false;
- const useFuncStarted = new ManualPromise<void>();
+ const useFuncStarted = new iso.ManualPromise<void>();
const useFunc = async (value: any) => {
if (called)
throw new Error(`Cannot provide fixture value for the second time`);
called = true;
this.value = value;
- this._useFuncFinished = new ManualPromise<void>();
+ this._useFuncFinished = new iso.ManualPromise<void>();
useFuncStarted.resolve();
await this._useFuncFinished;
};
diff --git a/packages/playwright/src/worker/testInfo.ts b/packages/playwright/src/worker/testInfo.ts
index 366eaa5971..54863e93cb 100644
--- a/packages/playwright/src/worker/testInfo.ts
+++ b/packages/playwright/src/worker/testInfo.ts
@@ -17,7 +17,7 @@
import fs from 'fs';
import path from 'path';
-import { captureRawStack, monotonicTime, sanitizeForFilePath, stringifyStackFrames, currentZone, createGuid, escapeWithQuotes, ManualPromise } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { TimeoutManager, TimeoutManagerError, kMaxDeadline } from './timeoutManager';
import { addSuffixToFilePath, filteredStackTrace, getContainedPath, normalizeAndSaveAttachment, sanitizeFilePathBeforeExtension, trimLongString, windowsFilesystemFriendlyLength } from '../util';
@@ -33,6 +33,8 @@ import type * as ipc from '../common/ipc';
import type { TestCase } from '../common/test';
import type { StackFrame } from '@protocol/channels';
+const { monotonicTime } = iso;
+
export type TestStepCategory = 'expect' | 'fixture' | 'hook' | 'pw:api' | 'test.step' | 'test.attach';
interface TestStepData {
@@ -89,7 +91,7 @@ export class TestInfoImpl implements TestInfo {
readonly _tracing: TestTracing;
readonly _uniqueSymbol;
- private _interruptedPromise = new ManualPromise<void>();
+ private _interruptedPromise = new iso.ManualPromise<void>();
_lastStepId = 0;
private readonly _requireFile: string;
readonly _projectInternal: FullProjectInternal;
@@ -211,9 +213,9 @@ export class TestInfoImpl implements TestInfo {
const sanitizedRelativePath = relativeTestFilePath.replace(process.platform === 'win32' ? new RegExp('\\\\', 'g') : new RegExp('/', 'g'), '-');
const fullTitleWithoutSpec = this.titlePath.slice(1).join(' ');
- let testOutputDir = trimLongString(sanitizedRelativePath + '-' + sanitizeForFilePath(fullTitleWithoutSpec), windowsFilesystemFriendlyLength);
+ let testOutputDir = trimLongString(sanitizedRelativePath + '-' + serverUtils.sanitizeForFilePath(fullTitleWithoutSpec), windowsFilesystemFriendlyLength);
if (projectInternal.id)
- testOutputDir += '-' + sanitizeForFilePath(projectInternal.id);
+ testOutputDir += '-' + serverUtils.sanitizeForFilePath(projectInternal.id);
if (this.retry)
testOutputDir += '-retry' + this.retry;
if (this.repeatEachIndex)
@@ -286,7 +288,7 @@ export class TestInfoImpl implements TestInfo {
}
private _parentStep() {
- return currentZone().data<TestStepInternal>('stepZone') ?? this._findLastPredefinedStep(this._steps);
+ return serverUtils.currentZone().data<TestStepInternal>('stepZone') ?? this._findLastPredefinedStep(this._steps);
}
_addStep(data: Readonly<TestStepData>, parentStep?: TestStepInternal): TestStepInternal {
@@ -300,7 +302,7 @@ export class TestInfoImpl implements TestInfo {
parentStep = this._parentStep();
}
- const filteredStack = filteredStackTrace(captureRawStack());
+ const filteredStack = filteredStackTrace(iso.captureRawStack());
let boxedStack = parentStep?.boxedStack;
let location = data.location;
if (!boxedStack && data.box) {
@@ -328,7 +330,7 @@ export class TestInfoImpl implements TestInfo {
(result.error as any)[stepSymbol] = step;
const error = testInfoError(result.error);
if (step.boxedStack)
- error.stack = `${error.message}\n${stringifyStackFrames(step.boxedStack).join('\n')}`;
+ error.stack = `${error.message}\n${iso.stringifyStackFrames(step.boxedStack).join('\n')}`;
step.error = error;
}
@@ -409,7 +411,7 @@ export class TestInfoImpl implements TestInfo {
const serialized = testInfoError(error);
const step: TestStepInternal | undefined = typeof error === 'object' ? (error as any)?.[stepSymbol] : undefined;
if (step && step.boxedStack)
- serialized.stack = `${(error as Error).name}: ${(error as Error).message}\n${stringifyStackFrames(step.boxedStack).join('\n')}`;
+ serialized.stack = `${(error as Error).name}: ${(error as Error).message}\n${iso.stringifyStackFrames(step.boxedStack).join('\n')}`;
this.errors.push(serialized);
this._tracing.appendForError(serialized);
}
@@ -486,7 +488,7 @@ export class TestInfoImpl implements TestInfo {
async attach(name: string, options: { path?: string, body?: string | Buffer, contentType?: string } = {}) {
const step = this._addStep({
- title: `Attach ${escapeWithQuotes(name, '"')}`,
+ title: `Attach ${iso.escapeWithQuotes(name, '"')}`,
category: 'test.attach',
});
this._attach(
@@ -506,8 +508,8 @@ export class TestInfoImpl implements TestInfo {
if (step) {
step.attachmentIndices.push(index);
} else {
- const stepId = `attach@${createGuid()}`;
- this._tracing.appendBeforeActionForStep({ stepId, title: `Attach ${escapeWithQuotes(attachment.name, '"')}`, category: 'test.attach', stack: [] });
+ const stepId = `attach@${serverUtils.createGuid()}`;
+ this._tracing.appendBeforeActionForStep({ stepId, title: `Attach ${iso.escapeWithQuotes(attachment.name, '"')}`, category: 'test.attach', stack: [] });
this._tracing.appendAfterActionForStep(stepId, undefined, [attachment]);
}
@@ -537,7 +539,7 @@ export class TestInfoImpl implements TestInfo {
_fsSanitizedTestName() {
const fullTitleWithoutSpec = this.titlePath.slice(1).join(' ');
- return sanitizeForFilePath(trimLongString(fullTitleWithoutSpec));
+ return serverUtils.sanitizeForFilePath(trimLongString(fullTitleWithoutSpec));
}
_resolveSnapshotPaths(kind: 'snapshot' | 'screenshot' | 'aria', name: string | string[] | undefined, updateSnapshotIndex: 'updateSnapshotIndex' | 'dontUpdateSnapshotIndex', anonymousExtension?: string) {
@@ -605,7 +607,7 @@ export class TestInfoImpl implements TestInfo {
_applyPathTemplate(template: string, nameArgument: string, ext: string) {
const relativeTestFilePath = path.relative(this.project.testDir, this._requireFile);
const parsedRelativeTestFilePath = path.parse(relativeTestFilePath);
- const projectNamePathSegment = sanitizeForFilePath(this.project.name);
+ const projectNamePathSegment = serverUtils.sanitizeForFilePath(this.project.name);
const snapshotPath = template
.replace(/\{(.)?testDir\}/g, '$1' + this.project.testDir)
diff --git a/packages/playwright/src/worker/testTracing.ts b/packages/playwright/src/worker/testTracing.ts
index 65367a1062..61fd37361b 100644
--- a/packages/playwright/src/worker/testTracing.ts
+++ b/packages/playwright/src/worker/testTracing.ts
@@ -17,7 +17,7 @@
import fs from 'fs';
import path from 'path';
-import { ManualPromise, SerializedFS, calculateSha1, createGuid, getPlaywrightVersion, monotonicTime } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { filteredStackTrace } from '../util';
@@ -28,6 +28,8 @@ import type { SerializedError, StackFrame } from '@protocol/channels';
import type * as trace from '@trace/trace';
import type EventEmitter from 'events';
+const { monotonicTime } = iso;
+
export type Attachment = TestInfo['attachments'][0];
export const testTraceEntryName = 'test.trace';
const version: trace.VERSION = 8;
@@ -39,7 +41,7 @@ type TraceOptions = { screenshots: boolean, snapshots: boolean, sources: boolean
export class TestTracing {
private _testInfo: TestInfoImpl;
private _options: TraceOptions | undefined;
- private _liveTraceFile: { file: string, fs: SerializedFS } | undefined;
+ private _liveTraceFile: { file: string, fs: serverUtils.SerializedFS } | undefined;
private _traceEvents: trace.TraceEvent[] = [];
private _temporaryTraceFiles: string[] = [];
private _artifactsDir: string;
@@ -56,7 +58,7 @@ export class TestTracing {
type: 'context-options',
origin: 'testRunner',
browserName: '',
- playwrightVersion: getPlaywrightVersion(),
+ playwrightVersion: serverUtils.getPlaywrightVersion(),
options: {},
platform: process.platform,
wallTime: Date.now(),
@@ -107,7 +109,7 @@ export class TestTracing {
if (!this._liveTraceFile && this._options.live) {
// Note that trace name must start with testId for live tracing to work.
- this._liveTraceFile = { file: path.join(this._tracesDir, `${this._testInfo.testId}-test.trace`), fs: new SerializedFS() };
+ this._liveTraceFile = { file: path.join(this._tracesDir, `${this._testInfo.testId}-test.trace`), fs: new serverUtils.SerializedFS() };
this._liveTraceFile.fs.mkdir(path.dirname(this._liveTraceFile.file));
const data = this._traceEvents.map(e => JSON.stringify(e)).join('\n') + '\n';
this._liveTraceFile.fs.writeFile(this._liveTraceFile.file, data);
@@ -139,7 +141,7 @@ export class TestTracing {
}
private _generateNextTraceRecordingPath() {
- const file = path.join(this._artifactsDir, createGuid() + '.zip');
+ const file = path.join(this._artifactsDir, serverUtils.createGuid() + '.zip');
this._temporaryTraceFiles.push(file);
return file;
}
@@ -202,7 +204,7 @@ export class TestTracing {
}
for (const sourceFile of sourceFiles) {
await fs.promises.readFile(sourceFile, 'utf8').then(source => {
- zipFile.addBuffer(Buffer.from(source), 'resources/src@' + calculateSha1(sourceFile) + '.txt');
+ zipFile.addBuffer(Buffer.from(source), 'resources/src@' + serverUtils.calculateSha1(sourceFile) + '.txt');
}).catch(() => {});
}
}
@@ -220,7 +222,7 @@ export class TestTracing {
if (content === undefined)
continue;
- const sha1 = calculateSha1(content);
+ const sha1 = serverUtils.calculateSha1(content);
attachment.sha1 = sha1;
delete attachment.path;
delete attachment.base64;
@@ -346,7 +348,7 @@ async function mergeTraceFiles(fileName: string, temporaryTraceFiles: string[])
return;
}
- const mergePromise = new ManualPromise();
+ const mergePromise = new iso.ManualPromise();
const { yazl, yauzl } = await import('playwright-core/lib/zipBundle');
const zipFile = new yazl.ZipFile();
const entryNames = new Set<string>();
@@ -354,7 +356,7 @@ async function mergeTraceFiles(fileName: string, temporaryTraceFiles: string[])
for (let i = temporaryTraceFiles.length - 1; i >= 0; --i) {
const tempFile = temporaryTraceFiles[i];
- const promise = new ManualPromise<void>();
+ const promise = new iso.ManualPromise<void>();
yauzl.open(tempFile, (err, inZipFile) => {
if (err) {
promise.reject(err);
diff --git a/packages/playwright/src/worker/timeoutManager.ts b/packages/playwright/src/worker/timeoutManager.ts
index ec4f0fb691..1cb31b538c 100644
--- a/packages/playwright/src/worker/timeoutManager.ts
+++ b/packages/playwright/src/worker/timeoutManager.ts
@@ -14,13 +14,15 @@
* limitations under the License.
*/
-import { ManualPromise, monotonicTime } from 'playwright-core/lib/utils';
-import { colors } from 'playwright-core/lib/utils';
+import { iso } from 'playwright-core/lib/coreBundle';
+import { colors } from 'playwright-core/lib/utilsBundle';
import { debugTest, formatLocation } from '../util';
import type { Location } from '../../types/testReporter';
+const { monotonicTime } = iso;
+
export type TimeSlot = {
timeout: number;
elapsed: number;
@@ -48,7 +50,7 @@ type Running = {
start: number;
deadline: number;
timer: NodeJS.Timeout | undefined;
- timeoutPromise: ManualPromise<any>;
+ timeoutPromise: iso.ManualPromise<any>;
};
export const kMaxDeadline = 2147483647; // 2^31-1
@@ -95,7 +97,7 @@ export class TimeoutManager {
start: monotonicTime(),
deadline: kMaxDeadline,
timer: undefined,
- timeoutPromise: new ManualPromise(),
+ timeoutPromise: new iso.ManualPromise(),
};
let debugTitle = '';
try {
diff --git a/packages/playwright/src/worker/workerMain.ts b/packages/playwright/src/worker/workerMain.ts
index 4fcd1e57e6..783b713bde 100644
--- a/packages/playwright/src/worker/workerMain.ts
+++ b/packages/playwright/src/worker/workerMain.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { ManualPromise, gracefullyCloseAll, removeFolders } from 'playwright-core/lib/utils';
-import { colors } from 'playwright-core/lib/utils';
+import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { colors } from 'playwright-core/lib/utilsBundle';
import { deserializeConfig } from '../common/configLoader';
import { setCurrentTestInfo, setIsWorkerProcess } from '../common/globals';
@@ -57,7 +57,7 @@ export class WorkerMain extends ProcessRunner {
// Whether the worker was requested to stop.
private _isStopped = false;
// This promise resolves once the single "run test group" call finishes.
- private _runFinished = new ManualPromise<void>();
+ private _runFinished = new iso.ManualPromise<void>();
private _currentTest: TestInfoImpl | null = null;
private _lastRunningTests: TestCase[] = [];
private _totalRunningTests = 0;
@@ -65,7 +65,7 @@ export class WorkerMain extends ProcessRunner {
// These suites still need afterAll hooks to be executed for the proper cleanup.
// Contains dynamic annotations originated by modifiers with a callback, e.g. `test.skip(() => true)`.
private _activeSuites = new Map<Suite, TestAnnotation[]>();
- private _resumePromise?: ManualPromise<ipc.ResumePayload>;
+ private _resumePromise?: iso.ManualPromise<ipc.ResumePayload>;
constructor(params: ipc.WorkerInitParams) {
super();
@@ -127,7 +127,7 @@ export class WorkerMain extends ProcessRunner {
await this._fixtureRunner.teardownScope('worker', fakeTestInfo, runnable).catch(() => {});
// Close any other browsers launched in this process. This includes anything launched
// manually in the test/hooks and internal browsers like Playwright Inspector.
- await fakeTestInfo._runWithTimeout(runnable, () => gracefullyCloseAll()).catch(() => {});
+ await fakeTestInfo._runWithTimeout(runnable, () => serverUtils.gracefullyCloseAll()).catch(() => {});
this._fatalErrors.push(...fakeTestInfo.errors);
} catch (e) {
this._fatalErrors.push(testInfoError(e));
@@ -216,7 +216,7 @@ export class WorkerMain extends ProcessRunner {
}
async runTestGroup(runPayload: ipc.RunPayload) {
- this._runFinished = new ManualPromise<void>();
+ this._runFinished = new iso.ManualPromise<void>();
const entries = new Map(runPayload.entries.map(e => [e.testId, e]));
let fatalUnknownTestIds: string[] | undefined;
try {
@@ -297,7 +297,7 @@ export class WorkerMain extends ProcessRunner {
onStepEnd: payload => this.dispatchEvent('stepEnd', payload),
onAttach: payload => this.dispatchEvent('attach', payload),
onTestPaused: payload => {
- this._resumePromise = new ManualPromise();
+ this._resumePromise = new iso.ManualPromise();
this.dispatchEvent('testPaused', payload);
return this._resumePromise;
},
@@ -383,7 +383,7 @@ export class WorkerMain extends ProcessRunner {
return;
}
- await removeFolders([testInfo.outputDir]);
+ await serverUtils.removeFolders([testInfo.outputDir]);
let testFunctionParams: object | null = null;
await testInfo._runAsStep({ title: 'Before Hooks', category: 'hook' }, async () => {
@@ -522,7 +522,7 @@ export class WorkerMain extends ProcessRunner {
const preserveOutput = this._config.config.preserveOutput === 'always' ||
(this._config.config.preserveOutput === 'failures-only' && testInfo._isFailure());
if (!preserveOutput)
- await removeFolders([testInfo.outputDir]);
+ await serverUtils.removeFolders([testInfo.outputDir]);
}
private _collectHooksAndModifiers(suite: Suite, type: 'beforeAll' | 'beforeEach' | 'afterAll' | 'afterEach', testInfo: TestInfoImpl) {
diff --git a/tests/config/testMode.ts b/tests/config/testMode.ts
index cd35822bf5..aa30c20910 100644
--- a/tests/config/testMode.ts
+++ b/tests/config/testMode.ts
@@ -14,11 +14,13 @@
* limitations under the License.
*/
-import { start } from '../../packages/playwright-core/lib/outofprocess';
+import { oop } from '../../packages/playwright-core/lib/coreBundle';
import type { Playwright } from '../../packages/playwright-core/lib/client/playwright';
export type TestModeName = 'default' | 'driver' | 'service' | 'service2' | 'wsl';
+const { start } = oop;
+
interface TestMode {
setup(): Promise<Playwright>;
teardown(): Promise<void>;
diff --git a/tests/config/utils.ts b/tests/config/utils.ts
index 85c21b8c00..df61cffcb0 100644
--- a/tests/config/utils.ts
+++ b/tests/config/utils.ts
@@ -22,7 +22,7 @@ import { TraceLoader } from '../../packages/playwright-core/src/utils/isomorphic
import { TraceModel } from '../../packages/playwright-core/src/utils/isomorphic/trace/traceModel';
import type { ActionTraceEvent, TraceEvent } from '@trace/trace';
import { renderTitleForCall } from '../../packages/playwright-core/lib/utils/isomorphic/protocolFormatter';
-import { DirTraceLoaderBackend, extractTrace } from '../../packages/playwright-core/lib/tools/trace/traceParser';
+import { tools } from '../../packages/playwright-core/lib/coreBundle';
import type { SnapshotStorage } from '../../packages/playwright-core/src/utils/isomorphic/trace/snapshotStorage';
export type BoundingBox = Awaited<ReturnType<Locator['boundingBox']>>;
@@ -167,8 +167,8 @@ export async function parseTraceRaw(file: string): Promise<{ events: any[], reso
export async function parseTrace(file: string): Promise<{ snapshots: SnapshotStorage, model: TraceModel }> {
const dir = file + '.extracted';
- await extractTrace(file, dir);
- const backend = new DirTraceLoaderBackend(dir);
+ await tools.extractTrace(file, dir);
+ const backend = new tools.DirTraceLoaderBackend(dir);
const loader = new TraceLoader();
await loader.load(backend);
return { model: new TraceModel(dir, loader.contextEntries), snapshots: loader.storage() };
diff --git a/tests/image_tools/fixtures.spec.ts b/tests/image_tools/fixtures.spec.ts
index 22a23a9eef..f091905096 100644
--- a/tests/image_tools/fixtures.spec.ts
+++ b/tests/image_tools/fixtures.spec.ts
@@ -16,7 +16,7 @@
import { test, expect } from '../playwright-test/stable-test-runner';
import { PNG } from 'playwright-core/lib/utilsBundle';
-import { compare } from 'playwright-core/lib/server/utils/image_tools/compare';
+import { compare } from '../../packages/playwright-core/src/server/utils/image_tools/compare';
import fs from 'fs';
import path from 'path';
diff --git a/tests/image_tools/unit.spec.ts b/tests/image_tools/unit.spec.ts
index 8d68cc28c0..c306ed2497 100644
--- a/tests/image_tools/unit.spec.ts
+++ b/tests/image_tools/unit.spec.ts
@@ -15,9 +15,9 @@
*/
import { test } from '../playwright-test/stable-test-runner';
-import { ssim, FastStats } from 'playwright-core/lib/server/utils/image_tools/stats';
-import { ImageChannel } from 'playwright-core/lib/server/utils/image_tools/imageChannel';
-import { srgb2xyz, xyz2lab, colorDeltaE94 } from 'playwright-core/lib/server/utils/image_tools/colorUtils';
+import { ssim, FastStats } from '../../packages/playwright-core/src/server/utils/image_tools/stats';
+import { ImageChannel } from '../../packages/playwright-core/src/server/utils/image_tools/imageChannel';
+import { srgb2xyz, xyz2lab, colorDeltaE94 } from '../../packages/playwright-core/src/server/utils/image_tools/colorUtils';
import referenceSSIM from 'ssim.js';
import { randomPNG, assertEqual, grayChannel } from './utils';
diff --git a/tests/image_tools/utils.ts b/tests/image_tools/utils.ts
index a3d933c9d9..7b645531ff 100644
--- a/tests/image_tools/utils.ts
+++ b/tests/image_tools/utils.ts
@@ -15,7 +15,7 @@
*/
import { PNG } from 'playwright-core/lib/utilsBundle';
-import { ImageChannel } from 'playwright-core/lib/server/utils/image_tools/imageChannel';
+import { ImageChannel } from '../../packages/playwright-core/src/server/utils/image_tools/imageChannel';
// mulberry32
export function createRandom(seed) {
diff --git a/tests/installation/fixture-scripts/driver-client-sigint.js b/tests/installation/fixture-scripts/driver-client-sigint.js
index 8a36efaeff..9e5cb197cc 100644
--- a/tests/installation/fixture-scripts/driver-client-sigint.js
+++ b/tests/installation/fixture-scripts/driver-client-sigint.js
@@ -16,12 +16,12 @@
// @ts-check
const pw = require.resolve('playwright');
-const oop = require.resolve('playwright-core/lib/outofprocess', { paths: [pw] });
-const { start } = require(oop);
+const coreBundle = require.resolve('playwright-core/lib/coreBundle', { paths: [pw] });
+const { oop } = require(coreBundle);
(async () => {
console.log('launching driver')
- const { playwright, stop } = await start();
+ const { playwright, stop } = await oop.start();
console.log('launched driver')
try {
const browser = await playwright.chromium.launch({ handleSIGINT: false });
diff --git a/tests/installation/fixture-scripts/driver-client.js b/tests/installation/fixture-scripts/driver-client.js
index 202a70abee..46812d649c 100644
--- a/tests/installation/fixture-scripts/driver-client.js
+++ b/tests/installation/fixture-scripts/driver-client.js
@@ -15,11 +15,11 @@
*/
const pw = require.resolve('playwright');
-const oop = require.resolve('playwright-core/lib/outofprocess', { paths: [pw] });
-const { start } = require(oop);
+const coreBundle = require.resolve('playwright-core/lib/coreBundle', { paths: [pw] });
+const { oop } = require(coreBundle);
(async () => {
- const { playwright, stop } = await start();
+ const { playwright, stop } = await oop.start();
console.log(`driver PID=${playwright.driverProcess.pid}`);
for (const browserType of ['chromium', 'firefox', 'webkit']) {
try {
diff --git a/tests/library/browsertype-launch-selenium.spec.ts b/tests/library/browsertype-launch-selenium.spec.ts
index b757e5b2ae..c8b2198fd2 100644
--- a/tests/library/browsertype-launch-selenium.spec.ts
+++ b/tests/library/browsertype-launch-selenium.spec.ts
@@ -18,7 +18,7 @@ import { playwrightTest as test, expect } from '../config/browserTest';
import type { TestInfo } from '@playwright/test';
import path from 'path';
import fs from 'fs';
-import { start } from '../../packages/playwright-core/lib/outofprocess';
+import { oop } from '../../packages/playwright-core/lib/coreBundle';
const chromeDriver = process.env.PWTEST_CHROMEDRIVER;
const brokenDriver = path.join(__dirname, '..', 'assets', 'selenium-grid', 'broken-selenium-driver.js');
@@ -188,7 +188,7 @@ test('selenium grid 3.141.59 standalone chromium through run-driver', async ({ b
});
await waitForPort(port);
- const { playwright: pw, stop } = await start({
+ const { playwright: pw, stop } = await oop.start({
SELENIUM_REMOTE_URL: `http://127.0.0.1:${port}/wd/hub`,
});
const browser = await pw.chromium.launch();
diff --git a/tests/library/headful.spec.ts b/tests/library/headful.spec.ts
index 5226f2ea35..e6803f8619 100644
--- a/tests/library/headful.spec.ts
+++ b/tests/library/headful.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { compare } from 'playwright-core/lib/server/utils/image_tools/compare';
+import { compare } from '../../packages/playwright-core/src/server/utils/image_tools/compare';
import { PNG } from 'playwright-core/lib/utilsBundle';
import { expect, playwrightTest as it } from '../config/browserTest';
diff --git a/tests/library/inspector/inspectorTest.ts b/tests/library/inspector/inspectorTest.ts
index 2838b0094f..495bad1694 100644
--- a/tests/library/inspector/inspectorTest.ts
+++ b/tests/library/inspector/inspectorTest.ts
@@ -22,7 +22,6 @@ import fs from 'fs';
import type { Source } from '../../../packages/recorder/src/recorderTypes';
import type { CommonFixtures, TestChildProcess } from '../../config/commonFixtures';
import { expect } from '@playwright/test';
-import { nodePlatform } from '../../../packages/playwright-core/lib/server/utils/nodePlatform';
export { expect } from '@playwright/test';
type CLITestArgs = {
@@ -47,7 +46,7 @@ const codegenLang2Id: Map<string, string> = new Map([
]);
const codegenLangId2lang = new Map([...codegenLang2Id.entries()].map(([lang, langId]) => [langId, lang]));
-const playwrightToAutomateInspector = require('../../../packages/playwright-core/lib/inProcessFactory').createInProcessPlaywright(nodePlatform);
+const playwrightToAutomateInspector = require('../../../packages/playwright-core/lib/inprocess').playwright;
export const test = contextTest.extend<CLITestArgs>({
recorderPageGetter: async ({ context, toImpl, mode, headless }, run, testInfo) => {
diff --git a/tests/mcp/config-resolve.spec.ts b/tests/mcp/config-resolve.spec.ts
index f30681c6dc..cca192fb47 100644
--- a/tests/mcp/config-resolve.spec.ts
+++ b/tests/mcp/config-resolve.spec.ts
@@ -19,10 +19,11 @@ import path from 'path';
import { test, expect } from '@playwright/test';
-import { resolveCLIConfigForCLI, resolveCLIConfigForMCP } from '../../packages/playwright-core/lib/tools/mcp/config';
-
+import { tools } from '../../packages/playwright-core/lib/coreBundle';
import type { Config } from '../../packages/playwright-core/src/tools/mcp/config.d';
+const { resolveCLIConfigForCLI, resolveCLIConfigForMCP } = tools;
+
// Empty env to isolate tests from the host environment.
const emptyEnv = {};
diff --git a/tests/mcp/fixtures.ts b/tests/mcp/fixtures.ts
index 4b7ad68199..812a134932 100644
--- a/tests/mcp/fixtures.ts
+++ b/tests/mcp/fixtures.ts
@@ -24,7 +24,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { ListRootsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { TestServer } from '../config/testserver';
import { serverFixtures } from '../config/serverFixtures';
-import { parseResponse } from '../../packages/playwright-core/lib/tools/backend/response';
+import { tools } from '../../packages/playwright-core/lib/coreBundle';
import { commonFixtures } from '../config/commonFixtures';
import { inheritAndCleanEnv } from '../config/utils';
@@ -35,7 +35,7 @@ import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
import type { Stream } from 'stream';
import type { ServerFixtures, ServerWorkerOptions } from '../config/serverFixtures';
-export { parseResponse };
+export const { parseResponse } = tools;
export type TestOptions = {
mcpArgs: string[] | undefined;
@@ -235,7 +235,7 @@ type Response = Awaited<ReturnType<Client['callTool']>>;
export const expect = baseExpect.extend({
toHaveResponse(response: Response, object: any) {
- const parsed = parseResponse(response, test.info().outputPath());
+ const parsed = tools.parseResponse(response, test.info().outputPath());
const text = parsed.text;
const isNot = this.isNot;
diff --git a/tests/mcp/library.spec.ts b/tests/mcp/library.spec.ts
index bc5dfc5cd0..c853b53097 100644
--- a/tests/mcp/library.spec.ts
+++ b/tests/mcp/library.spec.ts
@@ -20,8 +20,8 @@ import { test, expect } from './fixtures';
test('library can be used from CommonJS', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright-mcp/issues/456' } }, async ({}, testInfo) => {
const file = testInfo.outputPath('main.cjs');
await fs.writeFile(file, `
- import('playwright-core/lib/tools/exports')
- .then(playwrightMCP => playwrightMCP.createConnection())
+ import('playwright-core/lib/coreBundle')
+ .then(({ tools }) => tools.createConnection())
.then(() => console.log('OK'));
`);
expect(child_process.execSync(`node ${file}`, { encoding: 'utf-8' })).toContain('OK');
diff --git a/tests/mcp/profile-lock.spec.ts b/tests/mcp/profile-lock.spec.ts
index d47a1adafd..3d24fcc165 100644
--- a/tests/mcp/profile-lock.spec.ts
+++ b/tests/mcp/profile-lock.spec.ts
@@ -17,12 +17,12 @@
import { chromium } from 'playwright';
import { test, expect } from './fixtures';
-import { isProfileLocked } from '../../packages/playwright-core/lib/tools/mcp/browserFactory';
+import { tools } from '../../packages/playwright-core/lib/coreBundle';
test('isProfileLocked returns false for empty directory', async ({ mcpBrowser }, testInfo) => {
test.skip(!['chromium', 'chrome', 'msedge'].includes(mcpBrowser!), 'Chromium-only');
const dir = testInfo.outputPath('profile');
- expect(isProfileLocked(dir)).toBe(false);
+ expect(tools.isProfileLocked(dir)).toBe(false);
});
test('isProfileLocked detects a real browser holding the profile', async ({ mcpBrowser }, testInfo) => {
@@ -33,7 +33,7 @@ test('isProfileLocked detects a real browser holding the profile', async ({ mcpB
headless: true,
});
try {
- expect(isProfileLocked(userDataDir)).toBe(true);
+ expect(tools.isProfileLocked(userDataDir)).toBe(true);
} finally {
await context.close();
}
@@ -47,7 +47,7 @@ test('isProfileLocked returns false after browser closes', async ({ mcpBrowser }
headless: true,
});
await context.close();
- expect(isProfileLocked(userDataDir)).toBe(false);
+ expect(tools.isProfileLocked(userDataDir)).toBe(false);
});
test('locked profile produces actionable error on navigate', async ({ mcpBrowser, startClient, server }, testInfo) => {
diff --git a/tests/mcp/semver.spec.ts b/tests/mcp/semver.spec.ts
index e2df550c58..d5222371f8 100644
--- a/tests/mcp/semver.spec.ts
+++ b/tests/mcp/semver.spec.ts
@@ -15,7 +15,9 @@
*/
import { test, expect } from '@playwright/test';
-import { compareSemver } from '../../packages/playwright-core/lib/tools/utils/socketConnection';
+import { tools } from '../../packages/playwright-core/lib/coreBundle';
+
+const { compareSemver } = tools;
test('compareSemver', () => {
// Stable versions.
diff --git a/tests/playwright-test/perf.spec.ts b/tests/playwright-test/perf.spec.ts
deleted file mode 100644
index 8ab36b9bbd..0000000000
--- a/tests/playwright-test/perf.spec.ts
+++ /dev/null
@@ -1,33 +0,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.
- */
-
-import { test, expect } from './playwright-test-fixtures';
-
-test('should not load rare bundles during test run', async ({ runInlineTest }) => {
- const result = await runInlineTest({
- 'a.spec.ts': `
- import { test, expect } from '@playwright/test';
- test('pass', async ({ page }) => {});
- `
- }, {}, { PW_INSTRUMENT_MODULES: '1' });
- expect(result.exitCode).toBe(0);
- expect(result.passed).toBe(1);
- const output = result.output;
- expect(output).toContain('babelBundle');
- expect(output).not.toContain('mcpBundle');
- expect(output).not.toContain('zodBundle');
- expect(output).not.toContain('zipBundle');
-});
diff --git a/utils/linux-browser-dependencies/inside_docker/list_dependencies.js b/utils/linux-browser-dependencies/inside_docker/list_dependencies.js
index c99c784e30..8dcee31b68 100644
--- a/utils/linux-browser-dependencies/inside_docker/list_dependencies.js
+++ b/utils/linux-browser-dependencies/inside_docker/list_dependencies.js
@@ -4,7 +4,7 @@ const fs = require('fs');
const util = require('util');
const path = require('path');
const {spawn} = require('child_process');
-const {registryDirectory} = require('playwright-core/lib/server/registry/index');
+const {registryDirectory} = require('playwright-core/lib/coreBundle').registry;
const readdirAsync = util.promisify(fs.readdir.bind(fs));
const readFileAsync = util.promisify(fs.readFile.bind(fs));