forked from ChromeDevTools/devtools-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsources-helpers.ts
947 lines (825 loc) · 35.3 KB
/
sources-helpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
// Copyright 2020 The Chromium Authors. All rights reserved.
// 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 * as fs from 'fs';
import * as path from 'path';
import type * as puppeteer from 'puppeteer-core';
import {GEN_DIR} from '../../conductor/paths.js';
import {
$,
$$,
assertNotNullOrUndefined,
click,
clickElement,
clickMoreTabsButton,
getBrowserAndPages,
getPendingEvents,
getTestServerPort,
goToResource,
pasteText,
platform,
pressKey,
setCheckBox,
step,
timeout,
typeText,
waitFor,
waitForAria,
waitForFunction,
waitForFunctionWithTries,
waitForVisible,
} from '../../shared/helper.js';
import {openSoftContextMenuAndClickOnItem} from './context-menu-helpers.js';
import {veImpression} from './visual-logging-helpers.js';
export const ACTIVE_LINE = '.CodeMirror-activeline > pre > span';
export const PAUSE_BUTTON = '[aria-label="Pause script execution"]';
export const RESUME_BUTTON = '[aria-label="Resume script execution"]';
export const SOURCES_LINES_SELECTOR = '.CodeMirror-code > div';
export const PAUSE_INDICATOR_SELECTOR = '.paused-status';
export const CODE_LINE_COLUMN_SELECTOR = '.cm-lineNumbers';
export const CODE_LINE_SELECTOR = '.cm-lineNumbers .cm-gutterElement';
export const SCOPE_LOCAL_VALUES_SELECTOR = 'li[aria-label="Local"] + ol';
export const THREADS_SELECTOR = '[aria-label="Threads"]';
export const SELECTED_THREAD_SELECTOR = 'div.thread-item.selected > div.thread-item-title';
export const STEP_INTO_BUTTON = '[aria-label="Step into next function call"]';
export const STEP_OVER_BUTTON = '[aria-label="Step over next function call"]';
export const STEP_OUT_BUTTON = '[aria-label="Step out of current function"]';
export const TURNED_ON_PAUSE_BUTTON_SELECTOR = 'button.toolbar-state-on';
export const DEBUGGER_PAUSED_EVENT = 'DevTools.DebuggerPaused';
const WATCH_EXPRESSION_VALUE_SELECTOR = '.watch-expression-tree-item .object-value-string.value';
export const OVERRIDES_TAB_SELECTOR = '[aria-label="Overrides"]';
export const ENABLE_OVERRIDES_SELECTOR = '[aria-label="Select folder for overrides"]';
const CLEAR_CONFIGURATION_SELECTOR = '[aria-label="Clear configuration"]';
export const PAUSE_ON_UNCAUGHT_EXCEPTION_SELECTOR = '.pause-on-uncaught-exceptions';
export const BREAKPOINT_ITEM_SELECTOR = '.breakpoint-item';
export async function toggleNavigatorSidebar(frontend: puppeteer.Page) {
const modifierKey = platform === 'mac' ? 'Meta' : 'Control';
await frontend.keyboard.down(modifierKey);
await frontend.keyboard.down('Shift');
await frontend.keyboard.press('y');
await frontend.keyboard.up('Shift');
await frontend.keyboard.up(modifierKey);
}
export async function toggleDebuggerSidebar(frontend: puppeteer.Page) {
const modifierKey = platform === 'mac' ? 'Meta' : 'Control';
await frontend.keyboard.down(modifierKey);
await frontend.keyboard.down('Shift');
await frontend.keyboard.press('h');
await frontend.keyboard.up('Shift');
await frontend.keyboard.up(modifierKey);
}
export async function getLineNumberElement(lineNumber: number|string) {
const visibleLines = await $$(CODE_LINE_SELECTOR);
for (let i = 0; i < visibleLines.length; i++) {
const lineValue = await visibleLines[i].evaluate(node => node.textContent);
if (lineValue === `${lineNumber}`) {
return visibleLines[i];
}
}
return null;
}
export async function doubleClickSourceTreeItem(selector: string) {
await click(selector, {clickOptions: {clickCount: 2, offset: {x: 40, y: 10}}});
}
export async function waitForSourcesPanel(): Promise<void> {
// Wait for the navigation panel to show up
await waitFor('.navigator-file-tree-item, .empty-state');
}
export async function openSourcesPanel() {
// Locate the button for switching to the sources tab.
await click('#tab-sources');
await waitForSourcesPanel();
}
export async function openFileInSourcesPanel(testInput: string) {
await goToResource(`sources/${testInput}`);
await openSourcesPanel();
}
export async function openRecorderSubPane() {
const root = await waitFor('.navigator-tabbed-pane');
await clickMoreTabsButton(root);
await click('[aria-label="Recordings"]');
await waitFor('[aria-label="Add recording"]');
}
export async function createNewRecording(recordingName: string) {
const {frontend} = getBrowserAndPages();
await click('[aria-label="Add recording"]');
await waitFor('[aria-label^="Recording"]');
await typeText(recordingName);
await frontend.keyboard.press('Enter');
}
export async function openSnippetsSubPane() {
const root = await waitFor('.navigator-tabbed-pane');
await clickMoreTabsButton(root);
await click('[aria-label="Snippets"]');
await waitFor('[aria-label="New snippet"]');
}
/**
* Creates a new snippet, optionally pre-filling it with the provided content.
* `snippetName` must not contain spaces or special characters, otherwise
* `createNewSnippet` will time out.
* DevTools uses the escaped snippet name for the ARIA label. `createNewSnippet`
* doesn't mirror the escaping so it won't be able to wait for the snippet
* entry in the navigation tree to appear.
*/
export async function createNewSnippet(snippetName: string, content?: string) {
const {frontend} = getBrowserAndPages();
await click('[aria-label="New snippet"]');
await waitFor('[aria-label^="Script snippet"]');
await typeText(snippetName);
await frontend.keyboard.press('Enter');
await waitFor(`[aria-label*="${snippetName}"]`);
if (content) {
await pasteText(content);
await pressKey('s', {control: true});
}
}
export async function openWorkspaceSubPane() {
const root = await waitFor('.navigator-tabbed-pane');
await click('[aria-label="Workspace"]', {root});
await waitFor('[aria-label="Workspace panel"]');
}
export async function openOverridesSubPane() {
const root = await waitFor('.navigator-tabbed-pane');
await clickMoreTabsButton(root);
await click('[aria-label="Overrides"]');
await waitFor('[aria-label="Overrides panel"]');
}
export async function openFileInEditor(sourceFile: string) {
await waitForSourceFiles(
SourceFileEvents.SOURCE_FILE_LOADED, files => files.some(f => f.endsWith(sourceFile)),
// Open a particular file in the editor
() => doubleClickSourceTreeItem(`[aria-label="${sourceFile}, file"]`));
}
export async function openSourceCodeEditorForFile(sourceFile: string, testInput: string) {
await openFileInSourcesPanel(testInput);
await openFileInEditor(sourceFile);
}
export async function getSelectedSource(): Promise<string> {
const sourceTabPane = await waitFor('#sources-panel-sources-view .tabbed-pane');
const sourceTabs = await waitFor('.tabbed-pane-header-tab.selected', sourceTabPane);
return sourceTabs.evaluate(node => node.getAttribute('aria-label')) as Promise<string>;
}
export async function getBreakpointHitLocation() {
const breakpointHitHandle = await waitFor('.breakpoint-item.hit');
const locationHandle = await waitFor('.location', breakpointHitHandle);
const locationText = await locationHandle.evaluate(location => location.textContent);
const groupHandle = await breakpointHitHandle.evaluateHandle(x => x.parentElement);
const groupHeaderTitleHandle = await waitFor('.group-header-title', groupHandle);
const groupHeaderTitle = await groupHeaderTitleHandle?.evaluate(header => header.textContent);
return `${groupHeaderTitle}:${locationText}`;
}
export async function getOpenSources() {
const sourceTabPane = await waitFor('#sources-panel-sources-view .tabbed-pane');
const sourceTabs = await waitFor('.tabbed-pane-header-tabs', sourceTabPane);
const openSources =
await sourceTabs.$$eval('.tabbed-pane-header-tab', nodes => nodes.map(n => n.getAttribute('aria-label')));
return openSources;
}
export async function waitForHighlightedLine(lineNumber: number) {
await waitForFunction(async () => {
const selectedLine = await waitFor('.cm-highlightedLine');
const currentlySelectedLineNumber = await selectedLine.evaluate(line => {
return [...line.parentElement?.childNodes || []].indexOf(line);
});
const lineNumbers = await waitFor('.cm-lineNumbers');
const text = await lineNumbers.evaluate(
(node, lineNumber) => node.childNodes[lineNumber].textContent, currentlySelectedLineNumber + 1);
return Number(text) === lineNumber;
});
}
export async function getToolbarText() {
const toolbar = await waitFor('.sources-toolbar');
if (!toolbar) {
return [];
}
const textNodes = await $$('.toolbar-text', toolbar);
return Promise.all(textNodes.map(node => node.evaluate(node => node.textContent, node)));
}
export async function addBreakpointForLine(frontend: puppeteer.Page, index: number|string) {
const breakpointLine = await getLineNumberElement(index);
assertNotNullOrUndefined(breakpointLine);
await waitForFunction(async () => !(await isBreakpointSet(index)));
await clickElement(breakpointLine);
await waitForFunction(async () => await isBreakpointSet(index));
}
export async function removeBreakpointForLine(frontend: puppeteer.Page, index: number|string) {
const breakpointLine = await getLineNumberElement(index);
assertNotNullOrUndefined(breakpointLine);
await waitForFunction(async () => await isBreakpointSet(index));
await clickElement(breakpointLine);
await waitForFunction(async () => !(await isBreakpointSet(index)));
}
export async function addLogpointForLine(index: number, condition: string) {
const {frontend} = getBrowserAndPages();
const breakpointLine = await getLineNumberElement(index);
assertNotNullOrUndefined(breakpointLine);
await waitForFunction(async () => !(await isBreakpointSet(index)));
await clickElement(breakpointLine, {clickOptions: {button: 'right'}});
await click('aria/Add logpoint…');
const editDialog = await waitFor('.sources-edit-breakpoint-dialog');
const conditionEditor = await waitForAria('Code editor', editDialog);
await conditionEditor.focus();
await typeText(condition);
await frontend.keyboard.press('Enter');
await waitForFunction(async () => await isBreakpointSet(index));
}
export async function isBreakpointSet(lineNumber: number|string) {
const lineNumberElement = await getLineNumberElement(lineNumber);
const breakpointLineParentClasses = await lineNumberElement?.evaluate(n => n.className);
return breakpointLineParentClasses?.includes('cm-breakpoint');
}
/**
* @param lineNumber 1-based line number
* @param index 1-based index of the inline breakpoint in the given line
*/
export async function enableInlineBreakpointForLine(line: number, index: number) {
const {frontend} = getBrowserAndPages();
const decorationSelector = `pierce/.cm-content > :nth-child(${line}) > :nth-child(${index} of .cm-inlineBreakpoint)`;
await click(decorationSelector);
await waitForFunction(
() => frontend.$eval(decorationSelector, element => !element.classList.contains('cm-inlineBreakpoint-disabled')));
}
/**
* @param lineNumber 1-based line number
* @param index 1-based index of the inline breakpoint in the given line
* @param expectNoBreakpoint If we should wait for the line to not have any inline breakpoints after
* the click instead of a disabled one.
*/
export async function disableInlineBreakpointForLine(line: number, index: number, expectNoBreakpoint: boolean = false) {
const {frontend} = getBrowserAndPages();
const decorationSelector = `pierce/.cm-content > :nth-child(${line}) > :nth-child(${index} of .cm-inlineBreakpoint)`;
await click(decorationSelector);
if (expectNoBreakpoint) {
await waitForFunction(
() => frontend.$$eval(
`pierce/.cm-content > :nth-child(${line}) > .cm-inlineBreakpoint`, elements => elements.length === 0));
} else {
await waitForFunction(
() =>
frontend.$eval(decorationSelector, element => element.classList.contains('cm-inlineBreakpoint-disabled')));
}
}
export async function checkBreakpointDidNotActivate() {
await step('check that the script did not pause', async () => {
// TODO(almuthanna): make sure this check happens at a point where the pause indicator appears if it was active
const pauseIndicators = await $$(PAUSE_INDICATOR_SELECTOR);
const breakpointIndicator = await Promise.all(pauseIndicators.map(elements => {
return elements.evaluate(el => el.className);
}));
assert.lengthOf(breakpointIndicator, 0, 'script had been paused');
});
}
export async function getBreakpointDecorators(disabledOnly = false) {
const selector = `.cm-breakpoint${disabledOnly ? '-disabled' : ''}`;
const breakpointDecorators = await $$(selector);
return await Promise.all(
breakpointDecorators.map(breakpointDecorator => breakpointDecorator.evaluate(n => Number(n.textContent))));
}
export async function getNonBreakableLines() {
const selector = '.cm-nonBreakableLine';
await waitFor(selector);
const unbreakableLines = await $$(selector);
return await Promise.all(
unbreakableLines.map(unbreakableLine => unbreakableLine.evaluate(n => Number(n.textContent))));
}
export async function executionLineHighlighted() {
return await waitFor('.cm-executionLine');
}
export async function getCallFrameNames() {
const selector = '.call-frame-item:not(.hidden) .call-frame-item-title';
await waitFor(selector);
const items = await $$(selector);
const promises = items.map(handle => handle.evaluate(el => el.textContent as string));
const results = [];
for (const promise of promises) {
results.push(await promise);
}
return results;
}
export async function getCallFrameLocations() {
const selector = '.call-frame-item:not(.hidden) .call-frame-location';
await waitFor(selector);
const items = await $$(selector);
const promises = items.map(handle => handle.evaluate(el => el.textContent as string));
const results = [];
for (const promise of promises) {
results.push(await promise);
}
return results;
}
export async function switchToCallFrame(index: number) {
const selector = `.call-frame-item[aria-posinset="${index}"]`;
await click(selector);
await waitFor(selector + '[aria-selected="true"]');
}
export async function retrieveTopCallFrameScriptLocation(script: string, target: puppeteer.Page) {
// The script will run into a breakpoint, which means that it will not actually
// finish the evaluation, until we continue executing.
// Thus, we have to await it at a later point, while stepping through the code.
const scriptEvaluation = target.evaluate(script);
// Wait for the evaluation to be paused and shown in the UI
// and retrieve the top level call frame script location name
const scriptLocation = await retrieveTopCallFrameWithoutResuming();
// Resume the evaluation
await click(RESUME_BUTTON);
// Make sure to await the context evaluate before asserting
// Otherwise the Puppeteer process might crash on a failure assertion,
// as its execution context is destroyed
await scriptEvaluation;
return scriptLocation;
}
export async function retrieveTopCallFrameWithoutResuming() {
// Wait for the evaluation to be paused and shown in the UI
await waitFor(PAUSE_INDICATOR_SELECTOR);
// Retrieve the top level call frame script location name
const locationHandle = await waitFor('.call-frame-location');
const scriptLocation = await locationHandle.evaluate(location => location.textContent);
return scriptLocation;
}
export async function waitForStackTopMatch(matcher: RegExp) {
// The call stack is updated asynchronously, so let us wait until we see the correct one
// (or report the last one we have seen before timeout).
let stepLocation = '<no call stack>';
await waitForFunctionWithTries(async () => {
stepLocation = await retrieveTopCallFrameWithoutResuming() ?? '<invalid>';
return stepLocation?.match(matcher);
}, {tries: 10});
return stepLocation;
}
export async function setEventListenerBreakpoint(groupName: string, eventName: string) {
const {frontend} = getBrowserAndPages();
const eventListenerBreakpointsSection = await waitForAria('Event Listener Breakpoints');
const expanded = await eventListenerBreakpointsSection.evaluate(el => el.getAttribute('aria-expanded'));
if (expanded !== 'true') {
await click('[aria-label="Event Listener Breakpoints"]');
await waitFor('[aria-label="Event Listener Breakpoints"][aria-expanded="true"]');
}
const eventSelector = `input[type="checkbox"][title="${eventName}"]`;
const groupSelector = `input[type="checkbox"][title="${groupName}"]`;
const groupCheckbox = await waitFor(groupSelector);
await waitForVisible(groupSelector);
const eventCheckbox = await waitFor(eventSelector);
if (!(await eventCheckbox.evaluate(x => x.checkVisibility()))) {
// Unfortunately the shadow DOM makes it hard to find the expander element
// we are attempting to click on, so we click to the left of the checkbox
// bounding box.
const rectData = await groupCheckbox.evaluate(element => {
const {left, top, width, height} = element.getBoundingClientRect();
return {left, top, width, height};
});
await frontend.mouse.click(rectData.left - 10, rectData.top + rectData.height * .5);
await waitForVisible(eventSelector);
}
await setCheckBox(eventSelector, true);
}
declare global {
interface Window {
/* eslint-disable @typescript-eslint/naming-convention */
__sourceFileEvents: Map<number, {files: string[], handler: (e: Event) => void}>;
/* eslint-enable @typescript-eslint/naming-convention */
}
}
export const enum SourceFileEvents {
SOURCE_FILE_LOADED = 'source-file-loaded',
ADDED_TO_SOURCE_TREE = 'source-tree-file-added',
}
let nextEventHandlerId = 0;
export async function waitForSourceFiles<T>(
eventName: SourceFileEvents, waitCondition: (files: string[]) => boolean | Promise<boolean>,
action: () => T): Promise<T> {
const {frontend} = getBrowserAndPages();
const eventHandlerId = nextEventHandlerId++;
// Install new listener for the event
await frontend.evaluate((eventName, eventHandlerId) => {
if (!window.__sourceFileEvents) {
window.__sourceFileEvents = new Map();
}
const handler = (event: Event) => {
const {detail} = event as CustomEvent<string>;
if (!detail.includes('pptr:')) {
window.__sourceFileEvents.get(eventHandlerId)?.files.push(detail);
}
};
window.__sourceFileEvents.set(eventHandlerId, {files: [], handler});
window.addEventListener(eventName, handler);
}, eventName, eventHandlerId);
const result = await action();
await waitForFunction(async () => {
const files =
await frontend.evaluate(eventHandlerId => window.__sourceFileEvents.get(eventHandlerId)?.files, eventHandlerId);
assertNotNullOrUndefined(files);
return await waitCondition(files);
});
await frontend.evaluate((eventName, eventHandlerId) => {
const handler = window.__sourceFileEvents.get(eventHandlerId);
if (!handler) {
throw new Error('handler unexpectandly unregistered');
}
window.__sourceFileEvents.delete(eventHandlerId);
window.removeEventListener(eventName, handler.handler);
}, eventName, eventHandlerId);
return result;
}
export async function captureAddedSourceFiles(count: number, action: () => Promise<void>): Promise<string[]> {
let capturedFileNames!: string[];
await waitForSourceFiles(SourceFileEvents.ADDED_TO_SOURCE_TREE, files => {
capturedFileNames = files;
return files.length >= count;
}, action);
return capturedFileNames.map(f => new URL(`http://${f}`).pathname);
}
export async function reloadPageAndWaitForSourceFile(target: puppeteer.Page, sourceFile: string) {
await waitForSourceFiles(
SourceFileEvents.SOURCE_FILE_LOADED, files => files.some(f => f.endsWith(sourceFile)), () => target.reload());
}
export function isEqualOrAbbreviation(abbreviated: string, full: string): boolean {
const split = abbreviated.split('…');
if (split.length === 1) {
return abbreviated === full;
}
assert.lengthOf(split, 2);
return full.startsWith(split[0]) && full.endsWith(split[1]);
}
// Helpers for navigating the file tree.
export interface NestedFileSelector {
rootSelector: string;
domainSelector: string;
folderSelector?: string;
fileSelector: string;
}
export function createSelectorsForWorkerFile(
workerName: string, folderName: string, fileName: string, workerIndex = 1): NestedFileSelector {
const rootSelector = new Array(workerIndex).fill(`[aria-label="${workerName}, worker"]`).join(' ~ ');
const domainSelector = `${rootSelector} + ol > [aria-label="localhost:${getTestServerPort()}, domain"]`;
const folderSelector = `${domainSelector} + ol > [aria-label^="${folderName}, "]`;
const fileSelector = `${folderSelector} + ol > [aria-label="${fileName}, file"]`;
return {
rootSelector,
domainSelector,
folderSelector,
fileSelector,
};
}
async function isExpanded(sourceTreeItem: puppeteer.ElementHandle<Element>): Promise<boolean> {
return await sourceTreeItem.evaluate(element => {
return element.getAttribute('aria-expanded') === 'true';
});
}
export async function expandSourceTreeItem(selector: string) {
// FIXME(crbug/1112692): Refactor test to remove the timeout.
await timeout(50);
const sourceTreeItem = await waitFor(selector);
if (!await isExpanded(sourceTreeItem)) {
// FIXME(crbug/1112692): Refactor test to remove the timeout.
await timeout(50);
await doubleClickSourceTreeItem(selector);
}
}
export async function expandFileTree(selectors: NestedFileSelector) {
await expandSourceTreeItem(selectors.rootSelector);
await expandSourceTreeItem(selectors.domainSelector);
if (selectors.folderSelector) {
await expandSourceTreeItem(selectors.folderSelector);
}
// FIXME(crbug/1112692): Refactor test to remove the timeout.
await timeout(50);
return await waitFor(selectors.fileSelector);
}
export async function readSourcesTreeView(): Promise<string[]> {
const items = await $$('.navigator-folder-tree-item,.navigator-file-tree-item');
const promises = items.map(handle => handle.evaluate(el => el.textContent as string));
const results = await Promise.all(promises);
return results.map(item => item.replace(/localhost:[0-9]+/, 'localhost:XXXX'));
}
export async function readIgnoreListedSources(): Promise<string[]> {
const items = await $$('.navigator-folder-tree-item.is-ignore-listed,.navigator-file-tree-item.is-ignore-listed');
const promises = items.map(handle => handle.evaluate(el => el.textContent as string));
const results = await Promise.all(promises);
return results.map(item => item.replace(/localhost:[0-9]+/, 'localhost:XXXX'));
}
async function hasPausedEvents(frontend: puppeteer.Page): Promise<boolean> {
const events = await getPendingEvents(frontend, DEBUGGER_PAUSED_EVENT);
return Boolean(events && events.length);
}
export async function stepThroughTheCode() {
const {frontend} = getBrowserAndPages();
await getPendingEvents(frontend, DEBUGGER_PAUSED_EVENT);
await frontend.keyboard.press('F9');
await waitForFunction(() => hasPausedEvents(frontend));
await waitFor(PAUSE_INDICATOR_SELECTOR);
}
export async function stepIn() {
const {frontend} = getBrowserAndPages();
await getPendingEvents(frontend, DEBUGGER_PAUSED_EVENT);
await frontend.keyboard.press('F11');
await waitForFunction(() => hasPausedEvents(frontend));
await waitFor(PAUSE_INDICATOR_SELECTOR);
}
export async function stepOver() {
const {frontend} = getBrowserAndPages();
await getPendingEvents(frontend, DEBUGGER_PAUSED_EVENT);
await frontend.keyboard.press('F10');
await waitForFunction(() => hasPausedEvents(frontend));
await waitFor(PAUSE_INDICATOR_SELECTOR);
}
export async function stepOut() {
const {frontend} = getBrowserAndPages();
await getPendingEvents(frontend, DEBUGGER_PAUSED_EVENT);
await frontend.keyboard.down('Shift');
await frontend.keyboard.press('F11');
await frontend.keyboard.up('Shift');
await waitForFunction(() => hasPausedEvents(frontend));
await waitFor(PAUSE_INDICATOR_SELECTOR);
}
export async function openNestedWorkerFile(selectors: NestedFileSelector) {
await expandFileTree(selectors);
// FIXME(crbug/1112692): Refactor test to remove the timeout.
await timeout(50);
await click(selectors.fileSelector);
}
export async function inspectMemory(variableName: string) {
await openSoftContextMenuAndClickOnItem(
`[data-object-property-name-for-test="${variableName}"]`,
'Open in Memory inspector panel',
);
}
export async function typeIntoSourcesAndSave(text: string) {
const pane = await waitFor('.sources');
await pane.type(text);
await pressKey('s', {control: true});
}
export async function getScopeNames() {
const scopeElements = await $$('.scope-chain-sidebar-pane-section-title');
const scopeNames = await Promise.all(scopeElements.map(nodes => nodes.evaluate(n => n.textContent)));
return scopeNames;
}
export async function getValuesForScope(scope: string, expandCount: number, waitForNoOfValues: number) {
const scopeSelector = `[aria-label="${scope}"]`;
await waitFor(scopeSelector);
for (let i = 0; i < expandCount; i++) {
await click(`${scopeSelector} + ol li[aria-expanded=false]`);
}
const valueSelector = `${scopeSelector} + ol .name-and-value`;
const valueSelectorElements = await waitForFunction(async () => {
const elements = await $$(valueSelector);
if (elements.length >= waitForNoOfValues) {
return elements;
}
return undefined;
});
const values = await Promise.all(valueSelectorElements.map(elem => elem.evaluate(n => n.textContent as string)));
return values;
}
export async function getPausedMessages() {
const {frontend} = getBrowserAndPages();
const messageElement = await frontend.waitForSelector('.paused-message');
if (!messageElement) {
assert.fail('getPausedMessages: did not find .paused-message element.');
}
const statusMain = await waitFor('.status-main', messageElement);
const statusSub = await waitFor('.status-sub', messageElement);
return {
statusMain: await statusMain.evaluate(x => x.textContent),
statusSub: await statusSub.evaluate(x => x.textContent),
};
}
export async function getWatchExpressionsValues() {
const {frontend} = getBrowserAndPages();
await waitForFunction(async () => {
const expandedOption = await $('[aria-label="Watch"].expanded');
if (expandedOption) {
return true;
}
await click('[aria-label="Watch"]');
// Wait for the click event to settle.
await timeout(100);
return expandedOption !== null;
});
await frontend.keyboard.press('ArrowRight');
const watchExpressionValue = await $(WATCH_EXPRESSION_VALUE_SELECTOR);
if (!watchExpressionValue) {
return null;
}
const values = await $$(WATCH_EXPRESSION_VALUE_SELECTOR) as puppeteer.ElementHandle<HTMLElement>[];
return await Promise.all(values.map(value => value.evaluate(element => element.innerText)));
}
export async function runSnippet() {
const {frontend} = getBrowserAndPages();
const modifierKey = platform === 'mac' ? 'Meta' : 'Control';
await frontend.keyboard.down(modifierKey);
await frontend.keyboard.press('Enter');
await frontend.keyboard.up(modifierKey);
}
export async function evaluateSelectedTextInConsole() {
const {frontend} = getBrowserAndPages();
const modifierKey = platform === 'mac' ? 'Meta' : 'Control';
await frontend.keyboard.down(modifierKey);
await frontend.keyboard.down('Shift');
await frontend.keyboard.press('E');
await frontend.keyboard.up(modifierKey);
await frontend.keyboard.up('Shift');
}
export async function addSelectedTextToWatches() {
const {frontend} = getBrowserAndPages();
const modifierKey = platform === 'mac' ? 'Meta' : 'Control';
await frontend.keyboard.down(modifierKey);
await frontend.keyboard.down('Shift');
await frontend.keyboard.press('A');
await frontend.keyboard.up(modifierKey);
await frontend.keyboard.up('Shift');
}
export async function enableLocalOverrides() {
await clickMoreTabsButton();
await click(OVERRIDES_TAB_SELECTOR);
await click(ENABLE_OVERRIDES_SELECTOR);
await waitFor(CLEAR_CONFIGURATION_SELECTOR);
}
export interface LabelMapping {
label: string;
moduleOffset: number;
bytecode: number;
sourceLine: number;
labelLine: number;
labelColumn: number;
}
export class WasmLocationLabels {
readonly #mappings: Map<string, LabelMapping[]>;
readonly #source: string;
readonly #wasm: string;
constructor(source: string, wasm: string, mappings: Map<string, LabelMapping[]>) {
this.#mappings = mappings;
this.#source = source;
this.#wasm = wasm;
}
static load(source: string, wasm: string): WasmLocationLabels {
const mapFileName = path.join(GEN_DIR, 'test', 'e2e', 'resources', `${wasm}.map.json`);
const mapFile = JSON.parse(fs.readFileSync(mapFileName, {encoding: 'utf-8'})) as Array<{
source: string,
generatedLine: number,
generatedColumn: number,
bytecodeOffset: number,
originalLine: number,
originalColumn: number,
}>;
const sourceFileName = path.join(GEN_DIR, 'test', 'e2e', 'resources', source);
const sourceFile = fs.readFileSync(sourceFileName, {encoding: 'utf-8'});
const labels = new Map<string, number>();
for (const [index, line] of sourceFile.split('\n').entries()) {
if (line.trim().startsWith(';;@')) {
const label = line.trim().substr(3).trim();
assert.isFalse(labels.has(label), `Label ${label} must be unique`);
labels.set(label, index + 1);
}
}
const mappings = new Map<string, LabelMapping[]>();
for (const m of mapFile) {
const entry = mappings.get(m.source) ?? [];
if (entry.length === 0) {
mappings.set(m.source, entry);
}
const labelLine = m.originalLine as number;
const labelColumn = m.originalColumn as number;
const sourceLine = labels.get(`${m.source}:${labelLine}:${labelColumn}`);
assertNotNullOrUndefined(sourceLine);
entry.push({
label: m.source,
moduleOffset: m.generatedColumn,
bytecode: m.bytecodeOffset,
sourceLine,
labelLine,
labelColumn,
});
}
return new WasmLocationLabels(source, wasm, mappings);
}
async checkLocationForLabel(label: string) {
const pauseLocation = await retrieveTopCallFrameWithoutResuming();
const pausedLine = this.#mappings.get(label)!.find(
line => pauseLocation === `${path.basename(this.#wasm)}:0x${line.moduleOffset.toString(16)}` ||
pauseLocation === `${path.basename(this.#source)}:${line.sourceLine}`);
assertNotNullOrUndefined(pausedLine);
return pausedLine;
}
async addBreakpointsForLabelInSource(label: string) {
const {frontend} = getBrowserAndPages();
await openFileInEditor(path.basename(this.#source));
await Promise.all(this.#mappings.get(label)!.map(({sourceLine}) => addBreakpointForLine(frontend, sourceLine)));
}
async addBreakpointsForLabelInWasm(label: string) {
const {frontend} = getBrowserAndPages();
await openFileInEditor(path.basename(this.#wasm));
const visibleLines = await $$(CODE_LINE_SELECTOR);
const lineNumbers = await Promise.all(visibleLines.map(line => line.evaluate(node => node.textContent)));
const lineNumberLabels = new Map(lineNumbers.map(label => [Number(label), label]));
await Promise.all(this.#mappings.get(label)!.map(
({moduleOffset}) => addBreakpointForLine(frontend, lineNumberLabels.get(moduleOffset)!)));
}
async setBreakpointInSourceAndRun(label: string, script: string) {
const {target} = getBrowserAndPages();
await this.addBreakpointsForLabelInSource(label);
target.evaluate(script);
await this.checkLocationForLabel(label);
}
async setBreakpointInWasmAndRun(label: string, script: string) {
const {target} = getBrowserAndPages();
await this.addBreakpointsForLabelInWasm(label);
target.evaluate(script);
await this.checkLocationForLabel(label);
}
async continueAndCheckForLabel(label: string) {
await click(RESUME_BUTTON);
await this.checkLocationForLabel(label);
}
getMappingsForPlugin(): LabelMapping[] {
return Array.from(this.#mappings.values()).flat();
}
}
export async function retrieveCodeMirrorEditorContent(): Promise<Array<string>> {
const editor = await waitFor('[aria-label="Code editor"]');
return await editor.evaluate(
node => [...node.querySelectorAll('.cm-line')].map(node => node.textContent || '') || []);
}
export async function waitForLines(lineCount: number): Promise<void> {
await waitFor(new Array(lineCount).fill('.cm-line').join(' ~ '));
}
export async function isPrettyPrinted(): Promise<boolean> {
const prettyButton = await waitFor('[title="Pretty print"]');
const isPretty = await prettyButton.evaluate(e => e.classList.contains('toggled'));
return isPretty === true;
}
export function veImpressionForSourcesPanel() {
return veImpression('Panel', 'sources', [
veImpression(
'Toolbar', 'debug',
[
veImpression('Toggle', 'debugger.toggle-pause'),
veImpression('Action', 'debugger.step-over'),
veImpression('Action', 'debugger.step-into'),
veImpression('Action', 'debugger.step-out'),
veImpression('Action', 'debugger.step'),
veImpression('Toggle', 'debugger.toggle-breakpoints-active'),
]),
veImpression(
'Pane', 'debug',
[
veImpression('SectionHeader', 'sources.watch'),
veImpression('SectionHeader', 'sources.js-breakpoints'),
veImpression('SectionHeader', 'sources.scope-chain'),
veImpression('SectionHeader', 'sources.callstack'),
veImpression('SectionHeader', 'sources.xhr-breakpoints'),
veImpression('SectionHeader', 'sources.dom-breakpoints'),
veImpression('SectionHeader', 'sources.global-listeners'),
veImpression('SectionHeader', 'sources.event-listener-breakpoints'),
veImpression('SectionHeader', 'sources.csp-violation-breakpoints'),
veImpression('Section', 'sources.scope-chain'),
veImpression('Section', 'sources.callstack'),
veImpression(
'Section', 'sources.js-breakpoints',
[
veImpression('Toggle', 'pause-uncaught'),
veImpression('Toggle', 'pause-on-caught-exception'),
]),
]),
veImpression(
'Pane', 'editor',
[
veImpression('Toolbar', 'bottom'),
veImpression(
'Toolbar', 'top',
[
veImpression('ToggleSubpane', 'navigator'),
veImpression('ToggleSubpane', 'debugger'),
]),
]),
veImpression(
'Toolbar', 'navigator',
[
veImpression('DropDown', 'more-tabs'),
veImpression('PanelTabHeader', 'navigator-network'),
veImpression('PanelTabHeader', 'navigator-files'),
veImpression('DropDown', 'more-options'),
]),
veImpression(
'Pane', 'navigator-network',
[
veImpression(
'Tree', undefined,
[
veImpression(
'TreeItem', 'frame',
[
veImpression('Expand'),
veImpression(
'TreeItem', 'domain',
[
veImpression('Expand'),
veImpression('TreeItem', 'document', [
veImpression('Value', 'title'),
]),
]),
]),
]),
]),
]);
}