Skip to content

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

chore(test-runner): replace coreBundle/utilsBundle barrels with direct (#40095)

Pavel Feldmand4b541b5e1c1
diff --git a/packages/playwright/src/DEPS.list b/packages/playwright/src/DEPS.list
index 0ff8cb9f20..829803ab70 100644
--- a/packages/playwright/src/DEPS.list
+++ b/packages/playwright/src/DEPS.list
@@ -1,6 +1,8 @@
[*]
+@isomorphic/**
+@serverUtils/**
common/
-./utils.ts
+./util.ts
./utilsBundle.ts
[program.ts]
diff --git a/packages/playwright/src/agents/DEPS.list b/packages/playwright/src/agents/DEPS.list
index c7b2b6f801..8e77643e06 100644
--- a/packages/playwright/src/agents/DEPS.list
+++ b/packages/playwright/src/agents/DEPS.list
@@ -1,4 +1,5 @@
[*]
+@serverUtils/**
../mcp/sdk/
../mcp/test/
../common/
diff --git a/packages/playwright/src/agents/agentParser.ts b/packages/playwright/src/agents/agentParser.ts
index f9523d0ad5..1e39c94782 100644
--- a/packages/playwright/src/agents/agentParser.ts
+++ b/packages/playwright/src/agents/agentParser.ts
@@ -15,6 +15,7 @@
*/
import fs from 'fs';
+
import { yaml } from 'playwright-core/lib/utilsBundle';
type AgentSpecHeader = {
diff --git a/packages/playwright/src/agents/generateAgents.ts b/packages/playwright/src/agents/generateAgents.ts
index e4095fbda2..e2f40d58a6 100644
--- a/packages/playwright/src/agents/generateAgents.ts
+++ b/packages/playwright/src/agents/generateAgents.ts
@@ -18,7 +18,9 @@ import fs from 'fs';
import path from 'path';
import { colors, yaml } from 'playwright-core/lib/utilsBundle';
-import { serverUtils } from 'playwright-core/lib/coreBundle';
+
+import { mkdirIfNeeded } from '@serverUtils/fileUtils';
+
import { FullConfigInternal } from '../common/config';
import { defaultSeedFile, findSeedFile, seedFileContent, seedProject } from '../mcp/test/seed';
import { parseAgentSpec } from './agentParser';
@@ -317,7 +319,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 serverUtils.mkdirIfNeeded(filePath);
+ await mkdirIfNeeded(filePath);
await fs.promises.writeFile(filePath, content, 'utf-8');
}
diff --git a/packages/playwright/src/common/DEPS.list b/packages/playwright/src/common/DEPS.list
index d134d5a469..b9d8643a30 100644
--- a/packages/playwright/src/common/DEPS.list
+++ b/packages/playwright/src/common/DEPS.list
@@ -1,6 +1,7 @@
[*]
+@isomorphic/**
+@serverUtils/**
../util.ts
-../utilsBundle.ts
../transform
../isomorphic/teleReceiver.ts
diff --git a/packages/playwright/src/common/configLoader.ts b/packages/playwright/src/common/configLoader.ts
index d35d82dc6c..c511f294e6 100644
--- a/packages/playwright/src/common/configLoader.ts
+++ b/packages/playwright/src/common/configLoader.ts
@@ -17,7 +17,8 @@
import fs from 'fs';
import path from 'path';
-import { iso } from 'playwright-core/lib/coreBundle';
+import { isRegExp } from '@isomorphic/rtti';
+
import { requireOrImport, setSingleTSConfig, setTransformConfig } from '../transform/transform';
import { errorWithFile, fileIsModule } from '../util';
import { FullConfigInternal } from './config';
@@ -28,8 +29,6 @@ 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 898184c9a7..d412c3f502 100644
--- a/packages/playwright/src/common/process.ts
+++ b/packages/playwright/src/common/process.ts
@@ -15,13 +15,15 @@
*/
import 'playwright-core/lib/bootstrap';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+
+import { ManualPromise } from '@isomorphic/manualPromise';
+import { setTimeOrigin } from '@isomorphic/time';
+import { startProfiling, stopProfiling } from '@serverUtils/profiler';
+
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;
@@ -70,8 +72,8 @@ export function startProcessRunner(create: (params: any) => ProcessRunner) {
process.on('message', async (message: any) => {
if (message.method === '__init__') {
const { processParams, runnerParams } = message.params as { processParams: ProcessInitParams, runnerParams: any };
- void serverUtils.startProfiling();
- iso.setTimeOrigin(processParams.timeOrigin);
+ void startProfiling();
+ setTimeOrigin(processParams.timeOrigin);
processRunner = create(runnerParams);
processName = processParams.processName;
return;
@@ -113,7 +115,7 @@ async function gracefullyCloseAndExit(forceExit: boolean) {
// Meanwhile, try to gracefully shutdown.
await processRunner?.gracefullyClose().catch(() => {});
if (processName)
- await serverUtils.stopProfiling(processName).catch(() => {});
+ await stopProfiling(processName).catch(() => {});
// eslint-disable-next-line no-restricted-properties
process.exit(0);
}
@@ -140,7 +142,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 iso.ManualPromise<any>();
+ const promise = new 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 49050c85c1..651fa4af20 100644
--- a/packages/playwright/src/common/suiteUtils.ts
+++ b/packages/playwright/src/common/suiteUtils.ts
@@ -16,7 +16,9 @@
import path from 'path';
-import { serverUtils } from 'playwright-core/lib/coreBundle';
+import { calculateSha1 } from '@serverUtils/crypto';
+import { toPosixPath } from '@serverUtils/fileUtils';
+
import { createFileMatcher, forceRegExp, parseLocationArg } from '../util';
import type { FullProjectInternal } from './config';
@@ -33,7 +35,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 = serverUtils.calculateSha1(serverUtils.toPosixPath(relativeFile)).slice(0, 20);
+ const fileId = calculateSha1(toPosixPath(relativeFile)).slice(0, 20);
// Clone suite.
const result = suite._deepClone();
@@ -44,8 +46,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}]${serverUtils.toPosixPath(file)}\x1e${titles.join('\x1e')}`;
- const testId = fileId + '-' + serverUtils.calculateSha1(testIdExpression).slice(0, 20);
+ const testIdExpression = `[project=${project.id}]${toPosixPath(file)}\x1e${titles.join('\x1e')}`;
+ const testId = fileId + '-' + calculateSha1(testIdExpression).slice(0, 20);
test.id = testId;
test._projectId = project.id;
@@ -80,8 +82,8 @@ export function applyRepeatEachIndex(project: FullProjectInternal, fileSuite: Su
fileSuite.forEachTest((test, suite) => {
if (repeatEachIndex) {
const [file, ...titles] = test.titlePath();
- const testIdExpression = `[project=${project.id}]${serverUtils.toPosixPath(file)}\x1e${titles.join('\x1e')} (repeat:${repeatEachIndex})`;
- const testId = suite._fileId + '-' + serverUtils.calculateSha1(testIdExpression).slice(0, 20);
+ const testIdExpression = `[project=${project.id}]${toPosixPath(file)}\x1e${titles.join('\x1e')} (repeat:${repeatEachIndex})`;
+ const testId = suite._fileId + '-' + 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 7b0e0f2b3b..773ee29a2f 100644
--- a/packages/playwright/src/common/testType.ts
+++ b/packages/playwright/src/common/testType.ts
@@ -15,7 +15,12 @@
*/
import { errors } from 'playwright-core';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+
+import { monotonicTime } from '@isomorphic/time';
+import { raceAgainstDeadline } from '@isomorphic/timeoutRunner';
+import { getPackageManagerExecCommand } from '@serverUtils/env';
+import { currentZone } from '@serverUtils/zones';
+
import { currentTestInfo, currentlyLoadingFileSuite, setCurrentlyLoadingFileSuite } from './globals';
import { Suite, TestCase } from './test';
import { expect } from '../matchers/expect';
@@ -274,10 +279,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 serverUtils.currentZone().with('stepZone', step).run(async () => {
+ return await currentZone().with('stepZone', step).run(async () => {
try {
- let result: Awaited<ReturnType<typeof iso.raceAgainstDeadline<T>>> | undefined = undefined;
- result = await iso.raceAgainstDeadline(async () => {
+ let result: Awaited<ReturnType<typeof raceAgainstDeadline<T>>> | undefined = undefined;
+ result = await raceAgainstDeadline(async () => {
try {
return await step.info._runStepBody(expectation === 'skip', body, step.location);
} catch (e) {
@@ -287,7 +292,7 @@ export class TestTypeImpl {
testInfo._failWithError(e);
throw e;
}
- }, options.timeout ? iso.monotonicTime() + options.timeout : 0);
+ }, options.timeout ? monotonicTime() + options.timeout : 0);
if (result.timedOut)
throw new errors.TimeoutError(`Step timeout of ${options.timeout}ms exceeded.`);
step.complete({});
@@ -311,7 +316,7 @@ export class TestTypeImpl {
function throwIfRunningInsideJest() {
if (process.env.JEST_WORKER_ID) {
- const packageManagerCommand = serverUtils.getPackageManagerExecCommand();
+ const packageManagerCommand = 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 25474f50a4..0dd1352365 100644
--- a/packages/playwright/src/common/validators.ts
+++ b/packages/playwright/src/common/validators.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import { iso } from 'playwright-core/lib/coreBundle';
+import { validate } from '@isomorphic/jsonSchema';
+
+import type { JsonSchema } from '@isomorphic/jsonSchema';
import type { TestDetailsAnnotation } from '../../types/test';
import type { Location } from '../../types/testReporter';
-type JsonSchema = iso.JsonSchema;
-
const testAnnotationSchema: JsonSchema = {
type: 'object',
properties: {
@@ -54,7 +54,7 @@ type ValidTestDetails = {
};
export function validateTestDetails(details: unknown, location: Location): ValidTestDetails {
- const errors = iso.validate(details, testDetailsSchema, 'details');
+ const errors = 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 3c86c4f56f..32baf69c7e 100644
--- a/packages/playwright/src/errorContext.ts
+++ b/packages/playwright/src/errorContext.ts
@@ -17,7 +17,9 @@
import fs from 'fs';
import path from 'path';
-import { iso } from 'playwright-core/lib/coreBundle';
+import { parseErrorStack } from '@isomorphic/stackTrace';
+import { stripAnsiEscapes } from '@isomorphic/stringUtils';
+
import { relativeFilePath } from './util';
import type { TestInfoError } from '../types/test';
@@ -57,7 +59,7 @@ export function buildErrorContext(options: {
lines.push(
'',
'```',
- iso.stripAnsiEscapes(error.message || ''),
+ stripAnsiEscapes(error.message || ''),
'```',
);
}
@@ -95,7 +97,7 @@ function buildCodeFrame(error: TestInfoError, testLocation: { file: string; line
if (!stack)
return undefined;
- const parsed = iso.parseErrorStack(stack, path.sep);
+ const parsed = parseErrorStack(stack, path.sep);
const errorLocation = parsed.location;
if (!errorLocation)
return undefined;
@@ -114,7 +116,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 = iso.stripAnsiEscapes(error.message || '').split('\n')[0] || undefined;
+ const message = 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 f47cc7bcf2..b448bd5773 100644
--- a/packages/playwright/src/index.ts
+++ b/packages/playwright/src/index.ts
@@ -18,7 +18,14 @@ import fs from 'fs';
import path from 'path';
import * as playwrightLibrary from 'playwright-core';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { asLocatorDescription } from '@isomorphic/locatorGenerators';
+import { getActionGroup, renderTitleForCall } from '@isomorphic/protocolFormatter';
+import { escapeHTML } from '@isomorphic/stringUtils';
+import { jsonStringifyForceASCII } from '@serverUtils/ascii';
+import { createGuid } from '@serverUtils/crypto';
+import { debugMode } from '@serverUtils/debug';
+import { setBoxedStackPrefixes } from '@serverUtils/nodePlatform';
+import { currentZone } from '@serverUtils/zones';
import { buildErrorContext } from './errorContext';
import { currentTestInfo } from './common/globals';
import { rootTestType } from './common/testType';
@@ -39,7 +46,7 @@ import type { BrowserContext, BrowserContextOptions, LaunchOptions, Page, Tracin
export { expect } from './matchers/expect';
export const _baseTest: TestType<{}, {}> = rootTestType.test;
-serverUtils.setBoxedStackPrefixes([path.dirname(require.resolve('../package.json'))]);
+setBoxedStackPrefixes([path.dirname(require.resolve('../package.json'))]);
if ((process as any)['__pw_initiator__']) {
const originalStackTraceLimit = Error.stackTraceLimit;
@@ -111,7 +118,7 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
exposeNetwork: connectOptions.exposeNetwork,
headers: {
// HTTP headers are ASCII only (not UTF-8).
- 'x-playwright-launch-options': serverUtils.jsonStringifyForceASCII(_browserOptions),
+ 'x-playwright-launch-options': jsonStringifyForceASCII(_browserOptions),
...connectOptions.headers,
},
});
@@ -238,7 +245,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 (serverUtils.debugMode() === 'inspector')
+ if (debugMode() === 'inspector')
(testInfo as TestInfoImpl)._setIgnoreTimeouts(true);
playwright._defaultContextTimeout = actionTimeout || 0;
@@ -265,7 +272,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 = serverUtils.currentZone().data<TestStepInternal>('stepZone');
+ const zone = 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 +292,7 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
title: renderTitle(channel.type, channel.method, channel.params, data.title),
apiName: data.apiName,
params: channel.params,
- group: iso.getActionGroup({ type: channel.type, method: channel.method }),
+ group: getActionGroup({ type: channel.type, method: channel.method }),
}, tracingGroupSteps[tracingGroupSteps.length - 1]);
data.userData = step;
data.stepId = step.stepId;
@@ -642,7 +649,7 @@ class SnapshotRecorder {
return;
(page as any)[this.testInfo._uniqueSymbol] = true;
try {
- const path = temporary ? this._createTemporaryArtifact(serverUtils.createGuid() + this._extension) : this._createAttachmentPath();
+ const path = temporary ? this._createTemporaryArtifact(createGuid() + this._extension) : this._createAttachmentPath();
await this._doSnapshot(page, path);
if (temporary)
this._temporary.push(path);
@@ -850,15 +857,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>${iso.escapeHTML(p)}</div>`).join('')}
+ ${parts.map(p => `<div>${escapeHTML(p)}</div>`).join('')}
</div>`;
}
function renderTitle(type: string, method: string, params: Record<string, string> | undefined, title?: string) {
- const prefix = iso.renderTitleForCall({ title, type, method, params });
+ const prefix = renderTitleForCall({ title, type, method, params });
let selector;
if (params?.['selector'] && typeof params.selector === 'string')
- selector = iso.asLocatorDescription('javascript', params.selector);
+ selector = asLocatorDescription('javascript', params.selector);
return prefix + (selector ? ` ${selector}` : '');
}
diff --git a/packages/playwright/src/matchers/DEPS.list b/packages/playwright/src/matchers/DEPS.list
index b205c62130..678945834e 100644
--- a/packages/playwright/src/matchers/DEPS.list
+++ b/packages/playwright/src/matchers/DEPS.list
@@ -1,6 +1,7 @@
[*]
+@isomorphic/**
+@serverUtils/**
../common/
../mcp/test/browserBackend.ts
../util.ts
-../utilsBundle.ts
../worker/testInfo.ts
diff --git a/packages/playwright/src/matchers/expect.ts b/packages/playwright/src/matchers/expect.ts
index 48e92f4500..df7b0dd430 100644
--- a/packages/playwright/src/matchers/expect.ts
+++ b/packages/playwright/src/matchers/expect.ts
@@ -14,7 +14,11 @@
* limitations under the License.
*/
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { captureRawStack } from '@isomorphic/stackTrace';
+import { escapeWithQuotes, isString } from '@isomorphic/stringUtils';
+import { pollAgainstDeadline } from '@isomorphic/timeoutRunner';
+import { createGuid } from '@serverUtils/crypto';
+import { currentZone } from '@serverUtils/zones';
import { ExpectError, isJestError } from './matcherHint';
import {
@@ -78,7 +82,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 = iso.isString(messageOrOptions) ? messageOrOptions : messageOrOptions?.message || info.message;
+ const message = isString(messageOrOptions) ? messageOrOptions : messageOrOptions?.message || info.message;
const newInfo = { ...info, message };
if (newInfo.poll) {
if (typeof actual !== 'function')
@@ -94,7 +98,7 @@ function createExpect(info: ExpectMetaInfo, prefix: string[], userMatchers: Reco
if (property === 'extend') {
return (matchers: any) => {
- const qualifier = [...prefix, serverUtils.createGuid()];
+ const qualifier = [...prefix, createGuid()];
const wrappedMatchers: any = {};
for (const [name, matcher] of Object.entries(matchers)) {
@@ -119,7 +123,7 @@ function createExpect(info: ExpectMetaInfo, prefix: string[], userMatchers: Reco
if (property === 'poll') {
return (actual: unknown, messageOrOptions?: ExpectMessage & { timeout?: number, intervals?: number[] }) => {
- const poll = iso.isString(messageOrOptions) ? {} : messageOrOptions || {};
+ const poll = isString(messageOrOptions) ? {} : messageOrOptions || {};
return configure({ _poll: poll })(actual, messageOrOptions) as any;
};
}
@@ -299,13 +303,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 ${iso.escapeWithQuotes(defaultTitle, '"')}`;
+ const shortTitle = customMessage || `Expect ${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(iso.captureRawStack());
+ const stackFrames = filteredStackTrace(captureRawStack());
// toPass and poll matchers can contain other steps, expects and API calls,
// so they behave like a retriable step.
@@ -346,7 +350,7 @@ class ExpectMetaInfoProxyHandler implements ProxyHandler<any> {
try {
setMatcherCallContext({ expectInfo: this._info, testInfo, step: step.info });
const callback = () => matcher.call(target, ...args);
- const result = serverUtils.currentZone().with('stepZone', step).run(callback);
+ const result = currentZone().with('stepZone', step).run(callback);
if (result instanceof Promise)
return result.then(finalizer).catch(reportStepError);
finalizer();
@@ -364,7 +368,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 iso.pollAgainstDeadline<Error|undefined>(async () => {
+ const result = await 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 63016189b8..9bb3ccae6d 100644
--- a/packages/playwright/src/matchers/matcherHint.ts
+++ b/packages/playwright/src/matchers/matcherHint.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { iso } from 'playwright-core/lib/coreBundle';
+import { stringifyStackFrames } from '@isomorphic/stackTrace';
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' + iso.stringifyStackFrames(stackFrames).join('\n');
+ this.stack = this.name + ': ' + this.message + '\n' + stringifyStackFrames(stackFrames).join('\n');
}
}
diff --git a/packages/playwright/src/matchers/matchers.ts b/packages/playwright/src/matchers/matchers.ts
index 49ee539865..0c96eaff62 100644
--- a/packages/playwright/src/matchers/matchers.ts
+++ b/packages/playwright/src/matchers/matchers.ts
@@ -14,9 +14,16 @@
* limitations under the License.
*/
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { colors } from 'playwright-core/lib/utilsBundle';
+import { asLocatorDescription } from '@isomorphic/locatorGenerators';
+import { isTextualMimeType } from '@isomorphic/mimeType';
+import { isRegExp } from '@isomorphic/rtti';
+import { isString } from '@isomorphic/stringUtils';
+import { pollAgainstDeadline } from '@isomorphic/timeoutRunner';
+import { constructURLBasedOnBaseURL, isURLPattern } from '@isomorphic/urlMatch';
+import { formatMatcherMessage, serializeExpectedTextValues } from '@serverUtils/expectUtils';
+
import { expectTypes } from '../util';
import { toBeTruthy } from './toBeTruthy';
import { toEqual } from './toEqual';
@@ -33,9 +40,8 @@ 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';
-type InternalMatcherUtils = serverUtils.InternalMatcherUtils;
-type URLPattern = iso.URLPattern;
-const { serializeExpectedTextValues } = serverUtils;
+import type { InternalMatcherUtils } from '@serverUtils/expectUtils';
+import type { URLPattern } from '@isomorphic/urlMatch';
export type ExpectMatcherStateInternal = Omit<ExpectMatcherState, 'utils'> & {
_stepInfo?: TestStepInfoImpl;
@@ -246,7 +252,7 @@ export function toHaveAttribute(
) {
if (!options) {
// Update params for the case toHaveAttribute(name, options);
- if (typeof expected === 'object' && !iso.isRegExp(expected)) {
+ if (typeof expected === 'object' && !isRegExp(expected)) {
options = expected;
expected = undefined;
}
@@ -288,14 +294,14 @@ export function toContainClass(
options?: { timeout?: number },
) {
if (Array.isArray(expected)) {
- if (expected.some(e => iso.isRegExp(e)))
+ if (expected.some(e => 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 (iso.isRegExp(expected))
+ if (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]);
@@ -359,7 +365,7 @@ export function toHaveRole(
expected: string,
options?: { timeout?: number, ignoreCase?: boolean },
) {
- if (!iso.isString(expected))
+ if (!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]);
@@ -428,7 +434,7 @@ export function toHaveURL(
expected: string | RegExp | URLPattern | ((url: URL) => boolean),
options?: { ignoreCase?: boolean; timeout?: number },
) {
- if (iso.isURLPattern(expected))
+ if (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
@@ -436,7 +442,7 @@ export function toHaveURL(
return toHaveURLWithPredicate.call(this, page, expected, options);
const baseURL = (page.context() as any)._options.baseURL;
- expected = typeof expected === 'string' ? iso.constructURLBasedOnBaseURL(baseURL, expected) : expected;
+ expected = typeof expected === 'string' ? 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 });
@@ -451,13 +457,13 @@ export async function toBeOK(
expectTypes(response, ['APIResponse'], matcherName);
const contentType = response.headers()['content-type'];
- const isTextEncoding = contentType && iso.isTextualMimeType(contentType);
+ const isTextEncoding = contentType && isTextualMimeType(contentType);
const [log, text] = (this.isNot === response.ok()) ? await Promise.all([
response._fetchLog(),
isTextEncoding ? response.text() : null
]) : [];
- const message = () => serverUtils.formatMatcherMessage(this.utils, {
+ const message = () => formatMatcherMessage(this.utils, {
isNot: this.isNot,
promise: this.promise,
matcherName,
@@ -483,7 +489,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 iso.pollAgainstDeadline<Error|undefined>(async () => {
+ const result = await pollAgainstDeadline<Error|undefined>(async () => {
if (testInfo && currentTestInfo() !== testInfo)
return { continuePolling: false, result: undefined };
try {
@@ -513,7 +519,7 @@ export function computeMatcherTitleSuffix(matcherName: string, receiver: any, ar
}
if (receiver && typeof receiver === 'object' && (receiver as any)._apiName === 'Locator') {
try {
- return { long: ' ' + iso.asLocatorDescription('javascript', (receiver as LocatorEx)._selector) };
+ return { long: ' ' + asLocatorDescription('javascript', (receiver as LocatorEx)._selector) };
} catch {
}
}
diff --git a/packages/playwright/src/matchers/toBeTruthy.ts b/packages/playwright/src/matchers/toBeTruthy.ts
index e5bfb47e30..6fcaa8a3a2 100644
--- a/packages/playwright/src/matchers/toBeTruthy.ts
+++ b/packages/playwright/src/matchers/toBeTruthy.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { serverUtils } from 'playwright-core/lib/coreBundle';
+import { formatMatcherMessage } from '@serverUtils/expectUtils';
import { expectTypes } from '../util';
@@ -57,7 +57,7 @@ export async function toBeTruthy(
printedReceived = errorMessage ? '' : `Received: ${received}`;
}
const message = () => {
- return serverUtils.formatMatcherMessage(this.utils, {
+ return 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 40aac4e6f9..63e3fffb57 100644
--- a/packages/playwright/src/matchers/toEqual.ts
+++ b/packages/playwright/src/matchers/toEqual.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { isRegExp } from '@isomorphic/rtti';
+import { formatMatcherMessage } from '@serverUtils/expectUtils';
import { expectTypes } from '../util';
@@ -61,7 +62,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 (iso.isRegExp(exp))
+ if (isRegExp(exp))
return exp.test(rec) ? rec : exp;
return exp;
@@ -83,7 +84,7 @@ export async function toEqual<T>(
);
}
const message = () => {
- return serverUtils.formatMatcherMessage(this.utils, {
+ return 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 8d6667ad82..8f9e266b20 100644
--- a/packages/playwright/src/matchers/toHaveURL.ts
+++ b/packages/playwright/src/matchers/toHaveURL.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { urlMatches } from '@isomorphic/urlMatch';
+import { formatMatcherMessage, printReceivedStringContainExpectedResult } from '@serverUtils/expectUtils';
import type { MatcherResult } from './matcherHint';
import type { Page } from 'playwright-core';
@@ -39,7 +40,7 @@ export async function toHaveURLWithPredicate(
if (options?.ignoreCase) {
return (
!this.isNot ===
- iso.urlMatches(
+ urlMatches(
baseURL?.toLocaleLowerCase(),
lastCheckedURLString.toLocaleLowerCase(),
expected,
@@ -48,7 +49,7 @@ export async function toHaveURLWithPredicate(
}
return (
- !this.isNot === iso.urlMatches(baseURL, lastCheckedURLString, expected)
+ !this.isNot === urlMatches(baseURL, lastCheckedURLString, expected)
);
},
{ timeout },
@@ -100,7 +101,7 @@ function toHaveURLMessage(
} else {
if (pass) {
printedExpected = `Expected pattern: not ${state.utils.printExpected(expected)}`;
- const formattedReceived = serverUtils.printReceivedStringContainExpectedResult(state.utils, receivedString, null);
+ const formattedReceived = printReceivedStringContainExpectedResult(state.utils, receivedString, null);
printedReceived = `Received string: ${formattedReceived}`;
} else {
const labelExpected = `Expected ${typeof expected === 'string' ? 'string' : 'pattern'}`;
@@ -108,7 +109,7 @@ function toHaveURLMessage(
}
}
- return serverUtils.formatMatcherMessage(state.utils, {
+ return 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 9d4e13432d..1c3db807c4 100644
--- a/packages/playwright/src/matchers/toMatchAriaSnapshot.ts
+++ b/packages/playwright/src/matchers/toMatchAriaSnapshot.ts
@@ -18,7 +18,8 @@
import fs from 'fs';
import path from 'path';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { escapeTemplateString, isString } from '@isomorphic/stringUtils';
+import { formatMatcherMessage, printReceivedStringContainExpectedSubstring } from '@serverUtils/expectUtils';
import { expectTypes, fileExistsAsync } from '../util';
import { currentTestInfo } from '../common/globals';
@@ -57,7 +58,7 @@ export async function toMatchAriaSnapshot(
let expected: string;
let timeout: number;
let expectedPath: string | undefined;
- if (iso.isString(expectedParam)) {
+ if (isString(expectedParam)) {
expected = expectedParam;
timeout = options.timeout ?? this.timeout;
} else {
@@ -101,13 +102,13 @@ export async function toMatchAriaSnapshot(
if (errorMessage) {
printedExpected = `Expected: ${this.isNot ? 'not ' : ''}${this.utils.printExpected(expected)}`;
} else if (pass) {
- const receivedString = serverUtils.printReceivedStringContainExpectedSubstring(this.utils, typedReceived.raw, typedReceived.raw.indexOf(expected), expected.length);
+ const receivedString = 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 serverUtils.formatMatcherMessage(this.utils, {
+ return formatMatcherMessage(this.utils, {
isNot: this.isNot,
promise: this.promise,
matcherName,
@@ -145,7 +146,7 @@ export async function toMatchAriaSnapshot(
}
return { pass: true, message: () => '', name: 'toMatchAriaSnapshot' };
} else {
- const suggestedRebaseline = `\`\n${iso.escapeTemplateString(indent(typedReceived.regex, '{indent} '))}\n{indent}\``;
+ const suggestedRebaseline = `\`\n${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 5457e96840..ed06702da4 100644
--- a/packages/playwright/src/matchers/toMatchSnapshot.ts
+++ b/packages/playwright/src/matchers/toMatchSnapshot.ts
@@ -17,9 +17,12 @@
import fs from 'fs';
import path from 'path';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { colors } from 'playwright-core/lib/utilsBundle';
-import { mime } from 'playwright-core/lib/utilsBundle';
+
+import { getMimeTypeForPath } from '@isomorphic/mimeType';
+import { isString } from '@isomorphic/stringUtils';
+import { compareBuffersOrStrings, getComparator } from '@serverUtils/comparators';
+import { callLogText, formatMatcherMessage } from '@serverUtils/expectUtils';
import { addSuffixToFilePath, expectTypes } from '../util';
import { currentTestInfo } from '../common/globals';
@@ -30,8 +33,7 @@ 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';
-type Comparator = serverUtils.Comparator;
-type ImageComparatorOptions = serverUtils.ImageComparatorOptions;
+import type { Comparator, ImageComparatorOptions } from '@serverUtils/comparators';
type NameOrSegments = string | string[];
@@ -139,8 +141,8 @@ class SnapshotHelper {
this.locator = locator;
this.updateSnapshots = testInfo.config.updateSnapshots;
- this.mimeType = mime.getType(path.basename(this.expectedPath)) ?? 'application/octet-stream';
- this.comparator = serverUtils.getComparator(this.mimeType);
+ this.mimeType = getMimeTypeForPath(path.basename(this.expectedPath)) ?? 'application/octet-stream';
+ this.comparator = getComparator(this.mimeType);
this.testInfo = testInfo;
this.state = state;
@@ -237,7 +239,7 @@ class SnapshotHelper {
}
if (log?.length)
- output.push(serverUtils.callLogText(this.state.utils, log));
+ output.push(callLogText(this.state.utils, log));
else
output.push('');
@@ -282,7 +284,7 @@ export function toMatchSnapshot(
const expected = fs.readFileSync(helper.expectedPath);
if (helper.updateSnapshots === 'all') {
- if (!serverUtils.compareBuffersOrStrings(received, expected))
+ if (!compareBuffersOrStrings(received, expected))
return helper.handleMatching();
writeFileSync(helper.expectedPath, received);
/* eslint-disable no-console */
@@ -304,7 +306,7 @@ export function toMatchSnapshot(
if (!result)
return helper.handleMatching();
- const header = serverUtils.formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toMatchSnapshot', receiver: iso.isString(received) ? 'string' : 'Buffer', expectation: 'expected' });
+ const header = formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toMatchSnapshot', receiver: isString(received) ? 'string' : 'Buffer', expectation: 'expected' });
return helper.handleDifferent(received, expected, undefined, result.diff, header, result.errorMessage, undefined, this._stepInfo);
}
@@ -389,7 +391,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 = serverUtils.formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });
+ const header = 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);
}
@@ -414,7 +416,7 @@ export async function toHaveScreenshot(
if (!errorMessage) {
// Screenshot is matching, but is not necessarily the same as the expected.
- if (helper.updateSnapshots === 'all' && actual && serverUtils.compareBuffersOrStrings(actual, expected)) {
+ if (helper.updateSnapshots === 'all' && actual && compareBuffersOrStrings(actual, expected)) {
console.log(helper.expectedPath + ' is re-generated, writing actual.');
return writeFiles(actual);
}
@@ -424,12 +426,12 @@ export async function toHaveScreenshot(
if (helper.updateSnapshots === 'changed' || helper.updateSnapshots === 'all') {
if (actual)
return writeFiles(actual);
- let header = serverUtils.formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });
+ let header = 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 = serverUtils.formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, matcherName: 'toHaveScreenshot', locator: locator?.toString(), expectation: 'expected', timeout, timedOut });
+ const header = 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 c1b1634174..6ed27914f4 100644
--- a/packages/playwright/src/matchers/toMatchText.ts
+++ b/packages/playwright/src/matchers/toMatchText.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { serverUtils } from 'playwright-core/lib/coreBundle';
+import { formatMatcherMessage, printReceivedStringContainExpectedResult, printReceivedStringContainExpectedSubstring } from '@serverUtils/expectUtils';
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(serverUtils.formatMatcherMessage(this.utils, { promise: this.promise, isNot: this.isNot, locator: locator?.toString(), matcherName, expectation: 'expected', errorMessage }));
+ throw new Error(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 = serverUtils.printReceivedStringContainExpectedSubstring(this.utils, receivedString, receivedString.indexOf(expected), expected.length);
+ const formattedReceived = 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 = serverUtils.printReceivedStringContainExpectedResult(this.utils, receivedString, typeof expected.exec === 'function' ? expected.exec(receivedString) : null);
+ const formattedReceived = 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 serverUtils.formatMatcherMessage(this.utils, {
+ return formatMatcherMessage(this.utils, {
promise: this.promise,
isNot: this.isNot,
matcherName,
diff --git a/packages/playwright/src/mcp/test/DEPS.list b/packages/playwright/src/mcp/test/DEPS.list
index 9a85b42ac7..7cbd5ac0cd 100644
--- a/packages/playwright/src/mcp/test/DEPS.list
+++ b/packages/playwright/src/mcp/test/DEPS.list
@@ -1,4 +1,6 @@
[*]
+@isomorphic/**
+@serverUtils/**
../../reporters
../../runner
../../transform
diff --git a/packages/playwright/src/mcp/test/browserBackend.ts b/packages/playwright/src/mcp/test/browserBackend.ts
index fa2ba1a15d..a7d25045cd 100644
--- a/packages/playwright/src/mcp/test/browserBackend.ts
+++ b/packages/playwright/src/mcp/test/browserBackend.ts
@@ -15,7 +15,8 @@
*/
import crypto from 'crypto';
-import { iso } from 'playwright-core/lib/coreBundle';
+
+import { stripAnsiEscapes } from '@isomorphic/stringUtils';
import type { tools } from 'playwright-core/lib/coreBundle';
import type * as playwright from '../../../index';
@@ -74,7 +75,7 @@ async function generatePausedMessage(tools: typeof import('playwright-core/lib/c
if (testInfo.errors.length) {
lines.push(`### Paused on error:`);
for (const error of testInfo.errors)
- lines.push(iso.stripAnsiEscapes(error.message || ''));
+ lines.push(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 09ea5370ac..8b4ca5092c 100644
--- a/packages/playwright/src/mcp/test/seed.ts
+++ b/packages/playwright/src/mcp/test/seed.ts
@@ -17,7 +17,7 @@
import fs from 'fs';
import path from 'path';
-import { serverUtils } from 'playwright-core/lib/coreBundle';
+import { mkdirIfNeeded } from '@serverUtils/fileUtils';
import { collectFilesForProject, findTopLevelProjects } from '../../runner/projectUtils';
@@ -47,7 +47,7 @@ export async function ensureSeedFile(project: FullProjectInternal) {
if (seedFile)
return seedFile;
const seedFilePath = defaultSeedFile(project);
- await serverUtils.mkdirIfNeeded(seedFilePath);
+ await mkdirIfNeeded(seedFilePath);
await fs.promises.writeFile(seedFilePath, seedFileContent);
return seedFilePath;
}
diff --git a/packages/playwright/src/mcp/test/testContext.ts b/packages/playwright/src/mcp/test/testContext.ts
index dcbeb2ffde..22f35572d7 100644
--- a/packages/playwright/src/mcp/test/testContext.ts
+++ b/packages/playwright/src/mcp/test/testContext.ts
@@ -18,10 +18,14 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { tools } from 'playwright-core/lib/coreBundle';
import { debug } from 'playwright-core/lib/utilsBundle';
+import { noColors } from '@isomorphic/colors';
+import { ManualPromise } from '@isomorphic/manualPromise';
+import { escapeRegExp } from '@isomorphic/stringUtils';
+import { toPosixPath } from '@serverUtils/fileUtils';
+
import { terminalScreen } from '../../reporters/base';
import ListReporter from '../../reporters/list';
import { StringWriteStream } from './streams';
@@ -62,7 +66,7 @@ export class GeneratorJournal {
const result: string[] = [];
result.push(`# Plan`);
result.push(this._plan);
- result.push(`# Seed file: ${serverUtils.toPosixPath(path.relative(this._rootPath, this._seed.file))}`);
+ result.push(`# Seed file: ${toPosixPath(path.relative(this._rootPath, this._seed.file))}`);
result.push('```ts');
result.push(this._seed.content);
result.push('```');
@@ -128,7 +132,7 @@ export class TestContext {
const testRunner = new TestRunner(this._configLocation, {});
await testRunner.initialize({});
- const testPaused = new iso.ManualPromise<void>();
+ const testPaused = new ManualPromise<void>();
const testRunnerAndScreen: TestRunnerAndScreen = {
...createScreen(),
testRunner,
@@ -180,7 +184,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: ['/' + iso.escapeRegExp(seedFile) + '/'],
+ locations: ['/' + escapeRegExp(seedFile) + '/'],
projects: [projectName],
timeout: 0,
workers: 1,
@@ -276,7 +280,7 @@ export function createScreen() {
const screen = {
...terminalScreen,
isTTY: false,
- colors: iso.noColors,
+ colors: noColors,
stdout: stdout as unknown as NodeJS.WriteStream,
stderr: stderr as unknown as NodeJS.WriteStream,
};
diff --git a/packages/playwright/src/plugins/DEPS.list b/packages/playwright/src/plugins/DEPS.list
index 5b441c9e4e..ba0907d5c4 100644
--- a/packages/playwright/src/plugins/DEPS.list
+++ b/packages/playwright/src/plugins/DEPS.list
@@ -1,4 +1,5 @@
[*]
+@isomorphic/**
+@serverUtils/**
../common/
../util.ts
-../utilsBundle.ts
diff --git a/packages/playwright/src/plugins/gitCommitInfoPlugin.ts b/packages/playwright/src/plugins/gitCommitInfoPlugin.ts
index 82ddc77539..7713911fc6 100644
--- a/packages/playwright/src/plugins/gitCommitInfoPlugin.ts
+++ b/packages/playwright/src/plugins/gitCommitInfoPlugin.ts
@@ -16,7 +16,8 @@
import * as fs from 'fs';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { monotonicTime } from '@isomorphic/time';
+import { spawnAsync } from '@serverUtils/spawnAsync';
import type { TestRunnerPlugin } from './';
import type { FullConfig } from '../../types/testReporter';
@@ -179,13 +180,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 = iso.monotonicTime();
- const result = await serverUtils.spawnAsync(
+ const start = monotonicTime();
+ const result = await spawnAsync(
command,
[],
{ stdio: 'pipe', cwd, timeout: GIT_OPERATIONS_TIMEOUT_MS, shell: true }
);
- if (iso.monotonicTime() - start > GIT_OPERATIONS_TIMEOUT_MS) {
+ if (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 633fec4b29..4ec11a531b 100644
--- a/packages/playwright/src/plugins/webServerPlugin.ts
+++ b/packages/playwright/src/plugins/webServerPlugin.ts
@@ -16,9 +16,13 @@
import net from 'net';
import path from 'path';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
-import { colors } from 'playwright-core/lib/utilsBundle';
-import { debug } from 'playwright-core/lib/utilsBundle';
+import { colors, debug } from 'playwright-core/lib/utilsBundle';
+
+import { ManualPromise } from '@isomorphic/manualPromise';
+import { monotonicTime } from '@isomorphic/time';
+import { raceAgainstDeadline } from '@isomorphic/timeoutRunner';
+import { isURLAvailable } from '@serverUtils/network';
+import { launchProcess } from '@serverUtils/processLauncher';
import type { TestRunnerPlugin } from '.';
import type { FullConfig } from '../../types/testReporter';
@@ -55,7 +59,7 @@ export class WebServerPlugin implements TestRunnerPlugin {
private _options: WebServerPluginOptions;
private _checkPortOnly: boolean;
private _reporter?: ReporterV2;
- private _waitForStdioPromise: iso.ManualPromise | undefined;
+ private _waitForStdioPromise: ManualPromise | undefined;
name = 'playwright:webserver';
@@ -101,7 +105,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 serverUtils.launchProcess({
+ const { launchedProcess, gracefullyClose } = await launchProcess({
command: this._options.command,
env: {
...DEFAULT_ENVIRONMENT_VARIABLES,
@@ -142,7 +146,7 @@ export class WebServerPlugin implements TestRunnerPlugin {
debugWebServer(`Process started`);
if (this._options.wait?.stdout || this._options.wait?.stderr)
- this._waitForStdioPromise = new iso.ManualPromise();
+ this._waitForStdioPromise = new ManualPromise();
const stdioWaitCollectors = {
stdout: this._options.wait?.stdout ? '' : undefined,
stderr: this._options.wait?.stderr ? '' : undefined,
@@ -189,13 +193,13 @@ export class WebServerPlugin implements TestRunnerPlugin {
debugWebServer(`Waiting for availability...`);
const launchTimeout = this._options.timeout || 60 * 1000;
const cancellationToken = { canceled: false };
- const deadline = iso.monotonicTime() + launchTimeout;
+ const deadline = monotonicTime() + launchTimeout;
const racingPromises = [this._processExitedPromise];
if (this._isAvailableCallback)
- racingPromises.push(iso.raceAgainstDeadline(() => waitFor(this._isAvailableCallback!, cancellationToken), deadline));
+ racingPromises.push(raceAgainstDeadline(() => waitFor(this._isAvailableCallback!, cancellationToken), deadline));
if (this._waitForStdioPromise)
- racingPromises.push(iso.raceAgainstDeadline(() => this._waitForStdioPromise!, deadline));
+ racingPromises.push(raceAgainstDeadline(() => this._waitForStdioPromise!, deadline));
const { timedOut } = await Promise.race(racingPromises);
cancellationToken.canceled = true;
@@ -235,7 +239,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 () => serverUtils.isURLAvailable(urlObject, ignoreHTTPSErrors, debugWebServer, onStdErr);
+ return () => 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 78da782bfc..9be1485906 100644
--- a/packages/playwright/src/program.ts
+++ b/packages/playwright/src/program.ts
@@ -17,8 +17,12 @@
/* eslint-disable no-console */
import 'playwright-core/lib/bootstrap';
-import { libCli, serverUtils } from 'playwright-core/lib/coreBundle';
+
+import { libCli } from 'playwright-core/lib/coreBundle';
import { program } from 'playwright-core/lib/utilsBundle';
+
+import { gracefullyProcessExitDoNotHang } from '@serverUtils/processLauncher';
+
import { builtInReporters, defaultReporter, defaultTimeout } from './common/config';
export { program };
@@ -52,7 +56,7 @@ function addTestCommand(program: Command) {
await runTests(args, opts);
} catch (e) {
console.error(e);
- serverUtils.gracefullyProcessExitDoNotHang(1);
+ gracefullyProcessExitDoNotHang(1);
}
});
command.addHelpText('afterAll', `
@@ -125,7 +129,7 @@ function addMergeReportsCommand(program: Command) {
await mergeReports(dir, options);
} catch (e) {
console.error(e);
- serverUtils.gracefullyProcessExitDoNotHang(1);
+ gracefullyProcessExitDoNotHang(1);
}
});
command.option('-c, --config <file>', `Configuration file. Can be used to specify additional configuration for the output report.`);
diff --git a/packages/playwright/src/reportActions.ts b/packages/playwright/src/reportActions.ts
index ef5962d016..0df0a1ad86 100644
--- a/packages/playwright/src/reportActions.ts
+++ b/packages/playwright/src/reportActions.ts
@@ -17,7 +17,7 @@
import fs from 'fs';
import path from 'path';
-import { serverUtils } from 'playwright-core/lib/coreBundle';
+import { gracefullyProcessExitDoNotHang } from '@serverUtils/processLauncher';
import { builtInReporters, defaultReporter } from './common/config';
import { loadConfigFromFile, loadEmptyConfigForMergeReports } from './common/configLoader';
import { showHTMLReport } from './reporters/html';
@@ -46,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);
- serverUtils.gracefullyProcessExitDoNotHang(0);
+ gracefullyProcessExitDoNotHang(0);
}
function resolveReporterOption(reporter?: string): ReporterDescription[] | undefined {
diff --git a/packages/playwright/src/reporters/DEPS.list b/packages/playwright/src/reporters/DEPS.list
index 86e4a61ddb..475a0c25ac 100644
--- a/packages/playwright/src/reporters/DEPS.list
+++ b/packages/playwright/src/reporters/DEPS.list
@@ -1,4 +1,6 @@
[*]
+@isomorphic/**
+@serverUtils/**
../common/**
../isomorphic/**
../util.ts
diff --git a/packages/playwright/src/reporters/base.ts b/packages/playwright/src/reporters/base.ts
index 75c11e65b8..6a6f58124c 100644
--- a/packages/playwright/src/reporters/base.ts
+++ b/packages/playwright/src/reporters/base.ts
@@ -16,9 +16,13 @@
import path from 'path';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { colors as realColors } from 'playwright-core/lib/utilsBundle';
+import { noColors } from '@isomorphic/colors';
+import { msToString } from '@isomorphic/formatUtils';
+import { parseErrorStack } from '@isomorphic/stackTrace';
+import { getPackageManagerExecCommand } from '@serverUtils/env';
+
import { ansiRegex, resolveReporterOutputPath, stripAnsiEscapes } from '../util';
import { getEastAsianWidth } from '../utilsBundle';
@@ -110,7 +114,7 @@ export const terminalScreen: TerminalScreen = (() => {
else if (process.env.DEBUG_COLORS || process.env.FORCE_COLOR)
useColors = true;
- const colors = useColors ? realColors : iso.noColors;
+ const colors = useColors ? realColors : noColors;
return {
resolveFiles: 'cwd',
isTTY,
@@ -259,7 +263,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(` (${iso.msToString(this.result.duration)})`));
+ tokens.push(this.screen.colors.green(` ${expected} passed`) + this.screen.colors.dim(` (${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 +331,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(` (${iso.msToString(duration)})`));
+ this.writeLine(this.screen.colors.yellow(' Slow test file: ') + file + this.screen.colors.yellow(` (${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 +440,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 = serverUtils.getPackageManagerExecCommand();
+ const packageManagerCommand = getPackageManagerExecCommand();
resultLines.push(screen.colors.dim(` Usage:`));
resultLines.push('');
resultLines.push(screen.colors.dim(` ${packageManagerCommand} playwright show-trace ${quotePathIfNeeded(relativePath)}`));
@@ -612,7 +616,7 @@ export function prepareErrorStack(stack: string): {
stackLines: string[];
location?: Location;
} {
- return iso.parseErrorStack(stack, path.sep, !!process.env.PWDEBUGIMPL);
+ return 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 1bfc25189b..a9a7f102e4 100644
--- a/packages/playwright/src/reporters/blob.ts
+++ b/packages/playwright/src/reporters/blob.ts
@@ -18,10 +18,13 @@ import fs from 'fs';
import path from 'path';
import { Readable } from 'stream';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
-
import { mime } from 'playwright-core/lib/utilsBundle';
+import { ManualPromise } from '@isomorphic/manualPromise';
+import { calculateSha1, createGuid } from '@serverUtils/crypto';
+import { removeFolders, sanitizeForFilePath } from '@serverUtils/fileUtils';
+import { getUserAgent } from '@serverUtils/userAgent';
+
import { resolveOutputFile, CommonReporterOptions } from './base';
import { TeleReporterEmitter } from './teleEmitter';
@@ -44,13 +47,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 = serverUtils.createGuid();
+ this._salt = createGuid();
}
override onConfigure(config: FullConfig) {
const metadata: BlobReportMetadata = {
version: currentBlobReportVersion,
- userAgent: serverUtils.getUserAgent(),
+ userAgent: getUserAgent(),
// TODO: remove after some time, recommend config.tag instead.
name: process.env.PWTEST_BOT_NAME,
shard: config.shard ?? undefined,
@@ -77,7 +80,7 @@ export class BlobReporter extends TeleReporterEmitter {
const { yazl } = await import('playwright-core/lib/zipBundle');
const zipFile = new yazl.ZipFile();
- const zipFinishPromise = new iso.ManualPromise<undefined>();
+ const zipFinishPromise = new ManualPromise<undefined>();
const finishPromise = zipFinishPromise.catch(e => {
throw new Error(`Failed to write report ${zipFileName}: ` + e.message);
});
@@ -110,7 +113,7 @@ export class BlobReporter extends TeleReporterEmitter {
}
})!;
if (!process.env.PWTEST_BLOB_DO_NOT_REMOVE)
- await serverUtils.removeFolders([outputDir!]);
+ await removeFolders([outputDir!]);
await fs.promises.mkdir(path.dirname(outputFile), { recursive: true });
return outputFile;
}
@@ -118,7 +121,7 @@ export class BlobReporter extends TeleReporterEmitter {
private _defaultReportName(config: FullConfig) {
let reportName = 'report';
if (this._options._commandHash)
- reportName += '-' + serverUtils.sanitizeForFilePath(this._options._commandHash);
+ reportName += '-' + sanitizeForFilePath(this._options._commandHash);
if (config.shard) {
const paddedNumber = `${config.shard.current}`.padStart(`${config.shard.total}`.length, '0');
reportName = `${reportName}-${paddedNumber}`;
@@ -131,7 +134,7 @@ export class BlobReporter extends TeleReporterEmitter {
if (!attachment.path)
return attachment;
// Add run guid to avoid clashes between shards.
- const sha1 = serverUtils.calculateSha1(attachment.path + this._salt);
+ const sha1 = 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 6be25b9087..4ec6de8f04 100644
--- a/packages/playwright/src/reporters/github.ts
+++ b/packages/playwright/src/reporters/github.ts
@@ -16,7 +16,8 @@
import path from 'path';
-import { iso } from 'playwright-core/lib/coreBundle';
+import { noColors } from '@isomorphic/colors';
+import { msToString } from '@isomorphic/formatUtils';
import { TerminalReporter, formatResultFailure, formatRetry } from './base';
import { stripAnsiEscapes } from '../util';
@@ -66,7 +67,7 @@ export class GitHubReporter extends TerminalReporter {
constructor(options: { omitFailures?: boolean } = {}) {
super(options);
- this.screen = { ...this.screen, colors: iso.noColors };
+ this.screen = { ...this.screen, colors: noColors };
}
printsToStdio() {
@@ -95,7 +96,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 ${iso.msToString(duration)}`, {
+ this.githubLogger.warning(`${filePath} took ${msToString(duration)}`, {
title: 'Slow Test',
file: filePath,
});
diff --git a/packages/playwright/src/reporters/html.ts b/packages/playwright/src/reporters/html.ts
index 8212d9b9f7..69b198dbe6 100644
--- a/packages/playwright/src/reporters/html.ts
+++ b/packages/playwright/src/reporters/html.ts
@@ -18,11 +18,15 @@ import fs from 'fs';
import path from 'path';
import { Transform } from 'stream';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
-import { colors } from 'playwright-core/lib/utilsBundle';
+import { colors, mime, open } from 'playwright-core/lib/utilsBundle';
-import { open } from 'playwright-core/lib/utilsBundle';
-import { mime } from 'playwright-core/lib/utilsBundle';
+import { assert } from '@isomorphic/assert';
+import { MultiMap } from '@isomorphic/multimap';
+import { calculateSha1 } from '@serverUtils/crypto';
+import { copyFileAndMakeWritable, removeFolders, sanitizeForFilePath, toPosixPath } from '@serverUtils/fileUtils';
+import { getPackageManagerExecCommand } from '@serverUtils/env';
+import { HttpServer } from '@serverUtils/httpServer';
+import { gracefullyProcessExitDoNotHang } from '@serverUtils/processLauncher';
import { CommonReporterOptions, formatError, formatResultFailure, internalScreen } from './base';
import { codeFrameColumns } from '../transform/babelBundle';
@@ -141,7 +145,7 @@ class HtmlReporter implements ReporterV2 {
async onEnd(result: api.FullResult) {
const projectSuites = this.suite.suites;
- await serverUtils.removeFolders([this._outputFolder]);
+ await 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;
@@ -164,7 +168,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 = serverUtils.getPackageManagerExecCommand();
+ const packageManagerCommand = 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}` : '';
@@ -211,10 +215,10 @@ function standaloneDefaultFolder(): string {
export async function showHTMLReport(reportFolder: string | undefined, host: string = 'localhost', port?: number, testId?: string) {
const folder = reportFolder ?? standaloneDefaultFolder();
try {
- iso.assert(fs.statSync(folder).isDirectory());
+ assert(fs.statSync(folder).isDirectory());
} catch (e) {
writeLine(colors.red(`No report found at "${folder}"`));
- serverUtils.gracefullyProcessExitDoNotHang(1);
+ gracefullyProcessExitDoNotHang(1);
return;
}
const server = startHtmlReportServer(folder);
@@ -229,8 +233,8 @@ export async function showHTMLReport(reportFolder: string | undefined, host: str
await new Promise(() => {});
}
-export function startHtmlReportServer(folder: string): serverUtils.HttpServer {
- const server = new serverUtils.HttpServer();
+export function startHtmlReportServer(folder: string): HttpServer {
+ const server = new HttpServer();
server.routePrefix('/', (request, response) => {
let relativePath = new URL('http://localhost' + request.url).pathname;
if (relativePath.startsWith('/trace/file')) {
@@ -254,7 +258,7 @@ type DataMap = Map<string, { testFile: TestFile, testFileSummary: TestFileSummar
class HtmlBuilder {
private _config: api.FullConfig;
private _reportFolder: string;
- private _stepsInFile = new iso.MultiMap<string, TestStep>();
+ private _stepsInFile = new MultiMap<string, TestStep>();
private _dataZipFile: ZipFile;
private _hasTraces = false;
private _attachmentsBaseURL: string;
@@ -351,12 +355,12 @@ class HtmlBuilder {
for (const file of fs.readdirSync(traceViewerFolder)) {
if (file.endsWith('.map') || file.includes('watch') || file.includes('assets'))
continue;
- await serverUtils.copyFileAndMakeWritable(path.join(traceViewerFolder, file), path.join(traceViewerTargetFolder, file));
+ await 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 serverUtils.copyFileAndMakeWritable(path.join(traceViewerFolder, 'assets', file), path.join(traceViewerAssetsTargetFolder, file));
+ await copyFileAndMakeWritable(path.join(traceViewerFolder, 'assets', file), path.join(traceViewerAssetsTargetFolder, file));
}
}
@@ -405,7 +409,7 @@ class HtmlBuilder {
}
private _createEntryForSuite(data: DataMap, projectName: string, suite: api.Suite, fileName: string, deep: boolean) {
- const fileId = serverUtils.calculateSha1(fileName).slice(0, 20);
+ const fileId = calculateSha1(fileName).slice(0, 20);
let fileEntry = data.get(fileId);
if (!fileEntry) {
fileEntry = {
@@ -500,7 +504,7 @@ class HtmlBuilder {
let fileName = a.path;
try {
const buffer = fs.readFileSync(a.path);
- const sha1 = serverUtils.calculateSha1(buffer) + path.extname(a.path);
+ const sha1 = 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);
@@ -531,8 +535,8 @@ class HtmlBuilder {
}
fs.mkdirSync(path.join(this._reportFolder, 'data'), { recursive: true });
- const extension = serverUtils.sanitizeForFilePath(path.extname(a.name).replace(/^\./, '')) || mime.getExtension(a.contentType) || 'dat';
- const sha1 = serverUtils.calculateSha1(a.body) + '.' + extension;
+ const extension = sanitizeForFilePath(path.extname(a.name).replace(/^\./, '')) || mime.getExtension(a.contentType) || 'dat';
+ const sha1 = calculateSha1(a.body) + '.' + extension;
fs.writeFileSync(path.join(this._reportFolder, 'data', sha1), a.body);
return {
name: a.name,
@@ -615,7 +619,7 @@ class HtmlBuilder {
private _relativeLocation(location: api.Location | undefined): api.Location | undefined {
if (!location)
return undefined;
- const file = serverUtils.toPosixPath(path.relative(this._config.rootDir, location.file));
+ const file = toPosixPath(path.relative(this._config.rootDir, location.file));
return {
file,
line: location.line,
@@ -711,7 +715,7 @@ function dedupeSteps(steps: api.TestStep[]) {
return result;
}
-function createSnippets(stepsInFile: iso.MultiMap<string, TestStep>) {
+function createSnippets(stepsInFile: 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 c1a8ffc518..d2592f8846 100644
--- a/packages/playwright/src/reporters/internalReporter.ts
+++ b/packages/playwright/src/reporters/internalReporter.ts
@@ -16,7 +16,7 @@
import fs from 'fs';
-import { iso } from 'playwright-core/lib/coreBundle';
+import { monotonicTime } from '@isomorphic/time';
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 = iso.monotonicTime();
+ this._monotonicStartTime = monotonicTime();
this._reporter.onConfigure?.(config);
}
@@ -85,7 +85,7 @@ export class InternalReporter implements ReporterV2 {
return await this._reporter.onEnd?.({
...result,
startTime: this._startTime!,
- duration: iso.monotonicTime() - this._monotonicStartTime!,
+ duration: monotonicTime() - this._monotonicStartTime!,
});
}
diff --git a/packages/playwright/src/reporters/json.ts b/packages/playwright/src/reporters/json.ts
index 0da65f4f9d..25f1326bcc 100644
--- a/packages/playwright/src/reporters/json.ts
+++ b/packages/playwright/src/reporters/json.ts
@@ -17,7 +17,8 @@
import fs from 'fs';
import path from 'path';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { MultiMap } from '@isomorphic/multimap';
+import { toPosixPath } from '@serverUtils/fileUtils';
import { formatError, nonTerminalScreen, prepareErrorStack, resolveOutputFile, CommonReporterOptions } from './base';
import { getProjectId } from '../common/config';
@@ -26,8 +27,6 @@ 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;
@@ -99,7 +98,7 @@ class JSONReporter implements ReporterV2 {
}
private _mergeSuites(suites: Suite[]): JSONReportSuite[] {
- const fileSuites = new iso.MultiMap<string, JSONReportSuite>();
+ const fileSuites = new 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 f23d6b23eb..1177a5a515 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 { serverUtils } from 'playwright-core/lib/coreBundle';
+import { getAsBooleanFromENV } from '@serverUtils/env';
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 = 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.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.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 eac307695a..33f62f8123 100644
--- a/packages/playwright/src/reporters/list.ts
+++ b/packages/playwright/src/reporters/list.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { msToString } from '@isomorphic/formatUtils';
+import { getAsBooleanFromENV } from '@serverUtils/env';
import { markErrorsAsReported, TerminalReporter, stepSuffix } from './base';
import { stripAnsiEscapes } from '../util';
@@ -41,7 +42,7 @@ class ListReporter extends TerminalReporter {
constructor(options?: ListReporterOptions & CommonReporterOptions & TerminalReporterOptions) {
super(options);
- this._printSteps = serverUtils.getAsBooleanFromENV('PLAYWRIGHT_LIST_PRINT_STEPS', options?.printSteps);
+ this._printSteps = getAsBooleanFromENV('PLAYWRIGHT_LIST_PRINT_STEPS', options?.printSteps);
}
override onBegin(suite: Suite) {
@@ -125,7 +126,7 @@ class ListReporter extends TerminalReporter {
text = this.screen.colors.red(title);
else
text = title;
- text += this.screen.colors.dim(` (${iso.msToString(step.duration)})`);
+ text += this.screen.colors.dim(` (${msToString(step.duration)})`);
this._updateOrAppendLine(this._stepRows, step, text, prefix);
}
@@ -218,7 +219,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(` (${iso.msToString(result.duration)})`);
+ text += this._retrySuffix(result) + this.screen.colors.dim(` (${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 2d9bfe74bd..cf0439aa57 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 { serverUtils } from 'playwright-core/lib/coreBundle';
+import { ZipFile } from '@serverUtils/zipFile';
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 serverUtils.ZipFile(absolutePath);
+ const zipFile = new 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 86550a5a59..b1ab338dd7 100644
--- a/packages/playwright/src/reporters/teleEmitter.ts
+++ b/packages/playwright/src/reporters/teleEmitter.ts
@@ -16,7 +16,7 @@
import path from 'path';
-import { serverUtils } from 'playwright-core/lib/coreBundle';
+import { createGuid } from '@serverUtils/crypto';
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] = serverUtils.createGuid();
+ (result as any)[this._idSymbol] = 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] = serverUtils.createGuid();
+ (step as any)[this._idSymbol] = createGuid();
this._messageSink({
method: 'onStepBegin',
params: {
diff --git a/packages/playwright/src/runner/DEPS.list b/packages/playwright/src/runner/DEPS.list
index bc1cc6d763..63b99bb1a7 100644
--- a/packages/playwright/src/runner/DEPS.list
+++ b/packages/playwright/src/runner/DEPS.list
@@ -1,4 +1,6 @@
[*]
+@isomorphic/**
+@serverUtils/**
../../types.ts
../common/
../reporters/
diff --git a/packages/playwright/src/runner/dispatcher.ts b/packages/playwright/src/runner/dispatcher.ts
index eabf903bd2..a8fe019e8c 100644
--- a/packages/playwright/src/runner/dispatcher.ts
+++ b/packages/playwright/src/runner/dispatcher.ts
@@ -14,15 +14,18 @@
* limitations under the License.
*/
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { colors } from 'playwright-core/lib/utilsBundle';
+import { ManualPromise } from '@isomorphic/manualPromise';
+import { eventsHelper } from '@serverUtils/eventsHelper';
+
import { addSuggestedRebaseline } from './rebase';
import { WorkerHost } from './workerHost';
import { serializeConfig } from '../common/ipc';
import { addLocationAndSnippetToError } from '../reporters/internalReporter';
import { serializeError } from '../util';
+import type { RegisteredListener } from '@serverUtils/eventsHelper';
import type { FailureTracker } from './failureTracker';
import type { ProcessExitData } from './processHost';
import type { TestGroup } from './testGroups';
@@ -33,9 +36,6 @@ import type { Suite } from '../common/test';
import type { TestCase } from '../common/test';
import type { ReporterV2 } from '../reporters/reporterV2';
-const { eventsHelper } = serverUtils;
-
-
export type EnvByProjectId = Map<string, Record<string, string | undefined>>;
export class Dispatcher {
@@ -44,7 +44,7 @@ export class Dispatcher {
private _queue: TestGroup[] = [];
private _workerLimitPerProjectId = new Map<string, number>();
private _queuedOrRunningHashCount = new Map<string, number>();
- private _finished = new iso.ManualPromise<void>();
+ private _finished = new ManualPromise<void>();
private _isStopped = true;
private _config: FullConfigInternal;
@@ -277,14 +277,14 @@ export class Dispatcher {
}
class JobDispatcher {
- jobResult = new iso.ManualPromise<{ newJob?: TestGroup, didFail: boolean }>();
+ jobResult = new ManualPromise<{ newJob?: TestGroup, didFail: boolean }>();
readonly job: TestGroup;
private _config: FullConfigInternal;
private _reporter: ReporterV2;
private _failureTracker: FailureTracker;
private _stopCallback: () => void;
- private _listeners: serverUtils.RegisteredListener[] = [];
+ private _listeners: 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 163c3e8e16..26fcf12070 100644
--- a/packages/playwright/src/runner/loadUtils.ts
+++ b/packages/playwright/src/runner/loadUtils.ts
@@ -16,9 +16,11 @@
import path from 'path';
import fs from 'fs';
-import { serverUtils } from 'playwright-core/lib/coreBundle';
+
+import { toPosixPath } from '@serverUtils/fileUtils';
import { InProcessLoaderHost, OutOfProcessLoaderHost } from './loaderHost';
+import { sourceMapSupport } from '../utilsBundle';
import { createTitleMatcher, errorWithFile, parseLocationArg } from '../util';
import { buildProjectsClosure, collectFilesForProject, filterProjects } from './projectUtils';
import { createTestGroups, filterForShard } from './testGroups';
@@ -26,8 +28,8 @@ import { applyRepeatEachIndex, bindFileSuiteToProject, filterOnly, filterTestsRe
import { Suite } from '../common/test';
import { dependenciesForTestFile } from '../transform/compilationCache';
import { requireOrImport } from '../transform/transform';
-import { sourceMapSupport } from '../utilsBundle';
+import type { RawSourceMap } from '../utilsBundle';
import type { TestRun } from './tasks';
import type { TestGroup } from './testGroups';
import type { FullConfig, Reporter, TestError } from '../../types/testReporter';
@@ -35,7 +37,6 @@ import type { FullProjectInternal } from '../common/config';
import type { FullConfigInternal } from '../common/config';
import type { TestCase } from '../common/test';
import type { Matcher, TestCaseFilter } from '../util';
-import type { RawSourceMap } from '../utilsBundle';
export async function collectProjectsAndTestFiles(testRun: TestRun, doNotRunTestsOutsideProjectFilter: boolean) {
@@ -351,20 +352,20 @@ export async function loadTestList(config: FullConfigInternal, filePath: string)
project = tokens[0].substring(1, tokens[0].length - 1);
tokens.shift();
}
- return { project, file: serverUtils.toPosixPath(parseLocationArg(tokens[0]).file), titlePath: tokens.slice(1) };
+ return { project, file: 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 = serverUtils.toPosixPath(path.relative(config.config.rootDir, test.location.file));
+ const relativeFile = 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 = serverUtils.toPosixPath(path.relative(config.config.rootDir, file));
+ const relativeFile = 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 d8022a25ba..e8f5e5a5cf 100644
--- a/packages/playwright/src/runner/processHost.ts
+++ b/packages/playwright/src/runner/processHost.ts
@@ -17,9 +17,11 @@
import child_process from 'child_process';
import { EventEmitter } from 'events';
-import { iso } from 'playwright-core/lib/coreBundle';
import { debug } from 'playwright-core/lib/utilsBundle';
+import { assert } from '@isomorphic/assert';
+import { timeOrigin } from '@isomorphic/time';
+
import type { EnvProducedPayload, ProcessInitParams } from '../common/ipc';
import type { ProtocolRequest, ProtocolResponse } from '../common/process';
@@ -50,7 +52,7 @@ export class ProcessHost extends EventEmitter {
}
async startRunner(runnerParams: any, options: { onStdOut?: (chunk: Buffer | string) => void, onStdErr?: (chunk: Buffer | string) => void } = {}): Promise<ProcessExitData | undefined> {
- iso.assert(!this.process, 'Internal error: starting the same process twice');
+ assert(!this.process, 'Internal error: starting the same process twice');
this.process = child_process.fork(this._entryScript, {
// 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 +129,7 @@ export class ProcessHost extends EventEmitter {
const processParams: ProcessInitParams = {
processName: this._processName,
- timeOrigin: iso.timeOrigin(),
+ timeOrigin: timeOrigin(),
};
this.send({
diff --git a/packages/playwright/src/runner/projectUtils.ts b/packages/playwright/src/runner/projectUtils.ts
index d96717927d..c2f1b4ce46 100644
--- a/packages/playwright/src/runner/projectUtils.ts
+++ b/packages/playwright/src/runner/projectUtils.ts
@@ -18,9 +18,10 @@ import fs from 'fs';
import path from 'path';
import { promisify } from 'util';
-import { iso } from 'playwright-core/lib/coreBundle';
import { minimatch } from 'playwright-core/lib/utilsBundle';
+import { escapeRegExp } from '@isomorphic/stringUtils';
+
import { createFileMatcher } from '../util';
import type { FullConfigInternal, FullProjectInternal } from '../common/config';
@@ -30,7 +31,7 @@ const readFileAsync = promisify(fs.readFile);
const readDirAsync = promisify(fs.readdir);
function wildcardPatternToRegExp(pattern: string): RegExp {
- return new RegExp('^' + pattern.split('*').map(iso.escapeRegExp).join('.*') + '$', 'ig');
+ return new RegExp('^' + pattern.split('*').map(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 d01a752d15..fc2e20b81b 100644
--- a/packages/playwright/src/runner/rebase.ts
+++ b/packages/playwright/src/runner/rebase.ts
@@ -17,10 +17,8 @@
import fs from 'fs';
import path from 'path';
-
-import { iso } from 'playwright-core/lib/coreBundle';
-import { colors } from 'playwright-core/lib/utilsBundle';
-import { diff } from 'playwright-core/lib/utilsBundle';
+import { colors, diff } from 'playwright-core/lib/utilsBundle';
+import { MultiMap } from '@isomorphic/multimap';
import { filterProjects } from './projectUtils';
import { babelParse, traverse, types } from '../transform/babelBundle';
@@ -42,7 +40,7 @@ type Replacement = {
code: string;
};
-const suggestedRebaselines = new iso.MultiMap<string, Replacement>();
+const suggestedRebaselines = new 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 dc9926d2d2..67320be858 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 { serverUtils } from 'playwright-core/lib/coreBundle';
+import { calculateSha1 } from '@serverUtils/crypto';
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 = serverUtils.calculateSha1(fs.readFileSync(config.cliTestList));
+ command.cliTestList = calculateSha1(fs.readFileSync(config.cliTestList));
if (config.cliTestListInvert)
- command.cliTestListInvert = serverUtils.calculateSha1(fs.readFileSync(config.cliTestListInvert));
+ command.cliTestListInvert = calculateSha1(fs.readFileSync(config.cliTestListInvert));
if (Object.keys(command).length)
- parts.push(serverUtils.calculateSha1(JSON.stringify(command)).substring(0, 7));
+ parts.push(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 f6719c5c24..8b3116dac9 100644
--- a/packages/playwright/src/runner/taskRunner.ts
+++ b/packages/playwright/src/runner/taskRunner.ts
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import { iso } from 'playwright-core/lib/coreBundle';
-import { colors } from 'playwright-core/lib/utilsBundle';
-import { debug } from 'playwright-core/lib/utilsBundle';
+import { colors, debug } from 'playwright-core/lib/utilsBundle';
+import { ManualPromise } from '@isomorphic/manualPromise';
+import { monotonicTime } from '@isomorphic/time';
import { SigIntWatcher } from './sigIntWatcher';
import { serializeError } from '../util';
@@ -45,13 +45,13 @@ export class TaskRunner<Context> {
this._tasks.push(task);
}
- async run(context: Context, deadline: number, cancelPromise?: iso.ManualPromise<void>): Promise<FullResult['status']> {
+ async run(context: Context, deadline: number, cancelPromise?: 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 iso.ManualPromise<void>()): Promise<{ status: FullResult['status'], cleanup: () => Promise<FullResult['status']> }> {
+ async runDeferCleanup(context: Context, deadline: number, cancelPromise = new 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 iso.ManualPromise();
+ readonly promise = new ManualPromise();
private _timer: NodeJS.Timeout | undefined;
constructor(deadline: number) {
if (!deadline)
return;
- if (deadline - iso.monotonicTime() <= 0) {
+ if (deadline - 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 - iso.monotonicTime());
+ }, deadline - monotonicTime());
}
timedOut(): boolean {
diff --git a/packages/playwright/src/runner/tasks.ts b/packages/playwright/src/runner/tasks.ts
index 0447f781ff..57e88ee757 100644
--- a/packages/playwright/src/runner/tasks.ts
+++ b/packages/playwright/src/runner/tasks.ts
@@ -18,9 +18,12 @@ import fs from 'fs';
import path from 'path';
import { promisify } from 'util';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { debug } from 'playwright-core/lib/utilsBundle';
+import { ManualPromise } from '@isomorphic/manualPromise';
+import { monotonicTime } from '@isomorphic/time';
+import { removeFolders } from '@serverUtils/fileUtils';
+
import { Dispatcher } from './dispatcher';
import { FailureTracker } from './failureTracker';
import { collectProjectsAndTestFiles, createRootSuite, loadFileSuites, loadGlobalHook, loadTestList } from './loadUtils';
@@ -72,8 +75,8 @@ export class TestRun {
}
}
-export async function runTasks(testRun: TestRun, tasks: Task<TestRun>[], globalTimeout?: number, cancelPromise?: iso.ManualPromise<void>) {
- const deadline = globalTimeout ? iso.monotonicTime() + globalTimeout : 0;
+export async function runTasks(testRun: TestRun, tasks: Task<TestRun>[], globalTimeout?: number, cancelPromise?: ManualPromise<void>) {
+ const deadline = globalTimeout ? monotonicTime() + globalTimeout : 0;
const taskRunner = new TaskRunner<TestRun>(testRun.reporter, globalTimeout || 0);
for (const task of tasks)
taskRunner.addTask(task);
@@ -212,7 +215,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 => serverUtils.removeFolders([outputDir]).then(async ([error]) => {
+ await Promise.all(Array.from(outputDirs).map(outputDir => removeFolders([outputDir]).then(async ([error]) => {
if (!error)
return;
if ((error as any).code === 'EBUSY') {
@@ -220,7 +223,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 => serverUtils.removeFolders([path.join(outputDir, entry)])));
+ await Promise.all(entries.map(entry => 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 a9c40751a2..ec86d0ff2c 100644
--- a/packages/playwright/src/runner/testRunner.ts
+++ b/packages/playwright/src/runner/testRunner.ts
@@ -18,7 +18,11 @@ import EventEmitter from 'events';
import fs from 'fs';
import path from 'path';
-import { iso, serverUtils, registry } from 'playwright-core/lib/coreBundle';
+import { registry } from 'playwright-core/lib/coreBundle';
+
+import { ManualPromise } from '@isomorphic/manualPromise';
+import { setPlaywrightTestProcessEnv } from '@serverUtils/env';
+import { gracefullyProcessExitDoNotHang } from '@serverUtils/processLauncher';
import { loadConfig } from '../common/configLoader';
import { Watcher } from '../fsWatcher';
@@ -93,7 +97,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: iso.ManualPromise<void> } | undefined;
+ private _testRun: { run: Promise<reporterTypes.FullResult['status']>, stop: ManualPromise<void> } | undefined;
private _queue = Promise.resolve();
private _globalSetup: { cleanup: () => Promise<any> } | undefined;
private _devServer: { cleanup: () => Promise<any> } | undefined;
@@ -117,7 +121,7 @@ export class TestRunner extends EventEmitter<TestRunnerEventMap> {
watchTestDirs?: boolean;
populateDependenciesOnList?: boolean;
}) {
- serverUtils.setPlaywrightTestProcessEnv();
+ setPlaywrightTestProcessEnv();
this._watchTestDirs = !!params.watchTestDirs;
this._populateDependenciesOnList = !!params.populateDependenciesOnList;
this._startingEnv = { ...process.env };
@@ -353,7 +357,7 @@ export class TestRunner extends EventEmitter<TestRunnerEventMap> {
const configReporters = params.disableConfigReporters ? [] : await createReporters(config, 'test');
const reporter = new InternalReporter([...configReporters, userReporter]);
- const stop = new iso.ManualPromise();
+ const stop = new ManualPromise();
const tasks = [
createApplyRebaselinesTask(),
createLoadTask('out-of-process', { filterOnly: true, failOnLoadErrors: !!params.failOnLoadErrors, doNotRunDepsOutsideProjectFilter: params.doNotRunDepsOutsideProjectFilter }),
@@ -399,7 +403,7 @@ export class TestRunner extends EventEmitter<TestRunnerEventMap> {
}
async closeGracefully() {
- serverUtils.gracefullyProcessExitDoNotHang(0);
+ gracefullyProcessExitDoNotHang(0);
}
async stop() {
@@ -456,7 +460,7 @@ async function resolveCtDirs(config: FullConfigInternal) {
}
export async function runAllTestsWithConfig(config: FullConfigInternal): Promise<FullResultStatus> {
- serverUtils.setPlaywrightTestProcessEnv();
+ setPlaywrightTestProcessEnv();
const listOnly = config.cliListOnly;
diff --git a/packages/playwright/src/runner/testServer.ts b/packages/playwright/src/runner/testServer.ts
index 4315b2413f..2304818085 100644
--- a/packages/playwright/src/runner/testServer.ts
+++ b/packages/playwright/src/runner/testServer.ts
@@ -16,15 +16,21 @@
import util from 'util';
-import { iso, serverUtils, sever } from 'playwright-core/lib/coreBundle';
+import { sever } from 'playwright-core/lib/coreBundle';
import { debug, open } from 'playwright-core/lib/utilsBundle';
+import { ManualPromise } from '@isomorphic/manualPromise';
+import { isUnderTest } from '@serverUtils/debug';
+import { HttpServer } from '@serverUtils/httpServer';
+import { gracefullyProcessExitDoNotHang } from '@serverUtils/processLauncher';
+
import { loadConfig, resolveConfigLocation } from '../common/configLoader';
import ListReporter from '../reporters/list';
import { createReporterForTestServer } from './reporters';
import { SigIntWatcher } from './sigIntWatcher';
import { TestRunner, TestRunnerEvent } from './testRunner';
+import type { Transport } from '@serverUtils/httpServer';
import type * as reporterTypes from '../../types/testReporter';
import type { ConfigLocation } from '../common/config';
import type { ConfigCLIOverrides } from '../common/ipc';
@@ -52,7 +58,7 @@ class TestServer {
this._configCLIOverrides = configCLIOverrides;
}
- async start(options: { host?: string, port?: number }): Promise<serverUtils.HttpServer> {
+ async start(options: { host?: string, port?: number }): Promise<HttpServer> {
this._dispatcher = new TestServerDispatcher(this._configLocation, this._configCLIOverrides);
return await sever.startTraceViewerServer({ ...options, transport: this._dispatcher.transport });
}
@@ -87,7 +93,7 @@ export type RunTestsParams = {
};
export class TestServerDispatcher implements TestServerInterface {
- readonly transport: serverUtils.Transport;
+ readonly transport: Transport;
private _serializer = require.resolve('./uiModeReporter');
private _closeOnDisconnect = false;
private _testRunner: TestRunner;
@@ -102,7 +108,7 @@ export class TestServerDispatcher implements TestServerInterface {
dispatch: (method, params) => (this as any)[method](params),
onclose: () => {
if (this._closeOnDisconnect)
- serverUtils.gracefullyProcessExitDoNotHang(0);
+ gracefullyProcessExitDoNotHang(0);
},
};
@@ -136,7 +142,7 @@ export class TestServerDispatcher implements TestServerInterface {
async ping() {}
async open(params: Parameters<TestServerInterface['open']>[0]): ReturnType<TestServerInterface['open']> {
- if (serverUtils.isUnderTest())
+ if (isUnderTest())
return;
// eslint-disable-next-line no-console
open('vscode://file/' + params.location.file + ':' + params.location.line).catch(e => console.error(e));
@@ -271,14 +277,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: serverUtils.HttpServer, cancelPromise: iso.ManualPromise<void>) => {
+ return await innerRunTestServer(configLocation, configCLIOverrides, options, async (server: HttpServer, cancelPromise: ManualPromise<void>) => {
await sever.installRootRedirect(server, undefined, { ...options, webApp: 'uiMode.html' });
if (options.host !== undefined || options.port !== undefined) {
await sever.openTraceInBrowser(server.urlPrefix('human-readable'));
} else {
const channel = await installedChromiumChannelForUI(configLocation, configCLIOverrides);
const page = await sever.openTraceViewerApp(server.urlPrefix('precise'), 'chromium', {
- headless: serverUtils.isUnderTest() && process.env.PWTEST_HEADED_FOR_TEST !== '1',
+ headless: isUnderTest() && process.env.PWTEST_HEADED_FOR_TEST !== '1',
persistentContextOptions: {
handleSIGINT: false,
channel,
@@ -311,11 +317,11 @@ export async function runTestServer(configFile: string | undefined, configCLIOve
});
}
-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']> {
+async function innerRunTestServer(configLocation: ConfigLocation, configCLIOverrides: ConfigCLIOverrides, options: { host?: string, port?: number }, openUI: (server: HttpServer, cancelPromise: ManualPromise<void>) => Promise<void>): Promise<reporterTypes.FullResult['status']> {
const testServer = new TestServer(configLocation, configCLIOverrides);
- const cancelPromise = new iso.ManualPromise<void>();
+ const cancelPromise = new ManualPromise<void>();
const sigintWatcher = new SigIntWatcher();
- process.stdin.on('close', () => serverUtils.gracefullyProcessExitDoNotHang(0));
+ process.stdin.on('close', () => 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 f7e50eebc4..9ac1ca56f4 100644
--- a/packages/playwright/src/runner/watchMode.ts
+++ b/packages/playwright/src/runner/watchMode.ts
@@ -18,9 +18,14 @@ import path from 'path';
import readline from 'readline';
import { EventEmitter } from 'stream';
-import { iso, remote, serverUtils } from 'playwright-core/lib/coreBundle';
+import { remote } from 'playwright-core/lib/coreBundle';
import { colors } from 'playwright-core/lib/utilsBundle';
+import { ManualPromise } from '@isomorphic/manualPromise';
+import { createGuid } from '@serverUtils/crypto';
+import { getPackageManagerExecCommand } from '@serverUtils/env';
+import { eventsHelper } from '@serverUtils/eventsHelper';
+
import { separator, terminalScreen } from '../reporters/base';
import { enquirer } from '../utilsBundle';
import { TestServerDispatcher } from './testServer';
@@ -98,7 +103,7 @@ export async function runWatchModeLoop(configLocation: ConfigLocation, initialOp
const dirtyTestFiles = new Set<string>();
const dirtyTestIds = new Set<string>();
- let onDirtyTests = new iso.ManualPromise<'changed'>();
+ let onDirtyTests = new ManualPromise<'changed'>();
let queue = Promise.resolve();
const changedFiles = new Set<string>();
@@ -122,7 +127,7 @@ export async function runWatchModeLoop(configLocation: ConfigLocation, initialOp
if (dirtyTestIds.size > 0) {
onDirtyTests.resolve('changed');
- onDirtyTests = new iso.ManualPromise();
+ onDirtyTests = new ManualPromise();
}
});
});
@@ -272,21 +277,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 iso.ManualPromise<T>();
+ const promise = new 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 = serverUtils.eventsHelper.addEventListener(process.stdin, 'keypress', (text: string, key: any) => {
+ const listener = eventsHelper.addEventListener(process.stdin, 'keypress', (text: string, key: any) => {
const result = handler(text, key);
if (result)
promise.resolve(result);
});
const dispose = () => {
- serverUtils.eventsHelper.removeEventListeners([listener]);
+ eventsHelper.removeEventListeners([listener]);
rl.close();
if (process.stdin.isTTY)
process.stdin.setRawMode(false);
@@ -372,7 +377,7 @@ let connectWsEndpoint: string | undefined = undefined;
let seq = 1;
function printConfiguration(options: WatchModeOptions, title?: string) {
- const packageManagerCommand = serverUtils.getPackageManagerExecCommand();
+ const packageManagerCommand = getPackageManagerExecCommand();
const tokens: string[] = [];
tokens.push(`${packageManagerCommand} playwright test`);
if (options.projects)
@@ -418,7 +423,7 @@ ${colors.dim('Waiting for file changes. Press')} ${colors.bold('enter')} ${color
async function toggleShowBrowser() {
if (!showBrowserServer) {
- showBrowserServer = new remote.PlaywrightServer({ mode: 'extension', path: '/' + serverUtils.createGuid(), maxConnections: 1 });
+ showBrowserServer = new remote.PlaywrightServer({ mode: 'extension', path: '/' + 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 2975398145..bc984d1680 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 { serverUtils } from 'playwright-core/lib/coreBundle';
+import { removeFolders } from '@serverUtils/fileUtils';
import { ProcessHost } from './processHost';
import { stdioChunkToParams } from '../common/ipc';
@@ -77,7 +77,7 @@ export class WorkerHost extends ProcessHost {
}
override async onExit() {
- await serverUtils.removeFolders([this._params.artifactsDir]);
+ await removeFolders([this._params.artifactsDir]);
}
override async stop(didFail?: boolean) {
diff --git a/packages/playwright/src/testActions.ts b/packages/playwright/src/testActions.ts
index 7282044e35..003ecb6021 100644
--- a/packages/playwright/src/testActions.ts
+++ b/packages/playwright/src/testActions.ts
@@ -17,10 +17,10 @@
import fs from 'fs';
import path from 'path';
-import { serverUtils } from 'playwright-core/lib/coreBundle';
-import { builtInReporters } from './common/config';
+import { gracefullyProcessExitDoNotHang } from '@serverUtils/processLauncher';
+import { startProfiling, stopProfiling } from '@serverUtils/profiler';
-const { gracefullyProcessExitDoNotHang } = serverUtils;
+import { builtInReporters } from './common/config';
import { loadConfigFromFile, resolveConfigLocation } from './common/configLoader';
import { terminalScreen } from './reporters/base';
import { filterProjects } from './runner/projectUtils';
@@ -33,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 serverUtils.startProfiling();
+ await startProfiling();
const cliOverrides = overridesFromOptions(opts);
const config = await loadConfigFromFile(opts.config, cliOverrides, opts.deps === false);
@@ -64,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 serverUtils.stopProfiling('runner');
+ await stopProfiling('runner');
const exitCode = status === 'interrupted' ? 130 : (status === 'passed' ? 0 : 1);
gracefullyProcessExitDoNotHang(exitCode);
return;
@@ -82,14 +82,14 @@ export async function runTests(args: string[], opts: { [key: string]: any }) {
grep: opts.grep
}
);
- await serverUtils.stopProfiling('runner');
+ await stopProfiling('runner');
const exitCode = status === 'interrupted' ? 130 : (status === 'passed' ? 0 : 1);
gracefullyProcessExitDoNotHang(exitCode);
return;
}
const status = await runAllTestsWithConfig(config);
- await serverUtils.stopProfiling('runner');
+ await stopProfiling('runner');
const exitCode = status === 'interrupted' ? 130 : (status === 'passed' ? 0 : 1);
gracefullyProcessExitDoNotHang(exitCode);
}
diff --git a/packages/playwright/src/util.ts b/packages/playwright/src/util.ts
index 6871866d8a..08c1fdae80 100644
--- a/packages/playwright/src/util.ts
+++ b/packages/playwright/src/util.ts
@@ -19,16 +19,20 @@ import path from 'path';
import url from 'url';
import util from 'util';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { debug, mime, minimatch } from 'playwright-core/lib/utilsBundle';
+import { calculateSha1 } from '@serverUtils/crypto';
+import { sanitizeForFilePath } from '@serverUtils/fileUtils';
+import { isRegExp } from '@isomorphic/rtti';
+import { parseStackFrame, stringifyStackFrames } from '@isomorphic/stackTrace';
+import { ansiRegex, isString, stripAnsiEscapes } from '@isomorphic/stringUtils';
+
+import type { RawStack } from '@isomorphic/stackTrace';
import type { Location } from './../types/testReporter';
import type { TestInfoErrorImpl } from './common/ipc';
import type { StackFrame } from '@protocol/channels';
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'));
@@ -38,7 +42,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 = iso.stringifyStackFrames(filteredStackTrace(e.stack?.split('\n') || []));
+ const stackLines = stringifyStackFrames(filteredStackTrace(e.stack?.split('\n') || []));
return {
message: name + e.message,
stack: `${name}${e.message}${stackLines.map(line => '\n' + line).join('')}`,
@@ -57,7 +61,7 @@ export function filterStackFile(file: string) {
export function filteredStackTrace(rawStack: RawStack): StackFrame[] {
const frames: StackFrame[] = [];
for (const line of rawStack) {
- const frame = iso.parseStackFrame(line, path.sep, !!process.env.PWDEBUGIMPL);
+ const frame = parseStackFrame(line, path.sep, !!process.env.PWDEBUGIMPL);
if (!frame || !frame.file)
continue;
if (!filterStackFile(frame.file))
@@ -91,7 +95,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 (iso.isRegExp(pattern)) {
+ if (isRegExp(pattern)) {
reList.push(pattern);
} else {
if (!pattern.startsWith('**/'))
@@ -183,7 +187,7 @@ export const windowsFilesystemFriendlyLength = 60;
export function trimLongString(s: string, length = 100) {
if (s.length <= length)
return s;
- const hash = serverUtils.calculateSha1(s);
+ const hash = calculateSha1(s);
const middle = `-${hash.substring(0, 5)}-`;
const start = Math.floor((length - middle.length) / 2);
const end = length - middle.length - start;
@@ -199,7 +203,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 serverUtils.sanitizeForFilePath(base) + ext;
+ return sanitizeForFilePath(base) + ext;
}
/**
@@ -252,12 +256,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 = serverUtils.calculateSha1(options.path);
+ const hash = calculateSha1(options.path);
- if (!iso.isString(name))
+ if (!isString(name))
throw new Error('"name" should be string.');
- const sanitizedNamePrefix = serverUtils.sanitizeForFilePath(name) + '-';
+ const sanitizedNamePrefix = 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);
@@ -396,4 +400,4 @@ export async function removeDirAndLogToConsole(dir: string) {
}
}
-export const { ansiRegex, stripAnsiEscapes } = iso;
+export { ansiRegex, stripAnsiEscapes };
diff --git a/packages/playwright/src/worker/DEPS.list b/packages/playwright/src/worker/DEPS.list
index 1532b16c9f..336987116c 100644
--- a/packages/playwright/src/worker/DEPS.list
+++ b/packages/playwright/src/worker/DEPS.list
@@ -1,7 +1,8 @@
[*]
+@isomorphic/**
+@serverUtils/**
../common/
../transform/
../util.ts
-../utilBundle.ts
../matchers/**
../isomorphic/util.ts
diff --git a/packages/playwright/src/worker/fixtureRunner.ts b/packages/playwright/src/worker/fixtureRunner.ts
index 105f187124..3190feb15f 100644
--- a/packages/playwright/src/worker/fixtureRunner.ts
+++ b/packages/playwright/src/worker/fixtureRunner.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import { iso } from 'playwright-core/lib/coreBundle';
+import { ManualPromise } from '@isomorphic/manualPromise';
+import { escapeWithQuotes } from '@isomorphic/stringUtils';
import { fixtureParameterNames } from '../common/fixtures';
import { filterStackFile, formatLocation } from '../util';
@@ -31,7 +32,7 @@ class Fixture {
value: any;
failed = false;
- private _useFuncFinished: iso.ManualPromise<void> | undefined;
+ private _useFuncFinished: ManualPromise<void> | undefined;
private _selfTeardownComplete: Promise<void> | undefined;
private _setupDescription: FixtureDescription;
private _teardownDescription: FixtureDescription;
@@ -46,7 +47,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 ${iso.escapeWithQuotes(title, '"')}`, category: 'fixture', location };
+ this._stepInfo = { title: `Fixture ${escapeWithQuotes(title, '"')}`, category: 'fixture', location };
if (this.registration.box === 'self')
this._stepInfo = undefined;
else if (this.registration.box)
@@ -104,13 +105,13 @@ class Fixture {
}
let called = false;
- const useFuncStarted = new iso.ManualPromise<void>();
+ const useFuncStarted = new 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 iso.ManualPromise<void>();
+ this._useFuncFinished = new ManualPromise<void>();
useFuncStarted.resolve();
await this._useFuncFinished;
};
diff --git a/packages/playwright/src/worker/testInfo.ts b/packages/playwright/src/worker/testInfo.ts
index 0f29001550..ee8a215cee 100644
--- a/packages/playwright/src/worker/testInfo.ts
+++ b/packages/playwright/src/worker/testInfo.ts
@@ -17,7 +17,13 @@
import fs from 'fs';
import path from 'path';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { ManualPromise } from '@isomorphic/manualPromise';
+import { captureRawStack, stringifyStackFrames } from '@isomorphic/stackTrace';
+import { escapeWithQuotes } from '@isomorphic/stringUtils';
+import { monotonicTime } from '@isomorphic/time';
+import { createGuid } from '@serverUtils/crypto';
+import { sanitizeForFilePath } from '@serverUtils/fileUtils';
+import { currentZone } from '@serverUtils/zones';
import { TimeoutManager, TimeoutManagerError, kMaxDeadline } from './timeoutManager';
import { addSuffixToFilePath, filteredStackTrace, getContainedPath, normalizeAndSaveAttachment, sanitizeFilePathBeforeExtension, trimLongString, windowsFilesystemFriendlyLength } from '../util';
@@ -33,8 +39,6 @@ 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 {
@@ -91,7 +95,7 @@ export class TestInfoImpl implements TestInfo {
readonly _tracing: TestTracing;
readonly _uniqueSymbol;
- private _interruptedPromise = new iso.ManualPromise<void>();
+ private _interruptedPromise = new ManualPromise<void>();
_lastStepId = 0;
private readonly _requireFile: string;
readonly _projectInternal: FullProjectInternal;
@@ -213,9 +217,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 + '-' + serverUtils.sanitizeForFilePath(fullTitleWithoutSpec), windowsFilesystemFriendlyLength);
+ let testOutputDir = trimLongString(sanitizedRelativePath + '-' + sanitizeForFilePath(fullTitleWithoutSpec), windowsFilesystemFriendlyLength);
if (projectInternal.id)
- testOutputDir += '-' + serverUtils.sanitizeForFilePath(projectInternal.id);
+ testOutputDir += '-' + sanitizeForFilePath(projectInternal.id);
if (this.retry)
testOutputDir += '-retry' + this.retry;
if (this.repeatEachIndex)
@@ -288,7 +292,7 @@ export class TestInfoImpl implements TestInfo {
}
private _parentStep() {
- return serverUtils.currentZone().data<TestStepInternal>('stepZone') ?? this._findLastPredefinedStep(this._steps);
+ return currentZone().data<TestStepInternal>('stepZone') ?? this._findLastPredefinedStep(this._steps);
}
_addStep(data: Readonly<TestStepData>, parentStep?: TestStepInternal): TestStepInternal {
@@ -302,7 +306,7 @@ export class TestInfoImpl implements TestInfo {
parentStep = this._parentStep();
}
- const filteredStack = filteredStackTrace(iso.captureRawStack());
+ const filteredStack = filteredStackTrace(captureRawStack());
let boxedStack = parentStep?.boxedStack;
let location = data.location;
if (!boxedStack && data.box) {
@@ -330,7 +334,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${iso.stringifyStackFrames(step.boxedStack).join('\n')}`;
+ error.stack = `${error.message}\n${stringifyStackFrames(step.boxedStack).join('\n')}`;
step.error = error;
}
@@ -416,7 +420,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${iso.stringifyStackFrames(step.boxedStack).join('\n')}`;
+ serialized.stack = `${(error as Error).name}: ${(error as Error).message}\n${stringifyStackFrames(step.boxedStack).join('\n')}`;
this.errors.push(serialized);
this._tracing.appendForError(serialized);
}
@@ -493,7 +497,7 @@ export class TestInfoImpl implements TestInfo {
async attach(name: string, options: { path?: string, body?: string | Buffer, contentType?: string } = {}) {
const step = this._addStep({
- title: `Attach ${iso.escapeWithQuotes(name, '"')}`,
+ title: `Attach ${escapeWithQuotes(name, '"')}`,
category: 'test.attach',
});
this._attach(
@@ -513,8 +517,8 @@ export class TestInfoImpl implements TestInfo {
if (step) {
step.attachmentIndices.push(index);
} else {
- const stepId = `attach@${serverUtils.createGuid()}`;
- this._tracing.appendBeforeActionForStep({ stepId, title: `Attach ${iso.escapeWithQuotes(attachment.name, '"')}`, category: 'test.attach', stack: [] });
+ const stepId = `attach@${createGuid()}`;
+ this._tracing.appendBeforeActionForStep({ stepId, title: `Attach ${escapeWithQuotes(attachment.name, '"')}`, category: 'test.attach', stack: [] });
this._tracing.appendAfterActionForStep(stepId, undefined, [attachment]);
}
@@ -544,7 +548,7 @@ export class TestInfoImpl implements TestInfo {
_fsSanitizedTestName() {
const fullTitleWithoutSpec = this.titlePath.slice(1).join(' ');
- return serverUtils.sanitizeForFilePath(trimLongString(fullTitleWithoutSpec));
+ return sanitizeForFilePath(trimLongString(fullTitleWithoutSpec));
}
_resolveSnapshotPaths(kind: 'snapshot' | 'screenshot' | 'aria', name: string | string[] | undefined, updateSnapshotIndex: 'updateSnapshotIndex' | 'dontUpdateSnapshotIndex', anonymousExtension?: string) {
@@ -612,7 +616,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 = serverUtils.sanitizeForFilePath(this.project.name);
+ const projectNamePathSegment = 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 61fd37361b..88320d84fa 100644
--- a/packages/playwright/src/worker/testTracing.ts
+++ b/packages/playwright/src/worker/testTracing.ts
@@ -17,7 +17,11 @@
import fs from 'fs';
import path from 'path';
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
+import { ManualPromise } from '@isomorphic/manualPromise';
+import { monotonicTime } from '@isomorphic/time';
+import { calculateSha1, createGuid } from '@serverUtils/crypto';
+import { SerializedFS } from '@serverUtils/fileUtils';
+import { getPlaywrightVersion } from '@serverUtils/userAgent';
import { filteredStackTrace } from '../util';
@@ -28,8 +32,6 @@ 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;
@@ -41,7 +43,7 @@ type TraceOptions = { screenshots: boolean, snapshots: boolean, sources: boolean
export class TestTracing {
private _testInfo: TestInfoImpl;
private _options: TraceOptions | undefined;
- private _liveTraceFile: { file: string, fs: serverUtils.SerializedFS } | undefined;
+ private _liveTraceFile: { file: string, fs: SerializedFS } | undefined;
private _traceEvents: trace.TraceEvent[] = [];
private _temporaryTraceFiles: string[] = [];
private _artifactsDir: string;
@@ -58,7 +60,7 @@ export class TestTracing {
type: 'context-options',
origin: 'testRunner',
browserName: '',
- playwrightVersion: serverUtils.getPlaywrightVersion(),
+ playwrightVersion: getPlaywrightVersion(),
options: {},
platform: process.platform,
wallTime: Date.now(),
@@ -109,7 +111,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 serverUtils.SerializedFS() };
+ this._liveTraceFile = { file: path.join(this._tracesDir, `${this._testInfo.testId}-test.trace`), fs: new 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);
@@ -141,7 +143,7 @@ export class TestTracing {
}
private _generateNextTraceRecordingPath() {
- const file = path.join(this._artifactsDir, serverUtils.createGuid() + '.zip');
+ const file = path.join(this._artifactsDir, createGuid() + '.zip');
this._temporaryTraceFiles.push(file);
return file;
}
@@ -204,7 +206,7 @@ export class TestTracing {
}
for (const sourceFile of sourceFiles) {
await fs.promises.readFile(sourceFile, 'utf8').then(source => {
- zipFile.addBuffer(Buffer.from(source), 'resources/src@' + serverUtils.calculateSha1(sourceFile) + '.txt');
+ zipFile.addBuffer(Buffer.from(source), 'resources/src@' + calculateSha1(sourceFile) + '.txt');
}).catch(() => {});
}
}
@@ -222,7 +224,7 @@ export class TestTracing {
if (content === undefined)
continue;
- const sha1 = serverUtils.calculateSha1(content);
+ const sha1 = calculateSha1(content);
attachment.sha1 = sha1;
delete attachment.path;
delete attachment.base64;
@@ -348,7 +350,7 @@ async function mergeTraceFiles(fileName: string, temporaryTraceFiles: string[])
return;
}
- const mergePromise = new iso.ManualPromise();
+ const mergePromise = new ManualPromise();
const { yazl, yauzl } = await import('playwright-core/lib/zipBundle');
const zipFile = new yazl.ZipFile();
const entryNames = new Set<string>();
@@ -356,7 +358,7 @@ async function mergeTraceFiles(fileName: string, temporaryTraceFiles: string[])
for (let i = temporaryTraceFiles.length - 1; i >= 0; --i) {
const tempFile = temporaryTraceFiles[i];
- const promise = new iso.ManualPromise<void>();
+ const promise = new 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 1cb31b538c..d51da210ac 100644
--- a/packages/playwright/src/worker/timeoutManager.ts
+++ b/packages/playwright/src/worker/timeoutManager.ts
@@ -14,15 +14,15 @@
* limitations under the License.
*/
-import { iso } from 'playwright-core/lib/coreBundle';
import { colors } from 'playwright-core/lib/utilsBundle';
+import { ManualPromise } from '@isomorphic/manualPromise';
+import { monotonicTime } from '@isomorphic/time';
+
import { debugTest, formatLocation } from '../util';
import type { Location } from '../../types/testReporter';
-const { monotonicTime } = iso;
-
export type TimeSlot = {
timeout: number;
elapsed: number;
@@ -50,7 +50,7 @@ type Running = {
start: number;
deadline: number;
timer: NodeJS.Timeout | undefined;
- timeoutPromise: iso.ManualPromise<any>;
+ timeoutPromise: ManualPromise<any>;
};
export const kMaxDeadline = 2147483647; // 2^31-1
@@ -97,7 +97,7 @@ export class TimeoutManager {
start: monotonicTime(),
deadline: kMaxDeadline,
timer: undefined,
- timeoutPromise: new iso.ManualPromise(),
+ timeoutPromise: new ManualPromise(),
};
let debugTitle = '';
try {
diff --git a/packages/playwright/src/worker/workerMain.ts b/packages/playwright/src/worker/workerMain.ts
index 783b713bde..cd5d62f622 100644
--- a/packages/playwright/src/worker/workerMain.ts
+++ b/packages/playwright/src/worker/workerMain.ts
@@ -14,9 +14,12 @@
* limitations under the License.
*/
-import { iso, serverUtils } from 'playwright-core/lib/coreBundle';
import { colors } from 'playwright-core/lib/utilsBundle';
+import { ManualPromise } from '@isomorphic/manualPromise';
+import { removeFolders } from '@serverUtils/fileUtils';
+import { gracefullyCloseAll } from '@serverUtils/processLauncher';
+
import { deserializeConfig } from '../common/configLoader';
import { setCurrentTestInfo, setIsWorkerProcess } from '../common/globals';
import { stdioChunkToParams } from '../common/ipc';
@@ -57,7 +60,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 iso.ManualPromise<void>();
+ private _runFinished = new ManualPromise<void>();
private _currentTest: TestInfoImpl | null = null;
private _lastRunningTests: TestCase[] = [];
private _totalRunningTests = 0;
@@ -65,7 +68,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?: iso.ManualPromise<ipc.ResumePayload>;
+ private _resumePromise?: ManualPromise<ipc.ResumePayload>;
constructor(params: ipc.WorkerInitParams) {
super();
@@ -127,7 +130,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, () => serverUtils.gracefullyCloseAll()).catch(() => {});
+ await fakeTestInfo._runWithTimeout(runnable, () => gracefullyCloseAll()).catch(() => {});
this._fatalErrors.push(...fakeTestInfo.errors);
} catch (e) {
this._fatalErrors.push(testInfoError(e));
@@ -216,7 +219,7 @@ export class WorkerMain extends ProcessRunner {
}
async runTestGroup(runPayload: ipc.RunPayload) {
- this._runFinished = new iso.ManualPromise<void>();
+ this._runFinished = new ManualPromise<void>();
const entries = new Map(runPayload.entries.map(e => [e.testId, e]));
let fatalUnknownTestIds: string[] | undefined;
try {
@@ -297,7 +300,7 @@ export class WorkerMain extends ProcessRunner {
onStepEnd: payload => this.dispatchEvent('stepEnd', payload),
onAttach: payload => this.dispatchEvent('attach', payload),
onTestPaused: payload => {
- this._resumePromise = new iso.ManualPromise();
+ this._resumePromise = new ManualPromise();
this.dispatchEvent('testPaused', payload);
return this._resumePromise;
},
@@ -383,7 +386,7 @@ export class WorkerMain extends ProcessRunner {
return;
}
- await serverUtils.removeFolders([testInfo.outputDir]);
+ await removeFolders([testInfo.outputDir]);
let testFunctionParams: object | null = null;
await testInfo._runAsStep({ title: 'Before Hooks', category: 'hook' }, async () => {
@@ -522,7 +525,7 @@ export class WorkerMain extends ProcessRunner {
const preserveOutput = this._config.config.preserveOutput === 'always' ||
(this._config.config.preserveOutput === 'failures-only' && testInfo._isFailure());
if (!preserveOutput)
- await serverUtils.removeFolders([testInfo.outputDir]);
+ await removeFolders([testInfo.outputDir]);
}
private _collectHooksAndModifiers(suite: Suite, type: 'beforeAll' | 'beforeEach' | 'afterAll' | 'afterEach', testInfo: TestInfoImpl) {
diff --git a/tsconfig.json b/tsconfig.json
index 2b187e4099..d79ff44f1a 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -14,6 +14,7 @@
"@html-reporter/*": ["./packages/html-reporter/src/*"],
"@injected/*": ["./packages/injected/src/*"],
"@isomorphic/*": ["./packages/playwright-core/src/utils/isomorphic/*"],
+ "@serverUtils/*": ["./packages/playwright-core/src/server/utils/*"],
"@protocol/*": ["./packages/protocol/src/*"],
"@recorder/*": ["./packages/recorder/src/*"],
"@testIsomorphic/*": ["./packages/playwright/src/isomorphic/*"],
diff --git a/utils/build/build.js b/utils/build/build.js
index e3f9d4ed22..84d0785e5c 100644
--- a/utils/build/build.js
+++ b/utils/build/build.js
@@ -454,23 +454,48 @@ class CustomCallbackStep extends Step {
}
}
-// Plugin to convert dynamic import() of relative paths to require().
-// esbuild preserves dynamic import() even in CJS format, but we want
-// all local imports to use require() for consistency.
+// Single onLoad plugin that does two source-level rewrites:
+//
+// 1. `await import('./rel')` → `require('./rel')`. esbuild preserves dynamic
+// import() even in CJS format; we want local imports to use require()
+// uniformly.
+//
+// 2. `import { X } from '@isomorphic/foo'` / `'@serverUtils/bar'` →
+// `const { X } = require('playwright-core/lib/coreBundle').iso`
+// (same for serverUtils). Per-file esbuild (bundle:false) can't follow
+// path aliases to files outside the emitted tree, so we translate these
+// at source-load time into coreBundle namespace access. Bundled outputs
+// (transform/) use esbuild's `alias` option instead.
+//
+// Both rewrites must live in the SAME plugin because esbuild only runs one
+// onLoad handler per file; the first plugin that returns contents wins.
const dynamicImportToRequirePlugin = {
name: 'dynamic-import-to-require',
setup(build) {
build.onLoad({ filter: /\.ts$/ }, async (args) => {
- const contents = await fs.promises.readFile(args.path, 'utf8');
- if (!contents.includes('await import('))
+ let contents = await fs.promises.readFile(args.path, 'utf8');
+ const hasAwaitImport = contents.includes('await import(');
+ const isPlaywrightSrc = args.path.includes(`${path.sep}playwright${path.sep}src${path.sep}`);
+ const hasAlias = isPlaywrightSrc && (contents.includes("'@isomorphic/") || contents.includes("'@serverUtils/"));
+ if (!hasAwaitImport && !hasAlias)
return undefined;
- return {
- contents: contents.replace(
+ if (hasAwaitImport) {
+ contents = contents.replace(
/\bawait import\((['"]\..*?['"])\)/g,
(_, specifier) => `require(${specifier})`
- ),
- loader: 'ts',
- };
+ );
+ }
+ if (hasAlias) {
+ contents = contents.replace(
+ /import\s*\{([^}]*)\}\s*from\s*'@isomorphic\/[^']+';?/g,
+ (_, names) => `const {${names}} = require('playwright-core/lib/coreBundle').iso;`
+ );
+ contents = contents.replace(
+ /import\s*\{([^}]*)\}\s*from\s*'@serverUtils\/[^']+';?/g,
+ (_, names) => `const {${names}} = require('playwright-core/lib/coreBundle').serverUtils;`
+ );
+ }
+ return { contents, loader: 'ts' };
});
}
};
diff --git a/utils/check_deps.js b/utils/check_deps.js
index 9ba0e23265..269522d742 100644
--- a/utils/check_deps.js
+++ b/utils/check_deps.js
@@ -29,6 +29,7 @@ const packages = new Map();
packages.set('web', packagesDir + '/web/src/');
packages.set('injected', packagesDir + '/injected/src/');
packages.set('isomorphic', packagesDir + '/playwright-core/src/utils/isomorphic/');
+packages.set('serverUtils', packagesDir + '/playwright-core/src/server/utils/');
packages.set('testIsomorphic', packagesDir + '/playwright/src/isomorphic/');
const peerDependencies = ['electron', 'react', 'react-dom', 'react-dom/client', '@zip.js/zip.js', 'zod', 'zod/v3'];