[Underscore Migration] Migrate entrypoints This patch is part of the underscore migration that adds the private keyword to all properties that start with an underscore and removes the underscore. Bug:chromium:1207342 Change-Id: Iec114859ae3f46457bafa2d823e11add202c6eb2 Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3077887 Commit-Queue: Jan Scheffler <janscheffler@chromium.org> Auto-Submit: Jan Scheffler <janscheffler@chromium.org> Reviewed-by: Tim van der Lippe <tvanderlippe@chromium.org>
diff --git a/front_end/Tests.js b/front_end/Tests.js index 2f78ad9..70f8c84 100644 --- a/front_end/Tests.js +++ b/front_end/Tests.js
@@ -1052,7 +1052,7 @@ } function gotPreferences(prefs) { - Main.Main._instanceForTest._createSettings(prefs); + Main.Main.instanceForTest.createSettings(prefs); const localSetting = self.Common.settings.createLocalSetting('local', undefined); test.assertEquals('object', typeof localSetting.get());
diff --git a/front_end/entrypoints/formatter_worker/AcornTokenizer.ts b/front_end/entrypoints/formatter_worker/AcornTokenizer.ts index 842031e..741e327 100644 --- a/front_end/entrypoints/formatter_worker/AcornTokenizer.ts +++ b/front_end/entrypoints/formatter_worker/AcornTokenizer.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Platform from '../../core/platform/platform.js'; import * as TextUtils from '../../models/text_utils/text_utils.js'; import * as Acorn from '../../third_party/acorn/acorn.js'; @@ -17,7 +15,7 @@ * * To remedy the situation, we implement the peeking of tokens ourselves. * To do so, whenever we call `nextToken`, we already retrieve the token - * after it (in `_bufferedToken`), so that `_peekToken` can check if there + * after it (in `bufferedToken`), so that `_peekToken` can check if there * is more work to do. * * There are 2 catches: @@ -30,45 +28,45 @@ * receive the token and after that we receive the comment. However, when tokenizing * we should reverse the order and return the comment, before the token. * - * All that is to say that the `_bufferedToken` is only used for *true* tokens. + * All that is to say that the `bufferedToken` is only used for *true* tokens. * We mimic comments to be tokens to fix the reordering issue, but we store these - * separately to keep track of them. Any call to `_nextTokenInternal` will figure + * separately to keep track of them. Any call to `nextTokenInternal` will figure * out whether the next token should be the preceding comment or not. */ export class AcornTokenizer { - _content: string; - _comments: Acorn.Comment[]; - _tokenizer: { + private readonly content: string; + private readonly comments: Acorn.Comment[]; + private tokenizer: { getToken(): Acorn.Token, [Symbol.iterator](): Iterator<Acorn.Token>, }; - _textCursor: TextUtils.TextCursor.TextCursor; - _tokenLineStart: number; - _tokenLineEnd: number; - _tokenColumnStart: number; - _bufferedToken?: TokenOrComment; + private textCursor: TextUtils.TextCursor.TextCursor; + private tokenLineStartInternal: number; + private tokenLineEndInternal: number; + private tokenColumnStartInternal: number; + private bufferedToken?: TokenOrComment; constructor(content: string) { - this._content = content; - this._comments = []; - this._tokenizer = - Acorn.tokenizer(this._content, {onComment: this._comments, ecmaVersion: ECMA_VERSION, allowHashBang: true}); - const contentLineEndings = Platform.StringUtilities.findLineEndingIndexes(this._content); - this._textCursor = new TextUtils.TextCursor.TextCursor(contentLineEndings); - this._tokenLineStart = 0; - this._tokenLineEnd = 0; - this._tokenColumnStart = 0; + this.content = content; + this.comments = []; + this.tokenizer = + Acorn.tokenizer(this.content, {onComment: this.comments, ecmaVersion: ECMA_VERSION, allowHashBang: true}); + const contentLineEndings = Platform.StringUtilities.findLineEndingIndexes(this.content); + this.textCursor = new TextUtils.TextCursor.TextCursor(contentLineEndings); + this.tokenLineStartInternal = 0; + this.tokenLineEndInternal = 0; + this.tokenColumnStartInternal = 0; // If the first "token" should be a comment, we don't want to shift - // the comment from the array (which happens in `_nextTokenInternal`). + // the comment from the array (which happens in `nextTokenInternal`). // Therefore, we should bail out from retrieving the token if this // is the case. // // However, sometimes we have leading comments that are attached to tokens // themselves. In that case, we first retrieve the actual token, before // we see the comment itself. In that case, we should proceed and - // initialize `_bufferedToken` as normal, to allow us to fix the reordering. - if (this._comments.length === 0) { - this._nextTokenInternal(); + // initialize `bufferedToken` as normal, to allow us to fix the reordering. + if (this.comments.length === 0) { + this.nextTokenInternal(); } } @@ -96,59 +94,59 @@ return token.type === 'Block'; } - _nextTokenInternal(): TokenOrComment|undefined { - if (this._comments.length) { - const nextComment = this._comments.shift(); + private nextTokenInternal(): TokenOrComment|undefined { + if (this.comments.length) { + const nextComment = this.comments.shift(); // If this was the last comment to process, we need to make - // sure to update our `_bufferedToken` to become the actual + // sure to update our `bufferedToken` to become the actual // token. This only happens when we are processing the very // first comment of a file (usually a hashbang comment) // in which case we don't have to fix the reordering of tokens. - if (!this._bufferedToken && this._comments.length === 0) { - this._bufferedToken = this._tokenizer.getToken(); + if (!this.bufferedToken && this.comments.length === 0) { + this.bufferedToken = this.tokenizer.getToken(); } return nextComment; } - const token = this._bufferedToken; - this._bufferedToken = this._tokenizer.getToken(); + const token = this.bufferedToken; + this.bufferedToken = this.tokenizer.getToken(); return token; } nextToken(): TokenOrComment|null { - const token = this._nextTokenInternal(); + const token = this.nextTokenInternal(); if (!token || token.type === Acorn.tokTypes.eof) { return null; } - this._textCursor.advance(token.start); - this._tokenLineStart = this._textCursor.lineNumber(); - this._tokenColumnStart = this._textCursor.columnNumber(); + this.textCursor.advance(token.start); + this.tokenLineStartInternal = this.textCursor.lineNumber(); + this.tokenColumnStartInternal = this.textCursor.columnNumber(); - this._textCursor.advance(token.end); - this._tokenLineEnd = this._textCursor.lineNumber(); + this.textCursor.advance(token.end); + this.tokenLineEndInternal = this.textCursor.lineNumber(); return token; } peekToken(): TokenOrComment|null { - if (this._comments.length) { - return this._comments[0]; + if (this.comments.length) { + return this.comments[0]; } - if (!this._bufferedToken) { + if (!this.bufferedToken) { return null; } - return this._bufferedToken.type !== Acorn.tokTypes.eof ? this._bufferedToken : null; + return this.bufferedToken.type !== Acorn.tokTypes.eof ? this.bufferedToken : null; } tokenLineStart(): number { - return this._tokenLineStart; + return this.tokenLineStartInternal; } tokenLineEnd(): number { - return this._tokenLineEnd; + return this.tokenLineEndInternal; } tokenColumnStart(): number { - return this._tokenColumnStart; + return this.tokenColumnStartInternal; } }
diff --git a/front_end/entrypoints/formatter_worker/CSSFormatter.ts b/front_end/entrypoints/formatter_worker/CSSFormatter.ts index 2e9452d..9b1f44e 100644 --- a/front_end/entrypoints/formatter_worker/CSSFormatter.ts +++ b/front_end/entrypoints/formatter_worker/CSSFormatter.ts
@@ -28,8 +28,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Platform from '../../core/platform/platform.js'; import type {FormattedContentBuilder} from './FormattedContentBuilder.js'; @@ -42,21 +40,21 @@ }; export class CSSFormatter { - _builder: FormattedContentBuilder; - _toOffset!: number; - _fromOffset!: number; - _lineEndings!: number[]; - _lastLine: number; - _state: { + private readonly builder: FormattedContentBuilder; + private toOffset!: number; + private fromOffset!: number; + private lineEndings!: number[]; + private lastLine: number; + private state: { eatWhitespace: (boolean|undefined), seenProperty: (boolean|undefined), inPropertyValue: (boolean|undefined), afterClosingBrace: (boolean|undefined), }; constructor(builder: FormattedContentBuilder) { - this._builder = builder; - this._lastLine = -1; - this._state = { + this.builder = builder; + this.lastLine = -1; + this.state = { eatWhitespace: undefined, seenProperty: undefined, inPropertyValue: undefined, @@ -65,86 +63,86 @@ } format(text: string, lineEndings: number[], fromOffset: number, toOffset: number): void { - this._lineEndings = lineEndings; - this._fromOffset = fromOffset; - this._toOffset = toOffset; - this._state = { + this.lineEndings = lineEndings; + this.fromOffset = fromOffset; + this.toOffset = toOffset; + this.state = { eatWhitespace: undefined, seenProperty: undefined, inPropertyValue: undefined, afterClosingBrace: undefined, }; - this._lastLine = -1; + this.lastLine = -1; const tokenize = createTokenizer('text/css'); - const oldEnforce = this._builder.setEnforceSpaceBetweenWords(false); - tokenize(text.substring(this._fromOffset, this._toOffset), this._tokenCallback.bind(this)); - this._builder.setEnforceSpaceBetweenWords(oldEnforce); + const oldEnforce = this.builder.setEnforceSpaceBetweenWords(false); + tokenize(text.substring(this.fromOffset, this.toOffset), this.tokenCallback.bind(this)); + this.builder.setEnforceSpaceBetweenWords(oldEnforce); } - _tokenCallback(token: string, type: string|null, startPosition: number): void { - startPosition += this._fromOffset; - const startLine = Platform.ArrayUtilities.lowerBound( - this._lineEndings, startPosition, Platform.ArrayUtilities.DEFAULT_COMPARATOR); - if (startLine !== this._lastLine) { - this._state.eatWhitespace = true; + private tokenCallback(token: string, type: string|null, startPosition: number): void { + startPosition += this.fromOffset; + const startLine = + Platform.ArrayUtilities.lowerBound(this.lineEndings, startPosition, Platform.ArrayUtilities.DEFAULT_COMPARATOR); + if (startLine !== this.lastLine) { + this.state.eatWhitespace = true; } // The css- prefix is optional, as we override that in the tokenizer defined // in CodeMirrorTextEditor.js. In a worker context, we don't use the prefix. - if (type && (/^(css-)?property/.test(type) || /^(css-)?variable-2/.test(type)) && !this._state.inPropertyValue) { - this._state.seenProperty = true; + if (type && (/^(css-)?property/.test(type) || /^(css-)?variable-2/.test(type)) && !this.state.inPropertyValue) { + this.state.seenProperty = true; } - this._lastLine = startLine; + this.lastLine = startLine; // https://drafts.csswg.org/css-syntax/#whitespace const isWhitespace = /^(?:\r?\n|[\t\f\r ])+$/.test(token); if (isWhitespace) { - if (!this._state.eatWhitespace) { - this._builder.addSoftSpace(); + if (!this.state.eatWhitespace) { + this.builder.addSoftSpace(); } return; } - this._state.eatWhitespace = false; + this.state.eatWhitespace = false; if (token === '\n') { return; } if (token !== '}') { - if (this._state.afterClosingBrace) { - this._builder.addNewLine(true); + if (this.state.afterClosingBrace) { + this.builder.addNewLine(true); } - this._state.afterClosingBrace = false; + this.state.afterClosingBrace = false; } if (token === '}') { - if (this._state.inPropertyValue) { - this._builder.addNewLine(); + if (this.state.inPropertyValue) { + this.builder.addNewLine(); } - this._builder.decreaseNestingLevel(); - this._state.afterClosingBrace = true; - this._state.inPropertyValue = false; - } else if (token === ':' && !this._state.inPropertyValue && this._state.seenProperty) { - this._builder.addToken(token, startPosition); - this._builder.addSoftSpace(); - this._state.eatWhitespace = true; - this._state.inPropertyValue = true; - this._state.seenProperty = false; + this.builder.decreaseNestingLevel(); + this.state.afterClosingBrace = true; + this.state.inPropertyValue = false; + } else if (token === ':' && !this.state.inPropertyValue && this.state.seenProperty) { + this.builder.addToken(token, startPosition); + this.builder.addSoftSpace(); + this.state.eatWhitespace = true; + this.state.inPropertyValue = true; + this.state.seenProperty = false; return; } else if (token === '{') { - this._builder.addSoftSpace(); - this._builder.addToken(token, startPosition); - this._builder.addNewLine(); - this._builder.increaseNestingLevel(); + this.builder.addSoftSpace(); + this.builder.addToken(token, startPosition); + this.builder.addNewLine(); + this.builder.increaseNestingLevel(); return; } - this._builder.addToken(cssTrimEnd(token), startPosition); + this.builder.addToken(cssTrimEnd(token), startPosition); - if (type === 'comment' && !this._state.inPropertyValue && !this._state.seenProperty) { - this._builder.addNewLine(); + if (type === 'comment' && !this.state.inPropertyValue && !this.state.seenProperty) { + this.builder.addNewLine(); } - if (token === ';' && this._state.inPropertyValue) { - this._state.inPropertyValue = false; - this._builder.addNewLine(); + if (token === ';' && this.state.inPropertyValue) { + this.state.inPropertyValue = false; + this.builder.addNewLine(); } else if (token === '}') { - this._builder.addNewLine(); + this.builder.addNewLine(); } } }
diff --git a/front_end/entrypoints/formatter_worker/CSSRuleParser.ts b/front_end/entrypoints/formatter_worker/CSSRuleParser.ts index c3e2efa..12f21e9 100644 --- a/front_end/entrypoints/formatter_worker/CSSRuleParser.ts +++ b/front_end/entrypoints/formatter_worker/CSSRuleParser.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import type {Chunk, ChunkCallback} from './FormatterWorker.js'; import {createTokenizer} from './FormatterWorker.js';
diff --git a/front_end/entrypoints/formatter_worker/ESTreeWalker.ts b/front_end/entrypoints/formatter_worker/ESTreeWalker.ts index 3b5ebe0..ebd70f2 100644 --- a/front_end/entrypoints/formatter_worker/ESTreeWalker.ts +++ b/front_end/entrypoints/formatter_worker/ESTreeWalker.ts
@@ -2,22 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ import type * as Acorn from '../../third_party/acorn/acorn.js'; const SkipSubTreeObject: Object = {}; export class ESTreeWalker { - _beforeVisit: (arg0: Acorn.ESTree.Node) => (Object | undefined); - _afterVisit: Function; - _walkNulls: boolean; + private readonly beforeVisit: (arg0: Acorn.ESTree.Node) => (Object | undefined); + private readonly afterVisit: Function; + private walkNulls: boolean; constructor( beforeVisit: (arg0: Acorn.ESTree.Node) => (Object | undefined), afterVisit?: ((arg0: Acorn.ESTree.Node) => void)) { - this._beforeVisit = beforeVisit; - this._afterVisit = afterVisit || new Function(); - this._walkNulls = false; + this.beforeVisit = beforeVisit; + this.afterVisit = afterVisit || new Function(); + this.walkNulls = false; } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration @@ -27,15 +26,15 @@ } setWalkNulls(value: boolean): void { - this._walkNulls = value; + this.walkNulls = value; } walk(ast: Acorn.ESTree.Node): void { - this._innerWalk(ast, null); + this.innerWalk(ast, null); } - _innerWalk(node: Acorn.ESTree.Node, parent: Acorn.ESTree.Node|null): void { - if (!node && parent && this._walkNulls) { + private innerWalk(node: Acorn.ESTree.Node, parent: Acorn.ESTree.Node|null): void { + if (!node && parent && this.walkNulls) { const result = ({raw: 'null', value: null, parent: null} as Acorn.ESTree.SimpleLiteral); // Otherwise Closure can't handle the definition result.type = 'Literal'; @@ -48,8 +47,8 @@ } node.parent = parent; - if (this._beforeVisit.call(null, node) === ESTreeWalker.SkipSubtree) { - this._afterVisit.call(null, node); + if (this.beforeVisit.call(null, node) === ESTreeWalker.SkipSubtree) { + this.afterVisit.call(null, node); return; } @@ -63,10 +62,10 @@ const templateLiteral = (node as Acorn.ESTree.TemplateLiteral); const expressionsLength = templateLiteral.expressions.length; for (let i = 0; i < expressionsLength; ++i) { - this._innerWalk(templateLiteral.quasis[i], templateLiteral); - this._innerWalk(templateLiteral.expressions[i], templateLiteral); + this.innerWalk(templateLiteral.quasis[i], templateLiteral); + this.innerWalk(templateLiteral.expressions[i], templateLiteral); } - this._innerWalk(templateLiteral.quasis[expressionsLength], templateLiteral); + this.innerWalk(templateLiteral.quasis[expressionsLength], templateLiteral); } else { for (let i = 0; i < walkOrder.length; ++i) { // @ts-ignore We are doing type traversal here, but the strings @@ -76,19 +75,19 @@ // eslint-disable-next-line @typescript-eslint/no-explicit-any const entity = (node[walkOrder[i]] as any); if (Array.isArray(entity)) { - this._walkArray((entity as Acorn.ESTree.Node[]), node); + this.walkArray((entity as Acorn.ESTree.Node[]), node); } else { - this._innerWalk((entity as Acorn.ESTree.Node), node); + this.innerWalk((entity as Acorn.ESTree.Node), node); } } } - this._afterVisit.call(null, node); + this.afterVisit.call(null, node); } - _walkArray(nodeArray: Acorn.ESTree.Node[], parentNode: Acorn.ESTree.Node|null): void { + private walkArray(nodeArray: Acorn.ESTree.Node[], parentNode: Acorn.ESTree.Node|null): void { for (let i = 0; i < nodeArray.length; ++i) { - this._innerWalk(nodeArray[i], parentNode); + this.innerWalk(nodeArray[i], parentNode); } } }
diff --git a/front_end/entrypoints/formatter_worker/FormatterWorker.ts b/front_end/entrypoints/formatter_worker/FormatterWorker.ts index e5558d3..123effb 100644 --- a/front_end/entrypoints/formatter_worker/FormatterWorker.ts +++ b/front_end/entrypoints/formatter_worker/FormatterWorker.ts
@@ -28,8 +28,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Platform from '../../core/platform/platform.js'; import * as Root from '../../core/root/root.js'; import type * as Formatter from '../../models/formatter/formatter.js';
diff --git a/front_end/entrypoints/formatter_worker/HTMLFormatter.ts b/front_end/entrypoints/formatter_worker/HTMLFormatter.ts index 1ddcdb9..4f33eee 100644 --- a/front_end/entrypoints/formatter_worker/HTMLFormatter.ts +++ b/front_end/entrypoints/formatter_worker/HTMLFormatter.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Platform from '../../core/platform/platform.js'; import {CSSFormatter} from './CSSFormatter.js'; @@ -12,107 +10,107 @@ import {JavaScriptFormatter} from './JavaScriptFormatter.js'; export class HTMLFormatter { - _builder: FormattedContentBuilder; - _jsFormatter: JavaScriptFormatter; - _cssFormatter: CSSFormatter; - _text?: string; - _lineEndings?: number[]; - _model?: HTMLModel; + private readonly builder: FormattedContentBuilder; + private readonly jsFormatter: JavaScriptFormatter; + private readonly cssFormatter: CSSFormatter; + private text?: string; + private lineEndings?: number[]; + private model?: HTMLModel; constructor(builder: FormattedContentBuilder) { - this._builder = builder; - this._jsFormatter = new JavaScriptFormatter(builder); - this._cssFormatter = new CSSFormatter(builder); + this.builder = builder; + this.jsFormatter = new JavaScriptFormatter(builder); + this.cssFormatter = new CSSFormatter(builder); } format(text: string, lineEndings: number[]): void { - this._text = text; - this._lineEndings = lineEndings; - this._model = new HTMLModel(text); - this._walk(this._model.document()); + this.text = text; + this.lineEndings = lineEndings; + this.model = new HTMLModel(text); + this.walk(this.model.document()); } - _formatTokensTill(element: FormatterElement, offset: number): void { - if (!this._model) { + private formatTokensTill(element: FormatterElement, offset: number): void { + if (!this.model) { return; } - let nextToken = this._model.peekToken(); + let nextToken = this.model.peekToken(); while (nextToken && nextToken.startOffset < offset) { - const token = (this._model.nextToken() as Token); - this._formatToken(element, token); - nextToken = this._model.peekToken(); + const token = (this.model.nextToken() as Token); + this.formatToken(element, token); + nextToken = this.model.peekToken(); } } - _walk(element: FormatterElement): void { + private walk(element: FormatterElement): void { if (!element.openTag || !element.closeTag) { throw new Error('Element is missing open or close tag'); } if (element.parent) { - this._formatTokensTill(element.parent, element.openTag.startOffset); + this.formatTokensTill(element.parent, element.openTag.startOffset); } - this._beforeOpenTag(element); - this._formatTokensTill(element, element.openTag.endOffset); - this._afterOpenTag(element); + this.beforeOpenTag(element); + this.formatTokensTill(element, element.openTag.endOffset); + this.afterOpenTag(element); for (let i = 0; i < element.children.length; ++i) { - this._walk(element.children[i]); + this.walk(element.children[i]); } - this._formatTokensTill(element, element.closeTag.startOffset); - this._beforeCloseTag(element); - this._formatTokensTill(element, element.closeTag.endOffset); - this._afterCloseTag(element); + this.formatTokensTill(element, element.closeTag.startOffset); + this.beforeCloseTag(element); + this.formatTokensTill(element, element.closeTag.endOffset); + this.afterCloseTag(element); } - _beforeOpenTag(element: FormatterElement): void { - if (!this._model) { + private beforeOpenTag(element: FormatterElement): void { + if (!this.model) { return; } - if (!element.children.length || element === this._model.document()) { + if (!element.children.length || element === this.model.document()) { return; } - this._builder.addNewLine(); + this.builder.addNewLine(); } - _afterOpenTag(element: FormatterElement): void { - if (!this._model) { + private afterOpenTag(element: FormatterElement): void { + if (!this.model) { return; } - if (!element.children.length || element === this._model.document()) { + if (!element.children.length || element === this.model.document()) { return; } - this._builder.increaseNestingLevel(); - this._builder.addNewLine(); + this.builder.increaseNestingLevel(); + this.builder.addNewLine(); } - _beforeCloseTag(element: FormatterElement): void { - if (!this._model) { + private beforeCloseTag(element: FormatterElement): void { + if (!this.model) { return; } - if (!element.children.length || element === this._model.document()) { + if (!element.children.length || element === this.model.document()) { return; } - this._builder.decreaseNestingLevel(); - this._builder.addNewLine(); + this.builder.decreaseNestingLevel(); + this.builder.addNewLine(); } - _afterCloseTag(_element: FormatterElement): void { - this._builder.addNewLine(); + private afterCloseTag(_element: FormatterElement): void { + this.builder.addNewLine(); } - _formatToken(element: FormatterElement, token: Token): void { + private formatToken(element: FormatterElement, token: Token): void { if (Platform.StringUtilities.isWhitespace(token.value)) { return; } if (hasTokenInSet(token.type, 'comment') || hasTokenInSet(token.type, 'meta')) { - this._builder.addNewLine(); - this._builder.addToken(token.value.trim(), token.startOffset); - this._builder.addNewLine(); + this.builder.addNewLine(); + this.builder.addToken(token.value.trim(), token.startOffset); + this.builder.addNewLine(); return; } @@ -123,33 +121,33 @@ const isBodyToken = element.openTag.endOffset <= token.startOffset && token.startOffset < element.closeTag.startOffset; if (isBodyToken && element.name === 'style') { - this._builder.addNewLine(); - this._builder.increaseNestingLevel(); - this._cssFormatter.format(this._text || '', this._lineEndings || [], token.startOffset, token.endOffset); - this._builder.decreaseNestingLevel(); + this.builder.addNewLine(); + this.builder.increaseNestingLevel(); + this.cssFormatter.format(this.text || '', this.lineEndings || [], token.startOffset, token.endOffset); + this.builder.decreaseNestingLevel(); return; } if (isBodyToken && element.name === 'script') { - this._builder.addNewLine(); - this._builder.increaseNestingLevel(); - if (this._scriptTagIsJavaScript(element)) { - this._jsFormatter.format(this._text || '', this._lineEndings || [], token.startOffset, token.endOffset); + this.builder.addNewLine(); + this.builder.increaseNestingLevel(); + if (this.scriptTagIsJavaScript(element)) { + this.jsFormatter.format(this.text || '', this.lineEndings || [], token.startOffset, token.endOffset); } else { - this._builder.addToken(token.value, token.startOffset); - this._builder.addNewLine(); + this.builder.addToken(token.value, token.startOffset); + this.builder.addNewLine(); } - this._builder.decreaseNestingLevel(); + this.builder.decreaseNestingLevel(); return; } if (!isBodyToken && hasTokenInSet(token.type, 'attribute')) { - this._builder.addSoftSpace(); + this.builder.addSoftSpace(); } - this._builder.addToken(token.value, token.startOffset); + this.builder.addToken(token.value, token.startOffset); } - _scriptTagIsJavaScript(element: FormatterElement): boolean { + private scriptTagIsJavaScript(element: FormatterElement): boolean { if (!element.openTag) { return true; } @@ -202,37 +200,37 @@ } export class HTMLModel { - _state: ParseState; - _document: FormatterElement; - _stack: FormatterElement[]; - _tokens: Token[]; - _tokenIndex: number; - _attributes: Map<string, string>; - _attributeName: string; - _tagName: string; - _isOpenTag: boolean; - _tagStartOffset?: number|null; - _tagEndOffset?: number|null; + private state: ParseState; + private readonly documentInternal: FormatterElement; + private stack: FormatterElement[]; + private readonly tokens: Token[]; + private tokenIndex: number; + private attributes: Map<string, string>; + private attributeName: string; + private tagName: string; + private isOpenTag: boolean; + private tagStartOffset?: number|null; + private tagEndOffset?: number|null; constructor(text: string) { - this._state = ParseState.Initial; - this._document = new FormatterElement('document'); - this._document.openTag = new Tag('document', 0, 0, new Map(), true, false); - this._document.closeTag = new Tag('document', text.length, text.length, new Map(), false, false); + this.state = ParseState.Initial; + this.documentInternal = new FormatterElement('document'); + this.documentInternal.openTag = new Tag('document', 0, 0, new Map(), true, false); + this.documentInternal.closeTag = new Tag('document', text.length, text.length, new Map(), false, false); - this._stack = [this._document]; + this.stack = [this.documentInternal]; - this._tokens = []; - this._tokenIndex = 0; - this._build(text); + this.tokens = []; + this.tokenIndex = 0; + this.build(text); - this._attributes = new Map(); - this._attributeName = ''; - this._tagName = ''; - this._isOpenTag = false; + this.attributes = new Map(); + this.attributeName = ''; + this.tagName = ''; + this.isOpenTag = false; } - _build(text: string): void { + private build(text: string): void { const tokenizer = createTokenizer('text/html'); let lastOffset = 0; const lowerCaseText = text.toLowerCase(); @@ -242,7 +240,7 @@ if (lastOffset >= text.length) { break; } - const element = this._stack[this._stack.length - 1]; + const element = this.stack[this.stack.length - 1]; if (!element) { break; } @@ -259,16 +257,16 @@ const tokenStart = element.openTag.endOffset; const tokenEnd = lastOffset; const tokenValue = text.substring(tokenStart, tokenEnd); - this._tokens.push(new Token(tokenValue, new Set(), tokenStart, tokenEnd)); + this.tokens.push(new Token(tokenValue, new Set(), tokenStart, tokenEnd)); } - while (this._stack.length > 1) { - const element = this._stack[this._stack.length - 1]; + while (this.stack.length > 1) { + const element = this.stack[this.stack.length - 1]; if (!element) { break; } - this._popElement(new Tag(element.name, text.length, text.length, new Map(), false, false)); + this.popElement(new Tag(element.name, text.length, text.length, new Map(), false, false)); } function processToken( @@ -280,10 +278,10 @@ const tokenType = type ? new Set<string>(type.split(' ')) : new Set<string>(); const token = new Token(tokenValue, tokenType, tokenStart, tokenEnd); - this._tokens.push(token); - this._updateDOM(token); + this.tokens.push(token); + this.updateDOM(token); - const element = this._stack[this._stack.length - 1]; + const element = this.stack[this.stack.length - 1]; if (element && (element.name === 'script' || element.name === 'style') && element.openTag && element.openTag.endOffset === lastOffset) { return AbortTokenization; @@ -293,125 +291,124 @@ } } - _updateDOM(token: Token): void { + private updateDOM(token: Token): void { const value = token.value; const type = token.type; - switch (this._state) { + switch (this.state) { case ParseState.Initial: if (hasTokenInSet(type, 'bracket') && (value === '<' || value === '</')) { - this._onStartTag(token); - this._state = ParseState.Tag; + this.onStartTag(token); + this.state = ParseState.Tag; } return; case ParseState.Tag: if (hasTokenInSet(type, 'tag') && !hasTokenInSet(type, 'bracket')) { - this._tagName = value.trim().toLowerCase(); + this.tagName = value.trim().toLowerCase(); } else if (hasTokenInSet(type, 'attribute')) { - this._attributeName = value.trim().toLowerCase(); - this._attributes.set(this._attributeName, ''); - this._state = ParseState.AttributeName; + this.attributeName = value.trim().toLowerCase(); + this.attributes.set(this.attributeName, ''); + this.state = ParseState.AttributeName; } else if (hasTokenInSet(type, 'bracket') && (value === '>' || value === '/>')) { - this._onEndTag(token); - this._state = ParseState.Initial; + this.onEndTag(token); + this.state = ParseState.Initial; } return; case ParseState.AttributeName: if (!type.size && value === '=') { - this._state = ParseState.AttributeValue; + this.state = ParseState.AttributeValue; } else if (hasTokenInSet(type, 'bracket') && (value === '>' || value === '/>')) { - this._onEndTag(token); - this._state = ParseState.Initial; + this.onEndTag(token); + this.state = ParseState.Initial; } return; case ParseState.AttributeValue: if (hasTokenInSet(type, 'string')) { - this._attributes.set(this._attributeName, value); - this._state = ParseState.Tag; + this.attributes.set(this.attributeName, value); + this.state = ParseState.Tag; } else if (hasTokenInSet(type, 'bracket') && (value === '>' || value === '/>')) { - this._onEndTag(token); - this._state = ParseState.Initial; + this.onEndTag(token); + this.state = ParseState.Initial; } return; } } - _onStartTag(token: Token): void { - this._tagName = ''; - this._tagStartOffset = token.startOffset; - this._tagEndOffset = null; - this._attributes = new Map(); - this._attributeName = ''; - this._isOpenTag = token.value === '<'; + private onStartTag(token: Token): void { + this.tagName = ''; + this.tagStartOffset = token.startOffset; + this.tagEndOffset = null; + this.attributes = new Map(); + this.attributeName = ''; + this.isOpenTag = token.value === '<'; } - _onEndTag(token: Token): void { - this._tagEndOffset = token.endOffset; - const selfClosingTag = token.value === '/>' || SelfClosingTags.has(this._tagName); + private onEndTag(token: Token): void { + this.tagEndOffset = token.endOffset; + const selfClosingTag = token.value === '/>' || SelfClosingTags.has(this.tagName); const tag = new Tag( - this._tagName, this._tagStartOffset || 0, this._tagEndOffset, this._attributes, this._isOpenTag, - selfClosingTag); - this._onTagComplete(tag); + this.tagName, this.tagStartOffset || 0, this.tagEndOffset, this.attributes, this.isOpenTag, selfClosingTag); + this.onTagComplete(tag); } - _onTagComplete(tag: Tag): void { + private onTagComplete(tag: Tag): void { if (tag.isOpenTag) { - const topElement = this._stack[this._stack.length - 1]; + const topElement = this.stack[this.stack.length - 1]; if (topElement) { const tagSet = AutoClosingTags.get(topElement.name); - if (topElement !== this._document && topElement.openTag && topElement.openTag.selfClosingTag) { - this._popElement(autocloseTag(topElement, topElement.openTag.endOffset)); + if (topElement !== this.documentInternal && topElement.openTag && topElement.openTag.selfClosingTag) { + this.popElement(autocloseTag(topElement, topElement.openTag.endOffset)); } else if (tagSet && tagSet.has(tag.name)) { - this._popElement(autocloseTag(topElement, tag.startOffset)); + this.popElement(autocloseTag(topElement, tag.startOffset)); } - this._pushElement(tag); + this.pushElement(tag); } return; } - let lastTag = this._stack[this._stack.length - 1]; - while (this._stack.length > 1 && lastTag && lastTag.name !== tag.name) { - this._popElement(autocloseTag(lastTag, tag.startOffset)); - lastTag = this._stack[this._stack.length - 1]; + let lastTag = this.stack[this.stack.length - 1]; + while (this.stack.length > 1 && lastTag && lastTag.name !== tag.name) { + this.popElement(autocloseTag(lastTag, tag.startOffset)); + lastTag = this.stack[this.stack.length - 1]; } - if (this._stack.length === 1) { + if (this.stack.length === 1) { return; } - this._popElement(tag); + this.popElement(tag); function autocloseTag(element: FormatterElement, offset: number): Tag { return new Tag(element.name, offset, offset, new Map(), false, false); } } - _popElement(closeTag: Tag): void { - const element = this._stack.pop(); + private popElement(closeTag: Tag): void { + const element = this.stack.pop(); if (!element) { return; } element.closeTag = closeTag; } - _pushElement(openTag: Tag): void { - const topElement = this._stack[this._stack.length - 1]; + private pushElement(openTag: Tag): void { + const topElement = this.stack[this.stack.length - 1]; const newElement = new FormatterElement(openTag.name); if (topElement) { newElement.parent = topElement; topElement.children.push(newElement); } newElement.openTag = openTag; - this._stack.push(newElement); + this.stack.push(newElement); } peekToken(): Token|null { - return this._tokenIndex < this._tokens.length ? this._tokens[this._tokenIndex] : null; + return this.tokenIndex < this.tokens.length ? this.tokens[this.tokenIndex] : null; } nextToken(): Token|null { - return this._tokens[this._tokenIndex++]; + return this.tokens[this.tokenIndex++]; } document(): FormatterElement { - return this._document; + return this.documentInternal; } }
diff --git a/front_end/entrypoints/formatter_worker/HTMLOutline.ts b/front_end/entrypoints/formatter_worker/HTMLOutline.ts index 05fb593..e29a987 100644 --- a/front_end/entrypoints/formatter_worker/HTMLOutline.ts +++ b/front_end/entrypoints/formatter_worker/HTMLOutline.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Platform from '../../core/platform/platform.js'; import * as TextUtils from '../../models/text_utils/text_utils.js';
diff --git a/front_end/entrypoints/formatter_worker/JavaScriptFormatter.ts b/front_end/entrypoints/formatter_worker/JavaScriptFormatter.ts index c56e54d..7bc55bd 100644 --- a/front_end/entrypoints/formatter_worker/JavaScriptFormatter.ts +++ b/front_end/entrypoints/formatter_worker/JavaScriptFormatter.ts
@@ -28,8 +28,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Acorn from '../../third_party/acorn/acorn.js'; import type {TokenOrComment} from './AcornTokenizer.js'; @@ -38,30 +36,30 @@ import type {FormattedContentBuilder} from './FormattedContentBuilder.js'; export class JavaScriptFormatter { - _builder: FormattedContentBuilder; - _tokenizer!: AcornTokenizer; - _content!: string; - _fromOffset!: number; - _lastLineNumber!: number; - _toOffset?: number; + private readonly builder: FormattedContentBuilder; + private tokenizer!: AcornTokenizer; + private content!: string; + private fromOffset!: number; + private lastLineNumber!: number; + private toOffset?: number; constructor(builder: FormattedContentBuilder) { - this._builder = builder; + this.builder = builder; } format(text: string, lineEndings: number[], fromOffset: number, toOffset: number): void { - this._fromOffset = fromOffset; - this._toOffset = toOffset; - this._content = text.substring(this._fromOffset, this._toOffset); - this._lastLineNumber = 0; - this._tokenizer = new AcornTokenizer(this._content); - const ast = Acorn.parse(this._content, { + this.fromOffset = fromOffset; + this.toOffset = toOffset; + this.content = text.substring(this.fromOffset, this.toOffset); + this.lastLineNumber = 0; + this.tokenizer = new AcornTokenizer(this.content); + const ast = Acorn.parse(this.content, { ranges: false, preserveParens: true, allowImportExportEverywhere: true, ecmaVersion: ECMA_VERSION, allowHashBang: true, }); - const walker = new ESTreeWalker(this._beforeVisit.bind(this), this._afterVisit.bind(this)); + const walker = new ESTreeWalker(this.beforeVisit.bind(this), this.afterVisit.bind(this)); // @ts-ignore Technically, the acorn Node type is a subclass of Acorn.ESTree.Node. // However, the acorn package currently exports its type without specifying // this relationship. So while this is allowed on runtime, we can't properly @@ -69,55 +67,55 @@ walker.walk(ast); } - _push(token: Acorn.Token|Acorn.Comment|null, format: string): void { + private push(token: Acorn.Token|Acorn.Comment|null, format: string): void { for (let i = 0; i < format.length; ++i) { if (format[i] === 's') { - this._builder.addSoftSpace(); + this.builder.addSoftSpace(); } else if (format[i] === 'S') { - this._builder.addHardSpace(); + this.builder.addHardSpace(); } else if (format[i] === 'n') { - this._builder.addNewLine(); + this.builder.addNewLine(); } else if (format[i] === '>') { - this._builder.increaseNestingLevel(); + this.builder.increaseNestingLevel(); } else if (format[i] === '<') { - this._builder.decreaseNestingLevel(); + this.builder.decreaseNestingLevel(); } else if (format[i] === 't') { - if (this._tokenizer.tokenLineStart() - this._lastLineNumber > 1) { - this._builder.addNewLine(true); + if (this.tokenizer.tokenLineStart() - this.lastLineNumber > 1) { + this.builder.addNewLine(true); } - this._lastLineNumber = this._tokenizer.tokenLineEnd(); + this.lastLineNumber = this.tokenizer.tokenLineEnd(); if (token) { - this._builder.addToken(this._content.substring(token.start, token.end), this._fromOffset + token.start); + this.builder.addToken(this.content.substring(token.start, token.end), this.fromOffset + token.start); } } } } - _beforeVisit(node: Acorn.ESTree.Node): undefined { + private beforeVisit(node: Acorn.ESTree.Node): undefined { if (!node.parent) { return; } let token; - while ((token = this._tokenizer.peekToken()) && token.start < node.start) { - const token = (this._tokenizer.nextToken() as TokenOrComment); + while ((token = this.tokenizer.peekToken()) && token.start < node.start) { + const token = (this.tokenizer.nextToken() as TokenOrComment); // @ts-ignore Same reason as above about Acorn types and ESTree types - const format = this._formatToken(node.parent, token); - this._push(token, format); + const format = this.formatToken(node.parent, token); + this.push(token, format); } return; } - _afterVisit(node: Acorn.ESTree.Node): void { + private afterVisit(node: Acorn.ESTree.Node): void { let token; - while ((token = this._tokenizer.peekToken()) && token.start < node.end) { - const token = (this._tokenizer.nextToken() as TokenOrComment); - const format = this._formatToken(node, token); - this._push(token, format); + while ((token = this.tokenizer.peekToken()) && token.start < node.end) { + const token = (this.tokenizer.nextToken() as TokenOrComment); + const format = this.formatToken(node, token); + this.push(token, format); } - this._push(null, this._finishNode(node)); + this.push(null, this.finishNode(node)); } - _inForLoopHeader(node: Acorn.ESTree.Node): boolean { + private inForLoopHeader(node: Acorn.ESTree.Node): boolean { const parent = node.parent; if (!parent) { return false; @@ -133,7 +131,7 @@ return false; } - _formatToken(node: Acorn.ESTree.Node, tokenOrComment: TokenOrComment): string { + private formatToken(node: Acorn.ESTree.Node, tokenOrComment: TokenOrComment): string { const AT = AcornTokenizer; if (AT.lineComment(tokenOrComment)) { return 'tn'; @@ -243,7 +241,7 @@ // it exists. We can't fix that, unless we use proper typechecking allVariablesInitialized = allVariablesInitialized && Boolean(declarations[i].init); } - return !this._inForLoopHeader(node) && allVariablesInitialized ? 'nSSts' : 'ts'; + return !this.inForLoopHeader(node) && allVariablesInitialized ? 'nSSts' : 'ts'; } } else if (node.type === 'PropertyDefinition') { if (AT.punctuator(token, '=')) { @@ -358,13 +356,13 @@ return AT.keyword(token) && !AT.keyword(token, 'this') ? 'ts' : 't'; } - _finishNode(node: Acorn.ESTree.Node): string { + private finishNode(node: Acorn.ESTree.Node): string { if (node.type === 'WithStatement') { if (node.body && node.body.type !== 'BlockStatement') { return 'n<'; } } else if (node.type === 'VariableDeclaration') { - if (!this._inForLoopHeader(node)) { + if (!this.inForLoopHeader(node)) { return 'n'; } } else if (node.type === 'ForStatement' || node.type === 'ForOfStatement' || node.type === 'ForInStatement') {
diff --git a/front_end/entrypoints/formatter_worker/JavaScriptOutline.ts b/front_end/entrypoints/formatter_worker/JavaScriptOutline.ts index 6151770..a939297 100644 --- a/front_end/entrypoints/formatter_worker/JavaScriptOutline.ts +++ b/front_end/entrypoints/formatter_worker/JavaScriptOutline.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Platform from '../../core/platform/platform.js'; import * as TextUtils from '../../models/text_utils/text_utils.js'; import * as AcornLoose from '../../third_party/acorn-loose/acorn-loose.js';
diff --git a/front_end/entrypoints/heap_snapshot_worker/AllocationProfile.ts b/front_end/entrypoints/heap_snapshot_worker/AllocationProfile.ts index 29b1018..4e0a9ff 100644 --- a/front_end/entrypoints/heap_snapshot_worker/AllocationProfile.ts +++ b/front_end/entrypoints/heap_snapshot_worker/AllocationProfile.ts
@@ -28,50 +28,48 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import * as HeapSnapshotModel from '../../models/heap_snapshot_model/heap_snapshot_model.js'; export class AllocationProfile { // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/no-explicit-any - _strings: any; + private readonly strings: any; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/no-explicit-any - _liveObjectStats: any; - _nextNodeId: number; - _functionInfos: FunctionAllocationInfo[]; - _idToNode: {[x: number]: BottomUpAllocationNode|null}; - _idToTopDownNode: {[x: number]: TopDownAllocationNode}; - _collapsedTopNodeIdToFunctionInfo: {[x: number]: FunctionAllocationInfo}; - _traceTops: HeapSnapshotModel.HeapSnapshotModel.SerializedAllocationNode[]|null; - _traceTree: TopDownAllocationNode; + private readonly liveObjectStats: any; + private nextNodeId: number; + private functionInfos: FunctionAllocationInfo[]; + private idToNode: {[x: number]: BottomUpAllocationNode|null}; + private readonly idToTopDownNode: {[x: number]: TopDownAllocationNode}; + private collapsedTopNodeIdToFunctionInfo: {[x: number]: FunctionAllocationInfo}; + private traceTops: HeapSnapshotModel.HeapSnapshotModel.SerializedAllocationNode[]|null; + private readonly traceTree: TopDownAllocationNode; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(profile: any, liveObjectStats: any) { - this._strings = profile.strings; - this._liveObjectStats = liveObjectStats; + this.strings = profile.strings; + this.liveObjectStats = liveObjectStats; - this._nextNodeId = 1; - this._functionInfos = []; + this.nextNodeId = 1; + this.functionInfos = []; - this._idToNode = {}; + this.idToNode = {}; - this._idToTopDownNode = {}; + this.idToTopDownNode = {}; - this._collapsedTopNodeIdToFunctionInfo = {}; + this.collapsedTopNodeIdToFunctionInfo = {}; - this._traceTops = null; + this.traceTops = null; - this._buildFunctionAllocationInfos(profile); - this._traceTree = this._buildAllocationTree(profile, liveObjectStats); + this.buildFunctionAllocationInfos(profile); + this.traceTree = this.buildAllocationTree(profile, liveObjectStats); } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/no-explicit-any - _buildFunctionAllocationInfos(profile: any): void { - const strings = this._strings; + private buildFunctionAllocationInfos(profile: any): void { + const strings = this.strings; const functionInfoFields = profile.snapshot.meta.trace_function_info_fields; const functionNameOffset = functionInfoFields.indexOf('name'); @@ -83,7 +81,7 @@ const rawInfos = profile.trace_function_infos; const infoLength = rawInfos.length; - const functionInfos = this._functionInfos = new Array(infoLength / functionInfoFieldCount); + const functionInfos = this.functionInfos = new Array(infoLength / functionInfoFieldCount); let index = 0; for (let i = 0; i < infoLength; i += functionInfoFieldCount) { functionInfos[index++] = new FunctionAllocationInfo( @@ -94,10 +92,10 @@ // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/no-explicit-any - _buildAllocationTree(profile: any, liveObjectStats: any): TopDownAllocationNode { + private buildAllocationTree(profile: any, liveObjectStats: any): TopDownAllocationNode { const traceTreeRaw = profile.trace_tree; - const functionInfos = this._functionInfos; - const idToTopDownNode = this._idToTopDownNode; + const functionInfos = this.functionInfos; + const idToTopDownNode = this.idToTopDownNode; const traceNodeFields = profile.snapshot.meta.trace_node_fields; const nodeIdOffset = traceNodeFields.indexOf('id'); @@ -134,22 +132,22 @@ } serializeTraceTops(): HeapSnapshotModel.HeapSnapshotModel.SerializedAllocationNode[] { - if (this._traceTops) { - return this._traceTops; + if (this.traceTops) { + return this.traceTops; } - const result: HeapSnapshotModel.HeapSnapshotModel.SerializedAllocationNode[] = this._traceTops = []; - const functionInfos = this._functionInfos; + const result: HeapSnapshotModel.HeapSnapshotModel.SerializedAllocationNode[] = this.traceTops = []; + const functionInfos = this.functionInfos; for (let i = 0; i < functionInfos.length; i++) { const info = functionInfos[i]; if (info.totalCount === 0) { continue; } - const nodeId = this._nextNodeId++; + const nodeId = this.nextNodeId++; const isRoot = i === 0; - result.push(this._serializeNode( + result.push(this.serializeNode( nodeId, info, info.totalCount, info.totalSize, info.totalLiveCount, info.totalLiveSize, !isRoot)); - this._collapsedTopNodeIdToFunctionInfo[nodeId] = info; + this.collapsedTopNodeIdToFunctionInfo[nodeId] = info; } result.sort(function(a, b) { return b.size - a.size; @@ -158,24 +156,24 @@ } serializeCallers(nodeId: number): HeapSnapshotModel.HeapSnapshotModel.AllocationNodeCallers { - let node = this._ensureBottomUpNode(nodeId); + let node = this.ensureBottomUpNode(nodeId); const nodesWithSingleCaller = []; while (node.callers().length === 1) { node = node.callers()[0]; - nodesWithSingleCaller.push(this._serializeCaller(node)); + nodesWithSingleCaller.push(this.serializeCaller(node)); } const branchingCallers = []; const callers = node.callers(); for (let i = 0; i < callers.length; i++) { - branchingCallers.push(this._serializeCaller(callers[i])); + branchingCallers.push(this.serializeCaller(callers[i])); } return new HeapSnapshotModel.HeapSnapshotModel.AllocationNodeCallers(nodesWithSingleCaller, branchingCallers); } serializeAllocationStack(traceNodeId: number): HeapSnapshotModel.HeapSnapshotModel.AllocationStackFrame[] { - let node: (TopDownAllocationNode|null)|TopDownAllocationNode = this._idToTopDownNode[traceNodeId]; + let node: (TopDownAllocationNode|null)|TopDownAllocationNode = this.idToTopDownNode[traceNodeId]; const result = []; while (node) { const functionInfo = node.functionInfo; @@ -188,29 +186,29 @@ } traceIds(allocationNodeId: number): number[] { - return this._ensureBottomUpNode(allocationNodeId).traceTopIds; + return this.ensureBottomUpNode(allocationNodeId).traceTopIds; } - _ensureBottomUpNode(nodeId: number): BottomUpAllocationNode { - let node: (BottomUpAllocationNode|null) = this._idToNode[nodeId]; + private ensureBottomUpNode(nodeId: number): BottomUpAllocationNode { + let node: (BottomUpAllocationNode|null) = this.idToNode[nodeId]; if (!node) { - const functionInfo = this._collapsedTopNodeIdToFunctionInfo[nodeId]; + const functionInfo = this.collapsedTopNodeIdToFunctionInfo[nodeId]; node = functionInfo.bottomUpRoot(); - delete this._collapsedTopNodeIdToFunctionInfo[nodeId]; - this._idToNode[nodeId] = node; + delete this.collapsedTopNodeIdToFunctionInfo[nodeId]; + this.idToNode[nodeId] = node; } return /** @type {!BottomUpAllocationNode} */ node as BottomUpAllocationNode; } - _serializeCaller(node: BottomUpAllocationNode): HeapSnapshotModel.HeapSnapshotModel.SerializedAllocationNode { - const callerId = this._nextNodeId++; - this._idToNode[callerId] = node; - return this._serializeNode( + private serializeCaller(node: BottomUpAllocationNode): HeapSnapshotModel.HeapSnapshotModel.SerializedAllocationNode { + const callerId = this.nextNodeId++; + this.idToNode[callerId] = node; + return this.serializeNode( callerId, node.functionInfo, node.allocationCount, node.allocationSize, node.liveCount, node.liveSize, node.hasCallers()); } - _serializeNode( + private serializeNode( nodeId: number, functionInfo: FunctionAllocationInfo, count: number, size: number, liveCount: number, liveSize: number, hasChildren: boolean): HeapSnapshotModel.HeapSnapshotModel.SerializedAllocationNode { return new HeapSnapshotModel.HeapSnapshotModel.SerializedAllocationNode( @@ -250,7 +248,7 @@ liveCount: number; liveSize: number; traceTopIds: number[]; - _callers: BottomUpAllocationNode[]; + private readonly callersInternal: BottomUpAllocationNode[]; constructor(functionInfo: FunctionAllocationInfo) { this.functionInfo = functionInfo; this.allocationCount = 0; @@ -260,14 +258,14 @@ this.traceTopIds = []; - this._callers = []; + this.callersInternal = []; } addCaller(traceNode: TopDownAllocationNode): BottomUpAllocationNode { const functionInfo = traceNode.functionInfo; let result; - for (let i = 0; i < this._callers.length; i++) { - const caller = this._callers[i]; + for (let i = 0; i < this.callersInternal.length; i++) { + const caller = this.callersInternal[i]; if (caller.functionInfo === functionInfo) { result = caller; break; @@ -275,17 +273,17 @@ } if (!result) { result = new BottomUpAllocationNode(functionInfo); - this._callers.push(result); + this.callersInternal.push(result); } return result; } callers(): BottomUpAllocationNode[] { - return this._callers; + return this.callersInternal; } hasCallers(): boolean { - return this._callers.length > 0; + return this.callersInternal.length > 0; } } @@ -299,8 +297,8 @@ totalSize: number; totalLiveCount: number; totalLiveSize: number; - _traceTops: TopDownAllocationNode[]; - _bottomUpTree?: BottomUpAllocationNode; + private traceTops: TopDownAllocationNode[]; + private bottomUpTree?: BottomUpAllocationNode; constructor(functionName: string, scriptName: string, scriptId: number, line: number, column: number) { this.functionName = functionName; this.scriptName = scriptName; @@ -312,14 +310,14 @@ this.totalLiveCount = 0; this.totalLiveSize = 0; - this._traceTops = []; + this.traceTops = []; } addTraceTopNode(node: TopDownAllocationNode): void { if (node.allocationCount === 0) { return; } - this._traceTops.push(node); + this.traceTops.push(node); this.totalCount += node.allocationCount; this.totalSize += node.allocationSize; this.totalLiveCount += node.liveCount; @@ -327,21 +325,21 @@ } bottomUpRoot(): BottomUpAllocationNode|null { - if (!this._traceTops.length) { + if (!this.traceTops.length) { return null; } - if (!this._bottomUpTree) { - this._buildAllocationTraceTree(); + if (!this.bottomUpTree) { + this.buildAllocationTraceTree(); } - return /** @type {!BottomUpAllocationNode} */ this._bottomUpTree as BottomUpAllocationNode; + return /** @type {!BottomUpAllocationNode} */ this.bottomUpTree as BottomUpAllocationNode; } - _buildAllocationTraceTree(): void { - this._bottomUpTree = new BottomUpAllocationNode(this); + private buildAllocationTraceTree(): void { + this.bottomUpTree = new BottomUpAllocationNode(this); - for (let i = 0; i < this._traceTops.length; i++) { - let node: (TopDownAllocationNode|null)|TopDownAllocationNode = this._traceTops[i]; - let bottomUpNode: BottomUpAllocationNode = this._bottomUpTree; + for (let i = 0; i < this.traceTops.length; i++) { + let node: (TopDownAllocationNode|null)|TopDownAllocationNode = this.traceTops[i]; + let bottomUpNode: BottomUpAllocationNode = this.bottomUpTree; const count = node.allocationCount; const size = node.allocationSize; const liveCount = node.liveCount;
diff --git a/front_end/entrypoints/heap_snapshot_worker/HeapSnapshot.ts b/front_end/entrypoints/heap_snapshot_worker/HeapSnapshot.ts index aaae655..4c99535 100644 --- a/front_end/entrypoints/heap_snapshot_worker/HeapSnapshot.ts +++ b/front_end/entrypoints/heap_snapshot_worker/HeapSnapshot.ts
@@ -28,8 +28,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; import * as HeapSnapshotModel from '../../models/heap_snapshot_model/heap_snapshot_model.js'; @@ -48,17 +46,17 @@ } export class HeapSnapshotEdge implements HeapSnapshotItem { - _snapshot: HeapSnapshot; - _edges: Uint32Array; + snapshot: HeapSnapshot; + readonly edges: Uint32Array; edgeIndex: number; constructor(snapshot: HeapSnapshot, edgeIndex?: number) { - this._snapshot = snapshot; - this._edges = snapshot.containmentEdges; + this.snapshot = snapshot; + this.edges = snapshot.containmentEdges; this.edgeIndex = edgeIndex || 0; } clone(): HeapSnapshotEdge { - return new HeapSnapshotEdge(this._snapshot, this.edgeIndex); + return new HeapSnapshotEdge(this.snapshot, this.edgeIndex); } hasStringName(): boolean { @@ -70,15 +68,15 @@ } node(): HeapSnapshotNode { - return this._snapshot.createNode(this.nodeIndex()); + return this.snapshot.createNode(this.nodeIndex()); } nodeIndex(): number { - if (typeof this._snapshot._edgeToNodeOffset === 'undefined') { + if (typeof this.snapshot.getEdgeToNodeOffset() === 'undefined') { throw new Error('edgeToNodeOffset is undefined'); } - return this._edges[this.edgeIndex + this._snapshot._edgeToNodeOffset]; + return this.edges[this.edgeIndex + this.snapshot.getEdgeToNodeOffset()]; } toString(): string { @@ -86,7 +84,7 @@ } type(): string { - return this._snapshot._edgeTypes[this.rawType()]; + return this.snapshot.getEdgeTypes()[this.rawType()]; } itemIndex(): number { @@ -99,11 +97,11 @@ } rawType(): number { - if (typeof this._snapshot._edgeTypeOffset === 'undefined') { + if (typeof this.snapshot.getEdgeTypeOffset() === 'undefined') { throw new Error('edgeTypeOffset is undefined'); } - return this._edges[this.edgeIndex + this._snapshot._edgeTypeOffset]; + return this.edges[this.edgeIndex + this.snapshot.getEdgeTypeOffset()]; } isInvisible(): boolean { @@ -113,6 +111,10 @@ isWeak(): boolean { throw new Error('Not implemented'); } + + getSnapshot(): HeapSnapshot { + return this.snapshot; + } } /** @@ -134,51 +136,51 @@ } export class HeapSnapshotNodeIndexProvider implements HeapSnapshotItemIndexProvider { - _node: HeapSnapshotNode; + private node: HeapSnapshotNode; constructor(snapshot: HeapSnapshot) { - this._node = snapshot.createNode(); + this.node = snapshot.createNode(); } itemForIndex(index: number): HeapSnapshotNode { - this._node.nodeIndex = index; - return this._node; + this.node.nodeIndex = index; + return this.node; } } export class HeapSnapshotEdgeIndexProvider implements HeapSnapshotItemIndexProvider { - _edge: JSHeapSnapshotEdge; + private edge: JSHeapSnapshotEdge; constructor(snapshot: HeapSnapshot) { - this._edge = snapshot.createEdge(0); + this.edge = snapshot.createEdge(0); } itemForIndex(index: number): HeapSnapshotEdge { - this._edge.edgeIndex = index; - return this._edge; + this.edge.edgeIndex = index; + return this.edge; } } export class HeapSnapshotRetainerEdgeIndexProvider implements HeapSnapshotItemIndexProvider { - _retainerEdge: JSHeapSnapshotRetainerEdge; + private readonly retainerEdge: JSHeapSnapshotRetainerEdge; constructor(snapshot: HeapSnapshot) { - this._retainerEdge = snapshot.createRetainingEdge(0); + this.retainerEdge = snapshot.createRetainingEdge(0); } itemForIndex(index: number): HeapSnapshotRetainerEdge { - this._retainerEdge.setRetainerIndex(index); - return this._retainerEdge; + this.retainerEdge.setRetainerIndex(index); + return this.retainerEdge; } } export class HeapSnapshotEdgeIterator implements HeapSnapshotItemIterator { - _sourceNode: HeapSnapshotNode; + private readonly sourceNode: HeapSnapshotNode; edge: JSHeapSnapshotEdge; constructor(node: HeapSnapshotNode) { - this._sourceNode = node; - this.edge = node._snapshot.createEdge(node.edgeIndexesStart()); + this.sourceNode = node; + this.edge = node.getSnapshot().createEdge(node.edgeIndexesStart()); } hasNext(): boolean { - return this.edge.edgeIndex < this._sourceNode.edgeIndexesEnd(); + return this.edge.edgeIndex < this.sourceNode.edgeIndexesEnd(); } item(): HeapSnapshotEdge { @@ -186,121 +188,125 @@ } next(): void { - if (typeof this.edge._snapshot._edgeFieldsCount === 'undefined') { + if (typeof this.edge.getSnapshot().getEdgeFieldsCount() === 'undefined') { throw new Error('edgeFieldsCount is undefined'); } - this.edge.edgeIndex += this.edge._snapshot._edgeFieldsCount; + this.edge.edgeIndex += this.edge.getSnapshot().getEdgeFieldsCount(); } } export class HeapSnapshotRetainerEdge implements HeapSnapshotItem { - _snapshot: HeapSnapshot; - _retainerIndex!: number; - _globalEdgeIndex!: number; - _retainingNodeIndex?: number; - _edgeInstance?: JSHeapSnapshotEdge|null; - _nodeInstance?: HeapSnapshotNode|null; + snapshot: HeapSnapshot; + private retainerIndexInternal!: number; + private globalEdgeIndex!: number; + private retainingNodeIndex?: number; + private edgeInstance?: JSHeapSnapshotEdge|null; + private nodeInstance?: HeapSnapshotNode|null; constructor(snapshot: HeapSnapshot, retainerIndex: number) { - this._snapshot = snapshot; + this.snapshot = snapshot; this.setRetainerIndex(retainerIndex); } clone(): HeapSnapshotRetainerEdge { - return new HeapSnapshotRetainerEdge(this._snapshot, this.retainerIndex()); + return new HeapSnapshotRetainerEdge(this.snapshot, this.retainerIndex()); } hasStringName(): boolean { - return this._edge().hasStringName(); + return this.edge().hasStringName(); } name(): string { - return this._edge().name(); + return this.edge().name(); } node(): HeapSnapshotNode { - return this._node(); + return this.nodeInternal(); } nodeIndex(): number { - if (typeof this._retainingNodeIndex === 'undefined') { + if (typeof this.retainingNodeIndex === 'undefined') { throw new Error('retainingNodeIndex is undefined'); } - return this._retainingNodeIndex; + return this.retainingNodeIndex; } retainerIndex(): number { - return this._retainerIndex; + return this.retainerIndexInternal; } setRetainerIndex(retainerIndex: number): void { - if (retainerIndex === this._retainerIndex) { + if (retainerIndex === this.retainerIndexInternal) { return; } - if (!this._snapshot._retainingEdges || !this._snapshot._retainingNodes) { + if (!this.snapshot.getRetainingEdges() || !this.snapshot.getRetainingNodes()) { throw new Error('Snapshot does not contain retaining edges or retaining nodes'); } - this._retainerIndex = retainerIndex; - this._globalEdgeIndex = this._snapshot._retainingEdges[retainerIndex]; - this._retainingNodeIndex = this._snapshot._retainingNodes[retainerIndex]; - this._edgeInstance = null; - this._nodeInstance = null; + this.retainerIndexInternal = retainerIndex; + this.globalEdgeIndex = this.snapshot.getRetainingEdges()[retainerIndex]; + this.retainingNodeIndex = this.snapshot.getRetainingNodes()[retainerIndex]; + this.edgeInstance = null; + this.nodeInstance = null; } set edgeIndex(edgeIndex: number) { this.setRetainerIndex(edgeIndex); } - _node(): HeapSnapshotNode { - if (!this._nodeInstance) { - this._nodeInstance = this._snapshot.createNode(this._retainingNodeIndex); + private nodeInternal(): HeapSnapshotNode { + if (!this.nodeInstance) { + this.nodeInstance = this.snapshot.createNode(this.retainingNodeIndex); } - return this._nodeInstance; + return this.nodeInstance; } - _edge(): JSHeapSnapshotEdge { - if (!this._edgeInstance) { - this._edgeInstance = this._snapshot.createEdge(this._globalEdgeIndex); + edge(): JSHeapSnapshotEdge { + if (!this.edgeInstance) { + this.edgeInstance = this.snapshot.createEdge(this.globalEdgeIndex); } - return this._edgeInstance; + return this.edgeInstance; } toString(): string { - return this._edge().toString(); + return this.edge().toString(); } itemIndex(): number { - return this._retainerIndex; + return this.retainerIndexInternal; } serialize(): HeapSnapshotModel.HeapSnapshotModel.Edge { return new HeapSnapshotModel.HeapSnapshotModel.Edge( - this.name(), this.node().serialize(), this.type(), this._globalEdgeIndex); + this.name(), this.node().serialize(), this.type(), this.globalEdgeIndex); } type(): string { - return this._edge().type(); + return this.edge().type(); + } + + getSnapshot(): HeapSnapshot { + return this.snapshot; } } export class HeapSnapshotRetainerEdgeIterator implements HeapSnapshotItemIterator { - _retainersEnd: number; + private readonly retainersEnd: number; retainer: JSHeapSnapshotRetainerEdge; constructor(retainedNode: HeapSnapshotNode) { - const snapshot = retainedNode._snapshot; + const snapshot = retainedNode.getSnapshot(); const retainedNodeOrdinal = retainedNode.ordinal(); - if (!snapshot._firstRetainerIndex) { + if (!snapshot.getFirstRetainerIndex()) { throw new Error('Snapshot does not contain firstRetainerIndex'); } - const retainerIndex = snapshot._firstRetainerIndex[retainedNodeOrdinal]; - this._retainersEnd = snapshot._firstRetainerIndex[retainedNodeOrdinal + 1]; + const retainerIndex = snapshot.getFirstRetainerIndex()[retainedNodeOrdinal]; + this.retainersEnd = snapshot.getFirstRetainerIndex()[retainedNodeOrdinal + 1]; this.retainer = snapshot.createRetainingEdge(retainerIndex); } hasNext(): boolean { - return this.retainer.retainerIndex() < this._retainersEnd; + return this.retainer.retainerIndex() < this.retainersEnd; } item(): HeapSnapshotRetainerEdge { @@ -313,15 +319,15 @@ } export class HeapSnapshotNode implements HeapSnapshotItem { - _snapshot: HeapSnapshot; + snapshot: HeapSnapshot; nodeIndex: number; constructor(snapshot: HeapSnapshot, nodeIndex?: number) { - this._snapshot = snapshot; + this.snapshot = snapshot; this.nodeIndex = nodeIndex || 0; } distance(): number { - return this._snapshot._nodeDistances[this.nodeIndex / this._snapshot._nodeFieldCount]; + return this.snapshot.getNodeDistances()[this.nodeIndex / this.snapshot.getNodeFieldCount()]; } className(): string { @@ -333,8 +339,8 @@ } dominatorIndex(): number { - const nodeFieldCount = this._snapshot._nodeFieldCount; - return this._snapshot._dominatorsTree[this.nodeIndex / this._snapshot._nodeFieldCount] * nodeFieldCount; + const nodeFieldCount = this.snapshot.getNodeFieldCount(); + return this.snapshot.getDominatorsTree()[this.nodeIndex / this.snapshot.getNodeFieldCount()] * nodeFieldCount; } edges(): HeapSnapshotEdgeIterator { @@ -342,7 +348,7 @@ } edgesCount(): number { - return (this.edgeIndexesEnd() - this.edgeIndexesStart()) / this._snapshot._edgeFieldsCount; + return (this.edgeIndexesEnd() - this.edgeIndexesStart()) / this.snapshot.getEdgeFieldsCount(); } id(): number { @@ -354,7 +360,7 @@ } isRoot(): boolean { - return this.nodeIndex === this._snapshot._rootNodeIndex; + return this.nodeIndex === this.snapshot.rootNodeIndex; } isUserRoot(): boolean { @@ -374,11 +380,11 @@ } name(): string { - return this._snapshot.strings[this._name()]; + return this.snapshot.strings[this.nameInternal()]; } retainedSize(): number { - return this._snapshot._retainedSizes[this.ordinal()]; + return this.snapshot.getRetainedSizes()[this.ordinal()]; } retainers(): HeapSnapshotRetainerEdgeIterator { @@ -386,23 +392,23 @@ } retainersCount(): number { - const snapshot = this._snapshot; + const snapshot = this.snapshot; const ordinal = this.ordinal(); - return snapshot._firstRetainerIndex[ordinal + 1] - snapshot._firstRetainerIndex[ordinal]; + return snapshot.getFirstRetainerIndex()[ordinal + 1] - snapshot.getFirstRetainerIndex()[ordinal]; } selfSize(): number { - const snapshot = this._snapshot; - return snapshot.nodes[this.nodeIndex + snapshot._nodeSelfSizeOffset]; + const snapshot = this.snapshot; + return snapshot.nodes[this.nodeIndex + snapshot.getNodeSelfSizeOffset()]; } type(): string { - return this._snapshot._nodeTypes[this.rawType()]; + return this.snapshot.getNodeTypes()[this.rawType()]; } traceNodeId(): number { - const snapshot = this._snapshot; - return snapshot.nodes[this.nodeIndex + snapshot._nodeTraceNodeIdOffset]; + const snapshot = this.snapshot; + return snapshot.nodes[this.nodeIndex + snapshot.getNodeTraceNodeIdOffset()]; } itemIndex(): number { @@ -414,43 +420,47 @@ this.id(), this.name(), this.distance(), this.nodeIndex, this.retainedSize(), this.selfSize(), this.type()); } - _name(): number { - const snapshot = this._snapshot; - return snapshot.nodes[this.nodeIndex + snapshot._nodeNameOffset]; + private nameInternal(): number { + const snapshot = this.snapshot; + return snapshot.nodes[this.nodeIndex + snapshot.getNodeNameOffset()]; } edgeIndexesStart(): number { - return this._snapshot._firstEdgeIndexes[this.ordinal()]; + return this.snapshot.getFirstEdgeIndexes()[this.ordinal()]; } edgeIndexesEnd(): number { - return this._snapshot._firstEdgeIndexes[this.ordinal() + 1]; + return this.snapshot.getFirstEdgeIndexes()[this.ordinal() + 1]; } ordinal(): number { - return this.nodeIndex / this._snapshot._nodeFieldCount; + return this.nodeIndex / this.snapshot.getNodeFieldCount(); } - _nextNodeIndex(): number { - return this.nodeIndex + this._snapshot._nodeFieldCount; + nextNodeIndex(): number { + return this.nodeIndex + this.snapshot.getNodeFieldCount(); } rawType(): number { - const snapshot = this._snapshot; - return snapshot.nodes[this.nodeIndex + snapshot._nodeTypeOffset]; + const snapshot = this.snapshot; + return snapshot.nodes[this.nodeIndex + snapshot.getNodeTypeOffset()]; + } + + getSnapshot(): HeapSnapshot { + return this.snapshot; } } export class HeapSnapshotNodeIterator implements HeapSnapshotItemIterator { node: HeapSnapshotNode; - _nodesLength: number; + private readonly nodesLength: number; constructor(node: HeapSnapshotNode) { this.node = node; - this._nodesLength = node._snapshot.nodes.length; + this.nodesLength = node.getSnapshot().nodes.length; } hasNext(): boolean { - return this.node.nodeIndex < this._nodesLength; + return this.node.nodeIndex < this.nodesLength; } item(): HeapSnapshotNode { @@ -458,108 +468,108 @@ } next(): void { - this.node.nodeIndex = this.node._nextNodeIndex(); + this.node.nodeIndex = this.node.nextNodeIndex(); } } export class HeapSnapshotIndexRangeIterator implements HeapSnapshotItemIterator { - _itemProvider: HeapSnapshotItemIndexProvider; - _indexes: number[]|Uint32Array; - _position: number; + private readonly itemProvider: HeapSnapshotItemIndexProvider; + private readonly indexes: number[]|Uint32Array; + private position: number; constructor(itemProvider: HeapSnapshotItemIndexProvider, indexes: number[]|Uint32Array) { - this._itemProvider = itemProvider; - this._indexes = indexes; - this._position = 0; + this.itemProvider = itemProvider; + this.indexes = indexes; + this.position = 0; } hasNext(): boolean { - return this._position < this._indexes.length; + return this.position < this.indexes.length; } item(): HeapSnapshotItem { - const index = this._indexes[this._position]; - return this._itemProvider.itemForIndex(index); + const index = this.indexes[this.position]; + return this.itemProvider.itemForIndex(index); } next(): void { - ++this._position; + ++this.position; } } export class HeapSnapshotFilteredIterator implements HeapSnapshotItemIterator { - _iterator: HeapSnapshotItemIterator; - _filter: ((arg0: HeapSnapshotItem) => boolean)|undefined; + private iterator: HeapSnapshotItemIterator; + private filter: ((arg0: HeapSnapshotItem) => boolean)|undefined; constructor(iterator: HeapSnapshotItemIterator, filter?: ((arg0: HeapSnapshotItem) => boolean)) { - this._iterator = iterator; - this._filter = filter; - this._skipFilteredItems(); + this.iterator = iterator; + this.filter = filter; + this.skipFilteredItems(); } hasNext(): boolean { - return this._iterator.hasNext(); + return this.iterator.hasNext(); } item(): HeapSnapshotItem { - return this._iterator.item(); + return this.iterator.item(); } next(): void { - this._iterator.next(); - this._skipFilteredItems(); + this.iterator.next(); + this.skipFilteredItems(); } - _skipFilteredItems(): void { - while (this._iterator.hasNext() && this._filter && !this._filter(this._iterator.item())) { - this._iterator.next(); + private skipFilteredItems(): void { + while (this.iterator.hasNext() && this.filter && !this.filter(this.iterator.item())) { + this.iterator.next(); } } } export class HeapSnapshotProgress { - _dispatcher: HeapSnapshotWorkerDispatcher|undefined; + private readonly dispatcher: HeapSnapshotWorkerDispatcher|undefined; constructor(dispatcher?: HeapSnapshotWorkerDispatcher) { - this._dispatcher = dispatcher; + this.dispatcher = dispatcher; } updateStatus(status: string): void { - this._sendUpdateEvent(i18n.i18n.serializeUIString(status)); + this.sendUpdateEvent(i18n.i18n.serializeUIString(status)); } updateProgress(title: string, value: number, total: number): void { const percentValue = ((total ? (value / total) : 0) * 100).toFixed(0); - this._sendUpdateEvent(i18n.i18n.serializeUIString(title, {PH1: percentValue})); + this.sendUpdateEvent(i18n.i18n.serializeUIString(title, {PH1: percentValue})); } reportProblem(error: string): void { // May be undefined in tests. - if (this._dispatcher) { - this._dispatcher.sendEvent(HeapSnapshotModel.HeapSnapshotModel.HeapSnapshotProgressEvent.BrokenSnapshot, error); + if (this.dispatcher) { + this.dispatcher.sendEvent(HeapSnapshotModel.HeapSnapshotModel.HeapSnapshotProgressEvent.BrokenSnapshot, error); } } - _sendUpdateEvent(serializedText: string): void { + private sendUpdateEvent(serializedText: string): void { // May be undefined in tests. - if (this._dispatcher) { - this._dispatcher.sendEvent(HeapSnapshotModel.HeapSnapshotModel.HeapSnapshotProgressEvent.Update, serializedText); + if (this.dispatcher) { + this.dispatcher.sendEvent(HeapSnapshotModel.HeapSnapshotModel.HeapSnapshotProgressEvent.Update, serializedText); } } } export class HeapSnapshotProblemReport { - _errors: string[]; + private readonly errors: string[]; constructor(title: string) { - this._errors = [title]; + this.errors = [title]; } addError(error: string): void { - if (this._errors.length > 100) { + if (this.errors.length > 100) { return; } - this._errors.push(error); + this.errors.push(error); } toString(): string { - return this._errors.join('\n '); + return this.errors.join('\n '); } } export interface Profile { @@ -589,194 +599,193 @@ export abstract class HeapSnapshot { nodes: Uint32Array; containmentEdges: Uint32Array; - _metaNode: HeapSnapshotMetainfo; - _rawSamples: number[]; - _samples: HeapSnapshotModel.HeapSnapshotModel.Samples|null; + private readonly metaNode: HeapSnapshotMetainfo; + private readonly rawSamples: number[]; + private samples: HeapSnapshotModel.HeapSnapshotModel.Samples|null; strings: string[]; - _locations: number[]; - _progress: HeapSnapshotProgress; - _noDistance: number; - _rootNodeIndex: number; - _snapshotDiffs: { + private readonly locations: number[]; + private readonly progress: HeapSnapshotProgress; + private readonly noDistance: number; + rootNodeIndexInternal: number; + private snapshotDiffs: { [x: string]: { [x: string]: HeapSnapshotModel.HeapSnapshotModel.Diff, }, }; - _aggregatesForDiff!: { + private aggregatesForDiffInternal!: { [x: string]: HeapSnapshotModel.HeapSnapshotModel.AggregateForDiff, }; - _aggregates: { + private aggregates: { [x: string]: { [x: string]: AggregatedInfo, }, }; - _aggregatesSortedFlags: { + private aggregatesSortedFlags: { [x: string]: boolean, }; - _profile: Profile; - _nodeTypeOffset!: number; - _nodeNameOffset!: number; - _nodeIdOffset!: number; - _nodeSelfSizeOffset!: number; - _nodeEdgeCountOffset!: number; - _nodeTraceNodeIdOffset!: number; - _nodeFieldCount!: number; - _nodeTypes!: string[]; - _nodeArrayType!: number; - _nodeHiddenType!: number; - _nodeObjectType!: number; - _nodeNativeType!: number; - _nodeConsStringType!: number; - _nodeSlicedStringType!: number; - _nodeCodeType!: number; - _nodeSyntheticType!: number; - _edgeFieldsCount!: number; - _edgeTypeOffset!: number; - _edgeNameOffset!: number; - _edgeToNodeOffset!: number; - _edgeTypes!: string[]; - _edgeElementType!: number; - _edgeHiddenType!: number; - _edgeInternalType!: number; - _edgeShortcutType!: number; - _edgeWeakType!: number; - _edgeInvisibleType!: number; - _locationIndexOffset!: number; - _locationScriptIdOffset!: number; - _locationLineOffset!: number; - _locationColumnOffset!: number; - _locationFieldCount!: number; + private profile: Profile; + nodeTypeOffset!: number; + nodeNameOffset!: number; + nodeIdOffset!: number; + nodeSelfSizeOffset!: number; + private nodeEdgeCountOffset!: number; + nodeTraceNodeIdOffset!: number; + nodeFieldCount!: number; + nodeTypes!: string[]; + nodeArrayType!: number; + nodeHiddenType!: number; + nodeObjectType!: number; + nodeNativeType!: number; + nodeConsStringType!: number; + nodeSlicedStringType!: number; + nodeCodeType!: number; + nodeSyntheticType!: number; + edgeFieldsCount!: number; + edgeTypeOffset!: number; + edgeNameOffset!: number; + edgeToNodeOffset!: number; + edgeTypes!: string[]; + edgeElementType!: number; + edgeHiddenType!: number; + edgeInternalType!: number; + edgeShortcutType!: number; + edgeWeakType!: number; + edgeInvisibleType!: number; + private locationIndexOffset!: number; + private locationScriptIdOffset!: number; + private locationLineOffset!: number; + private locationColumnOffset!: number; + private locationFieldCount!: number; nodeCount!: number; - _edgeCount!: number; - _retainedSizes!: Float64Array; - _firstEdgeIndexes!: Uint32Array; - _retainingNodes!: Uint32Array; - _retainingEdges!: Uint32Array; - _firstRetainerIndex!: Uint32Array; - _nodeDistances!: Int32Array; - _firstDominatedNodeIndex!: Uint32Array; - _dominatedNodes!: Uint32Array; - _dominatorsTree!: Uint32Array; - _allocationProfile!: AllocationProfile; - _nodeDetachednessOffset!: number; - _locationMap!: Map<number, HeapSnapshotModel.HeapSnapshotModel.Location>; - _lazyStringCache!: { + private edgeCount!: number; + retainedSizes!: Float64Array; + firstEdgeIndexes!: Uint32Array; + retainingNodes!: Uint32Array; + retainingEdges!: Uint32Array; + firstRetainerIndex!: Uint32Array; + nodeDistances!: Int32Array; + private firstDominatedNodeIndex!: Uint32Array; + private dominatedNodes!: Uint32Array; + dominatorsTree!: Uint32Array; + private allocationProfile!: AllocationProfile; + private nodeDetachednessOffset!: number; + private locationMap!: Map<number, HeapSnapshotModel.HeapSnapshotModel.Location>; + lazyStringCache!: { [x: string]: string, }; constructor(profile: Profile, progress: HeapSnapshotProgress) { this.nodes = profile.nodes; this.containmentEdges = profile.edges; - this._metaNode = profile.snapshot.meta; - this._rawSamples = profile.samples; - this._samples = null; + this.metaNode = profile.snapshot.meta; + this.rawSamples = profile.samples; + this.samples = null; this.strings = profile.strings; - this._locations = profile.locations; - this._progress = progress; + this.locations = profile.locations; + this.progress = progress; - this._noDistance = -5; - this._rootNodeIndex = 0; + this.noDistance = -5; + this.rootNodeIndexInternal = 0; if (profile.snapshot.root_index) { - this._rootNodeIndex = profile.snapshot.root_index; + this.rootNodeIndexInternal = profile.snapshot.root_index; } - this._snapshotDiffs = {}; + this.snapshotDiffs = {}; - this._aggregates = {}; + this.aggregates = {}; - this._aggregatesSortedFlags = {}; - this._profile = profile; + this.aggregatesSortedFlags = {}; + this.profile = profile; } initialize(): void { - const meta = this._metaNode; + const meta = this.metaNode; - this._nodeTypeOffset = meta.node_fields.indexOf('type'); - this._nodeNameOffset = meta.node_fields.indexOf('name'); - this._nodeIdOffset = meta.node_fields.indexOf('id'); - this._nodeSelfSizeOffset = meta.node_fields.indexOf('self_size'); - this._nodeEdgeCountOffset = meta.node_fields.indexOf('edge_count'); - this._nodeTraceNodeIdOffset = meta.node_fields.indexOf('trace_node_id'); - this._nodeDetachednessOffset = meta.node_fields.indexOf('detachedness'); - this._nodeFieldCount = meta.node_fields.length; + this.nodeTypeOffset = meta.node_fields.indexOf('type'); + this.nodeNameOffset = meta.node_fields.indexOf('name'); + this.nodeIdOffset = meta.node_fields.indexOf('id'); + this.nodeSelfSizeOffset = meta.node_fields.indexOf('self_size'); + this.nodeEdgeCountOffset = meta.node_fields.indexOf('edge_count'); + this.nodeTraceNodeIdOffset = meta.node_fields.indexOf('trace_node_id'); + this.nodeDetachednessOffset = meta.node_fields.indexOf('detachedness'); + this.nodeFieldCount = meta.node_fields.length; - this._nodeTypes = meta.node_types[this._nodeTypeOffset]; - this._nodeArrayType = this._nodeTypes.indexOf('array'); - this._nodeHiddenType = this._nodeTypes.indexOf('hidden'); - this._nodeObjectType = this._nodeTypes.indexOf('object'); - this._nodeNativeType = this._nodeTypes.indexOf('native'); - this._nodeConsStringType = this._nodeTypes.indexOf('concatenated string'); - this._nodeSlicedStringType = this._nodeTypes.indexOf('sliced string'); - this._nodeCodeType = this._nodeTypes.indexOf('code'); - this._nodeSyntheticType = this._nodeTypes.indexOf('synthetic'); + this.nodeTypes = meta.node_types[this.nodeTypeOffset]; + this.nodeArrayType = this.nodeTypes.indexOf('array'); + this.nodeHiddenType = this.nodeTypes.indexOf('hidden'); + this.nodeObjectType = this.nodeTypes.indexOf('object'); + this.nodeNativeType = this.nodeTypes.indexOf('native'); + this.nodeConsStringType = this.nodeTypes.indexOf('concatenated string'); + this.nodeSlicedStringType = this.nodeTypes.indexOf('sliced string'); + this.nodeCodeType = this.nodeTypes.indexOf('code'); + this.nodeSyntheticType = this.nodeTypes.indexOf('synthetic'); - this._edgeFieldsCount = meta.edge_fields.length; - this._edgeTypeOffset = meta.edge_fields.indexOf('type'); - this._edgeNameOffset = meta.edge_fields.indexOf('name_or_index'); - this._edgeToNodeOffset = meta.edge_fields.indexOf('to_node'); + this.edgeFieldsCount = meta.edge_fields.length; + this.edgeTypeOffset = meta.edge_fields.indexOf('type'); + this.edgeNameOffset = meta.edge_fields.indexOf('name_or_index'); + this.edgeToNodeOffset = meta.edge_fields.indexOf('to_node'); - this._edgeTypes = meta.edge_types[this._edgeTypeOffset]; - this._edgeTypes.push('invisible'); - this._edgeElementType = this._edgeTypes.indexOf('element'); - this._edgeHiddenType = this._edgeTypes.indexOf('hidden'); - this._edgeInternalType = this._edgeTypes.indexOf('internal'); - this._edgeShortcutType = this._edgeTypes.indexOf('shortcut'); - this._edgeWeakType = this._edgeTypes.indexOf('weak'); - this._edgeInvisibleType = this._edgeTypes.indexOf('invisible'); + this.edgeTypes = meta.edge_types[this.edgeTypeOffset]; + this.edgeTypes.push('invisible'); + this.edgeElementType = this.edgeTypes.indexOf('element'); + this.edgeHiddenType = this.edgeTypes.indexOf('hidden'); + this.edgeInternalType = this.edgeTypes.indexOf('internal'); + this.edgeShortcutType = this.edgeTypes.indexOf('shortcut'); + this.edgeWeakType = this.edgeTypes.indexOf('weak'); + this.edgeInvisibleType = this.edgeTypes.indexOf('invisible'); const locationFields = meta.location_fields || []; - this._locationIndexOffset = locationFields.indexOf('object_index'); - this._locationScriptIdOffset = locationFields.indexOf('script_id'); - this._locationLineOffset = locationFields.indexOf('line'); - this._locationColumnOffset = locationFields.indexOf('column'); - this._locationFieldCount = locationFields.length; + this.locationIndexOffset = locationFields.indexOf('object_index'); + this.locationScriptIdOffset = locationFields.indexOf('script_id'); + this.locationLineOffset = locationFields.indexOf('line'); + this.locationColumnOffset = locationFields.indexOf('column'); + this.locationFieldCount = locationFields.length; - this.nodeCount = this.nodes.length / this._nodeFieldCount; - this._edgeCount = this.containmentEdges.length / this._edgeFieldsCount; + this.nodeCount = this.nodes.length / this.nodeFieldCount; + this.edgeCount = this.containmentEdges.length / this.edgeFieldsCount; - this._retainedSizes = new Float64Array(this.nodeCount); - this._firstEdgeIndexes = new Uint32Array(this.nodeCount + 1); - this._retainingNodes = new Uint32Array(this._edgeCount); - this._retainingEdges = new Uint32Array(this._edgeCount); - this._firstRetainerIndex = new Uint32Array(this.nodeCount + 1); - this._nodeDistances = new Int32Array(this.nodeCount); - this._firstDominatedNodeIndex = new Uint32Array(this.nodeCount + 1); - this._dominatedNodes = new Uint32Array(this.nodeCount - 1); + this.retainedSizes = new Float64Array(this.nodeCount); + this.firstEdgeIndexes = new Uint32Array(this.nodeCount + 1); + this.retainingNodes = new Uint32Array(this.edgeCount); + this.retainingEdges = new Uint32Array(this.edgeCount); + this.firstRetainerIndex = new Uint32Array(this.nodeCount + 1); + this.nodeDistances = new Int32Array(this.nodeCount); + this.firstDominatedNodeIndex = new Uint32Array(this.nodeCount + 1); + this.dominatedNodes = new Uint32Array(this.nodeCount - 1); - this._progress.updateStatus('Building edge indexes…'); - this._buildEdgeIndexes(); - this._progress.updateStatus('Building retainers…'); - this._buildRetainers(); - this._progress.updateStatus('Propagating DOM state…'); - this._propagateDOMState(); - this._progress.updateStatus('Calculating node flags…'); + this.progress.updateStatus('Building edge indexes…'); + this.buildEdgeIndexes(); + this.progress.updateStatus('Building retainers…'); + this.buildRetainers(); + this.progress.updateStatus('Propagating DOM state…'); + this.propagateDOMState(); + this.progress.updateStatus('Calculating node flags…'); this.calculateFlags(); - this._progress.updateStatus('Calculating distances…'); + this.progress.updateStatus('Calculating distances…'); this.calculateDistances(); - this._progress.updateStatus('Building postorder index…'); - const result = this._buildPostOrderIndex(); + this.progress.updateStatus('Building postorder index…'); + const result = this.buildPostOrderIndex(); // Actually it is array that maps node ordinal number to dominator node ordinal number. - this._progress.updateStatus('Building dominator tree…'); - this._dominatorsTree = - this._buildDominatorTree(result.postOrderIndex2NodeOrdinal, result.nodeOrdinal2PostOrderIndex); - this._progress.updateStatus('Calculating retained sizes…'); - this._calculateRetainedSizes(result.postOrderIndex2NodeOrdinal); - this._progress.updateStatus('Building dominated nodes…'); - this._buildDominatedNodes(); - this._progress.updateStatus('Calculating statistics…'); + this.progress.updateStatus('Building dominator tree…'); + this.dominatorsTree = this.buildDominatorTree(result.postOrderIndex2NodeOrdinal, result.nodeOrdinal2PostOrderIndex); + this.progress.updateStatus('Calculating retained sizes…'); + this.calculateRetainedSizes(result.postOrderIndex2NodeOrdinal); + this.progress.updateStatus('Building dominated nodes…'); + this.buildDominatedNodes(); + this.progress.updateStatus('Calculating statistics…'); this.calculateStatistics(); - this._progress.updateStatus('Calculating samples…'); - this._buildSamples(); - this._progress.updateStatus('Building locations…'); - this._buildLocationMap(); - this._progress.updateStatus('Finished processing.'); + this.progress.updateStatus('Calculating samples…'); + this.buildSamples(); + this.progress.updateStatus('Building locations…'); + this.buildLocationMap(); + this.progress.updateStatus('Finished processing.'); - if (this._profile.snapshot.trace_function_count) { - this._progress.updateStatus('Building allocation statistics…'); + if (this.profile.snapshot.trace_function_count) { + this.progress.updateStatus('Building allocation statistics…'); const nodes = this.nodes; const nodesLength = nodes.length; - const nodeFieldCount = this._nodeFieldCount; + const nodeFieldCount = this.nodeFieldCount; const node = this.rootNode(); const liveObjects: {[x: number]: {count: number, size: number, ids: number[]}} = {}; for (let nodeIndex = 0; nodeIndex < nodesLength; nodeIndex += nodeFieldCount) { @@ -794,18 +803,18 @@ stats.size += node.selfSize(); stats.ids.push(node.id()); } - this._allocationProfile = new AllocationProfile(this._profile, liveObjects); - this._progress.updateStatus('done'); + this.allocationProfile = new AllocationProfile(this.profile, liveObjects); + this.progress.updateStatus('done'); } } - _buildEdgeIndexes(): void { + private buildEdgeIndexes(): void { const nodes = this.nodes; const nodeCount = this.nodeCount; - const firstEdgeIndexes = this._firstEdgeIndexes; - const nodeFieldCount = this._nodeFieldCount; - const edgeFieldsCount = this._edgeFieldsCount; - const nodeEdgeCountOffset = this._nodeEdgeCountOffset; + const firstEdgeIndexes = this.firstEdgeIndexes; + const nodeFieldCount = this.nodeFieldCount; + const edgeFieldsCount = this.edgeFieldsCount; + const nodeEdgeCountOffset = this.nodeEdgeCountOffset; firstEdgeIndexes[nodeCount] = this.containmentEdges.length; for (let nodeOrdinal = 0, edgeIndex = 0; nodeOrdinal < nodeCount; ++nodeOrdinal) { firstEdgeIndexes[nodeOrdinal] = edgeIndex; @@ -813,18 +822,18 @@ } } - _buildRetainers(): void { - const retainingNodes = this._retainingNodes; - const retainingEdges = this._retainingEdges; - // Index of the first retainer in the _retainingNodes and _retainingEdges + private buildRetainers(): void { + const retainingNodes = this.retainingNodes; + const retainingEdges = this.retainingEdges; + // Index of the first retainer in the retainingNodes and retainingEdges // arrays. Addressed by retained node index. - const firstRetainerIndex = this._firstRetainerIndex; + const firstRetainerIndex = this.firstRetainerIndex; const containmentEdges = this.containmentEdges; - const edgeFieldsCount = this._edgeFieldsCount; - const nodeFieldCount = this._nodeFieldCount; - const edgeToNodeOffset = this._edgeToNodeOffset; - const firstEdgeIndexes = this._firstEdgeIndexes; + const edgeFieldsCount = this.edgeFieldsCount; + const nodeFieldCount = this.nodeFieldCount; + const edgeToNodeOffset = this.edgeToNodeOffset; + const firstEdgeIndexes = this.firstEdgeIndexes; const nodeCount = this.nodeCount; for (let toNodeFieldIndex = edgeToNodeOffset, l = containmentEdges.length; toNodeFieldIndex < l; @@ -865,44 +874,44 @@ abstract createEdge(_edgeIndex: number): JSHeapSnapshotEdge; abstract createRetainingEdge(_retainerIndex: number): JSHeapSnapshotRetainerEdge; - _allNodes(): HeapSnapshotNodeIterator { + private allNodes(): HeapSnapshotNodeIterator { return new HeapSnapshotNodeIterator(this.rootNode()); } rootNode(): HeapSnapshotNode { - return this.createNode(this._rootNodeIndex); + return this.createNode(this.rootNodeIndexInternal); } get rootNodeIndex(): number { - return this._rootNodeIndex; + return this.rootNodeIndexInternal; } get totalSize(): number { return this.rootNode().retainedSize(); } - _getDominatedIndex(nodeIndex: number): number { - if (nodeIndex % this._nodeFieldCount) { + private getDominatedIndex(nodeIndex: number): number { + if (nodeIndex % this.nodeFieldCount) { throw new Error('Invalid nodeIndex: ' + nodeIndex); } - return this._firstDominatedNodeIndex[nodeIndex / this._nodeFieldCount]; + return this.firstDominatedNodeIndex[nodeIndex / this.nodeFieldCount]; } - _createFilter(nodeFilter: HeapSnapshotModel.HeapSnapshotModel.NodeFilter): + private createFilter(nodeFilter: HeapSnapshotModel.HeapSnapshotModel.NodeFilter): ((arg0: HeapSnapshotNode) => boolean)|undefined { const minNodeId = nodeFilter.minNodeId; const maxNodeId = nodeFilter.maxNodeId; const allocationNodeId = nodeFilter.allocationNodeId; let filter; if (typeof allocationNodeId === 'number') { - filter = this._createAllocationStackFilter(allocationNodeId); + filter = this.createAllocationStackFilter(allocationNodeId); if (!filter) { throw new Error('Unable to create filter'); } // @ts-ignore key can be added as a static property filter.key = 'AllocationNodeId: ' + allocationNodeId; } else if (typeof minNodeId === 'number' && typeof maxNodeId === 'number') { - filter = this._createNodeIdFilter(minNodeId, maxNodeId); + filter = this.createNodeIdFilter(minNodeId, maxNodeId); // @ts-ignore key can be added as a static property filter.key = 'NodeIdRange: ' + minNodeId + '..' + maxNodeId; } @@ -937,13 +946,13 @@ return []; } - const filter = this._createFilter(nodeFilter); + const filter = this.createFilter(nodeFilter); const nodeIds = []; const nodesLength = this.nodes.length; const nodes = this.nodes; - const nodeNameOffset = this._nodeNameOffset; - const nodeIdOffset = this._nodeIdOffset; - const nodeFieldCount = this._nodeFieldCount; + const nodeNameOffset = this.nodeNameOffset; + const nodeIdOffset = this.nodeIdOffset; + const nodeFieldCount = this.nodeFieldCount; const node = this.rootNode(); for (let nodeIndex = 0; nodeIndex < nodesLength; nodeIndex += nodeFieldCount) { @@ -960,13 +969,13 @@ aggregatesWithFilter(nodeFilter: HeapSnapshotModel.HeapSnapshotModel.NodeFilter): {[x: string]: HeapSnapshotModel.HeapSnapshotModel.Aggregate} { - const filter = this._createFilter(nodeFilter); - // @ts-ignore key is added in _createFilter + const filter = this.createFilter(nodeFilter); + // @ts-ignore key is added in createFilter const key = filter ? filter.key : 'allObjects'; return this.getAggregatesByClassName(false, key, filter); } - _createNodeIdFilter(minNodeId: number, maxNodeId: number): (arg0: HeapSnapshotNode) => boolean { + private createNodeIdFilter(minNodeId: number, maxNodeId: number): (arg0: HeapSnapshotNode) => boolean { function nodeIdFilter(node: HeapSnapshotNode): boolean { const id = node.id(); return id > minNodeId && id <= maxNodeId; @@ -974,12 +983,13 @@ return nodeIdFilter; } - _createAllocationStackFilter(bottomUpAllocationNodeId: number): ((arg0: HeapSnapshotNode) => boolean)|undefined { - if (!this._allocationProfile) { + private createAllocationStackFilter(bottomUpAllocationNodeId: number): + ((arg0: HeapSnapshotNode) => boolean)|undefined { + if (!this.allocationProfile) { throw new Error('No Allocation Profile provided'); } - const traceIds = this._allocationProfile.traceIds(bottomUpAllocationNodeId); + const traceIds = this.allocationProfile.traceIds(bottomUpAllocationNodeId); if (!traceIds.length) { return undefined; } @@ -996,23 +1006,23 @@ getAggregatesByClassName(sortedIndexes: boolean, key?: string, filter?: ((arg0: HeapSnapshotNode) => boolean)): {[x: string]: HeapSnapshotModel.HeapSnapshotModel.Aggregate} { - const aggregates = this._buildAggregates(filter); + const aggregates = this.buildAggregates(filter); let aggregatesByClassName; - if (key && this._aggregates[key]) { - aggregatesByClassName = this._aggregates[key]; + if (key && this.aggregates[key]) { + aggregatesByClassName = this.aggregates[key]; } else { - this._calculateClassesRetainedSize(aggregates.aggregatesByClassIndex, filter); + this.calculateClassesRetainedSize(aggregates.aggregatesByClassIndex, filter); aggregatesByClassName = aggregates.aggregatesByClassName; if (key) { - this._aggregates[key] = aggregatesByClassName; + this.aggregates[key] = aggregatesByClassName; } } - if (sortedIndexes && (!key || !this._aggregatesSortedFlags[key])) { - this._sortAggregateIndexes(aggregates.aggregatesByClassName); + if (sortedIndexes && (!key || !this.aggregatesSortedFlags[key])) { + this.sortAggregateIndexes(aggregates.aggregatesByClassName); if (key) { - this._aggregatesSortedFlags[key] = sortedIndexes; + this.aggregatesSortedFlags[key] = sortedIndexes; } } @@ -1022,11 +1032,11 @@ } allocationTracesTops(): HeapSnapshotModel.HeapSnapshotModel.SerializedAllocationNode[] { - return this._allocationProfile.serializeTraceTops(); + return this.allocationProfile.serializeTraceTops(); } allocationNodeCallers(nodeId: number): HeapSnapshotModel.HeapSnapshotModel.AllocationNodeCallers { - return this._allocationProfile.serializeCallers(nodeId); + return this.allocationProfile.serializeCallers(nodeId); } allocationStack(nodeIndex: number): HeapSnapshotModel.HeapSnapshotModel.AllocationStackFrame[]|null { @@ -1035,16 +1045,16 @@ if (!allocationNodeId) { return null; } - return this._allocationProfile.serializeAllocationStack(allocationNodeId); + return this.allocationProfile.serializeAllocationStack(allocationNodeId); } aggregatesForDiff(): {[x: string]: HeapSnapshotModel.HeapSnapshotModel.AggregateForDiff} { - if (this._aggregatesForDiff) { - return this._aggregatesForDiff; + if (this.aggregatesForDiffInternal) { + return this.aggregatesForDiffInternal; } const aggregatesByClassName = this.getAggregatesByClassName(true, 'allObjects'); - this._aggregatesForDiff = {}; + this.aggregatesForDiffInternal = {}; const node = this.createNode(); for (const className in aggregatesByClassName) { @@ -1058,9 +1068,9 @@ selfSizes[i] = node.selfSize(); } - this._aggregatesForDiff[className] = {indexes: indexes, ids: ids, selfSizes: selfSizes}; + this.aggregatesForDiffInternal[className] = {indexes: indexes, ids: ids, selfSizes: selfSizes}; } - return this._aggregatesForDiff; + return this.aggregatesForDiffInternal; } isUserRoot(_node: HeapSnapshotNode): boolean { @@ -1069,8 +1079,8 @@ calculateDistances(filter?: ((arg0: HeapSnapshotNode, arg1: HeapSnapshotEdge) => boolean)): void { const nodeCount = this.nodeCount; - const distances = this._nodeDistances; - const noDistance = this._noDistance; + const distances = this.nodeDistances; + const noDistance = this.noDistance; for (let i = 0; i < nodeCount; ++i) { distances[i] = noDistance; } @@ -1086,29 +1096,29 @@ nodesToVisit[nodesToVisitLength++] = node.nodeIndex; } } - this._bfs(nodesToVisit, nodesToVisitLength, distances, filter); + this.bfs(nodesToVisit, nodesToVisitLength, distances, filter); // BFS for objects not reached from user roots. distances[this.rootNode().ordinal()] = nodesToVisitLength > 0 ? HeapSnapshotModel.HeapSnapshotModel.baseSystemDistance : 0; nodesToVisit[0] = this.rootNode().nodeIndex; nodesToVisitLength = 1; - this._bfs(nodesToVisit, nodesToVisitLength, distances, filter); + this.bfs(nodesToVisit, nodesToVisitLength, distances, filter); } - _bfs( + private bfs( nodesToVisit: Uint32Array, nodesToVisitLength: number, distances: Int32Array, filter?: ((arg0: HeapSnapshotNode, arg1: HeapSnapshotEdge) => boolean)): void { // Preload fields into local variables for better performance. - const edgeFieldsCount = this._edgeFieldsCount; - const nodeFieldCount = this._nodeFieldCount; + const edgeFieldsCount = this.edgeFieldsCount; + const nodeFieldCount = this.nodeFieldCount; const containmentEdges = this.containmentEdges; - const firstEdgeIndexes = this._firstEdgeIndexes; - const edgeToNodeOffset = this._edgeToNodeOffset; - const edgeTypeOffset = this._edgeTypeOffset; + const firstEdgeIndexes = this.firstEdgeIndexes; + const edgeToNodeOffset = this.edgeToNodeOffset; + const edgeTypeOffset = this.edgeTypeOffset; const nodeCount = this.nodeCount; - const edgeWeakType = this._edgeWeakType; - const noDistance = this._noDistance; + const edgeWeakType = this.edgeWeakType; + const noDistance = this.noDistance; let index = 0; const edge = this.createEdge(0); @@ -1144,7 +1154,7 @@ } } - _buildAggregates(filter?: ((arg0: HeapSnapshotNode) => boolean)): + private buildAggregates(filter?: ((arg0: HeapSnapshotNode) => boolean)): {aggregatesByClassName: {[x: string]: AggregatedInfo}, aggregatesByClassIndex: {[x: number]: AggregatedInfo}} { const aggregates: {[x: number]: AggregatedInfo} = {}; @@ -1153,12 +1163,12 @@ const classIndexes = []; const nodes = this.nodes; const nodesLength = nodes.length; - const nodeNativeType = this._nodeNativeType; - const nodeFieldCount = this._nodeFieldCount; - const selfSizeOffset = this._nodeSelfSizeOffset; - const nodeTypeOffset = this._nodeTypeOffset; + const nodeNativeType = this.nodeNativeType; + const nodeFieldCount = this.nodeFieldCount; + const selfSizeOffset = this.nodeSelfSizeOffset; + const nodeTypeOffset = this.nodeTypeOffset; const node = this.rootNode(); - const nodeDistances = this._nodeDistances; + const nodeDistances = this.nodeDistances; for (let nodeIndex = 0; nodeIndex < nodesLength; nodeIndex += nodeFieldCount) { node.nodeIndex = nodeIndex; @@ -1212,21 +1222,21 @@ return {aggregatesByClassName: aggregatesByClassName, aggregatesByClassIndex: aggregates}; } - _calculateClassesRetainedSize( + private calculateClassesRetainedSize( aggregates: {[x: number]: AggregatedInfo}, filter?: ((arg0: HeapSnapshotNode) => boolean)): void { - const rootNodeIndex = this._rootNodeIndex; + const rootNodeIndex = this.rootNodeIndexInternal; const node = this.createNode(rootNodeIndex); const list = [rootNodeIndex]; const sizes = [-1]; const classes = []; const seenClassNameIndexes = new Map<number, boolean>(); - const nodeFieldCount = this._nodeFieldCount; - const nodeTypeOffset = this._nodeTypeOffset; - const nodeNativeType = this._nodeNativeType; - const dominatedNodes = this._dominatedNodes; + const nodeFieldCount = this.nodeFieldCount; + const nodeTypeOffset = this.nodeTypeOffset; + const nodeNativeType = this.nodeNativeType; + const dominatedNodes = this.dominatedNodes; const nodes = this.nodes; - const firstDominatedNodeIndex = this._firstDominatedNodeIndex; + const firstDominatedNodeIndex = this.firstDominatedNodeIndex; while (list.length) { const nodeIndex = (list.pop() as number); @@ -1259,7 +1269,7 @@ } } - _sortAggregateIndexes(aggregates: {[x: string]: AggregatedInfo}): void { + private sortAggregateIndexes(aggregates: {[x: string]: AggregatedInfo}): void { const nodeA = this.createNode(); const nodeB = this.createNode(); @@ -1276,21 +1286,21 @@ * The function checks is the edge should be considered during building * postorder iterator and dominator tree. */ - _isEssentialEdge(nodeIndex: number, edgeType: number): boolean { + private isEssentialEdge(nodeIndex: number, edgeType: number): boolean { // Shortcuts at the root node have special meaning of marking user global objects. - return edgeType !== this._edgeWeakType && - (edgeType !== this._edgeShortcutType || nodeIndex === this._rootNodeIndex); + return edgeType !== this.edgeWeakType && + (edgeType !== this.edgeShortcutType || nodeIndex === this.rootNodeIndexInternal); } - _buildPostOrderIndex(): {postOrderIndex2NodeOrdinal: Uint32Array, nodeOrdinal2PostOrderIndex: Uint32Array} { - const nodeFieldCount = this._nodeFieldCount; + private buildPostOrderIndex(): {postOrderIndex2NodeOrdinal: Uint32Array, nodeOrdinal2PostOrderIndex: Uint32Array} { + const nodeFieldCount = this.nodeFieldCount; const nodeCount = this.nodeCount; - const rootNodeOrdinal = this._rootNodeIndex / nodeFieldCount; + const rootNodeOrdinal = this.rootNodeIndexInternal / nodeFieldCount; - const edgeFieldsCount = this._edgeFieldsCount; - const edgeTypeOffset = this._edgeTypeOffset; - const edgeToNodeOffset = this._edgeToNodeOffset; - const firstEdgeIndexes = this._firstEdgeIndexes; + const edgeFieldsCount = this.edgeFieldsCount; + const edgeTypeOffset = this.edgeTypeOffset; + const edgeToNodeOffset = this.edgeToNodeOffset; + const firstEdgeIndexes = this.firstEdgeIndexes; const containmentEdges = this.containmentEdges; const mapAndFlag = this.userObjectsMapAndFlag(); @@ -1320,7 +1330,7 @@ if (edgeIndex < edgesEnd) { stackCurrentEdge[stackTop] += edgeFieldsCount; const edgeType = containmentEdges[edgeIndex + edgeTypeOffset]; - if (!this._isEssentialEdge(nodeOrdinal * nodeFieldCount, edgeType)) { + if (!this.isEssentialEdge(nodeOrdinal * nodeFieldCount, edgeType)) { continue; } const childNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; @@ -1360,7 +1370,7 @@ stackNodes[0] = rootNodeOrdinal; stackCurrentEdge[0] = firstEdgeIndexes[rootNodeOrdinal + 1]; // no need to reiterate its edges for (let i = 0; i < nodeCount; ++i) { - if (visited[i] || !this._hasOnlyWeakRetainers(i)) { + if (visited[i] || !this.hasOnlyWeakRetainers(i)) { continue; } @@ -1408,14 +1418,14 @@ }; } - _hasOnlyWeakRetainers(nodeOrdinal: number): boolean { - const edgeTypeOffset = this._edgeTypeOffset; - const edgeWeakType = this._edgeWeakType; - const edgeShortcutType = this._edgeShortcutType; + private hasOnlyWeakRetainers(nodeOrdinal: number): boolean { + const edgeTypeOffset = this.edgeTypeOffset; + const edgeWeakType = this.edgeWeakType; + const edgeShortcutType = this.edgeShortcutType; const containmentEdges = this.containmentEdges; - const retainingEdges = this._retainingEdges; - const beginRetainerIndex = this._firstRetainerIndex[nodeOrdinal]; - const endRetainerIndex = this._firstRetainerIndex[nodeOrdinal + 1]; + const retainingEdges = this.retainingEdges; + const beginRetainerIndex = this.firstRetainerIndex[nodeOrdinal]; + const endRetainerIndex = this.firstRetainerIndex[nodeOrdinal + 1]; for (let retainerIndex = beginRetainerIndex; retainerIndex < endRetainerIndex; ++retainerIndex) { const retainerEdgeIndex = retainingEdges[retainerIndex]; const retainerEdgeType = containmentEdges[retainerEdgeIndex + edgeTypeOffset]; @@ -1429,17 +1439,18 @@ // The algorithm is based on the article: // K. Cooper, T. Harvey and K. Kennedy "A Simple, Fast Dominance Algorithm" // Softw. Pract. Exper. 4 (2001), pp. 1-10. - _buildDominatorTree(postOrderIndex2NodeOrdinal: Uint32Array, nodeOrdinal2PostOrderIndex: Uint32Array): Uint32Array { - const nodeFieldCount = this._nodeFieldCount; - const firstRetainerIndex = this._firstRetainerIndex; - const retainingNodes = this._retainingNodes; - const retainingEdges = this._retainingEdges; - const edgeFieldsCount = this._edgeFieldsCount; - const edgeTypeOffset = this._edgeTypeOffset; - const edgeToNodeOffset = this._edgeToNodeOffset; - const firstEdgeIndexes = this._firstEdgeIndexes; + private buildDominatorTree(postOrderIndex2NodeOrdinal: Uint32Array, nodeOrdinal2PostOrderIndex: Uint32Array): + Uint32Array { + const nodeFieldCount = this.nodeFieldCount; + const firstRetainerIndex = this.firstRetainerIndex; + const retainingNodes = this.retainingNodes; + const retainingEdges = this.retainingEdges; + const edgeFieldsCount = this.edgeFieldsCount; + const edgeTypeOffset = this.edgeTypeOffset; + const edgeToNodeOffset = this.edgeToNodeOffset; + const firstEdgeIndexes = this.firstEdgeIndexes; const containmentEdges = this.containmentEdges; - const rootNodeIndex = this._rootNodeIndex; + const rootNodeIndex = this.rootNodeIndexInternal; const mapAndFlag = this.userObjectsMapAndFlag(); const flags = mapAndFlag ? mapAndFlag.map : null; @@ -1460,11 +1471,11 @@ let nodeOrdinal; { // Mark the root direct children as affected. - nodeOrdinal = this._rootNodeIndex / nodeFieldCount; + nodeOrdinal = this.rootNodeIndexInternal / nodeFieldCount; const endEdgeIndex = firstEdgeIndexes[nodeOrdinal + 1]; for (let edgeIndex = firstEdgeIndexes[nodeOrdinal]; edgeIndex < endEdgeIndex; edgeIndex += edgeFieldsCount) { const edgeType = containmentEdges[edgeIndex + edgeTypeOffset]; - if (!this._isEssentialEdge(this._rootNodeIndex, edgeType)) { + if (!this.isEssentialEdge(this.rootNodeIndexInternal, edgeType)) { continue; } const childNodeOrdinal = containmentEdges[edgeIndex + edgeToNodeOffset] / nodeFieldCount; @@ -1495,7 +1506,7 @@ const retainerEdgeIndex = retainingEdges[retainerIndex]; const retainerEdgeType = containmentEdges[retainerEdgeIndex + edgeTypeOffset]; const retainerNodeIndex = retainingNodes[retainerIndex]; - if (!this._isEssentialEdge(retainerNodeIndex, retainerEdgeType)) { + if (!this.isEssentialEdge(retainerNodeIndex, retainerEdgeType)) { continue; } orphanNode = false; @@ -1554,13 +1565,13 @@ return dominatorsTree; } - _calculateRetainedSizes(postOrderIndex2NodeOrdinal: Uint32Array): void { + private calculateRetainedSizes(postOrderIndex2NodeOrdinal: Uint32Array): void { const nodeCount = this.nodeCount; const nodes = this.nodes; - const nodeSelfSizeOffset = this._nodeSelfSizeOffset; - const nodeFieldCount = this._nodeFieldCount; - const dominatorsTree = this._dominatorsTree; - const retainedSizes = this._retainedSizes; + const nodeSelfSizeOffset = this.nodeSelfSizeOffset; + const nodeFieldCount = this.nodeFieldCount; + const dominatorsTree = this.dominatorsTree; + const retainedSizes = this.retainedSizes; for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; ++nodeOrdinal) { retainedSizes[nodeOrdinal] = nodes[nodeOrdinal * nodeFieldCount + nodeSelfSizeOffset]; @@ -1574,24 +1585,24 @@ } } - _buildDominatedNodes(): void { + private buildDominatedNodes(): void { // Builds up two arrays: // - "dominatedNodes" is a continuous array, where each node owns an // interval (can be empty) with corresponding dominated nodes. // - "indexArray" is an array of indexes in the "dominatedNodes" // with the same positions as in the _nodeIndex. - const indexArray = this._firstDominatedNodeIndex; + const indexArray = this.firstDominatedNodeIndex; // All nodes except the root have dominators. - const dominatedNodes = this._dominatedNodes; + const dominatedNodes = this.dominatedNodes; // Count the number of dominated nodes for each node. Skip the root (node at // index 0) as it is the only node that dominates itself. - const nodeFieldCount = this._nodeFieldCount; - const dominatorsTree = this._dominatorsTree; + const nodeFieldCount = this.nodeFieldCount; + const dominatorsTree = this.dominatorsTree; let fromNodeOrdinal = 0; let toNodeOrdinal: number = this.nodeCount; - const rootNodeOrdinal = this._rootNodeIndex / nodeFieldCount; + const rootNodeOrdinal = this.rootNodeIndexInternal / nodeFieldCount; if (rootNodeOrdinal === fromNodeOrdinal) { fromNodeOrdinal = 1; } else if (rootNodeOrdinal === toNodeOrdinal - 1) { @@ -1624,14 +1635,14 @@ /** * Iterates children of a node. */ - _iterateFilteredChildren( + private iterateFilteredChildren( nodeOrdinal: number, edgeFilterCallback: (arg0: number) => boolean, childCallback: (arg0: number) => void): void { - const beginEdgeIndex = this._firstEdgeIndexes[nodeOrdinal]; - const endEdgeIndex = this._firstEdgeIndexes[nodeOrdinal + 1]; - for (let edgeIndex = beginEdgeIndex; edgeIndex < endEdgeIndex; edgeIndex += this._edgeFieldsCount) { - const childNodeIndex = this.containmentEdges[edgeIndex + this._edgeToNodeOffset]; - const childNodeOrdinal = childNodeIndex / this._nodeFieldCount; - const type = this.containmentEdges[edgeIndex + this._edgeTypeOffset]; + const beginEdgeIndex = this.firstEdgeIndexes[nodeOrdinal]; + const endEdgeIndex = this.firstEdgeIndexes[nodeOrdinal + 1]; + for (let edgeIndex = beginEdgeIndex; edgeIndex < endEdgeIndex; edgeIndex += this.edgeFieldsCount) { + const childNodeIndex = this.containmentEdges[edgeIndex + this.edgeToNodeOffset]; + const childNodeOrdinal = childNodeIndex / this.nodeFieldCount; + const type = this.containmentEdges[edgeIndex + this.edgeTypeOffset]; if (!edgeFilterCallback(type)) { continue; } @@ -1642,7 +1653,7 @@ /** * Adds a string to the snapshot. */ - _addString(string: string): number { + private addString(string: string): number { this.strings.push(string); return this.strings.length - 1; } @@ -1660,8 +1671,8 @@ * - Name of any detached node is changed from "<Name>"" to * "Detached <Name>". */ - _propagateDOMState(): void { - if (this._nodeDetachednessOffset === -1) { + private propagateDOMState(): void { + if (this.nodeDetachednessOffset === -1) { return; } @@ -1677,13 +1688,13 @@ * Adds a 'Detached ' prefix to the name of a node. */ const addDetachedPrefixToNodeName = function(snapshot: HeapSnapshot, nodeIndex: number): void { - const oldStringIndex = snapshot.nodes[nodeIndex + snapshot._nodeNameOffset]; + const oldStringIndex = snapshot.nodes[nodeIndex + snapshot.nodeNameOffset]; let newStringIndex = stringIndexCache.get(oldStringIndex); if (newStringIndex === undefined) { - newStringIndex = snapshot._addString('Detached ' + snapshot.strings[oldStringIndex]); + newStringIndex = snapshot.addString('Detached ' + snapshot.strings[oldStringIndex]); stringIndexCache.set(oldStringIndex, newStringIndex); } - snapshot.nodes[nodeIndex + snapshot._nodeNameOffset] = newStringIndex; + snapshot.nodes[nodeIndex + snapshot.nodeNameOffset] = newStringIndex; }; /** @@ -1696,17 +1707,17 @@ return; } - const nodeIndex = nodeOrdinal * snapshot._nodeFieldCount; + const nodeIndex = nodeOrdinal * snapshot.nodeFieldCount; // Early bailout: Do not propagate the state (and name change) through JavaScript. Every // entry point into embedder code is a node that knows its own state. All embedder nodes // have their node type set to native. - if (snapshot.nodes[nodeIndex + snapshot._nodeTypeOffset] !== snapshot._nodeNativeType) { + if (snapshot.nodes[nodeIndex + snapshot.nodeTypeOffset] !== snapshot.nodeNativeType) { visited[nodeOrdinal] = 1; return; } - snapshot.nodes[nodeIndex + snapshot._nodeDetachednessOffset] = newState; + snapshot.nodes[nodeIndex + snapshot.nodeDetachednessOffset] = newState; if (newState === DOMLinkState.Attached) { attached.push(nodeOrdinal); @@ -1720,10 +1731,9 @@ }; const propagateState = function(snapshot: HeapSnapshot, parentNodeOrdinal: number, newState: number): void { - snapshot._iterateFilteredChildren( + snapshot.iterateFilteredChildren( parentNodeOrdinal, - edgeType => - ![snapshot._edgeHiddenType, snapshot._edgeInvisibleType, snapshot._edgeWeakType].includes(edgeType), + edgeType => ![snapshot.edgeHiddenType, snapshot.edgeInvisibleType, snapshot.edgeWeakType].includes(edgeType), nodeOrdinal => processNode(snapshot, nodeOrdinal, newState)); }; @@ -1732,7 +1742,7 @@ // through processing to have their name adjusted and them enqueued in // the respective queues. for (let nodeOrdinal = 0; nodeOrdinal < this.nodeCount; ++nodeOrdinal) { - const state = this.nodes[nodeOrdinal * this._nodeFieldCount + this._nodeDetachednessOffset]; + const state = this.nodes[nodeOrdinal * this.nodeFieldCount + this.nodeDetachednessOffset]; // Bail out for objects that have no known state. For all other objects set that state. if (state === DOMLinkState.Unknown) { continue; @@ -1747,7 +1757,7 @@ // 3. If the parent is not attached, then the child inherits the parent's state. while (detached.length !== 0) { const nodeOrdinal = (detached.pop() as number); - const nodeState = this.nodes[nodeOrdinal * this._nodeFieldCount + this._nodeDetachednessOffset]; + const nodeState = this.nodes[nodeOrdinal * this.nodeFieldCount + this.nodeDetachednessOffset]; // Ignore if the node has been found through propagating forward attached state. if (nodeState === DOMLinkState.Attached) { continue; @@ -1758,8 +1768,8 @@ console.timeEnd('propagateDOMState'); } - _buildSamples(): void { - const samples = this._rawSamples; + private buildSamples(): void { + const samples = this.rawSamples; if (!samples || !samples.length) { return; } @@ -1768,8 +1778,8 @@ const timestamps = new Array(sampleCount); const lastAssignedIds = new Array(sampleCount); - const timestampOffset = this._metaNode.sample_fields.indexOf('timestamp_us'); - const lastAssignedIdOffset = this._metaNode.sample_fields.indexOf('last_assigned_id'); + const timestampOffset = this.metaNode.sample_fields.indexOf('timestamp_us'); + const lastAssignedIdOffset = this.metaNode.sample_fields.indexOf('last_assigned_id'); for (let i = 0; i < sampleCount; i++) { sizeForRange[i] = 0; timestamps[i] = (samples[2 * i + timestampOffset]) / 1000; @@ -1778,7 +1788,7 @@ const nodes = this.nodes; const nodesLength = nodes.length; - const nodeFieldCount = this._nodeFieldCount; + const nodeFieldCount = this.nodeFieldCount; const node = this.rootNode(); for (let nodeIndex = 0; nodeIndex < nodesLength; nodeIndex += nodeFieldCount) { node.nodeIndex = nodeIndex; @@ -1796,30 +1806,30 @@ } sizeForRange[rangeIndex] += node.selfSize(); } - this._samples = new HeapSnapshotModel.HeapSnapshotModel.Samples(timestamps, lastAssignedIds, sizeForRange); + this.samples = new HeapSnapshotModel.HeapSnapshotModel.Samples(timestamps, lastAssignedIds, sizeForRange); } - _buildLocationMap(): void { + private buildLocationMap(): void { const map = new Map<number, HeapSnapshotModel.HeapSnapshotModel.Location>(); - const locations = this._locations; + const locations = this.locations; - for (let i = 0; i < locations.length; i += this._locationFieldCount) { - const nodeIndex = locations[i + this._locationIndexOffset]; - const scriptId = locations[i + this._locationScriptIdOffset]; - const line = locations[i + this._locationLineOffset]; - const col = locations[i + this._locationColumnOffset]; + for (let i = 0; i < locations.length; i += this.locationFieldCount) { + const nodeIndex = locations[i + this.locationIndexOffset]; + const scriptId = locations[i + this.locationScriptIdOffset]; + const line = locations[i + this.locationLineOffset]; + const col = locations[i + this.locationColumnOffset]; map.set(nodeIndex, new HeapSnapshotModel.HeapSnapshotModel.Location(scriptId, line, col)); } - this._locationMap = map; + this.locationMap = map; } getLocation(nodeIndex: number): HeapSnapshotModel.HeapSnapshotModel.Location|null { - return this._locationMap.get(nodeIndex) || null; + return this.locationMap.get(nodeIndex) || null; } getSamples(): HeapSnapshotModel.HeapSnapshotModel.Samples|null { - return this._samples; + return this.samples; } calculateFlags(): void { @@ -1840,7 +1850,7 @@ {[x: string]: HeapSnapshotModel.HeapSnapshotModel.Diff} { let snapshotDiff: {[x: string]: HeapSnapshotModel.HeapSnapshotModel.Diff}|{ [x: string]: HeapSnapshotModel.HeapSnapshotModel.Diff, - } = this._snapshotDiffs[baseSnapshotId]; + } = this.snapshotDiffs[baseSnapshotId]; if (snapshotDiff) { return snapshotDiff; } @@ -1851,7 +1861,7 @@ const aggregates = this.getAggregatesByClassName(true, 'allObjects'); for (const className in baseSnapshotAggregates) { const baseAggregate = baseSnapshotAggregates[className]; - const diff = this._calculateDiffForClass(baseAggregate, aggregates[className]); + const diff = this.calculateDiffForClass(baseAggregate, aggregates[className]); if (diff) { snapshotDiff[className] = diff; } @@ -1861,17 +1871,17 @@ if (className in baseSnapshotAggregates) { continue; } - const classDiff = this._calculateDiffForClass(emptyBaseAggregate, aggregates[className]); + const classDiff = this.calculateDiffForClass(emptyBaseAggregate, aggregates[className]); if (classDiff) { snapshotDiff[className] = classDiff; } } - this._snapshotDiffs[baseSnapshotId] = snapshotDiff; + this.snapshotDiffs[baseSnapshotId] = snapshotDiff; return snapshotDiff; } - _calculateDiffForClass( + private calculateDiffForClass( baseAggregate: HeapSnapshotModel.HeapSnapshotModel.AggregateForDiff, aggregate: HeapSnapshotModel.HeapSnapshotModel.Aggregate): HeapSnapshotModel.HeapSnapshotModel.Diff|null { const baseIds = baseAggregate.ids; @@ -1926,8 +1936,8 @@ return diff; } - _nodeForSnapshotObjectId(snapshotObjectId: number): HeapSnapshotNode|null { - for (let it = this._allNodes(); it.hasNext(); it.next()) { + private nodeForSnapshotObjectId(snapshotObjectId: number): HeapSnapshotNode|null { + for (let it = this.allNodes(); it.hasNext(); it.next()) { if (it.node.id() === snapshotObjectId) { return it.node; } @@ -1936,7 +1946,7 @@ } nodeClassName(snapshotObjectId: number): string|null { - const node = this._nodeForSnapshotObjectId(snapshotObjectId); + const node = this.nodeForSnapshotObjectId(snapshotObjectId); if (node) { return node.className(); } @@ -1945,7 +1955,7 @@ idsOfObjectsWithName(name: string): number[] { const ids = []; - for (let it = this._allNodes(); it.hasNext(); it.next()) { + for (let it = this.allNodes(); it.hasNext(); it.next()) { if (it.item().name() === name) { ids.push(it.item().id()); } @@ -1983,7 +1993,7 @@ } createAddedNodesProvider(baseSnapshotId: string, className: string): HeapSnapshotNodesProvider { - const snapshotDiff = this._snapshotDiffs[baseSnapshotId]; + const snapshotDiff = this.snapshotDiffs[baseSnapshotId]; const diffForClass = snapshotDiff[className]; return new HeapSnapshotNodesProvider(this, diffForClass.addedIndexes); } @@ -1997,12 +2007,12 @@ return new HeapSnapshotNodesProvider(this, this.aggregatesWithFilter(nodeFilter)[className].idxs); } - _maxJsNodeId(): number { - const nodeFieldCount = this._nodeFieldCount; + private maxJsNodeId(): number { + const nodeFieldCount = this.nodeFieldCount; const nodes = this.nodes; const nodesLength = nodes.length; let id = 0; - for (let nodeIndex = this._nodeIdOffset; nodeIndex < nodesLength; nodeIndex += nodeFieldCount) { + for (let nodeIndex = this.nodeIdOffset; nodeIndex < nodesLength; nodeIndex += nodeFieldCount) { const nextId = nodes[nodeIndex]; // JS objects have odd ids, skip native objects. if (nextId % 2 === 0) { @@ -2017,7 +2027,143 @@ updateStaticData(): HeapSnapshotModel.HeapSnapshotModel.StaticData { return new HeapSnapshotModel.HeapSnapshotModel.StaticData( - this.nodeCount, this._rootNodeIndex, this.totalSize, this._maxJsNodeId()); + this.nodeCount, this.rootNodeIndexInternal, this.totalSize, this.maxJsNodeId()); + } + + getNodeTypeOffset(): number { + return this.nodeTypeOffset; + } + + getNodeNameOffset(): number { + return this.nodeNameOffset; + } + + getNodeIdOffset(): number { + return this.nodeIdOffset; + } + + getNodeSelfSizeOffset(): number { + return this.nodeSelfSizeOffset; + } + + getNodeTraceNodeIdOffset(): number { + return this.nodeTraceNodeIdOffset; + } + + getNodeFieldCount(): number { + return this.nodeFieldCount; + } + + getNodeTypes(): Array<string> { + return this.nodeTypes; + } + + getNodeArrayType(): number { + return this.nodeArrayType; + } + + getNodeHiddenType(): number { + return this.nodeHiddenType; + } + + getNodeObjectType(): number { + return this.nodeObjectType; + } + + getNodeNativeType(): number { + return this.nodeNativeType; + } + + getNodeConsStringType(): number { + return this.nodeConsStringType; + } + + getNodeSlicedStringType(): number { + return this.nodeSlicedStringType; + } + + getNodeCodeType(): number { + return this.nodeCodeType; + } + + getNodeSyntheticType(): number { + return this.nodeSyntheticType; + } + + getEdgeFieldsCount(): number { + return this.edgeFieldsCount; + } + + getEdgeTypeOffset(): number { + return this.edgeTypeOffset; + } + + getEdgeNameOffset(): number { + return this.edgeNameOffset; + } + + getEdgeToNodeOffset(): number { + return this.edgeToNodeOffset; + } + + getEdgeTypes(): Array<string> { + return this.edgeTypes; + } + + getEdgeElementType(): number { + return this.edgeElementType; + } + + getEdgeHiddenType(): number { + return this.edgeHiddenType; + } + + getEdgeInternalType(): number { + return this.edgeInternalType; + } + + getEdgeShortcutType(): number { + return this.edgeShortcutType; + } + + getEdgeWeakType(): number { + return this.edgeWeakType; + } + + getEdgeInvisibleType(): number { + return this.edgeInvisibleType; + } + + getRetainedSizes(): Float64Array { + return this.retainedSizes; + } + + getFirstEdgeIndexes(): Uint32Array { + return this.firstEdgeIndexes; + } + + getRetainingNodes(): Uint32Array { + return this.retainingNodes; + } + + getRetainingEdges(): Uint32Array { + return this.retainingEdges; + } + + getFirstRetainerIndex(): Uint32Array { + return this.firstRetainerIndex; + } + + getNodeDistances(): Int32Array { + return this.nodeDistances; + } + + getDominatorsTree(): Uint32Array { + return this.dominatorsTree; + } + + getLazyStringCache(): {[x: string]: string} { + return this.lazyStringCache; } } @@ -2052,83 +2198,91 @@ } export abstract class HeapSnapshotItemProvider { - _iterator: HeapSnapshotItemIterator; - _indexProvider: HeapSnapshotItemIndexProvider; - _isEmpty: boolean; - _iterationOrder: number[]|null; - _currentComparator: HeapSnapshotModel.HeapSnapshotModel.ComparatorConfig|null; - _sortedPrefixLength: number; - _sortedSuffixLength: number; + readonly iterator: HeapSnapshotItemIterator; + private readonly indexProvider: HeapSnapshotItemIndexProvider; + private readonly isEmptyInternal: boolean; + iterationOrder: number[]|null; + currentComparator: HeapSnapshotModel.HeapSnapshotModel.ComparatorConfig|null; + private sortedPrefixLength: number; + private sortedSuffixLength: number; constructor(iterator: HeapSnapshotItemIterator, indexProvider: HeapSnapshotItemIndexProvider) { - this._iterator = iterator; - this._indexProvider = indexProvider; - this._isEmpty = !iterator.hasNext(); - this._iterationOrder = null; - this._currentComparator = null; - this._sortedPrefixLength = 0; - this._sortedSuffixLength = 0; + this.iterator = iterator; + this.indexProvider = indexProvider; + this.isEmptyInternal = !iterator.hasNext(); + this.iterationOrder = null; + this.currentComparator = null; + this.sortedPrefixLength = 0; + this.sortedSuffixLength = 0; } - _createIterationOrder(): void { - if (this._iterationOrder) { + createIterationOrder(): void { + if (this.iterationOrder) { return; } - this._iterationOrder = []; - for (let iterator = this._iterator; iterator.hasNext(); iterator.next()) { - this._iterationOrder.push(iterator.item().itemIndex()); + this.iterationOrder = []; + for (let iterator = this.iterator; iterator.hasNext(); iterator.next()) { + this.iterationOrder.push(iterator.item().itemIndex()); } } isEmpty(): boolean { - return this._isEmpty; + return this.isEmptyInternal; } serializeItemsRange(begin: number, end: number): HeapSnapshotModel.HeapSnapshotModel.ItemsRange { - this._createIterationOrder(); + this.createIterationOrder(); if (begin > end) { throw new Error('Start position > end position: ' + begin + ' > ' + end); } - if (!this._iterationOrder) { + if (!this.iterationOrder) { throw new Error('Iteration order undefined'); } - if (end > this._iterationOrder.length) { - end = this._iterationOrder.length; + if (end > this.iterationOrder.length) { + end = this.iterationOrder.length; } - if (this._sortedPrefixLength < end && begin < this._iterationOrder.length - this._sortedSuffixLength && - this._currentComparator) { - const currentComparator = this._currentComparator; + if (this.sortedPrefixLength < end && begin < this.iterationOrder.length - this.sortedSuffixLength && + this.currentComparator) { + const currentComparator = this.currentComparator; this.sort( - currentComparator, this._sortedPrefixLength, this._iterationOrder.length - 1 - this._sortedSuffixLength, - begin, end - 1); - if (begin <= this._sortedPrefixLength) { - this._sortedPrefixLength = end; + currentComparator, this.sortedPrefixLength, this.iterationOrder.length - 1 - this.sortedSuffixLength, begin, + end - 1); + if (begin <= this.sortedPrefixLength) { + this.sortedPrefixLength = end; } - if (end >= this._iterationOrder.length - this._sortedSuffixLength) { - this._sortedSuffixLength = this._iterationOrder.length - begin; + if (end >= this.iterationOrder.length - this.sortedSuffixLength) { + this.sortedSuffixLength = this.iterationOrder.length - begin; } } let position = begin; const count = end - begin; const result = new Array(count); for (let i = 0; i < count; ++i) { - const itemIndex = this._iterationOrder[position++]; - const item = this._indexProvider.itemForIndex(itemIndex); + const itemIndex = this.iterationOrder[position++]; + const item = this.indexProvider.itemForIndex(itemIndex); result[i] = item.serialize(); } - return new HeapSnapshotModel.HeapSnapshotModel.ItemsRange(begin, end, this._iterationOrder.length, result); + return new HeapSnapshotModel.HeapSnapshotModel.ItemsRange(begin, end, this.iterationOrder.length, result); } sortAndRewind(comparator: HeapSnapshotModel.HeapSnapshotModel.ComparatorConfig): void { - this._currentComparator = comparator; - this._sortedPrefixLength = 0; - this._sortedSuffixLength = 0; + this.currentComparator = comparator; + this.sortedPrefixLength = 0; + this.sortedSuffixLength = 0; } abstract sort( comparator: HeapSnapshotModel.HeapSnapshotModel.ComparatorConfig, leftBound: number, rightBound: number, windowLeft: number, windowRight: number): void; + + getIterationOrder(): Array<number>|null { + return this.iterationOrder; + } + + getCurrentComparator(): HeapSnapshotModel.HeapSnapshotModel.ComparatorConfig|null { + return this.currentComparator; + } } export class HeapSnapshotEdgesProvider extends HeapSnapshotItemProvider { @@ -2151,7 +2305,7 @@ const ascending1 = comparator.ascending1; const ascending2 = comparator.ascending2; - const edgeA = (this._iterator.item() as HeapSnapshotEdge).clone(); + const edgeA = (this.iterator.item() as HeapSnapshotEdge).clone(); const edgeB = edgeA.clone(); const nodeA = this.snapshot.createNode(); const nodeB = this.snapshot.createNode(); @@ -2221,19 +2375,20 @@ return result; } - if (!this._iterationOrder) { + const iterationOrder = this.getIterationOrder(); + if (!iterationOrder) { throw new Error('Iteration order not defined'); } if (fieldName1 === '!edgeName') { Platform.ArrayUtilities.sortRange( - this._iterationOrder, compareEdgeAndNode, leftBound, rightBound, windowLeft, windowRight); + iterationOrder, compareEdgeAndNode, leftBound, rightBound, windowLeft, windowRight); } else if (fieldName2 === '!edgeName') { Platform.ArrayUtilities.sortRange( - this._iterationOrder, compareNodeAndEdge, leftBound, rightBound, windowLeft, windowRight); + iterationOrder, compareNodeAndEdge, leftBound, rightBound, windowLeft, windowRight); } else { Platform.ArrayUtilities.sortRange( - this._iterationOrder, compareNodeAndNode, leftBound, rightBound, windowLeft, windowRight); + iterationOrder, compareNodeAndNode, leftBound, rightBound, windowLeft, windowRight); } } } @@ -2248,36 +2403,37 @@ } nodePosition(snapshotObjectId: number): number { - this._createIterationOrder(); + this.createIterationOrder(); const node = this.snapshot.createNode(); let i = 0; - if (!this._iterationOrder) { + const iterationOrder = this.getIterationOrder(); + if (!iterationOrder) { throw new Error('Iteration order not defined'); } - for (; i < this._iterationOrder.length; i++) { - node.nodeIndex = this._iterationOrder[i]; + for (; i < iterationOrder.length; i++) { + node.nodeIndex = iterationOrder[i]; if (node.id() === snapshotObjectId) { break; } } - if (i === this._iterationOrder.length) { + if (i === iterationOrder.length) { return -1; } - const targetNodeIndex = this._iterationOrder[i]; + const targetNodeIndex = iterationOrder[i]; let smallerCount = 0; - const currentComparator = (this._currentComparator as HeapSnapshotModel.HeapSnapshotModel.ComparatorConfig); - const compare = this._buildCompareFunction(currentComparator); - for (let i = 0; i < this._iterationOrder.length; i++) { - if (compare(this._iterationOrder[i], targetNodeIndex) < 0) { + const currentComparator = this.currentComparator as HeapSnapshotModel.HeapSnapshotModel.ComparatorConfig; + const compare = this.buildCompareFunction(currentComparator); + for (let i = 0; i < iterationOrder.length; i++) { + if (compare(iterationOrder[i], targetNodeIndex) < 0) { ++smallerCount; } } return smallerCount; } - _buildCompareFunction(comparator: HeapSnapshotModel.HeapSnapshotModel.ComparatorConfig): + private buildCompareFunction(comparator: HeapSnapshotModel.HeapSnapshotModel.ComparatorConfig): (arg0: number, arg1: number) => number { const nodeA = this.snapshot.createNode(); const nodeB = this.snapshot.createNode(); @@ -2314,36 +2470,37 @@ sort( comparator: HeapSnapshotModel.HeapSnapshotModel.ComparatorConfig, leftBound: number, rightBound: number, windowLeft: number, windowRight: number): void { - if (!this._iterationOrder) { + const iterationOrder = this.getIterationOrder(); + if (!iterationOrder) { throw new Error('Iteration order not defined'); } Platform.ArrayUtilities.sortRange( - this._iterationOrder, this._buildCompareFunction(comparator), leftBound, rightBound, windowLeft, windowRight); + iterationOrder, this.buildCompareFunction(comparator), leftBound, rightBound, windowLeft, windowRight); } } export class JSHeapSnapshot extends HeapSnapshot { - _nodeFlags: { + readonly nodeFlags: { // bit flags canBeQueried: number, detachedDOMTreeNode: number, pageObject: number, // The idea is to track separately the objects owned by the page and the objects owned by debugger. }; - _lazyStringCache: {}; - _flags!: Uint32Array; - _statistics?: HeapSnapshotModel.HeapSnapshotModel.Statistics; + lazyStringCache: {}; + private flags!: Uint32Array; + private statistics?: HeapSnapshotModel.HeapSnapshotModel.Statistics; constructor(profile: Profile, progress: HeapSnapshotProgress) { super(profile, progress); - this._nodeFlags = { + this.nodeFlags = { // bit flags canBeQueried: 1, detachedDOMTreeNode: 2, pageObject: 4, // The idea is to track separately the objects owned by the page and the objects owned by debugger. }; - this._lazyStringCache = {}; + this.lazyStringCache = {}; this.initialize(); } @@ -2372,10 +2529,10 @@ } calculateFlags(): void { - this._flags = new Uint32Array(this.nodeCount); - this._markDetachedDOMTreeNodes(); - this._markQueriableHeapObjects(); - this._markPageOwnedNodes(); + this.flags = new Uint32Array(this.nodeCount); + this.markDetachedDOMTreeNodes(); + this.markQueriableHeapObjects(); + this.markPageOwnedNodes(); } calculateDistances(): void { @@ -2413,20 +2570,20 @@ } userObjectsMapAndFlag(): {map: Uint32Array, flag: number}|null { - return {map: this._flags, flag: this._nodeFlags.pageObject}; + return {map: this.flags, flag: this.nodeFlags.pageObject}; } - _flagsOfNode(node: HeapSnapshotNode): number { - return this._flags[node.nodeIndex / this._nodeFieldCount]; + flagsOfNode(node: HeapSnapshotNode): number { + return this.flags[node.nodeIndex / this.getNodeFieldCount()]; } - _markDetachedDOMTreeNodes(): void { + private markDetachedDOMTreeNodes(): void { const nodes = this.nodes; const nodesLength = nodes.length; - const nodeFieldCount = this._nodeFieldCount; - const nodeNativeType = this._nodeNativeType; - const nodeTypeOffset = this._nodeTypeOffset; - const flag = this._nodeFlags.detachedDOMTreeNode; + const nodeFieldCount = this.getNodeFieldCount(); + const nodeNativeType = this.getNodeNativeType(); + const nodeTypeOffset = this.getNodeTypeOffset(); + const flag = this.nodeFlags.detachedDOMTreeNode; const node = this.rootNode(); for (let nodeIndex = 0, ordinal = 0; nodeIndex < nodesLength; nodeIndex += nodeFieldCount, ordinal++) { const nodeType = nodes[nodeIndex + nodeTypeOffset]; @@ -2435,28 +2592,28 @@ } node.nodeIndex = nodeIndex; if (node.name().startsWith('Detached ')) { - this._flags[ordinal] |= flag; + this.flags[ordinal] |= flag; } } } - _markQueriableHeapObjects(): void { + private markQueriableHeapObjects(): void { // Allow runtime properties query for objects accessible from Window objects // via regular properties, and for DOM wrappers. Trying to access random objects // can cause a crash due to insonsistent state of internal properties of wrappers. - const flag = this._nodeFlags.canBeQueried; - const hiddenEdgeType = this._edgeHiddenType; - const internalEdgeType = this._edgeInternalType; - const invisibleEdgeType = this._edgeInvisibleType; - const weakEdgeType = this._edgeWeakType; - const edgeToNodeOffset = this._edgeToNodeOffset; - const edgeTypeOffset = this._edgeTypeOffset; - const edgeFieldsCount = this._edgeFieldsCount; + const flag = this.nodeFlags.canBeQueried; + const hiddenEdgeType = this.getEdgeHiddenType(); + const internalEdgeType = this.getEdgeInternalType(); + const invisibleEdgeType = this.getEdgeInvisibleType(); + const weakEdgeType = this.getEdgeWeakType(); + const edgeToNodeOffset = this.getEdgeToNodeOffset(); + const edgeTypeOffset = this.getEdgeTypeOffset(); + const edgeFieldsCount = this.getEdgeFieldsCount(); const containmentEdges = this.containmentEdges; - const nodeFieldCount = this._nodeFieldCount; - const firstEdgeIndexes = this._firstEdgeIndexes; + const nodeFieldCount = this.getNodeFieldCount(); + const firstEdgeIndexes = this.getFirstEdgeIndexes(); - const flags = (this._flags as Uint32Array); + const flags = (this.flags as Uint32Array); const list: number[] = []; for (let iter = this.rootNode().edges(); iter.hasNext(); iter.next()) { @@ -2489,25 +2646,25 @@ } } - _markPageOwnedNodes(): void { - const edgeShortcutType = this._edgeShortcutType; - const edgeElementType = this._edgeElementType; - const edgeToNodeOffset = this._edgeToNodeOffset; - const edgeTypeOffset = this._edgeTypeOffset; - const edgeFieldsCount = this._edgeFieldsCount; - const edgeWeakType = this._edgeWeakType; - const firstEdgeIndexes = this._firstEdgeIndexes; + private markPageOwnedNodes(): void { + const edgeShortcutType = this.getEdgeShortcutType(); + const edgeElementType = this.getEdgeElementType(); + const edgeToNodeOffset = this.getEdgeToNodeOffset(); + const edgeTypeOffset = this.getEdgeTypeOffset(); + const edgeFieldsCount = this.getEdgeFieldsCount(); + const edgeWeakType = this.getEdgeWeakType(); + const firstEdgeIndexes = this.getFirstEdgeIndexes(); const containmentEdges = this.containmentEdges; - const nodeFieldCount = this._nodeFieldCount; + const nodeFieldCount = this.getNodeFieldCount(); const nodesCount = this.nodeCount; - const flags = (this._flags as Uint32Array); - const pageObjectFlag = this._nodeFlags.pageObject; + const flags = (this.flags as Uint32Array); + const pageObjectFlag = this.nodeFlags.pageObject; const nodesToVisit = new Uint32Array(nodesCount); let nodesToVisitLength = 0; - const rootNodeOrdinal = this._rootNodeIndex / nodeFieldCount; + const rootNodeOrdinal = this.rootNodeIndex / nodeFieldCount; const node = this.rootNode(); // Populate the entry points. They are Window objects and DOM Tree Roots. @@ -2550,16 +2707,16 @@ } calculateStatistics(): void { - const nodeFieldCount = this._nodeFieldCount; + const nodeFieldCount = this.getNodeFieldCount(); const nodes = this.nodes; const nodesLength = nodes.length; - const nodeTypeOffset = this._nodeTypeOffset; - const nodeSizeOffset = this._nodeSelfSizeOffset; - const nodeNativeType = this._nodeNativeType; - const nodeCodeType = this._nodeCodeType; - const nodeConsStringType = this._nodeConsStringType; - const nodeSlicedStringType = this._nodeSlicedStringType; - const distances = this._nodeDistances; + const nodeTypeOffset = this.getNodeTypeOffset(); + const nodeSizeOffset = this.getNodeSelfSizeOffset(); + const nodeNativeType = this.getNodeNativeType(); + const nodeCodeType = this.getNodeCodeType(); + const nodeConsStringType = this.getNodeConsStringType(); + const nodeSlicedStringType = this.getNodeSlicedStringType(); + const distances = this.getNodeDistances(); let sizeNative = 0; let sizeCode = 0; let sizeStrings = 0; @@ -2582,30 +2739,30 @@ } else if (nodeType === nodeConsStringType || nodeType === nodeSlicedStringType || node.type() === 'string') { sizeStrings += nodeSize; } else if (node.name() === 'Array') { - sizeJSArrays += this._calculateArraySize(node); + sizeJSArrays += this.calculateArraySize(node); } } - this._statistics = new HeapSnapshotModel.HeapSnapshotModel.Statistics(); - this._statistics.total = this.totalSize; - this._statistics.v8heap = this.totalSize - sizeNative; - this._statistics.native = sizeNative; - this._statistics.code = sizeCode; - this._statistics.jsArrays = sizeJSArrays; - this._statistics.strings = sizeStrings; - this._statistics.system = sizeSystem; + this.statistics = new HeapSnapshotModel.HeapSnapshotModel.Statistics(); + this.statistics.total = this.totalSize; + this.statistics.v8heap = this.totalSize - sizeNative; + this.statistics.native = sizeNative; + this.statistics.code = sizeCode; + this.statistics.jsArrays = sizeJSArrays; + this.statistics.strings = sizeStrings; + this.statistics.system = sizeSystem; } - _calculateArraySize(node: HeapSnapshotNode): number { + private calculateArraySize(node: HeapSnapshotNode): number { let size = node.selfSize(); const beginEdgeIndex = node.edgeIndexesStart(); const endEdgeIndex = node.edgeIndexesEnd(); const containmentEdges = this.containmentEdges; const strings = this.strings; - const edgeToNodeOffset = this._edgeToNodeOffset; - const edgeTypeOffset = this._edgeTypeOffset; - const edgeNameOffset = this._edgeNameOffset; - const edgeFieldsCount = this._edgeFieldsCount; - const edgeInternalType = this._edgeInternalType; + const edgeToNodeOffset = this.getEdgeToNodeOffset(); + const edgeTypeOffset = this.getEdgeTypeOffset(); + const edgeNameOffset = this.getEdgeNameOffset(); + const edgeFieldsCount = this.getEdgeFieldsCount(); + const edgeInternalType = this.getEdgeInternalType(); for (let edgeIndex = beginEdgeIndex; edgeIndex < endEdgeIndex; edgeIndex += edgeFieldsCount) { const edgeType = containmentEdges[edgeIndex + edgeTypeOffset]; if (edgeType !== edgeInternalType) { @@ -2626,7 +2783,7 @@ } getStatistics(): HeapSnapshotModel.HeapSnapshotModel.Statistics { - return /** @type {!HeapSnapshotModel.HeapSnapshotModel.Statistics} */ this._statistics as + return /** @type {!HeapSnapshotModel.HeapSnapshotModel.Statistics} */ this.statistics as HeapSnapshotModel.HeapSnapshotModel.Statistics; } } @@ -2637,9 +2794,9 @@ } canBeQueried(): boolean { - const snapshot = (this._snapshot as JSHeapSnapshot); - const flags = snapshot._flagsOfNode(this); - return Boolean(flags & snapshot._nodeFlags.canBeQueried); + const snapshot = (this.getSnapshot() as JSHeapSnapshot); + const flags = snapshot.flagsOfNode(this); + return Boolean(flags & snapshot.nodeFlags.canBeQueried); } rawName(): string { @@ -2647,32 +2804,32 @@ } name(): string { - const snapshot = this._snapshot; - if (this.rawType() === snapshot._nodeConsStringType) { - let string: string = snapshot._lazyStringCache[this.nodeIndex]; + const snapshot = this.getSnapshot(); + if (this.rawType() === snapshot.getNodeConsStringType()) { + let string: string = snapshot.getLazyStringCache()[this.nodeIndex]; if (typeof string === 'undefined') { - string = this._consStringName(); - snapshot._lazyStringCache[this.nodeIndex] = string; + string = this.consStringName(); + snapshot.getLazyStringCache()[this.nodeIndex] = string; } return string; } return this.rawName(); } - _consStringName(): string { - const snapshot = this._snapshot; - const consStringType = snapshot._nodeConsStringType; - const edgeInternalType = snapshot._edgeInternalType; - const edgeFieldsCount = snapshot._edgeFieldsCount; - const edgeToNodeOffset = snapshot._edgeToNodeOffset; - const edgeTypeOffset = snapshot._edgeTypeOffset; - const edgeNameOffset = snapshot._edgeNameOffset; + private consStringName(): string { + const snapshot = this.getSnapshot(); + const consStringType = snapshot.getNodeConsStringType(); + const edgeInternalType = snapshot.getEdgeInternalType(); + const edgeFieldsCount = snapshot.getEdgeFieldsCount(); + const edgeToNodeOffset = snapshot.getEdgeToNodeOffset(); + const edgeTypeOffset = snapshot.getEdgeTypeOffset(); + const edgeNameOffset = snapshot.getEdgeNameOffset(); const strings = snapshot.strings; const edges = snapshot.containmentEdges; - const firstEdgeIndexes = snapshot._firstEdgeIndexes; - const nodeFieldCount = snapshot._nodeFieldCount; - const nodeTypeOffset = snapshot._nodeTypeOffset; - const nodeNameOffset = snapshot._nodeNameOffset; + const firstEdgeIndexes = snapshot.getFirstEdgeIndexes(); + const nodeFieldCount = snapshot.getNodeFieldCount(); + const nodeTypeOffset = snapshot.getNodeTypeOffset(); + const nodeNameOffset = snapshot.getNodeNameOffset(); const nodes = snapshot.nodes; const nodesStack = []; nodesStack.push(this.nodeIndex); @@ -2723,30 +2880,30 @@ } classIndex(): number { - const snapshot = this._snapshot; + const snapshot = this.getSnapshot(); const nodes = snapshot.nodes; - const type = nodes[this.nodeIndex + snapshot._nodeTypeOffset]; - if (type === snapshot._nodeObjectType || type === snapshot._nodeNativeType) { - return nodes[this.nodeIndex + snapshot._nodeNameOffset]; + const type = nodes[this.nodeIndex + snapshot.getNodeTypeOffset()]; + if (type === snapshot.getNodeObjectType() || type === snapshot.getNodeNativeType()) { + return nodes[this.nodeIndex + snapshot.getNodeNameOffset()]; } return -1 - type; } id(): number { - const snapshot = this._snapshot; - return snapshot.nodes[this.nodeIndex + snapshot._nodeIdOffset]; + const snapshot = this.getSnapshot(); + return snapshot.nodes[this.nodeIndex + snapshot.getNodeIdOffset()]; } isHidden(): boolean { - return this.rawType() === this._snapshot._nodeHiddenType; + return this.rawType() === this.getSnapshot().getNodeHiddenType(); } isArray(): boolean { - return this.rawType() === this._snapshot._nodeArrayType; + return this.rawType() === this.getSnapshot().getNodeArrayType(); } isSynthetic(): boolean { - return this.rawType() === this._snapshot._nodeSyntheticType; + return this.rawType() === this.getSnapshot().getNodeSyntheticType(); } isUserRoot(): boolean { @@ -2759,12 +2916,12 @@ serialize(): HeapSnapshotModel.HeapSnapshotModel.Node { const result = super.serialize(); - const snapshot = (this._snapshot as JSHeapSnapshot); - const flags = snapshot._flagsOfNode(this); - if (flags & snapshot._nodeFlags.canBeQueried) { + const snapshot = (this.getSnapshot() as JSHeapSnapshot); + const flags = snapshot.flagsOfNode(this); + if (flags & snapshot.nodeFlags.canBeQueried) { result.canBeQueried = true; } - if (flags & snapshot._nodeFlags.detachedDOMTreeNode) { + if (flags & snapshot.nodeFlags.detachedDOMTreeNode) { result.detachedDOMTreeNode = true; } return result; @@ -2777,44 +2934,44 @@ } clone(): JSHeapSnapshotEdge { - const snapshot = (this._snapshot as JSHeapSnapshot); + const snapshot = (this.getSnapshot() as JSHeapSnapshot); return new JSHeapSnapshotEdge(snapshot, this.edgeIndex); } hasStringName(): boolean { if (!this.isShortcut()) { - return this._hasStringName(); + return this.hasStringNameInternal(); } // @ts-ignore parseInt is successful against numbers. - return isNaN(parseInt(this._name(), 10)); + return isNaN(parseInt(this.name(), 10)); } isElement(): boolean { - return this.rawType() === this._snapshot._edgeElementType; + return this.rawType() === this.getSnapshot().getEdgeElementType(); } isHidden(): boolean { - return this.rawType() === this._snapshot._edgeHiddenType; + return this.rawType() === this.getSnapshot().getEdgeHiddenType(); } isWeak(): boolean { - return this.rawType() === this._snapshot._edgeWeakType; + return this.rawType() === this.getSnapshot().getEdgeWeakType(); } isInternal(): boolean { - return this.rawType() === this._snapshot._edgeInternalType; + return this.rawType() === this.getSnapshot().getEdgeInternalType(); } isInvisible(): boolean { - return this.rawType() === this._snapshot._edgeInvisibleType; + return this.rawType() === this.getSnapshot().getEdgeInvisibleType(); } isShortcut(): boolean { - return this.rawType() === this._snapshot._edgeShortcutType; + return this.rawType() === this.getSnapshot().getEdgeShortcutType(); } name(): string { - const name = this._name(); + const name = this.nameInternal(); if (!this.isShortcut()) { return String(name); } @@ -2847,22 +3004,22 @@ return '?' + name + '?'; } - _hasStringName(): boolean { + private hasStringNameInternal(): boolean { const type = this.rawType(); - const snapshot = this._snapshot; - return type !== snapshot._edgeElementType && type !== snapshot._edgeHiddenType; + const snapshot = this.getSnapshot(); + return type !== snapshot.getEdgeElementType() && type !== snapshot.getEdgeHiddenType(); } - _name(): string|number { - return this._hasStringName() ? this._snapshot.strings[this._nameOrIndex()] : this._nameOrIndex(); + private nameInternal(): string|number { + return this.hasStringName() ? this.getSnapshot().strings[this.nameOrIndex()] : this.nameOrIndex(); } - _nameOrIndex(): number { - return this._edges[this.edgeIndex + this._snapshot._edgeNameOffset]; + private nameOrIndex(): number { + return this.edges[this.edgeIndex + this.getSnapshot().getEdgeNameOffset()]; } rawType(): number { - return this._edges[this.edgeIndex + this._snapshot._edgeTypeOffset]; + return this.edges[this.edgeIndex + this.getSnapshot().getEdgeTypeOffset()]; } } @@ -2872,28 +3029,28 @@ } clone(): JSHeapSnapshotRetainerEdge { - const snapshot = (this._snapshot as JSHeapSnapshot); + const snapshot = (this.getSnapshot() as JSHeapSnapshot); return new JSHeapSnapshotRetainerEdge(snapshot, this.retainerIndex()); } isHidden(): boolean { - return this._edge().isHidden(); + return this.edge().isHidden(); } isInternal(): boolean { - return this._edge().isInternal(); + return this.edge().isInternal(); } isInvisible(): boolean { - return this._edge().isInvisible(); + return this.edge().isInvisible(); } isShortcut(): boolean { - return this._edge().isShortcut(); + return this.edge().isShortcut(); } isWeak(): boolean { - return this._edge().isWeak(); + return this.edge().isWeak(); } } export interface AggregatedInfo {
diff --git a/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotLoader.ts b/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotLoader.ts index 690556a..f7beaad 100644 --- a/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotLoader.ts +++ b/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotLoader.ts
@@ -28,88 +28,86 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import * as TextUtils from '../../models/text_utils/text_utils.js'; import {HeapSnapshotProgress, JSHeapSnapshot} from './HeapSnapshot.js'; import type {HeapSnapshotHeader, Profile} from './HeapSnapshot.js'; import type {HeapSnapshotWorkerDispatcher} from './HeapSnapshotWorkerDispatcher.js'; export class HeapSnapshotLoader { - _progress: HeapSnapshotProgress; - _buffer: string; - _dataCallback: ((value: string|PromiseLike<string>) => void)|null; - _done: boolean; + private readonly progress: HeapSnapshotProgress; + private buffer: string; + private dataCallback: ((value: string|PromiseLike<string>) => void)|null; + private done: boolean; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/no-explicit-any - _snapshot?: {[x: string]: any}; - _array!: number[]|Uint32Array|null; - _arrayIndex!: number; + private snapshot?: {[x: string]: any}; + private array!: number[]|Uint32Array|null; + private arrayIndex!: number; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/no-explicit-any - _json?: any; + private json?: any; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/no-explicit-any - _jsonTokenizer?: any; + private jsonTokenizer?: any; constructor(dispatcher: HeapSnapshotWorkerDispatcher) { - this._reset(); - this._progress = new HeapSnapshotProgress(dispatcher); - this._buffer = ''; - this._dataCallback = null; - this._done = false; - this._parseInput(); + this.reset(); + this.progress = new HeapSnapshotProgress(dispatcher); + this.buffer = ''; + this.dataCallback = null; + this.done = false; + this.parseInput(); } dispose(): void { - this._reset(); + this.reset(); } - _reset(): void { - this._json = ''; - this._snapshot = undefined; + private reset(): void { + this.json = ''; + this.snapshot = undefined; } close(): void { - this._done = true; - if (this._dataCallback) { - this._dataCallback(''); + this.done = true; + if (this.dataCallback) { + this.dataCallback(''); } } buildSnapshot(): JSHeapSnapshot { - this._snapshot = this._snapshot || {}; + this.snapshot = this.snapshot || {}; - this._progress.updateStatus('Processing snapshot…'); - const result = new JSHeapSnapshot((this._snapshot as Profile), this._progress); - this._reset(); + this.progress.updateStatus('Processing snapshot…'); + const result = new JSHeapSnapshot((this.snapshot as Profile), this.progress); + this.reset(); return result; } - _parseUintArray(): boolean { + private parseUintArray(): boolean { let index = 0; const char0 = '0'.charCodeAt(0); const char9 = '9'.charCodeAt(0); const closingBracket = ']'.charCodeAt(0); - const length = this._json.length; + const length = this.json.length; while (true) { while (index < length) { - const code = this._json.charCodeAt(index); + const code = this.json.charCodeAt(index); if (char0 <= code && code <= char9) { break; } else if (code === closingBracket) { - this._json = this._json.slice(index + 1); + this.json = this.json.slice(index + 1); return false; } ++index; } if (index === length) { - this._json = ''; + this.json = ''; return true; } let nextNumber = 0; const startIndex = index; while (index < length) { - const code = this._json.charCodeAt(index); + const code = this.json.charCodeAt(index); if (char0 > code || code > char9) { break; } @@ -118,142 +116,141 @@ ++index; } if (index === length) { - this._json = this._json.slice(startIndex); + this.json = this.json.slice(startIndex); return true; } - if (!this._array) { + if (!this.array) { throw new Error('Array not instantiated'); } - this._array[this._arrayIndex++] = nextNumber; + this.array[this.arrayIndex++] = nextNumber; } } - _parseStringsArray(): void { - this._progress.updateStatus('Parsing strings…'); - const closingBracketIndex = this._json.lastIndexOf(']'); + private parseStringsArray(): void { + this.progress.updateStatus('Parsing strings…'); + const closingBracketIndex = this.json.lastIndexOf(']'); if (closingBracketIndex === -1) { throw new Error('Incomplete JSON'); } - this._json = this._json.slice(0, closingBracketIndex + 1); + this.json = this.json.slice(0, closingBracketIndex + 1); - if (!this._snapshot) { + if (!this.snapshot) { throw new Error('No snapshot in parseStringsArray'); } - this._snapshot.strings = JSON.parse(this._json); + this.snapshot.strings = JSON.parse(this.json); } write(chunk: string): void { - this._buffer += chunk; - if (!this._dataCallback) { + this.buffer += chunk; + if (!this.dataCallback) { return; } - this._dataCallback(this._buffer); - this._dataCallback = null; - this._buffer = ''; + this.dataCallback(this.buffer); + this.dataCallback = null; + this.buffer = ''; } - _fetchChunk(): Promise<string> { - return this._done ? Promise.resolve(this._buffer) : new Promise(r => { - this._dataCallback = r; + private fetchChunk(): Promise<string> { + return this.done ? Promise.resolve(this.buffer) : new Promise(r => { + this.dataCallback = r; }); } - async _findToken(token: string, startIndex?: number): Promise<number> { + private async findToken(token: string, startIndex?: number): Promise<number> { while (true) { - const pos = this._json.indexOf(token, startIndex || 0); + const pos = this.json.indexOf(token, startIndex || 0); if (pos !== -1) { return pos; } - startIndex = this._json.length - token.length + 1; - this._json += await this._fetchChunk(); + startIndex = this.json.length - token.length + 1; + this.json += await this.fetchChunk(); } } - async _parseArray(name: string, title: string, length?: number): Promise<number[]|Uint32Array> { - const nameIndex = await this._findToken(name); - const bracketIndex = await this._findToken('[', nameIndex); - this._json = this._json.slice(bracketIndex + 1); - this._array = length ? new Uint32Array(length) : []; - this._arrayIndex = 0; - while (this._parseUintArray()) { + private async parseArray(name: string, title: string, length?: number): Promise<number[]|Uint32Array> { + const nameIndex = await this.findToken(name); + const bracketIndex = await this.findToken('[', nameIndex); + this.json = this.json.slice(bracketIndex + 1); + this.array = length ? new Uint32Array(length) : []; + this.arrayIndex = 0; + while (this.parseUintArray()) { if (length) { - this._progress.updateProgress(title, this._arrayIndex, this._array.length); + this.progress.updateProgress(title, this.arrayIndex, this.array.length); } else { - this._progress.updateStatus(title); + this.progress.updateStatus(title); } - this._json += await this._fetchChunk(); + this.json += await this.fetchChunk(); } - const result = this._array; - this._array = null; + const result = this.array; + this.array = null; return result; } - async _parseInput(): Promise<void> { + private async parseInput(): Promise<void> { const snapshotToken = '"snapshot"'; - const snapshotTokenIndex = await this._findToken(snapshotToken); + const snapshotTokenIndex = await this.findToken(snapshotToken); if (snapshotTokenIndex === -1) { throw new Error('Snapshot token not found'); } - this._progress.updateStatus('Loading snapshot info…'); - const json = this._json.slice(snapshotTokenIndex + snapshotToken.length + 1); - this._jsonTokenizer = new TextUtils.TextUtils.BalancedJSONTokenizer(metaJSON => { - this._json = this._jsonTokenizer.remainder(); - this._jsonTokenizer = null; + this.progress.updateStatus('Loading snapshot info…'); + const json = this.json.slice(snapshotTokenIndex + snapshotToken.length + 1); + this.jsonTokenizer = new TextUtils.TextUtils.BalancedJSONTokenizer(metaJSON => { + this.json = this.jsonTokenizer.remainder(); + this.jsonTokenizer = null; - this._snapshot = this._snapshot || {}; - this._snapshot.snapshot = (JSON.parse(metaJSON) as HeapSnapshotHeader); + this.snapshot = this.snapshot || {}; + this.snapshot.snapshot = (JSON.parse(metaJSON) as HeapSnapshotHeader); }); - this._jsonTokenizer.write(json); - while (this._jsonTokenizer) { - this._jsonTokenizer.write(await this._fetchChunk()); + this.jsonTokenizer.write(json); + while (this.jsonTokenizer) { + this.jsonTokenizer.write(await this.fetchChunk()); } - this._snapshot = this._snapshot || {}; - const nodes = await this._parseArray( + this.snapshot = this.snapshot || {}; + const nodes = await this.parseArray( '"nodes"', 'Loading nodes… {PH1}%', - this._snapshot.snapshot.meta.node_fields.length * this._snapshot.snapshot.node_count); - this._snapshot.nodes = (nodes as Uint32Array); + this.snapshot.snapshot.meta.node_fields.length * this.snapshot.snapshot.node_count); + this.snapshot.nodes = (nodes as Uint32Array); - const edges = await this._parseArray( + const edges = await this.parseArray( '"edges"', 'Loading edges… {PH1}%', - this._snapshot.snapshot.meta.edge_fields.length * this._snapshot.snapshot.edge_count); - this._snapshot.edges = (edges as Uint32Array); + this.snapshot.snapshot.meta.edge_fields.length * this.snapshot.snapshot.edge_count); + this.snapshot.edges = (edges as Uint32Array); - if (this._snapshot.snapshot.trace_function_count) { - const traceFunctionInfos = await this._parseArray( + if (this.snapshot.snapshot.trace_function_count) { + const traceFunctionInfos = await this.parseArray( '"trace_function_infos"', 'Loading allocation traces… {PH1}%', - this._snapshot.snapshot.meta.trace_function_info_fields.length * - this._snapshot.snapshot.trace_function_count); - this._snapshot.trace_function_infos = (traceFunctionInfos as Uint32Array); + this.snapshot.snapshot.meta.trace_function_info_fields.length * this.snapshot.snapshot.trace_function_count); + this.snapshot.trace_function_infos = (traceFunctionInfos as Uint32Array); - const thisTokenEndIndex = await this._findToken(':'); - const nextTokenIndex = await this._findToken('"', thisTokenEndIndex); - const openBracketIndex = this._json.indexOf('['); - const closeBracketIndex = this._json.lastIndexOf(']', nextTokenIndex); - this._snapshot.trace_tree = JSON.parse(this._json.substring(openBracketIndex, closeBracketIndex + 1)); - this._json = this._json.slice(closeBracketIndex + 1); + const thisTokenEndIndex = await this.findToken(':'); + const nextTokenIndex = await this.findToken('"', thisTokenEndIndex); + const openBracketIndex = this.json.indexOf('['); + const closeBracketIndex = this.json.lastIndexOf(']', nextTokenIndex); + this.snapshot.trace_tree = JSON.parse(this.json.substring(openBracketIndex, closeBracketIndex + 1)); + this.json = this.json.slice(closeBracketIndex + 1); } - if (this._snapshot.snapshot.meta.sample_fields) { - const samples = await this._parseArray('"samples"', 'Loading samples…'); - this._snapshot.samples = (samples as number[]); + if (this.snapshot.snapshot.meta.sample_fields) { + const samples = await this.parseArray('"samples"', 'Loading samples…'); + this.snapshot.samples = (samples as number[]); } - if (this._snapshot.snapshot.meta['location_fields']) { - const locations = await this._parseArray('"locations"', 'Loading locations…'); - this._snapshot.locations = (locations as number[]); + if (this.snapshot.snapshot.meta['location_fields']) { + const locations = await this.parseArray('"locations"', 'Loading locations…'); + this.snapshot.locations = (locations as number[]); } else { - this._snapshot.locations = []; + this.snapshot.locations = []; } - this._progress.updateStatus('Loading strings…'); - const stringsTokenIndex = await this._findToken('"strings"'); - const bracketIndex = await this._findToken('[', stringsTokenIndex); - this._json = this._json.slice(bracketIndex); - while (!this._done) { - this._json += await this._fetchChunk(); + this.progress.updateStatus('Loading strings…'); + const stringsTokenIndex = await this.findToken('"strings"'); + const bracketIndex = await this.findToken('[', stringsTokenIndex); + this.json = this.json.slice(bracketIndex); + while (!this.done) { + this.json += await this.fetchChunk(); } - this._parseStringsArray(); + this.parseStringsArray(); } }
diff --git a/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotWorkerDispatcher.ts b/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotWorkerDispatcher.ts index 29a7c17..7a1d656 100644 --- a/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotWorkerDispatcher.ts +++ b/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotWorkerDispatcher.ts
@@ -28,8 +28,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import type * as HeapSnapshotModel from '../../models/heap_snapshot_model/heap_snapshot_model.js'; interface DispatcherResponse { callId?: number; @@ -43,20 +41,20 @@ export class HeapSnapshotWorkerDispatcher { // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/no-explicit-any - _objects: any[]; - _global: Worker; - _postMessage: Function; + private objects: any[]; + private readonly global: Worker; + private readonly postMessage: Function; constructor(globalObject: Worker, postMessage: Function) { - this._objects = []; - this._global = globalObject; - this._postMessage = postMessage; + this.objects = []; + this.global = globalObject; + this.postMessage = postMessage; } - _findFunction(name: string): Function { + private findFunction(name: string): Function { const path = name.split('.'); // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/no-explicit-any - let result = (this._global as any); + let result = (this.global as any); for (let i = 0; i < path.length; ++i) { result = result[path[i]]; } @@ -66,7 +64,7 @@ // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/no-explicit-any sendEvent(name: string, data: any): void { - this._postMessage({eventName: name, data: data}); + this.postMessage({eventName: name, data: data}); } dispatchMessage({data}: {data: HeapSnapshotModel.HeapSnapshotModel.WorkerCommand}): void { @@ -75,32 +73,32 @@ try { switch (data.disposition) { case 'create': { - const constructorFunction = this._findFunction(data.methodName); + const constructorFunction = this.findFunction(data.methodName); // @ts-ignore - this._objects[data.objectId] = new constructorFunction(this); + this.objects[data.objectId] = new constructorFunction(this); break; } case 'dispose': { - delete this._objects[data.objectId]; + delete this.objects[data.objectId]; break; } case 'getter': { - const object = this._objects[data.objectId]; + const object = this.objects[data.objectId]; const result = object[data.methodName]; response.result = result; break; } case 'factory': { - const object = this._objects[data.objectId]; + const object = this.objects[data.objectId]; const result = object[data.methodName].apply(object, data.methodArguments); if (result) { - this._objects[data.newObjectId] = result; + this.objects[data.newObjectId] = result; } response.result = Boolean(result); break; } case 'method': { - const object = this._objects[data.objectId]; + const object = this.objects[data.objectId]; response.result = object[data.methodName].apply(object, data.methodArguments); break; } @@ -120,6 +118,6 @@ response.errorMethodName = data.methodName; } } - this._postMessage(response); + this.postMessage(response); } }
diff --git a/front_end/entrypoints/inspector_main/InspectorMain.ts b/front_end/entrypoints/inspector_main/InspectorMain.ts index 9ef05e8..f2fbb4d 100644 --- a/front_end/entrypoints/inspector_main/InspectorMain.ts +++ b/front_end/entrypoints/inspector_main/InspectorMain.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as Host from '../../core/host/host.js'; import * as i18n from '../../core/i18n/i18n.js'; @@ -145,21 +143,21 @@ let nodeIndicatorInstance: NodeIndicator; export class NodeIndicator implements UI.Toolbar.Provider { - _element: Element; - _button: UI.Toolbar.ToolbarItem; + private readonly element: Element; + private readonly button: UI.Toolbar.ToolbarItem; private constructor() { const element = document.createElement('div'); const shadowRoot = UI.Utils.createShadowRootWithCoreStyles( element, {cssFile: 'entrypoints/inspector_main/nodeIcon.css', delegatesFocus: undefined}); - this._element = shadowRoot.createChild('div', 'node-icon'); + this.element = shadowRoot.createChild('div', 'node-icon'); element.addEventListener( 'click', () => Host.InspectorFrontendHost.InspectorFrontendHostInstance.openNodeFrontend(), false); - this._button = new UI.Toolbar.ToolbarItem(element); - this._button.setTitle(i18nString(UIStrings.openDedicatedTools)); + this.button = new UI.Toolbar.ToolbarItem(element); + this.button.setTitle(i18nString(UIStrings.openDedicatedTools)); SDK.TargetManager.TargetManager.instance().addEventListener( - SDK.TargetManager.Events.AvailableTargetsChanged, event => this._update(event.data)); - this._button.setVisible(false); - this._update([]); + SDK.TargetManager.Events.AvailableTargetsChanged, event => this.update(event.data)); + this.button.setVisible(false); + this.update([]); } static instance(opts: { forceNew: boolean|null, @@ -172,16 +170,16 @@ return nodeIndicatorInstance; } - _update(targetInfos: Protocol.Target.TargetInfo[]): void { + private update(targetInfos: Protocol.Target.TargetInfo[]): void { const hasNode = Boolean(targetInfos.find(target => target.type === 'node' && !target.attached)); - this._element.classList.toggle('inactive', !hasNode); + this.element.classList.toggle('inactive', !hasNode); if (hasNode) { - this._button.setVisible(true); + this.button.setVisible(true); } } item(): UI.Toolbar.ToolbarItem|null { - return this._button; + return this.button; } } @@ -205,44 +203,44 @@ } export class BackendSettingsSync implements SDK.TargetManager.Observer { - _autoAttachSetting: Common.Settings.Setting<boolean>; - _adBlockEnabledSetting: Common.Settings.Setting<boolean>; - _emulatePageFocusSetting: Common.Settings.Setting<boolean>; + private readonly autoAttachSetting: Common.Settings.Setting<boolean>; + private readonly adBlockEnabledSetting: Common.Settings.Setting<boolean>; + private readonly emulatePageFocusSetting: Common.Settings.Setting<boolean>; constructor() { - this._autoAttachSetting = Common.Settings.Settings.instance().moduleSetting('autoAttachToCreatedPages'); - this._autoAttachSetting.addChangeListener(this._updateAutoAttach, this); - this._updateAutoAttach(); + this.autoAttachSetting = Common.Settings.Settings.instance().moduleSetting('autoAttachToCreatedPages'); + this.autoAttachSetting.addChangeListener(this.updateAutoAttach, this); + this.updateAutoAttach(); - this._adBlockEnabledSetting = Common.Settings.Settings.instance().moduleSetting('network.adBlockingEnabled'); - this._adBlockEnabledSetting.addChangeListener(this._update, this); + this.adBlockEnabledSetting = Common.Settings.Settings.instance().moduleSetting('network.adBlockingEnabled'); + this.adBlockEnabledSetting.addChangeListener(this.update, this); - this._emulatePageFocusSetting = Common.Settings.Settings.instance().moduleSetting('emulatePageFocus'); - this._emulatePageFocusSetting.addChangeListener(this._update, this); + this.emulatePageFocusSetting = Common.Settings.Settings.instance().moduleSetting('emulatePageFocus'); + this.emulatePageFocusSetting.addChangeListener(this.update, this); SDK.TargetManager.TargetManager.instance().observeTargets(this); } - _updateTarget(target: SDK.Target.Target): void { + private updateTarget(target: SDK.Target.Target): void { if (target.type() !== SDK.Target.Type.Frame || target.parentTarget()) { return; } - target.pageAgent().invoke_setAdBlockingEnabled({enabled: this._adBlockEnabledSetting.get()}); - target.emulationAgent().invoke_setFocusEmulationEnabled({enabled: this._emulatePageFocusSetting.get()}); + target.pageAgent().invoke_setAdBlockingEnabled({enabled: this.adBlockEnabledSetting.get()}); + target.emulationAgent().invoke_setFocusEmulationEnabled({enabled: this.emulatePageFocusSetting.get()}); } - _updateAutoAttach(): void { - Host.InspectorFrontendHost.InspectorFrontendHostInstance.setOpenNewWindowForPopups(this._autoAttachSetting.get()); + private updateAutoAttach(): void { + Host.InspectorFrontendHost.InspectorFrontendHostInstance.setOpenNewWindowForPopups(this.autoAttachSetting.get()); } - _update(): void { + private update(): void { for (const target of SDK.TargetManager.TargetManager.instance().targets()) { - this._updateTarget(target); + this.updateTarget(target); } } targetAdded(target: SDK.Target.Target): void { - this._updateTarget(target); + this.updateTarget(target); } targetRemoved(_target: SDK.Target.Target): void {
diff --git a/front_end/entrypoints/inspector_main/RenderingOptions.ts b/front_end/entrypoints/inspector_main/RenderingOptions.ts index 66564cc..6de93db 100644 --- a/front_end/entrypoints/inspector_main/RenderingOptions.ts +++ b/front_end/entrypoints/inspector_main/RenderingOptions.ts
@@ -28,8 +28,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as UI from '../../ui/legacy/legacy.js'; @@ -212,68 +210,68 @@ super(true); this.registerRequiredCSS('entrypoints/inspector_main/renderingOptions.css'); - this._appendCheckbox( + this.appendCheckbox( i18nString(UIStrings.paintFlashing), i18nString(UIStrings.highlightsAreasOfThePageGreen), Common.Settings.Settings.instance().moduleSetting('showPaintRects')); - this._appendCheckbox( + this.appendCheckbox( i18nString(UIStrings.layoutShiftRegions), i18nString(UIStrings.highlightsAreasOfThePageBlueThat), Common.Settings.Settings.instance().moduleSetting('showLayoutShiftRegions')); - this._appendCheckbox( + this.appendCheckbox( i18nString(UIStrings.layerBorders), i18nString(UIStrings.showsLayerBordersOrangeoliveAnd), Common.Settings.Settings.instance().moduleSetting('showDebugBorders')); - this._appendCheckbox( + this.appendCheckbox( i18nString(UIStrings.frameRenderingStats), i18nString(UIStrings.plotsFrameThroughputDropped), Common.Settings.Settings.instance().moduleSetting('showFPSCounter')); - this._appendCheckbox( + this.appendCheckbox( i18nString(UIStrings.scrollingPerformanceIssues), i18nString(UIStrings.highlightsElementsTealThatCan), Common.Settings.Settings.instance().moduleSetting('showScrollBottleneckRects')); - this._appendCheckbox( + this.appendCheckbox( i18nString(UIStrings.highlightAdFrames), i18nString(UIStrings.highlightsFramesRedDetectedToBe), Common.Settings.Settings.instance().moduleSetting('showAdHighlights')); - this._appendCheckbox( + this.appendCheckbox( i18nString(UIStrings.hittestBorders), i18nString(UIStrings.showsBordersAroundHittestRegions), Common.Settings.Settings.instance().moduleSetting('showHitTestBorders')); - this._appendCheckbox( + this.appendCheckbox( i18nString(UIStrings.coreWebVitals), i18nString(UIStrings.showsAnOverlayWithCoreWebVitals), Common.Settings.Settings.instance().moduleSetting('showWebVitals')); - this._appendCheckbox( + this.appendCheckbox( i18nString(UIStrings.disableLocalFonts), i18nString(UIStrings.disablesLocalSourcesInFontface), Common.Settings.Settings.instance().moduleSetting('localFontsDisabled')); - this._appendCheckbox( + this.appendCheckbox( i18nString(UIStrings.emulateAFocusedPage), i18nString(UIStrings.emulatesAFocusedPage), Common.Settings.Settings.instance().moduleSetting('emulatePageFocus')); this.contentElement.createChild('div').classList.add('panel-section-separator'); - this._appendSelect( + this.appendSelect( i18nString(UIStrings.forcesMediaTypeForTestingPrint), Common.Settings.Settings.instance().moduleSetting('emulatedCSSMedia')); - this._appendSelect( + this.appendSelect( i18nString(UIStrings.forcesCssPreferscolorschemeMedia), Common.Settings.Settings.instance().moduleSetting('emulatedCSSMediaFeaturePrefersColorScheme')); - this._appendSelect( + this.appendSelect( i18nString(UIStrings.forcesCssPrefersreducedmotion), Common.Settings.Settings.instance().moduleSetting('emulatedCSSMediaFeaturePrefersReducedMotion')); if (supportsPrefersReducedData()) { - this._appendSelect( + this.appendSelect( i18nString(UIStrings.forcesCssPrefersreduceddataMedia), Common.Settings.Settings.instance().moduleSetting('emulatedCSSMediaFeaturePrefersReducedData')); } - this._appendSelect( + this.appendSelect( i18nString(UIStrings.forcesCssColorgamutMediaFeature), Common.Settings.Settings.instance().moduleSetting('emulatedCSSMediaFeatureColorGamut')); this.contentElement.createChild('div').classList.add('panel-section-separator'); - this._appendSelect( + this.appendSelect( i18nString(UIStrings.forcesVisionDeficiencyEmulation), Common.Settings.Settings.instance().moduleSetting('emulatedVisionDeficiency')); this.contentElement.createChild('div').classList.add('panel-section-separator'); - this._appendCheckbox( + this.appendCheckbox( i18nString(UIStrings.disableAvifImageFormat), i18nString(UIStrings.requiresAPageReloadToApplyAnd), Common.Settings.Settings.instance().moduleSetting('avifFormatDisabled')); - const webpCheckbox = this._appendCheckbox( + const webpCheckbox = this.appendCheckbox( i18nString(UIStrings.disableWebpImageFormat), i18nString(UIStrings.requiresAPageReloadToApplyAnd), Common.Settings.Settings.instance().moduleSetting('webpFormatDisabled')); @@ -283,7 +281,7 @@ if (!hasSupport) { return; } - webpCheckbox.before(this._createCheckbox( + webpCheckbox.before(this.createCheckbox( i18nString(UIStrings.disableJpegXlImageFormat), i18nString(UIStrings.requiresAPageReloadToApplyAnd), Common.Settings.Settings.instance().moduleSetting('jpegXlFormatDisabled'))); }); @@ -300,23 +298,23 @@ return renderingOptionsViewInstance; } - _createCheckbox(label: string, subtitle: string, setting: Common.Settings.Setting<boolean>): + private createCheckbox(label: string, subtitle: string, setting: Common.Settings.Setting<boolean>): UI.UIUtils.CheckboxLabel { const checkboxLabel = UI.UIUtils.CheckboxLabel.create(label, false, subtitle); UI.SettingsUI.bindCheckbox(checkboxLabel.checkboxElement, setting); return checkboxLabel; } - _appendCheckbox(label: string, subtitle: string, setting: Common.Settings.Setting<boolean>): + private appendCheckbox(label: string, subtitle: string, setting: Common.Settings.Setting<boolean>): UI.UIUtils.CheckboxLabel { - const checkbox = this._createCheckbox(label, subtitle, setting); + const checkbox = this.createCheckbox(label, subtitle, setting); this.contentElement.appendChild(checkbox); return checkbox; } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _appendSelect(label: string, setting: Common.Settings.Setting<any>): void { + private appendSelect(label: string, setting: Common.Settings.Setting<any>): void { const control = UI.SettingsUI.createControlForSetting(setting, label); if (control) { this.contentElement.appendChild(control);
diff --git a/front_end/entrypoints/js_app/JsMain.ts b/front_end/entrypoints/js_app/JsMain.ts index c69d534..982492a 100644 --- a/front_end/entrypoints/js_app/JsMain.ts +++ b/front_end/entrypoints/js_app/JsMain.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as Host from '../../core/host/host.js'; import * as i18n from '../../core/i18n/i18n.js';
diff --git a/front_end/entrypoints/main/MainImpl.ts b/front_end/entrypoints/main/MainImpl.ts index ee637f7..ca936cf 100644 --- a/front_end/entrypoints/main/MainImpl.ts +++ b/front_end/entrypoints/main/MainImpl.ts
@@ -32,8 +32,6 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as Host from '../../core/host/host.js'; import * as i18n from '../../core/i18n/i18n.js'; @@ -115,12 +113,12 @@ const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class MainImpl { - _lateInitDonePromise!: Promise<void>; + private lateInitDonePromise!: Promise<void>; constructor() { - MainImpl._instanceForTest = this; + MainImpl.instanceForTest = this; Platform.runOnWindowLoad(() => { - this._loaded(); + this.loaded(); }); } @@ -138,7 +136,7 @@ console.timeEnd(label); } - async _loaded(): Promise<void> { + private async loaded(): Promise<void> { console.timeStamp('Main._loaded'); await Root.Runtime.appStarted; Root.Runtime.Runtime.setPlatform(Host.Platform.platform()); @@ -147,9 +145,9 @@ }); console.timeStamp('Main._gotPreferences'); - this._createSettings(prefs); + this.createSettings(prefs); await this.requestAndRegisterLocaleData(); - this._createAppUI(); + this.createAppUI(); } async requestAndRegisterLocaleData(): Promise<void> { @@ -185,10 +183,10 @@ } } - _createSettings(prefs: { + private createSettings(prefs: { [x: string]: string, }): void { - this._initializeExperiments(); + this.initializeExperiments(); let storagePrefix = ''; if (Host.Platform.isCustomDevtoolsFrontend()) { storagePrefix = '__custom__'; @@ -219,7 +217,7 @@ } } - _initializeExperiments(): void { + private initializeExperiments(): void { Root.Runtime.experiments.register('applyCustomStylesheet', 'Allow extensions to load custom stylesheets'); Root.Runtime.experiments.register('captureNodeCreationStacks', 'Capture node creation stacks'); Root.Runtime.experiments.register('sourcesPrettyPrint', 'Automatically pretty print in the Sources Panel'); @@ -347,7 +345,7 @@ Host.userMetrics.experimentEnabledAtLaunch(experiment.name); } } - async _createAppUI(): Promise<void> { + private async createAppUI(): Promise<void> { MainImpl.time('Main._createAppUI'); // @ts-ignore layout test global @@ -370,7 +368,7 @@ } UI.UIUtils.installComponentRootStyles((document.body as Element)); - this._addMainEventListeners(document); + this.addMainEventListeners(document); const canDock = Boolean(Root.Runtime.Runtime.queryParam('can_dock')); // @ts-ignore layout test global @@ -402,7 +400,7 @@ // @ts-ignore layout test global self.SDK.domDebuggerManager = SDK.DOMDebuggerModel.DOMDebuggerManager.instance({forceNew: true}); SDK.TargetManager.TargetManager.instance().addEventListener( - SDK.TargetManager.Events.SuspendStateChanged, this._onSuspendStateChanged.bind(this)); + SDK.TargetManager.Events.SuspendStateChanged, this.onSuspendStateChanged.bind(this)); // @ts-ignore layout test global self.Workspace.fileManager = Workspace.FileManager.FileManager.instance({forceNew: true}); @@ -474,7 +472,7 @@ // @ts-ignore layout test global self.UI.shortcutRegistry = UI.ShortcutRegistry.ShortcutRegistry.instance({forceNew: true, actionRegistry: actionRegistryInstance}); - this._registerMessageSinkListener(); + this.registerMessageSinkListener(); MainImpl.timeEnd('Main._createAppUI'); @@ -482,10 +480,10 @@ if (!appProvider) { throw new Error('Unable to boot DevTools, as the appprovider is missing'); } - await this._showAppUI(await appProvider.loadAppProvider()); + await this.showAppUI(await appProvider.loadAppProvider()); } - async _showAppUI(appProvider: Object): Promise<void> { + private async showAppUI(appProvider: Object): Promise<void> { MainImpl.time('Main._showAppUI'); const app = (appProvider as Common.AppProvider.AppProvider).createApp(); // It is important to kick controller lifetime after apps are instantiated. @@ -501,7 +499,7 @@ }, this); } Host.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener( - Host.InspectorFrontendHostAPI.Events.RevealSourceLine, this._revealSourceLine, this); + Host.InspectorFrontendHostAPI.Events.RevealSourceLine, this.revealSourceLine, this); await UI.InspectorView.InspectorView.instance().createToolbars(); Host.InspectorFrontendHost.InspectorFrontendHostInstance.loadCompleted(); @@ -512,11 +510,11 @@ } // Allow UI cycles to repaint prior to creating connection. - setTimeout(this._initializeTarget.bind(this), 0); + setTimeout(this.initializeTarget.bind(this), 0); MainImpl.timeEnd('Main._showAppUI'); } - async _initializeTarget(): Promise<void> { + private async initializeTarget(): Promise<void> { MainImpl.time('Main._initializeTarget'); // We rely on having the early initialization runnables registered in Common when an app loads its @@ -528,11 +526,11 @@ // Used for browser tests. Host.InspectorFrontendHost.InspectorFrontendHostInstance.readyForTest(); // Asynchronously run the extensions. - setTimeout(this._lateInitialization.bind(this), 100); + setTimeout(this.lateInitialization.bind(this), 100); MainImpl.timeEnd('Main._initializeTarget'); } - _lateInitialization(): void { + private lateInitialization(): void { MainImpl.time('Main._lateInitialization'); Extensions.ExtensionServer.ExtensionServer.instance().initializeExtensions(); const promises: Promise<void>[] = @@ -555,15 +553,15 @@ Common.Settings.Settings.instance().moduleSetting(setting).addChangeListener(changeListener); } } - this._lateInitDonePromise = Promise.all(promises).then(() => undefined); + this.lateInitDonePromise = Promise.all(promises).then(() => undefined); MainImpl.timeEnd('Main._lateInitialization'); } lateInitDonePromiseForTest(): Promise<void>|null { - return this._lateInitDonePromise; + return this.lateInitDonePromise; } - _registerMessageSinkListener(): void { + private registerMessageSinkListener(): void { Common.Console.Console.instance().addEventListener(Common.Console.Events.MessageAdded, messageAdded); function messageAdded(event: Common.EventTarget.EventTargetEvent): void { @@ -574,7 +572,7 @@ } } - _revealSourceLine(event: Common.EventTarget.EventTargetEvent): void { + private revealSourceLine(event: Common.EventTarget.EventTargetEvent): void { const url = (event.data['url'] as string); const lineNumber = (event.data['lineNumber'] as number); const columnNumber = (event.data['columnNumber'] as number); @@ -598,13 +596,13 @@ Workspace.Workspace.Events.UISourceCodeAdded, listener); } - _postDocumentKeyDown(event: Event): void { + private postDocumentKeyDown(event: Event): void { if (!event.handled) { UI.ShortcutRegistry.ShortcutRegistry.instance().handleShortcut((event as KeyboardEvent)); } } - _redispatchClipboardEvent(event: Event): void { + private redispatchClipboardEvent(event: Event): void { const eventCopy = new CustomEvent('clipboard-' + event.type, {bubbles: true}); // @ts-ignore Used in ElementsTreeOutline eventCopy['original'] = event; @@ -618,27 +616,27 @@ } } - _contextMenuEventFired(event: Event): void { + private contextMenuEventFired(event: Event): void { if (event.handled || (event.target as HTMLElement).classList.contains('popup-glasspane')) { event.preventDefault(); } } - _addMainEventListeners(document: Document): void { - document.addEventListener('keydown', this._postDocumentKeyDown.bind(this), false); - document.addEventListener('beforecopy', this._redispatchClipboardEvent.bind(this), true); - document.addEventListener('copy', this._redispatchClipboardEvent.bind(this), false); - document.addEventListener('cut', this._redispatchClipboardEvent.bind(this), false); - document.addEventListener('paste', this._redispatchClipboardEvent.bind(this), false); - document.addEventListener('contextmenu', this._contextMenuEventFired.bind(this), true); + private addMainEventListeners(document: Document): void { + document.addEventListener('keydown', this.postDocumentKeyDown.bind(this), false); + document.addEventListener('beforecopy', this.redispatchClipboardEvent.bind(this), true); + document.addEventListener('copy', this.redispatchClipboardEvent.bind(this), false); + document.addEventListener('cut', this.redispatchClipboardEvent.bind(this), false); + document.addEventListener('paste', this.redispatchClipboardEvent.bind(this), false); + document.addEventListener('contextmenu', this.contextMenuEventFired.bind(this), true); } - _onSuspendStateChanged(): void { + private onSuspendStateChanged(): void { const suspended = SDK.TargetManager.TargetManager.instance().allTargetsSuspended(); UI.InspectorView.InspectorView.instance().onSuspendStateChanged(suspended); } - static _instanceForTest: MainImpl|null = null; + static instanceForTest: MainImpl|null = null; } // @ts-ignore Exported for Tests.js @@ -721,11 +719,11 @@ let mainMenuItemInstance: MainMenuItem; export class MainMenuItem implements UI.Toolbar.Provider { - _item: UI.Toolbar.ToolbarMenuButton; + private readonly itemInternal: UI.Toolbar.ToolbarMenuButton; constructor() { - this._item = new UI.Toolbar.ToolbarMenuButton(this._handleContextMenu.bind(this), true); - this._item.element.classList.add('main-menu'); - this._item.setTitle(i18nString(UIStrings.customizeAndControlDevtools)); + this.itemInternal = new UI.Toolbar.ToolbarMenuButton(this.handleContextMenu.bind(this), true); + this.itemInternal.element.classList.add('main-menu'); + this.itemInternal.setTitle(i18nString(UIStrings.customizeAndControlDevtools)); } static instance(opts: { @@ -740,10 +738,10 @@ } item(): UI.Toolbar.ToolbarItem|null { - return this._item; + return this.itemInternal; } - _handleContextMenu(contextMenu: UI.ContextMenu.ContextMenu): void { + private handleContextMenu(contextMenu: UI.ContextMenu.ContextMenu): void { if (UI.DockController.DockController.instance().canDock()) { const dockItemElement = document.createElement('div'); dockItemElement.classList.add('flex-centered'); @@ -806,7 +804,7 @@ contextMenu.headerSection().appendCustomItem(dockItemElement); } - const button = (this._item.element as HTMLButtonElement); + const button = (this.itemInternal.element as HTMLButtonElement); function setDockSide(side: string): void { UI.DockController.DockController.instance().once(UI.DockController.Events.AfterDockSideChanged).then(() => { @@ -869,10 +867,10 @@ let settingsButtonProviderInstance: SettingsButtonProvider; export class SettingsButtonProvider implements UI.Toolbar.Provider { - _settingsButton: UI.Toolbar.ToolbarButton; + private readonly settingsButton: UI.Toolbar.ToolbarButton; private constructor() { const settingsActionId = 'settings.show'; - this._settingsButton = + this.settingsButton = UI.Toolbar.Toolbar.createActionButtonForId(settingsActionId, {showLabel: false, userActionCode: undefined}); } @@ -888,19 +886,19 @@ } item(): UI.Toolbar.ToolbarItem|null { - return this._settingsButton; + return this.settingsButton; } } export class PauseListener { constructor() { SDK.TargetManager.TargetManager.instance().addModelListener( - SDK.DebuggerModel.DebuggerModel, SDK.DebuggerModel.Events.DebuggerPaused, this._debuggerPaused, this); + SDK.DebuggerModel.DebuggerModel, SDK.DebuggerModel.Events.DebuggerPaused, this.debuggerPaused, this); } - _debuggerPaused(event: Common.EventTarget.EventTargetEvent<SDK.DebuggerModel.DebuggerModel>): void { + private debuggerPaused(event: Common.EventTarget.EventTargetEvent<SDK.DebuggerModel.DebuggerModel>): void { SDK.TargetManager.TargetManager.instance().removeModelListener( - SDK.DebuggerModel.DebuggerModel, SDK.DebuggerModel.Events.DebuggerPaused, this._debuggerPaused, this); + SDK.DebuggerModel.DebuggerModel, SDK.DebuggerModel.Events.DebuggerPaused, this.debuggerPaused, this); const debuggerModel = event.data; const debuggerPausedDetails = debuggerModel.debuggerPausedDetails(); UI.Context.Context.instance().setFlavor(SDK.Target.Target, debuggerModel.target());
diff --git a/front_end/entrypoints/node_main/NodeConnectionsPanel.ts b/front_end/entrypoints/node_main/NodeConnectionsPanel.ts index 6564985..297fcaa 100644 --- a/front_end/entrypoints/node_main/NodeConnectionsPanel.ts +++ b/front_end/entrypoints/node_main/NodeConnectionsPanel.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import type * as Common from '../../core/common/common.js'; import * as Host from '../../core/host/host.js'; import * as i18n from '../../core/i18n/i18n.js'; @@ -39,8 +37,8 @@ let nodeConnectionsPanelInstance: NodeConnectionsPanel; export class NodeConnectionsPanel extends UI.Panel.Panel { - _config!: Adb.Config; - _networkDiscoveryView: NodeConnectionsView; + private config!: Adb.Config; + private readonly networkDiscoveryView: NodeConnectionsView; private constructor() { super('node-connection'); this.registerRequiredCSS('entrypoints/node_main/nodeConnectionsPanel.css'); @@ -52,7 +50,7 @@ image.src = 'https://nodejs.org/static/images/logos/nodejs-new-pantone-black.svg'; Host.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener( - Host.InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged, this._devicesDiscoveryConfigChanged, this); + Host.InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged, this.devicesDiscoveryConfigChanged, this); this.contentElement.tabIndex = 0; this.setDefaultFocusedElement(this.contentElement); @@ -61,11 +59,11 @@ Host.InspectorFrontendHost.InspectorFrontendHostInstance.setDevicesUpdatesEnabled(false); Host.InspectorFrontendHost.InspectorFrontendHostInstance.setDevicesUpdatesEnabled(true); - this._networkDiscoveryView = new NodeConnectionsView(config => { - this._config.networkDiscoveryConfig = config; - Host.InspectorFrontendHost.InspectorFrontendHostInstance.setDevicesDiscoveryConfig(this._config); + this.networkDiscoveryView = new NodeConnectionsView(config => { + this.config.networkDiscoveryConfig = config; + Host.InspectorFrontendHost.InspectorFrontendHostInstance.setDevicesDiscoveryConfig(this.config); }); - this._networkDiscoveryView.show(container); + this.networkDiscoveryView.show(container); } static instance(opts: { @@ -79,22 +77,22 @@ return nodeConnectionsPanelInstance; } - _devicesDiscoveryConfigChanged(event: Common.EventTarget.EventTargetEvent): void { - this._config = (event.data as Adb.Config); - this._networkDiscoveryView.discoveryConfigChanged(this._config.networkDiscoveryConfig); + private devicesDiscoveryConfigChanged(event: Common.EventTarget.EventTargetEvent): void { + this.config = (event.data as Adb.Config); + this.networkDiscoveryView.discoveryConfigChanged(this.config.networkDiscoveryConfig); } } export class NodeConnectionsView extends UI.Widget.VBox implements UI.ListWidget.Delegate<Adb.PortForwardingRule> { - _callback: (arg0: Adb.NetworkDiscoveryConfig) => void; - _list: UI.ListWidget.ListWidget<Adb.PortForwardingRule>; - _editor: UI.ListWidget.Editor<Adb.PortForwardingRule>|null; - _networkDiscoveryConfig: { + private readonly callback: (arg0: Adb.NetworkDiscoveryConfig) => void; + private readonly list: UI.ListWidget.ListWidget<Adb.PortForwardingRule>; + private editor: UI.ListWidget.Editor<Adb.PortForwardingRule>|null; + private networkDiscoveryConfig: { address: string, }[]; constructor(callback: (arg0: Adb.NetworkDiscoveryConfig) => void) { super(); - this._callback = callback; + this.callback = callback; this.element.classList.add('network-discovery-view'); const networkDiscoveryFooter = this.element.createChild('div', 'network-discovery-footer'); @@ -103,42 +101,42 @@ networkDiscoveryFooter.appendChild( i18n.i18n.getFormatLocalizedString(str_, UIStrings.specifyNetworkEndpointAnd, {PH1: documentationLink})); - this._list = new UI.ListWidget.ListWidget(this); - this._list.registerRequiredCSS('entrypoints/node_main/nodeConnectionsPanel.css'); - this._list.element.classList.add('network-discovery-list'); + this.list = new UI.ListWidget.ListWidget(this); + this.list.registerRequiredCSS('entrypoints/node_main/nodeConnectionsPanel.css'); + this.list.element.classList.add('network-discovery-list'); const placeholder = document.createElement('div'); placeholder.classList.add('network-discovery-list-empty'); placeholder.textContent = i18nString(UIStrings.noConnectionsSpecified); - this._list.setEmptyPlaceholder(placeholder); - this._list.show(this.element); - this._editor = null; + this.list.setEmptyPlaceholder(placeholder); + this.list.show(this.element); + this.editor = null; const addButton = UI.UIUtils.createTextButton( - i18nString(UIStrings.addConnection), this._addNetworkTargetButtonClicked.bind(this), - 'add-network-target-button', true /* primary */); + i18nString(UIStrings.addConnection), this.addNetworkTargetButtonClicked.bind(this), 'add-network-target-button', + true /* primary */); this.element.appendChild(addButton); - this._networkDiscoveryConfig = []; + this.networkDiscoveryConfig = []; this.element.classList.add('node-frontend'); } - _update(): void { - const config = this._networkDiscoveryConfig.map(item => item.address); - this._callback.call(null, config); + private update(): void { + const config = this.networkDiscoveryConfig.map(item => item.address); + this.callback.call(null, config); } - _addNetworkTargetButtonClicked(): void { - this._list.addNewItem(this._networkDiscoveryConfig.length, {address: '', port: ''}); + private addNetworkTargetButtonClicked(): void { + this.list.addNewItem(this.networkDiscoveryConfig.length, {address: '', port: ''}); } discoveryConfigChanged(networkDiscoveryConfig: Adb.NetworkDiscoveryConfig): void { - this._networkDiscoveryConfig = []; - this._list.clear(); + this.networkDiscoveryConfig = []; + this.list.clear(); for (const address of networkDiscoveryConfig) { const item = {address: address, port: ''}; - this._networkDiscoveryConfig.push(item); - this._list.appendItem(item, true); + this.networkDiscoveryConfig.push(item); + this.list.appendItem(item, true); } } @@ -150,32 +148,32 @@ } removeItemRequested(rule: Adb.PortForwardingRule, index: number): void { - this._networkDiscoveryConfig.splice(index, 1); - this._list.removeItem(index); - this._update(); + this.networkDiscoveryConfig.splice(index, 1); + this.list.removeItem(index); + this.update(); } commitEdit(rule: Adb.PortForwardingRule, editor: UI.ListWidget.Editor<Adb.PortForwardingRule>, isNew: boolean): void { rule.address = editor.control('address').value.trim(); if (isNew) { - this._networkDiscoveryConfig.push(rule); + this.networkDiscoveryConfig.push(rule); } - this._update(); + this.update(); } beginEdit(rule: Adb.PortForwardingRule): UI.ListWidget.Editor<Adb.PortForwardingRule> { - const editor = this._createEditor(); + const editor = this.createEditor(); editor.control('address').value = rule.address; return editor; } - _createEditor(): UI.ListWidget.Editor<Adb.PortForwardingRule> { - if (this._editor) { - return this._editor; + private createEditor(): UI.ListWidget.Editor<Adb.PortForwardingRule> { + if (this.editor) { + return this.editor; } const editor = new UI.ListWidget.Editor<Adb.PortForwardingRule>(); - this._editor = editor; + this.editor = editor; const content = editor.contentElement(); const fields = content.createChild('div', 'network-discovery-edit-row'); const input =
diff --git a/front_end/entrypoints/node_main/NodeMain.ts b/front_end/entrypoints/node_main/NodeMain.ts index acd888a..6d638e7 100644 --- a/front_end/entrypoints/node_main/NodeMain.ts +++ b/front_end/entrypoints/node_main/NodeMain.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as Host from '../../core/host/host.js'; import * as i18n from '../../core/i18n/i18n.js'; @@ -50,29 +48,29 @@ Common.Runnable.registerEarlyInitializationRunnable(NodeMainImpl.instance); export class NodeChildTargetManager extends SDK.SDKModel.SDKModel implements ProtocolProxyApi.TargetDispatcher { - _targetManager: SDK.TargetManager.TargetManager; - _parentTarget: SDK.Target.Target; - _targetAgent: ProtocolProxyApi.TargetApi; - _childTargets: Map<string, SDK.Target.Target>; - _childConnections: Map<string, NodeConnection>; + private readonly targetManager: SDK.TargetManager.TargetManager; + private readonly parentTarget: SDK.Target.Target; + private readonly targetAgent: ProtocolProxyApi.TargetApi; + private readonly childTargets: Map<string, SDK.Target.Target>; + private readonly childConnections: Map<string, NodeConnection>; constructor(parentTarget: SDK.Target.Target) { super(parentTarget); - this._targetManager = parentTarget.targetManager(); - this._parentTarget = parentTarget; - this._targetAgent = parentTarget.targetAgent(); - this._childTargets = new Map(); - this._childConnections = new Map(); + this.targetManager = parentTarget.targetManager(); + this.parentTarget = parentTarget; + this.targetAgent = parentTarget.targetAgent(); + this.childTargets = new Map(); + this.childConnections = new Map(); parentTarget.registerTargetDispatcher(this); - this._targetAgent.invoke_setDiscoverTargets({discover: true}); + this.targetAgent.invoke_setDiscoverTargets({discover: true}); Host.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener( - Host.InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged, this._devicesDiscoveryConfigChanged, this); + Host.InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged, this.devicesDiscoveryConfigChanged, this); Host.InspectorFrontendHost.InspectorFrontendHostInstance.setDevicesUpdatesEnabled(false); Host.InspectorFrontendHost.InspectorFrontendHostInstance.setDevicesUpdatesEnabled(true); } - _devicesDiscoveryConfigChanged(event: Common.EventTarget.EventTargetEvent): void { + private devicesDiscoveryConfigChanged(event: Common.EventTarget.EventTargetEvent): void { const config = (event.data as Adb.Config); const locations = []; for (const address of config.networkDiscoveryConfig) { @@ -82,21 +80,21 @@ locations.push({host: parts[0], port: port}); } } - this._targetAgent.invoke_setRemoteLocations({locations}); + this.targetAgent.invoke_setRemoteLocations({locations}); } dispose(): void { Host.InspectorFrontendHost.InspectorFrontendHostInstance.events.removeEventListener( - Host.InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged, this._devicesDiscoveryConfigChanged, this); + Host.InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged, this.devicesDiscoveryConfigChanged, this); - for (const sessionId of this._childTargets.keys()) { + for (const sessionId of this.childTargets.keys()) { this.detachedFromTarget({sessionId}); } } targetCreated({targetInfo}: Protocol.Target.TargetCreatedEvent): void { if (targetInfo.type === 'node' && !targetInfo.attached) { - this._targetAgent.invoke_attachToTarget({targetId: targetInfo.targetId, flatten: false}); + this.targetAgent.invoke_attachToTarget({targetId: targetInfo.targetId, flatten: false}); } } @@ -108,25 +106,25 @@ attachedToTarget({sessionId, targetInfo}: Protocol.Target.AttachedToTargetEvent): void { const name = i18nString(UIStrings.nodejsS, {PH1: targetInfo.url}); - const connection = new NodeConnection(this._targetAgent, sessionId); - this._childConnections.set(sessionId, connection); - const target = this._targetManager.createTarget( - targetInfo.targetId, name, SDK.Target.Type.Node, this._parentTarget, undefined, undefined, connection); - this._childTargets.set(sessionId, target); + const connection = new NodeConnection(this.targetAgent, sessionId); + this.childConnections.set(sessionId, connection); + const target = this.targetManager.createTarget( + targetInfo.targetId, name, SDK.Target.Type.Node, this.parentTarget, undefined, undefined, connection); + this.childTargets.set(sessionId, target); target.runtimeAgent().invoke_runIfWaitingForDebugger(); } detachedFromTarget({sessionId}: Protocol.Target.DetachedFromTargetEvent): void { - const childTarget = this._childTargets.get(sessionId); + const childTarget = this.childTargets.get(sessionId); if (childTarget) { childTarget.dispose('target terminated'); } - this._childTargets.delete(sessionId); - this._childConnections.delete(sessionId); + this.childTargets.delete(sessionId); + this.childConnections.delete(sessionId); } receivedMessageFromTarget({sessionId, message}: Protocol.Target.ReceivedMessageFromTargetEvent): void { - const connection = this._childConnections.get(sessionId); + const connection = this.childConnections.get(sessionId); const onMessage = connection ? connection.onMessage : null; if (onMessage) { onMessage.call(null, message); @@ -138,15 +136,15 @@ } export class NodeConnection implements ProtocolClient.InspectorBackend.Connection { - _targetAgent: ProtocolProxyApi.TargetApi; - _sessionId: string; + private readonly targetAgent: ProtocolProxyApi.TargetApi; + private readonly sessionId: string; onMessage: ((arg0: (Object|string)) => void)|null; - _onDisconnect: ((arg0: string) => void)|null; + private onDisconnect: ((arg0: string) => void)|null; constructor(targetAgent: ProtocolProxyApi.TargetApi, sessionId: string) { - this._targetAgent = targetAgent; - this._sessionId = sessionId; + this.targetAgent = targetAgent; + this.sessionId = sessionId; this.onMessage = null; - this._onDisconnect = null; + this.onDisconnect = null; } setOnMessage(onMessage: (arg0: (Object|string)) => void): void { @@ -154,20 +152,20 @@ } setOnDisconnect(onDisconnect: (arg0: string) => void): void { - this._onDisconnect = onDisconnect; + this.onDisconnect = onDisconnect; } sendRawMessage(message: string): void { - this._targetAgent.invoke_sendMessageToTarget({message, sessionId: this._sessionId}); + this.targetAgent.invoke_sendMessageToTarget({message, sessionId: this.sessionId}); } async disconnect(): Promise<void> { - if (this._onDisconnect) { - this._onDisconnect.call(null, 'force disconnect'); + if (this.onDisconnect) { + this.onDisconnect.call(null, 'force disconnect'); } - this._onDisconnect = null; + this.onDisconnect = null; this.onMessage = null; - await this._targetAgent.invoke_detachFromTarget({sessionId: this._sessionId}); + await this.targetAgent.invoke_detachFromTarget({sessionId: this.sessionId}); } }
diff --git a/front_end/entrypoints/startup/RuntimeInstantiator.ts b/front_end/entrypoints/startup/RuntimeInstantiator.ts index c3ce6c1..b9c4730 100644 --- a/front_end/entrypoints/startup/RuntimeInstantiator.ts +++ b/front_end/entrypoints/startup/RuntimeInstantiator.ts
@@ -28,8 +28,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import '../../core/root/root-legacy.js'; import * as RootModule from '../../core/root/root.js';
diff --git a/front_end/entrypoints/wasmparser_worker/WasmParserWorker.ts b/front_end/entrypoints/wasmparser_worker/WasmParserWorker.ts index e777a60..af07ae4 100644 --- a/front_end/entrypoints/wasmparser_worker/WasmParserWorker.ts +++ b/front_end/entrypoints/wasmparser_worker/WasmParserWorker.ts
@@ -28,8 +28,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as WasmParser from '../../third_party/wasmparser/wasmparser.js';
diff --git a/front_end/entrypoints/worker_app/WorkerMain.ts b/front_end/entrypoints/worker_app/WorkerMain.ts index 1da0ca6..6893255 100644 --- a/front_end/entrypoints/worker_app/WorkerMain.ts +++ b/front_end/entrypoints/worker_app/WorkerMain.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as SDK from '../../core/sdk/sdk.js';
diff --git a/front_end/panels/profiler/HeapSnapshotGridNodes.ts b/front_end/panels/profiler/HeapSnapshotGridNodes.ts index f03f8ab..f352b20 100644 --- a/front_end/panels/profiler/HeapSnapshotGridNodes.ts +++ b/front_end/panels/profiler/HeapSnapshotGridNodes.ts
@@ -770,7 +770,7 @@ return new HeapSnapshotModel.HeapSnapshotModel.ComparatorConfig( 'retainedSize', sortAscending, '!edgeName', true); case 'distance': - return new HeapSnapshotModel.HeapSnapshotModel.ComparatorConfig('distance', sortAscending, '_name', true); + return new HeapSnapshotModel.HeapSnapshotModel.ComparatorConfig('distance', sortAscending, 'name', true); default: return new HeapSnapshotModel.HeapSnapshotModel.ComparatorConfig('!edgeName', true, 'retainedSize', false); }
diff --git a/scripts/check_experiments.js b/scripts/check_experiments.js index 1ee1cda..28c82ea 100644 --- a/scripts/check_experiments.js +++ b/scripts/check_experiments.js
@@ -124,7 +124,7 @@ } // Find function in MainImpl Class - const initializeExperimentNode = findFunctionInClass(mainImplClassNode, '_initializeExperiments'); + const initializeExperimentNode = findFunctionInClass(mainImplClassNode, 'initializeExperiments'); if (!initializeExperimentNode) { return null; }