| // Copyright 2022 The Chromium Authors | |
| // Use of this source code is governed by a BSD-style license that can be | |
| // found in the LICENSE file. | |
| import {assert} from 'chai'; | |
| import {assertNotNullOrUndefined} from '../core/platform/platform.js'; | |
| import * as ProtocolClient from '../core/protocol_client/protocol_client.js'; | |
| import * as SDK from '../core/sdk/sdk.js'; | |
| import * as Protocol from '../generated/protocol.js'; | |
| import {type CommandHandlerResponse, MockCDPConnection} from './MockCDPConnection.js'; | |
| import type {LoadResult} from './SourceMapHelpers.js'; | |
| import {createTarget} from './TargetHelpers.js'; | |
| import {TestUniverse} from './TestUniverse.js'; | |
| interface ScriptDescription { | |
| url: string; | |
| content: string; | |
| hasSourceURL?: boolean; | |
| startLine?: number; | |
| startColumn?: number; | |
| isContentScript?: boolean; | |
| embedderName?: string; | |
| executionContextId?: number; | |
| scriptLanguage?: Protocol.Debugger.ScriptLanguage; | |
| } | |
| interface ScopePosition { | |
| type: Protocol.Debugger.ScopeType; | |
| startLine: number; | |
| startColumn: number; | |
| endLine: number; | |
| endColumn: number; | |
| } | |
| function scopePositionFromOffsets( | |
| descriptor: string, type: Protocol.Debugger.ScopeType, startOffset: number, endOffset: number): ScopePosition { | |
| return { | |
| type, | |
| startLine: descriptor.substring(0, startOffset).replace(/[^\n]/g, '').length, | |
| endLine: descriptor.substring(0, endOffset).replace(/[^\n]/g, '').length, | |
| startColumn: startOffset - descriptor.lastIndexOf('\n', startOffset - 1) - 1, | |
| endColumn: endOffset - descriptor.lastIndexOf('\n', endOffset - 1) - 1, | |
| }; | |
| } | |
| export function parseScopeChain(scopeDescriptor: string): ScopePosition[] { | |
| // Identify function scope. | |
| const functionStart = scopeDescriptor.indexOf('{'); | |
| if (functionStart < 0) { | |
| throw new Error('Test descriptor must contain "{"'); | |
| } | |
| const functionEnd = scopeDescriptor.indexOf('}', functionStart); | |
| if (functionEnd < 0) { | |
| throw new Error('Test descriptor must contain "}"'); | |
| } | |
| const scopeChain = | |
| [scopePositionFromOffsets(scopeDescriptor, Protocol.Debugger.ScopeType.Local, functionStart, functionEnd + 1)]; | |
| // Find the block scope. | |
| const blockScopeStart = scopeDescriptor.indexOf('<'); | |
| if (blockScopeStart >= 0) { | |
| const blockScopeEnd = scopeDescriptor.indexOf('>'); | |
| if (blockScopeEnd < 0) { | |
| throw new Error('Test descriptor must contain matching ">" for "<"'); | |
| } | |
| scopeChain.unshift(scopePositionFromOffsets( | |
| scopeDescriptor, Protocol.Debugger.ScopeType.Block, blockScopeStart, blockScopeEnd + 1)); | |
| } | |
| // Find the closure scope. | |
| const closureScopeStart = scopeDescriptor.indexOf('['); | |
| if (closureScopeStart >= 0) { | |
| const closureScopeEnd = scopeDescriptor.indexOf(']'); | |
| if (closureScopeEnd < 0) { | |
| throw new Error('Test descriptor must contain matching "]" for "["'); | |
| } | |
| scopeChain.push(scopePositionFromOffsets(scopeDescriptor, Protocol.Debugger.ScopeType.Closure, closureScopeStart, | |
| closureScopeEnd + 1)); | |
| } | |
| return scopeChain; | |
| } | |
| interface SetBreakpointByUrlResponseHandler { | |
| response: Promise<CommandHandlerResponse<'Debugger.setBreakpointByUrl'>>; | |
| callback: () => void; | |
| isOneShot: boolean; | |
| } | |
| /** | |
| * Drop-in replacement for {@link MockProtocolBackend} but doesn't use any global state. | |
| * | |
| * Creates a new {@link TestUniverse}, accessible via `mockDebuggerBackend.universe`. | |
| */ | |
| export class MockDebuggerBackend { | |
| readonly universe: TestUniverse; | |
| /** The mock connection used for all targets created with this MockDebuggerBackend instance */ | |
| readonly cdpConnection: MockCDPConnection; | |
| readonly #scriptSources = new Map<string, string>(); | |
| readonly #sourceMapContents = new Map<string, string>(); | |
| readonly #objectProperties = new Map<string, Array<{name: string, value?: number}>>(); | |
| readonly #setBreakpointByUrlResponses = new Map<string, SetBreakpointByUrlResponseHandler>(); | |
| readonly #removeBreakpointCallbacks = new Map<Protocol.Debugger.BreakpointId, () => void>(); | |
| #nextObjectIndex = 0; | |
| #nextScriptIndex = 0; | |
| constructor() { | |
| this.universe = new TestUniverse({ | |
| pageResourceLoaderOptions: { | |
| loadOverride: async (url: string) => this.#loadSourceMap(url), | |
| }, | |
| }); | |
| this.cdpConnection = new MockCDPConnection(); | |
| this.cdpConnection.setHandler('Debugger.getScriptSource', this.#getScriptSourceHandler.bind(this)); | |
| this.cdpConnection.setHandler('Runtime.getProperties', this.#getPropertiesHandler.bind(this)); | |
| this.cdpConnection.setHandler('Debugger.setBreakpointByUrl', this.#setBreakpointByUrlHandler.bind(this)); | |
| this.cdpConnection.setSuccessHandler('Storage.getStorageKey', () => ({storageKey: 'test-key'})); | |
| this.cdpConnection.setHandler('Debugger.removeBreakpoint', this.#removeBreakpointHandler.bind(this)); | |
| this.cdpConnection.setSuccessHandler('Debugger.resume', () => ({})); | |
| this.cdpConnection.setSuccessHandler( | |
| 'Debugger.enable', () => ({debuggerId: 'DEBUGGER_ID' as Protocol.Runtime.UniqueDebuggerId})); | |
| this.cdpConnection.setSuccessHandler( | |
| 'Debugger.setInstrumentationBreakpoint', () => ({} as Protocol.Debugger.SetInstrumentationBreakpointResponse)); | |
| this.universe.pageResourceLoader; // Eagerly trigger creation. | |
| } | |
| createTarget(options?: Parameters<typeof createTarget>[0]): SDK.Target.Target { | |
| return createTarget({ | |
| ...options, | |
| targetManager: this.universe.targetManager, | |
| connection: Boolean(options?.parentTarget) ? undefined : this.cdpConnection, | |
| }); | |
| } | |
| dispatchDebuggerPause( | |
| script: SDK.Script.Script, reason: Protocol.Debugger.PausedEventReason, functionName = '', | |
| scopeChain: Protocol.Debugger.Scope[] = []): void { | |
| const target = script.debuggerModel.target(); | |
| if (reason === Protocol.Debugger.PausedEventReason.Instrumentation) { | |
| // Instrumentation pauses don't pass call frames, they only pass the script id in the 'data' field. | |
| this.cdpConnection.dispatchEvent( | |
| 'Debugger.paused', | |
| { | |
| callFrames: [], | |
| reason, | |
| data: {scriptId: script.scriptId}, | |
| }, | |
| target.sessionId, | |
| ); | |
| } else { | |
| const callFrames: Protocol.Debugger.CallFrame[] = [ | |
| { | |
| callFrameId: '1' as Protocol.Debugger.CallFrameId, | |
| functionName, | |
| url: script.sourceURL, | |
| scopeChain, | |
| location: { | |
| scriptId: script.scriptId, | |
| lineNumber: 0, | |
| }, | |
| this: {type: 'object'} as Protocol.Runtime.RemoteObject, | |
| }, | |
| ]; | |
| this.cdpConnection.dispatchEvent( | |
| 'Debugger.paused', | |
| { | |
| callFrames, | |
| reason, | |
| }, | |
| target.sessionId, | |
| ); | |
| } | |
| } | |
| dispatchDebuggerPauseWithNoCallFrames(target: SDK.Target.Target, reason: Protocol.Debugger.PausedEventReason): void { | |
| this.cdpConnection.dispatchEvent( | |
| 'Debugger.paused', | |
| { | |
| callFrames: [], | |
| reason, | |
| }, | |
| target.sessionId, | |
| ); | |
| } | |
| async addScript(target: SDK.Target.Target, scriptDescription: ScriptDescription, sourceMap: { | |
| url: string, | |
| content: string|SDK.SourceMap.SourceMapV3, | |
| }|null): Promise<SDK.Script.Script> { | |
| const scriptId = 'SCRIPTID.' + this.#nextScriptIndex++; | |
| this.#scriptSources.set(scriptId, scriptDescription.content); | |
| const startLine = scriptDescription.startLine ?? 0; | |
| const startColumn = scriptDescription.startColumn ?? 0; | |
| const endLine = startLine + (scriptDescription.content.match(/^/gm)?.length ?? 1) - 1; | |
| let endColumn = scriptDescription.content.length - scriptDescription.content.lastIndexOf('\n') - 1; | |
| if (startLine === endLine) { | |
| endColumn += startColumn; | |
| } | |
| this.cdpConnection.dispatchEvent('Debugger.scriptParsed', { | |
| scriptId: scriptId as Protocol.Runtime.ScriptId, | |
| url: scriptDescription.url, | |
| startLine, | |
| startColumn, | |
| endLine, | |
| endColumn, | |
| buildId: '', | |
| executionContextId: (scriptDescription?.executionContextId ?? 1) as Protocol.Runtime.ExecutionContextId, | |
| executionContextAuxData: {isDefault: !scriptDescription.isContentScript}, | |
| hash: '', | |
| hasSourceURL: Boolean(scriptDescription.hasSourceURL), | |
| ...(sourceMap ? {sourceMapURL: sourceMap.url} : null), | |
| embedderName: | |
| scriptDescription.embedderName ?? (scriptDescription.hasSourceURL ? undefined : scriptDescription.url), | |
| scriptLanguage: scriptDescription.scriptLanguage, | |
| }, | |
| target.sessionId); | |
| const debuggerModel = target.model(SDK.DebuggerModel.DebuggerModel) as SDK.DebuggerModel.DebuggerModel; | |
| const scriptObject = debuggerModel.scriptForId(scriptId); | |
| assertNotNullOrUndefined(scriptObject); | |
| if (sourceMap) { | |
| let {content} = sourceMap; | |
| if (typeof content !== 'string') { | |
| content = JSON.stringify(content); | |
| } | |
| this.#sourceMapContents.set(sourceMap.url, content); | |
| // Wait until the source map loads. | |
| const loadedSourceMap = await debuggerModel.sourceMapManager().sourceMapForClientPromise(scriptObject); | |
| assert.strictEqual(loadedSourceMap?.url() as string, sourceMap.url); | |
| } | |
| return scriptObject; | |
| } | |
| #createProtocolLocation(scriptId: string, lineNumber: number, columnNumber: number): Protocol.Debugger.Location { | |
| return {scriptId: scriptId as Protocol.Runtime.ScriptId, lineNumber, columnNumber}; | |
| } | |
| #createProtocolScope(type: Protocol.Debugger.ScopeType, object: Protocol.Runtime.RemoteObject, scriptId: string, | |
| startLine: number, startColumn: number, endLine: number, | |
| endColumn: number): Protocol.Debugger.Scope&{ | |
| startLocation: Protocol.Debugger.Location, | |
| endLocation: Protocol.Debugger.Location, | |
| } | |
| { | |
| return { | |
| type, | |
| object, | |
| startLocation: this.#createProtocolLocation(scriptId, startLine, startColumn), | |
| endLocation: this.#createProtocolLocation(scriptId, endLine, endColumn), | |
| }; | |
| } | |
| createSimpleRemoteObject(properties: Array<{name: string, value?: number}>): Protocol.Runtime.RemoteObject { | |
| const objectId = 'OBJECTID.' + this.#nextObjectIndex++; | |
| this.#objectProperties.set(objectId, properties); | |
| return {type: Protocol.Runtime.RemoteObjectType.Object, objectId: objectId as Protocol.Runtime.RemoteObjectId}; | |
| } | |
| // In the |scopeDescriptor|, '{' and '}' characters mark the positions of function | |
| // offset start and end, '<' and '>' mark the positions of the nested scope | |
| // start and end (if '<', '>' are missing then the nested scope is the function scope). | |
| // Other characters in |scopeDescriptor| are not significant (so that tests can use the other characters in | |
| // the descriptors to describe other assertions). | |
| // Positions in |scopeDescriptor| are relative to the script content. For inline scripts (i.e. scripts with | |
| // a `startLine` or `startColumn` but without a sourceURL), they are shifted into raw V8 positions, which | |
| // are relative to the start of the surrounding document. | |
| // |scopeObjects| and |emptyReasons| are index-aligned with the resulting scope chain (inner-most first). | |
| async createCallFrame(target: SDK.Target.Target, script: ScriptDescription, scopeDescriptor: string, | |
| sourceMap: {url: string, content: string}|null, | |
| scopeObjects: Protocol.Runtime.RemoteObject[] = [], | |
| emptyReasons: Array<Protocol.Debugger.ScopeEmptyReason|undefined> = []): | |
| Promise<SDK.DebuggerModel.CallFrame> { | |
| const debuggerModel = target.model(SDK.DebuggerModel.DebuggerModel) as SDK.DebuggerModel.DebuggerModel; | |
| const scriptObject = await this.addScript(target, script, sourceMap); | |
| const lineOffset = script.hasSourceURL ? 0 : script.startLine ?? 0; | |
| const columnOffset = script.hasSourceURL ? 0 : script.startColumn ?? 0; | |
| const toRawLine = (line: number): number => line + lineOffset; | |
| const toRawColumn = (line: number, column: number): number => line === 0 ? column + columnOffset : column; | |
| const parsedScopes = parseScopeChain(scopeDescriptor); | |
| const scopeChain = parsedScopes.map( | |
| s => this.#createProtocolScope(s.type, {type: Protocol.Runtime.RemoteObjectType.Object}, scriptObject.scriptId, | |
| toRawLine(s.startLine), toRawColumn(s.startLine, s.startColumn), | |
| toRawLine(s.endLine), toRawColumn(s.endLine, s.endColumn))); | |
| const innerScope = scopeChain[0]; | |
| assert.isAtMost(scopeObjects.length, scopeChain.length); | |
| for (let i = 0; i < scopeObjects.length; ++i) { | |
| scopeChain[i].object = scopeObjects[i]; | |
| } | |
| assert.isAtMost(emptyReasons.length, scopeChain.length); | |
| for (let i = 0; i < emptyReasons.length; ++i) { | |
| const emptyReason = emptyReasons[i]; | |
| if (emptyReason !== undefined) { | |
| scopeChain[i].emptyReason = emptyReason; | |
| } | |
| } | |
| const payload: Protocol.Debugger.CallFrame = { | |
| callFrameId: '0' as Protocol.Debugger.CallFrameId, | |
| functionName: 'test', | |
| location: innerScope.startLocation, | |
| url: scriptObject.sourceURL, | |
| scopeChain, | |
| this: {type: 'object'} as Protocol.Runtime.RemoteObject, | |
| canBeRestarted: false, | |
| }; | |
| return new SDK.DebuggerModel.CallFrame(debuggerModel, scriptObject, payload, 0); | |
| } | |
| #getBreakpointKey(url: string, lineNumber: number): string { | |
| return url + '@:' + lineNumber; | |
| } | |
| responderToBreakpointByUrlRequest(url: string, lineNumber: number): | |
| (response: CommandHandlerResponse<'Debugger.setBreakpointByUrl'>| | |
| ProtocolClient.CDPConnection.CommandResult<'Debugger.setBreakpointByUrl'>) => Promise<void> { | |
| const {promise: responsePromise, resolve: responseCallback} = | |
| Promise.withResolvers<CommandHandlerResponse<'Debugger.setBreakpointByUrl'>>(); | |
| const {promise: requestPromise, resolve: requestCallback} = Promise.withResolvers<void>(); | |
| const key = this.#getBreakpointKey(url, lineNumber); | |
| this.#setBreakpointByUrlResponses.set(key, {response: responsePromise, callback: requestCallback, isOneShot: true}); | |
| return async (response: CommandHandlerResponse<'Debugger.setBreakpointByUrl'>| | |
| ProtocolClient.CDPConnection.CommandResult<'Debugger.setBreakpointByUrl'>) => { | |
| if ('result' in response || 'error' in response) { | |
| responseCallback(response as CommandHandlerResponse<'Debugger.setBreakpointByUrl'>); | |
| } else { | |
| responseCallback( | |
| {result: response as ProtocolClient.CDPConnection.CommandResult<'Debugger.setBreakpointByUrl'>}); | |
| } | |
| await requestPromise; | |
| }; | |
| } | |
| setBreakpointByUrlToFail(url: string, lineNumber: number): void { | |
| const key = this.#getBreakpointKey(url, lineNumber); | |
| const responsePromise = Promise.resolve(serverError('Breakpoint error')); | |
| this.#setBreakpointByUrlResponses.set(key, {response: responsePromise, callback: () => {}, isOneShot: false}); | |
| } | |
| breakpointRemovedPromise(breakpointId: Protocol.Debugger.BreakpointId): Promise<void> { | |
| return new Promise<void>(resolve => this.#removeBreakpointCallbacks.set(breakpointId, resolve)); | |
| } | |
| #getScriptSourceHandler(request: Protocol.Debugger.GetScriptSourceRequest): | |
| CommandHandlerResponse<'Debugger.getScriptSource'> { | |
| const scriptSource = this.#scriptSources.get(request.scriptId); | |
| if (scriptSource) { | |
| return {result: {scriptSource}}; | |
| } | |
| return serverError('Unknown script'); | |
| } | |
| #setBreakpointByUrlHandler(request: Protocol.Debugger.SetBreakpointByUrlRequest): | |
| Promise<CommandHandlerResponse<'Debugger.setBreakpointByUrl'>> { | |
| const key = this.#getBreakpointKey(request.url ?? '', request.lineNumber); | |
| const responseCallback = this.#setBreakpointByUrlResponses.get(key); | |
| if (responseCallback) { | |
| if (responseCallback.isOneShot) { | |
| this.#setBreakpointByUrlResponses.delete(key); | |
| } | |
| // Announce to the client that the breakpoint request arrived. | |
| responseCallback.callback(); | |
| // Return the response promise. | |
| return responseCallback.response; | |
| } | |
| console.error('Unexpected setBreakpointByUrl request', request); | |
| return Promise.resolve(serverError('Unknown breakpoint')); | |
| } | |
| #removeBreakpointHandler(request: Protocol.Debugger.RemoveBreakpointRequest): | |
| CommandHandlerResponse<'Debugger.removeBreakpoint'> { | |
| const callback = this.#removeBreakpointCallbacks.get(request.breakpointId); | |
| if (callback) { | |
| callback(); | |
| } | |
| return {result: {}}; | |
| } | |
| #getPropertiesHandler(request: Protocol.Runtime.GetPropertiesRequest) { | |
| const objectProperties = this.#objectProperties.get(request.objectId as string); | |
| if (!objectProperties) { | |
| return {result: {result: []}}; | |
| } | |
| const result: Protocol.Runtime.PropertyDescriptor[] = []; | |
| for (const property of objectProperties) { | |
| result.push({ | |
| name: property.name, | |
| value: { | |
| type: Protocol.Runtime.RemoteObjectType.Number, | |
| value: property.value, | |
| description: `${property.value}`, | |
| }, | |
| writable: true, | |
| configurable: true, | |
| enumerable: true, | |
| isOwn: true, | |
| }); | |
| } | |
| return {result: {result}}; | |
| } | |
| #loadSourceMap(url: string): LoadResult { | |
| const content = this.#sourceMapContents.get(url); | |
| if (!content) { | |
| return { | |
| success: false, | |
| content: '', | |
| errorDescription: | |
| {message: 'source map not found', statusCode: 123, netError: 0, netErrorName: '', urlValid: true}, | |
| }; | |
| } | |
| return { | |
| success: true, | |
| content, | |
| errorDescription: {message: '', statusCode: 0, netError: 0, netErrorName: '', urlValid: true}, | |
| }; | |
| } | |
| } | |
| function serverError(message: string): {error: ProtocolClient.CDPConnection.CDPError} { | |
| return { | |
| error: { | |
| code: ProtocolClient.CDPConnection.CDPErrorStatus.SERVER_ERROR, | |
| message, | |
| }, | |
| }; | |
| } |