Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore: split ContextRecorder from inspector (#9250)
Dmitry Gozmanf3648a66a3f5
diff --git a/src/server/supplements/recorderSupplement.ts b/src/server/supplements/recorderSupplement.tsindex 9a233ddd44..07138f4b08 100644--- a/src/server/supplements/recorderSupplement.ts+++ b/src/server/supplements/recorderSupplement.ts@@ -35,28 +35,23 @@ import { CallLog, CallLogStatus, EventData, Mode, Source, UIState } from './recoimport { createGuid, isUnderTest, monotonicTime } from '../../utils/utils';import { metadataToCallLog } from './recorder/recorderUtils';import { Debugger } from './debugger';+import { EventEmitter } from 'events';type BindingSource = { frame: Frame, page: Page };const symbol = Symbol('RecorderSupplement');export class RecorderSupplement implements InstrumentationListener {- private _generator: CodeGenerator;- private _pageAliases = new Map<Page, string>();- private _lastPopupOrdinal = 0;- private _lastDialogOrdinal = 0;- private _lastDownloadOrdinal = 0;- private _timers = new Set<NodeJS.Timeout>();private _context: BrowserContext;private _mode: Mode;private _highlightedSelector = '';private _recorderApp: RecorderApp | null = null;- private _params: channels.BrowserContextRecorderSupplementEnableParams;private _currentCallsMetadata = new Map<CallMetadata, SdkObject>();- private _recorderSources: Source[];+ private _recorderSources: Source[] = [];private _userSources = new Map<string, Source>();private _allMetadatas = new Map<string, CallMetadata>();private _debugger: Debugger;+ private _contextRecorder: ContextRecorder;static showInspector(context: BrowserContext) {RecorderSupplement.show(context, {}).catch(() => {});@@ -73,59 +68,11 @@ export class RecorderSupplement implements InstrumentationListener {}constructor(context: BrowserContext, params: channels.BrowserContextRecorderSupplementEnableParams) {+ this._mode = params.startRecording ? 'recording' : 'none';+ this._contextRecorder = new ContextRecorder(context, params);this._context = context;this._debugger = Debugger.lookup(context)!;context.instrumentation.addListener(this);- this._params = params;- this._mode = params.startRecording ? 'recording' : 'none';- const language = params.language || context._browser.options.sdkLanguage;-- const languages = new Set([- new JavaLanguageGenerator(),- new JavaScriptLanguageGenerator(false),- new JavaScriptLanguageGenerator(true),- new PythonLanguageGenerator(false),- new PythonLanguageGenerator(true),- new CSharpLanguageGenerator(),- ]);- const primaryLanguage = [...languages].find(l => l.id === language)!;- if (!primaryLanguage)- throw new Error(`\n===============================\nUnsupported language: '${language}'\n===============================\n`);-- languages.delete(primaryLanguage);- const orderedLanguages = [primaryLanguage, ...languages];-- this._recorderSources = [];- const generator = new CodeGenerator(context._browser.options.name, !!params.startRecording, params.launchOptions || {}, params.contextOptions || {}, params.device, params.saveStorage);- let text = '';- generator.on('change', () => {- this._recorderSources = [];- for (const languageGenerator of orderedLanguages) {- const source: Source = {- file: languageGenerator.fileName,- text: generator.generateText(languageGenerator),- language: languageGenerator.highlighter,- highlight: []- };- source.revealLine = source.text.split('\n').length - 1;- this._recorderSources.push(source);- if (languageGenerator === orderedLanguages[0])- text = source.text;- }- this._pushAllSources();- this._recorderApp?.setFile(primaryLanguage.fileName);- });- if (params.outputFile) {- context.on(BrowserContext.Events.BeforeClose, () => {- fs.writeFileSync(params.outputFile!, text);- text = '';- });- process.on('exit', () => {- if (text)- fs.writeFileSync(params.outputFile!, text);- });- }- this._generator = generator;}async install() {@@ -159,7 +106,7 @@ export class RecorderSupplement implements InstrumentationListener {return;}if (data.event === 'clear') {- this._clearScript();+ this._contextRecorder.clearScript();return;}});@@ -170,25 +117,15 @@ export class RecorderSupplement implements InstrumentationListener {this._pushAllSources()]);- this._context.on(BrowserContext.Events.Page, page => this._onPage(page));- for (const page of this._context.pages())- this._onPage(page);-this._context.once(BrowserContext.Events.Close, () => {- for (const timer of this._timers)- clearTimeout(timer);- this._timers.clear();+ this._contextRecorder.dispose();recorderApp.close().catch(() => {});});-- // Input actions that potentially lead to navigation are intercepted on the page and are- // performed by the Playwright.- await this._context.exposeBinding('_playwrightRecorderPerformAction', false,- (source: BindingSource, action: actions.Action) => this._performAction(source.frame, action));-- // Other non-essential actions are simply being recorded.- await this._context.exposeBinding('_playwrightRecorderRecordAction', false,- (source: BindingSource, action: actions.Action) => this._recordAction(source.frame, action));+ this._contextRecorder.on(ContextRecorder.Events.Change, (data: { sources: Source[], primaryFileName: string }) => {+ this._recorderSources = data.sources;+ this._pushAllSources();+ this._recorderApp?.setFile(data.primaryFileName);+ });await this._context.exposeBinding('_playwrightRecorderState', false, source => {let actionSelector = this._highlightedSelector;@@ -216,10 +153,10 @@ export class RecorderSupplement implements InstrumentationListener {await this._context.exposeBinding('_playwrightResume', false, () => {this._debugger.resume(false);});-- await this._context.extendInjectedScript(recorderSource.source, { isUnderTest: isUnderTest() });await this._context.extendInjectedScript(consoleApiSource.source);+ await this._contextRecorder.install();+if (this._debugger.isPaused())this._pausedStateChanged();this._debugger.on(Debugger.Events.PausedStateChanged, () => this._pausedStateChanged());@@ -241,8 +178,8 @@ export class RecorderSupplement implements InstrumentationListener {private _setMode(mode: Mode) {this._mode = mode;this._recorderApp?.setMode(this._mode);- this._generator.setEnabled(this._mode === 'recording');- Debugger.lookup(this._context)!.setMuted(this._mode === 'recording');+ this._contextRecorder.setEnabled(this._mode === 'recording');+ this._debugger.setMuted(this._mode === 'recording');if (this._mode !== 'none')this._context.pages()[0].bringToFront().catch(() => {});}@@ -252,6 +189,193 @@ export class RecorderSupplement implements InstrumentationListener {page.mainFrame().evaluateExpression('window._playwrightRefreshOverlay()', false, undefined, 'main').catch(() => {});}+ async onBeforeCall(sdkObject: SdkObject, metadata: CallMetadata) {+ if (this._mode === 'recording')+ return;+ this._currentCallsMetadata.set(metadata, sdkObject);+ this._allMetadatas.set(metadata.id, metadata);+ this._updateUserSources();+ this.updateCallLog([metadata]);+ if (metadata.params && metadata.params.selector) {+ this._highlightedSelector = metadata.params.selector;+ this._recorderApp?.setSelector(this._highlightedSelector).catch(() => {});+ }+ }++ async onAfterCall(sdkObject: SdkObject, metadata: CallMetadata) {+ if (this._mode === 'recording')+ return;+ if (!metadata.error)+ this._currentCallsMetadata.delete(metadata);+ this._updateUserSources();+ this.updateCallLog([metadata]);+ }++ private _updateUserSources() {+ // Remove old decorations.+ for (const source of this._userSources.values()) {+ source.highlight = [];+ source.revealLine = undefined;+ }++ // Apply new decorations.+ let fileToSelect = undefined;+ for (const metadata of this._currentCallsMetadata.keys()) {+ if (!metadata.stack || !metadata.stack[0])+ continue;+ const { file, line } = metadata.stack[0];+ let source = this._userSources.get(file);+ if (!source) {+ source = { file, text: this._readSource(file), highlight: [], language: languageForFile(file) };+ this._userSources.set(file, source);+ }+ if (line) {+ const paused = this._debugger.isPaused(metadata);+ source.highlight.push({ line, type: metadata.error ? 'error' : (paused ? 'paused' : 'running') });+ source.revealLine = line;+ fileToSelect = source.file;+ }+ }+ this._pushAllSources();+ if (fileToSelect)+ this._recorderApp?.setFile(fileToSelect);+ }++ private _pushAllSources() {+ this._recorderApp?.setSources([...this._recorderSources, ...this._userSources.values()]);+ }++ async onBeforeInputAction(sdkObject: SdkObject, metadata: CallMetadata) {+ }++ async onCallLog(logName: string, message: string, sdkObject: SdkObject, metadata: CallMetadata): Promise<void> {+ this.updateCallLog([metadata]);+ }++ updateCallLog(metadatas: CallMetadata[]) {+ if (this._mode === 'recording')+ return;+ const logs: CallLog[] = [];+ for (const metadata of metadatas) {+ if (!metadata.method)+ continue;+ let status: CallLogStatus = 'done';+ if (this._currentCallsMetadata.has(metadata))+ status = 'in-progress';+ if (this._debugger.isPaused(metadata))+ status = 'paused';+ logs.push(metadataToCallLog(metadata, status));+ }+ this._recorderApp?.updateCallLogs(logs);+ }++ private _readSource(fileName: string): string {+ try {+ return fs.readFileSync(fileName, 'utf-8');+ } catch (e) {+ return '// No source available';+ }+ }+}++class ContextRecorder extends EventEmitter {+ static Events = {+ Change: 'change'+ };++ private _generator: CodeGenerator;+ private _pageAliases = new Map<Page, string>();+ private _lastPopupOrdinal = 0;+ private _lastDialogOrdinal = 0;+ private _lastDownloadOrdinal = 0;+ private _timers = new Set<NodeJS.Timeout>();+ private _context: BrowserContext;+ private _params: channels.BrowserContextRecorderSupplementEnableParams;+ private _recorderSources: Source[];++ constructor(context: BrowserContext, params: channels.BrowserContextRecorderSupplementEnableParams) {+ super();+ this._context = context;+ this._params = params;+ const language = params.language || context._browser.options.sdkLanguage;++ const languages = new Set([+ new JavaLanguageGenerator(),+ new JavaScriptLanguageGenerator(false),+ new JavaScriptLanguageGenerator(true),+ new PythonLanguageGenerator(false),+ new PythonLanguageGenerator(true),+ new CSharpLanguageGenerator(),+ ]);+ const primaryLanguage = [...languages].find(l => l.id === language)!;+ if (!primaryLanguage)+ throw new Error(`\n===============================\nUnsupported language: '${language}'\n===============================\n`);++ languages.delete(primaryLanguage);+ const orderedLanguages = [primaryLanguage, ...languages];++ this._recorderSources = [];+ const generator = new CodeGenerator(context._browser.options.name, !!params.startRecording, params.launchOptions || {}, params.contextOptions || {}, params.device, params.saveStorage);+ let text = '';+ generator.on('change', () => {+ this._recorderSources = [];+ for (const languageGenerator of orderedLanguages) {+ const source: Source = {+ file: languageGenerator.fileName,+ text: generator.generateText(languageGenerator),+ language: languageGenerator.highlighter,+ highlight: []+ };+ source.revealLine = source.text.split('\n').length - 1;+ this._recorderSources.push(source);+ if (languageGenerator === orderedLanguages[0])+ text = source.text;+ }+ this.emit(ContextRecorder.Events.Change, {+ sources: this._recorderSources,+ primaryFileName: primaryLanguage.fileName+ });+ });+ if (params.outputFile) {+ context.on(BrowserContext.Events.BeforeClose, () => {+ fs.writeFileSync(params.outputFile!, text);+ text = '';+ });+ process.on('exit', () => {+ if (text)+ fs.writeFileSync(params.outputFile!, text);+ });+ }+ this._generator = generator;+ }++ async install() {+ this._context.on(BrowserContext.Events.Page, page => this._onPage(page));+ for (const page of this._context.pages())+ this._onPage(page);++ // Input actions that potentially lead to navigation are intercepted on the page and are+ // performed by the Playwright.+ await this._context.exposeBinding('_playwrightRecorderPerformAction', false,+ (source: BindingSource, action: actions.Action) => this._performAction(source.frame, action));++ // Other non-essential actions are simply being recorded.+ await this._context.exposeBinding('_playwrightRecorderRecordAction', false,+ (source: BindingSource, action: actions.Action) => this._recordAction(source.frame, action));++ await this._context.extendInjectedScript(recorderSource.source, { isUnderTest: isUnderTest() });+ }++ setEnabled(enabled: boolean) {+ this._generator.setEnabled(enabled);+ }++ dispose() {+ for (const timer of this._timers)+ clearTimeout(timer);+ this._timers.clear();+ }+private async _onPage(page: Page) {// First page is called page, others are called popup1, popup2, etc.const frame = page.mainFrame();@@ -290,7 +414,7 @@ export class RecorderSupplement implements InstrumentationListener {}}- private _clearScript(): void {+ clearScript(): void {this._generator.restart();if (!!this._params.startRecording) {for (const page of this._context.pages())@@ -389,6 +513,7 @@ export class RecorderSupplement implements InstrumentationListener {const popupAlias = this._pageAliases.get(popup)!;this._generator.signal(pageAlias, page.mainFrame(), { name: 'popup', popupAlias });}+private _onDownload(page: Page) {const pageAlias = this._pageAliases.get(page)!;this._generator.signal(pageAlias, page.mainFrame(), { name: 'download', downloadAlias: String(++this._lastDownloadOrdinal) });@@ -398,94 +523,6 @@ export class RecorderSupplement implements InstrumentationListener {const pageAlias = this._pageAliases.get(page)!;this._generator.signal(pageAlias, page.mainFrame(), { name: 'dialog', dialogAlias: String(++this._lastDialogOrdinal) });}-- async onBeforeCall(sdkObject: SdkObject, metadata: CallMetadata) {- if (this._mode === 'recording')- return;- this._currentCallsMetadata.set(metadata, sdkObject);- this._allMetadatas.set(metadata.id, metadata);- this._updateUserSources();- this.updateCallLog([metadata]);- if (metadata.params && metadata.params.selector) {- this._highlightedSelector = metadata.params.selector;- this._recorderApp?.setSelector(this._highlightedSelector).catch(() => {});- }- }-- async onAfterCall(sdkObject: SdkObject, metadata: CallMetadata) {- if (this._mode === 'recording')- return;- if (!metadata.error)- this._currentCallsMetadata.delete(metadata);- this._updateUserSources();- this.updateCallLog([metadata]);- }-- private _updateUserSources() {- // Remove old decorations.- for (const source of this._userSources.values()) {- source.highlight = [];- source.revealLine = undefined;- }-- // Apply new decorations.- let fileToSelect = undefined;- for (const metadata of this._currentCallsMetadata.keys()) {- if (!metadata.stack || !metadata.stack[0])- continue;- const { file, line } = metadata.stack[0];- let source = this._userSources.get(file);- if (!source) {- source = { file, text: this._readSource(file), highlight: [], language: languageForFile(file) };- this._userSources.set(file, source);- }- if (line) {- const paused = this._debugger.isPaused(metadata);- source.highlight.push({ line, type: metadata.error ? 'error' : (paused ? 'paused' : 'running') });- source.revealLine = line;- fileToSelect = source.file;- }- }- this._pushAllSources();- if (fileToSelect)- this._recorderApp?.setFile(fileToSelect);- }-- private _pushAllSources() {- this._recorderApp?.setSources([...this._recorderSources, ...this._userSources.values()]);- }-- async onBeforeInputAction(sdkObject: SdkObject, metadata: CallMetadata) {- }-- async onCallLog(logName: string, message: string, sdkObject: SdkObject, metadata: CallMetadata): Promise<void> {- this.updateCallLog([metadata]);- }-- updateCallLog(metadatas: CallMetadata[]) {- if (this._mode === 'recording')- return;- const logs: CallLog[] = [];- for (const metadata of metadatas) {- if (!metadata.method)- continue;- let status: CallLogStatus = 'done';- if (this._currentCallsMetadata.has(metadata))- status = 'in-progress';- if (this._debugger.isPaused(metadata))- status = 'paused';- logs.push(metadataToCallLog(metadata, status));- }- this._recorderApp?.updateCallLogs(logs);- }-- private _readSource(fileName: string): string {- try {- return fs.readFileSync(fileName, 'utf-8');- } catch (e) {- return '// No source available';- }- }}function languageForFile(file: string) {