From f515d586a8bbfeaf8443abaa0be26bf2ef9f278a Mon Sep 17 00:00:00 2001 From: Bharat Middha <5100938+bmiddha@users.noreply.github.com> Date: Wed, 19 Aug 2026 14:26:22 -0700 Subject: [PATCH 1/4] refactor: use ECMAScript #private fields Convert TS private class property declarations to native #private fields across api-extractor, api-documenter, and core libraries, stripping the conventional leading underscore. Excludes node-core-library: its bundled rollup .d.ts is consumed by ES5-target build-test fixtures, and #private syntax anywhere in that file breaks their typecheck (TS18028). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8ebd5bf2-c44b-42d5-be25-e7936d4b0a14 --- apps/api-documenter/src/cli/BaseAction.ts | 12 +- apps/api-documenter/src/cli/YamlAction.ts | 20 +-- .../documenters/ExperimentalYamlDocumenter.ts | 36 ++--- .../src/documenters/MarkdownDocumenter.ts | 104 +++++++------- .../src/documenters/OfficeYamlDocumenter.ts | 24 ++-- .../src/documenters/YamlDocumenter.ts | 52 +++---- .../src/markdown/CustomMarkdownEmitter.ts | 6 +- apps/api-documenter/src/nodes/DocTable.ts | 10 +- apps/api-documenter/src/nodes/DocTableRow.ts | 10 +- .../src/plugin/MarkdownDocumenterAccessor.ts | 6 +- .../src/utils/IndentedWriter.ts | 90 ++++++------ .../src/analyzer/AstDeclaration.ts | 28 ++-- .../src/analyzer/AstReferenceResolver.ts | 26 ++-- apps/api-extractor/src/analyzer/AstSymbol.ts | 14 +- .../src/analyzer/AstSymbolTable.ts | 108 +++++++-------- .../src/analyzer/ExportAnalyzer.ts | 84 ++++++------ .../src/analyzer/PackageMetadataManager.ts | 20 +-- apps/api-extractor/src/analyzer/Span.ts | 54 ++++---- .../api-extractor/src/api/ExtractorMessage.ts | 18 +-- .../src/cli/ApiExtractorCommandLine.ts | 8 +- apps/api-extractor/src/cli/RunAction.ts | 46 +++---- apps/api-extractor/src/collector/Collector.ts | 88 ++++++------ .../src/collector/CollectorEntity.ts | 60 ++++---- .../src/collector/MessageRouter.ts | 80 +++++------ .../src/collector/SourceMapper.ts | 18 +-- .../src/enhancers/DocCommentEnhancer.ts | 34 ++--- .../src/generators/ApiModelGenerator.ts | 102 +++++++------- .../DeclarationReferenceGenerator.ts | 32 ++--- .../src/generators/IndentedWriter.ts | 84 ++++++------ .../src/items/ApiDeclaredItem.ts | 26 ++-- .../src/items/ApiDocumentedItem.ts | 6 +- .../api-extractor-model/src/items/ApiItem.ts | 18 +-- .../api-extractor-model/src/mixins/Excerpt.ts | 26 ++-- .../api-extractor-model/src/model/ApiClass.ts | 6 +- .../src/model/ApiInterface.ts | 6 +- .../api-extractor-model/src/model/ApiModel.ts | 36 ++--- .../src/model/ApiPackage.ts | 12 +- .../src/model/ModelReferenceResolver.ts | 6 +- .../src/model/Parameter.ts | 10 +- .../src/model/SourceLocation.ts | 14 +- .../src/model/TypeParameter.ts | 10 +- .../credential-cache/src/CredentialCache.ts | 56 ++++---- .../src/CertificateStore.ts | 72 +++++----- .../src/ConfigurationFileBase.ts | 54 ++++---- libraries/lookup-by-path/src/LookupByPath.ts | 40 +++--- .../module-minifier/src/LocalMinifier.ts | 20 +-- .../src/MessagePortMinifier.ts | 10 +- .../module-minifier/src/WorkerPoolMinifier.ts | 85 ++++++------ .../npm-check-fork/src/NpmRegistryClient.ts | 20 +-- libraries/operation-graph/src/Operation.ts | 22 +-- .../src/OperationExecutionManager.ts | 22 +-- .../src/OperationGroupRecord.ts | 42 +++--- libraries/operation-graph/src/Stopwatch.ts | 42 +++--- libraries/operation-graph/src/WatchLoop.ts | 76 +++++------ libraries/operation-graph/src/WorkQueue.ts | 44 +++--- .../package-extractor/src/ArchiveManager.ts | 6 +- .../package-extractor/src/AssetHandler.ts | 82 +++++------ .../package-extractor/src/SymlinkAnalyzer.ts | 26 ++-- .../cli/CreateLinksCommandLineParser.ts | 12 +- .../cli/actions/CreateLinksAction.ts | 30 ++-- .../cli/actions/RemoveLinksAction.ts | 8 +- libraries/rig-package/src/RigConfig.ts | 28 ++-- .../stream-collator/src/CollatedTerminal.ts | 10 +- .../stream-collator/src/CollatedWriter.ts | 22 +-- .../stream-collator/src/StreamCollator.ts | 66 ++++----- libraries/terminal/src/CallbackWritable.ts | 6 +- .../terminal/src/DiscardStdoutTransform.ts | 14 +- .../src/PrefixProxyTerminalProvider.ts | 36 ++--- libraries/terminal/src/ProblemCollector.ts | 26 ++-- libraries/terminal/src/SplitterTransform.ts | 16 +-- libraries/terminal/src/StdioLineTransform.ts | 28 ++-- libraries/terminal/src/StdioSummarizer.ts | 58 ++++---- .../src/StringBufferTerminalProvider.ts | 40 +++--- libraries/terminal/src/Terminal.ts | 10 +- .../terminal/src/TerminalStreamWritable.ts | 14 +- libraries/terminal/src/TerminalTable.ts | 76 +++++------ libraries/terminal/src/TerminalWritable.ts | 12 +- .../terminal/src/TextRewriterTransform.ts | 16 +-- .../src/test/ProblemCollector.test.ts | 4 +- libraries/tree-pattern/src/TreePattern.ts | 6 +- .../src/parameters/BaseClasses.ts | 6 +- .../CommandLineChoiceListParameter.ts | 10 +- .../parameters/CommandLineChoiceParameter.ts | 12 +- .../parameters/CommandLineFlagParameter.ts | 10 +- .../CommandLineIntegerListParameter.ts | 10 +- .../parameters/CommandLineIntegerParameter.ts | 12 +- .../src/parameters/CommandLineRemainder.ts | 6 +- .../CommandLineStringListParameter.ts | 10 +- .../parameters/CommandLineStringParameter.ts | 12 +- .../src/providers/AliasCommandLineAction.ts | 10 +- .../src/providers/CommandLineAction.ts | 18 +-- .../providers/CommandLineParameterProvider.ts | 88 ++++++------ .../src/providers/CommandLineParser.ts | 52 +++---- .../src/providers/ScopedCommandLineAction.ts | 62 ++++----- .../src/providers/TabCompletionAction.ts | 34 ++--- .../src/test/AliasedCommandLineAction.test.ts | 28 ++-- .../test/AmbiguousCommandLineParser.test.ts | 88 ++++++------ .../src/test/CommandLineParser.test.ts | 6 +- .../test/ConflictingCommandLineParser.test.ts | 18 +-- .../src/test/ScopedCommandLineAction.test.ts | 22 +-- .../src/test/test-cli/PushAction.ts | 10 +- .../src/test/test-cli/RunAction.ts | 6 +- .../src/test/test-cli/WidgetCommandLine.ts | 6 +- .../typings-generator/src/TypingsGenerator.ts | 30 ++-- libraries/worker-pool/src/WorkerPool.ts | 128 +++++++++--------- .../src/RushStackFeature.ts | 6 +- 106 files changed, 1702 insertions(+), 1705 deletions(-) diff --git a/apps/api-documenter/src/cli/BaseAction.ts b/apps/api-documenter/src/cli/BaseAction.ts index fbd3f10a14f..3e8303f0f76 100644 --- a/apps/api-documenter/src/cli/BaseAction.ts +++ b/apps/api-documenter/src/cli/BaseAction.ts @@ -26,13 +26,13 @@ export interface IBuildApiModelResult { } export abstract class BaseAction extends CommandLineAction { - private readonly _inputFolderParameter: CommandLineStringParameter; - private readonly _outputFolderParameter: CommandLineStringParameter; + readonly #inputFolderParameter: CommandLineStringParameter; + readonly #outputFolderParameter: CommandLineStringParameter; protected constructor(options: ICommandLineActionOptions) { super(options); - this._inputFolderParameter = this.defineStringParameter({ + this.#inputFolderParameter = this.defineStringParameter({ parameterLongName: '--input-folder', parameterShortName: '-i', argumentName: 'FOLDER1', @@ -41,7 +41,7 @@ export abstract class BaseAction extends CommandLineAction { ` If omitted, the default is "./input"` }); - this._outputFolderParameter = this.defineStringParameter({ + this.#outputFolderParameter = this.defineStringParameter({ parameterLongName: '--output-folder', parameterShortName: '-o', argumentName: 'FOLDER2', @@ -55,12 +55,12 @@ export abstract class BaseAction extends CommandLineAction { protected buildApiModel(): IBuildApiModelResult { const apiModel: ApiModel = new ApiModel(); - const inputFolder: string = this._inputFolderParameter.value || './input'; + const inputFolder: string = this.#inputFolderParameter.value || './input'; if (!FileSystem.exists(inputFolder)) { throw new Error('The input folder does not exist: ' + inputFolder); } - const outputFolder: string = this._outputFolderParameter.value || `./${this.actionName}`; + const outputFolder: string = this.#outputFolderParameter.value || `./${this.actionName}`; FileSystem.ensureFolder(outputFolder); for (const filename of FileSystem.readFolderItemNames(inputFolder)) { diff --git a/apps/api-documenter/src/cli/YamlAction.ts b/apps/api-documenter/src/cli/YamlAction.ts index 7ed4161fb2d..b9cae1880b3 100644 --- a/apps/api-documenter/src/cli/YamlAction.ts +++ b/apps/api-documenter/src/cli/YamlAction.ts @@ -12,9 +12,9 @@ import { YamlDocumenter, type YamlFormat } from '../documenters/YamlDocumenter'; import { OfficeYamlDocumenter } from '../documenters/OfficeYamlDocumenter'; export class YamlAction extends BaseAction { - private readonly _officeParameter: CommandLineFlagParameter; - private readonly _newDocfxNamespacesParameter: CommandLineFlagParameter; - private readonly _yamlFormatParameter: IRequiredCommandLineChoiceParameter; + readonly #officeParameter: CommandLineFlagParameter; + readonly #newDocfxNamespacesParameter: CommandLineFlagParameter; + readonly #yamlFormatParameter: IRequiredCommandLineChoiceParameter; public constructor(parser: ApiDocumenterCommandLine) { super({ @@ -26,11 +26,11 @@ export class YamlAction extends BaseAction { ' pipeline.' }); - this._officeParameter = this.defineFlagParameter({ + this.#officeParameter = this.defineFlagParameter({ parameterLongName: '--office', description: `Enables some additional features specific to Office Add-ins` }); - this._newDocfxNamespacesParameter = this.defineFlagParameter({ + this.#newDocfxNamespacesParameter = this.defineFlagParameter({ parameterLongName: '--new-docfx-namespaces', description: `This enables an experimental feature that will be officially released with the next major version` + @@ -38,7 +38,7 @@ export class YamlAction extends BaseAction { ` adds them to the table of contents. This will also affect file layout as namespaced items will be nested` + ` under a directory for the namespace instead of just within the package.` }); - this._yamlFormatParameter = this.defineChoiceParameter({ + this.#yamlFormatParameter = this.defineChoiceParameter({ parameterLongName: '--yaml-format', alternatives: ['udp', 'sdp'], defaultValue: 'sdp', @@ -52,12 +52,12 @@ export class YamlAction extends BaseAction { protected override async onExecuteAsync(): Promise { const { apiModel, inputFolder, outputFolder } = this.buildApiModel(); - const yamlDocumenter: YamlDocumenter = this._officeParameter.value - ? new OfficeYamlDocumenter(apiModel, inputFolder, this._newDocfxNamespacesParameter.value) + const yamlDocumenter: YamlDocumenter = this.#officeParameter.value + ? new OfficeYamlDocumenter(apiModel, inputFolder, this.#newDocfxNamespacesParameter.value) : new YamlDocumenter( apiModel, - this._newDocfxNamespacesParameter.value, - this._yamlFormatParameter.value + this.#newDocfxNamespacesParameter.value, + this.#yamlFormatParameter.value ); yamlDocumenter.generateFiles(outputFolder); diff --git a/apps/api-documenter/src/documenters/ExperimentalYamlDocumenter.ts b/apps/api-documenter/src/documenters/ExperimentalYamlDocumenter.ts index 69c0efbdc2f..58bf457ec26 100644 --- a/apps/api-documenter/src/documenters/ExperimentalYamlDocumenter.ts +++ b/apps/api-documenter/src/documenters/ExperimentalYamlDocumenter.ts @@ -14,22 +14,22 @@ import type { DocumenterConfig } from './DocumenterConfig'; * API Documenter. It is not ready for general usage yet. Its design may change in the future. */ export class ExperimentalYamlDocumenter extends YamlDocumenter { - private _config: IConfigTableOfContents; - private _tocPointerMap: { [key: string]: IYamlTocItem }; - private _catchAllPointer: IYamlTocItem | undefined; + #config: IConfigTableOfContents; + #tocPointerMap: { [key: string]: IYamlTocItem }; + #catchAllPointer: IYamlTocItem | undefined; public constructor(apiModel: ApiModel, documenterConfig: DocumenterConfig) { super(apiModel, documenterConfig.configFile.newDocfxNamespaces); - this._config = documenterConfig.configFile.tableOfContents!; + this.#config = documenterConfig.configFile.tableOfContents!; - this._tocPointerMap = {}; + this.#tocPointerMap = {}; - this._generateTocPointersMap(this._config.tocConfig); + this._generateTocPointersMap(this.#config.tocConfig); } protected override buildYamlTocFile(apiItems: ReadonlyArray): IYamlTocFile { this._buildTocItems2(apiItems); - return this._config.tocConfig; + return this.#config.tocConfig; } private _buildTocItems2(apiItems: ReadonlyArray): IYamlTocItem[] { @@ -69,7 +69,7 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { // Parses the tocConfig object to build a pointers map of nodes where we want to sort out the API items private _generateTocPointersMap(tocConfig: IYamlTocFile | IYamlTocItem): void { - const { catchAllCategory } = this._config; + const { catchAllCategory } = this.#config; if (tocConfig.items) { for (const tocItem of tocConfig.items) { @@ -78,9 +78,9 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { } else { // check for presence of the `catchAllCategory` config option if (catchAllCategory && tocItem.name === catchAllCategory) { - this._catchAllPointer = tocItem; + this.#catchAllPointer = tocItem; } else { - this._tocPointerMap[tocItem.name] = tocItem; + this.#tocPointerMap[tocItem.name] = tocItem; } } } @@ -91,7 +91,7 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { * Filtering out the api-item by inlineTags or category name presence in the item name. */ private _filterItem(apiItem: ApiItem, tocItem: IYamlTocItem): void { - const { categoryInlineTag, categorizeByName } = this._config; + const { categoryInlineTag, categorizeByName } = this.#config; const { name: itemName } = tocItem; let filtered: boolean = false; @@ -104,20 +104,20 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { const tagContent: string | undefined = docInlineTag && docInlineTag.tagContent && docInlineTag.tagContent.trim(); - if (tagContent && this._tocPointerMap[tagContent]) { + if (tagContent && this.#tocPointerMap[tagContent]) { // null assertion used because when pointer map was created we checked for presence of empty `items` array - this._tocPointerMap[tagContent].items!.push(tocItem); + this.#tocPointerMap[tagContent].items!.push(tocItem); filtered = true; } } // If not filtered by inline tag and `categorizeByName` config is enabled attempt to filter it by category name. if (!filtered && categorizeByName) { - const pointers: string[] = Object.keys(this._tocPointerMap); + const pointers: string[] = Object.keys(this.#tocPointerMap); for (let i: number = 0, length: number = pointers.length; i < length; i++) { if (itemName.indexOf(pointers[i]) !== -1) { // null assertion used because when pointer map was created we checked for presence of empty `items` array - this._tocPointerMap[pointers[i]].items!.push(tocItem); + this.#tocPointerMap[pointers[i]].items!.push(tocItem); filtered = true; break; } @@ -125,8 +125,8 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { } // If item still not filtered and a `catchAllCategory` config provided push it to it. - if (!filtered && this._catchAllPointer && this._catchAllPointer.items) { - this._catchAllPointer.items.push(tocItem); + if (!filtered && this.#catchAllPointer && this.#catchAllPointer.items) { + this.#catchAllPointer.items.push(tocItem); } } @@ -155,7 +155,7 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { } private _shouldNotIncludeInPointersMap(item: IYamlTocItem): boolean { - const { nonEmptyCategoryNodeNames } = this._config; + const { nonEmptyCategoryNodeNames } = this.#config; if (nonEmptyCategoryNodeNames && nonEmptyCategoryNodeNames.length) { return nonEmptyCategoryNodeNames.indexOf(item.name) === -1; } diff --git a/apps/api-documenter/src/documenters/MarkdownDocumenter.ts b/apps/api-documenter/src/documenters/MarkdownDocumenter.ts index 203509cf816..8094e4d0e63 100644 --- a/apps/api-documenter/src/documenters/MarkdownDocumenter.ts +++ b/apps/api-documenter/src/documenters/MarkdownDocumenter.ts @@ -77,29 +77,29 @@ export interface IMarkdownDocumenterOptions { * For more info: https://en.wikipedia.org/wiki/Markdown */ export class MarkdownDocumenter { - private readonly _apiModel: ApiModel; - private readonly _documenterConfig: DocumenterConfig | undefined; - private readonly _tsdocConfiguration: TSDocConfiguration; - private readonly _markdownEmitter: CustomMarkdownEmitter; - private readonly _outputFolder: string; - private readonly _pluginLoader: PluginLoader; + readonly #apiModel: ApiModel; + readonly #documenterConfig: DocumenterConfig | undefined; + readonly #tsdocConfiguration: TSDocConfiguration; + readonly #markdownEmitter: CustomMarkdownEmitter; + readonly #outputFolder: string; + readonly #pluginLoader: PluginLoader; public constructor(options: IMarkdownDocumenterOptions) { - this._apiModel = options.apiModel; - this._documenterConfig = options.documenterConfig; - this._outputFolder = options.outputFolder; - this._tsdocConfiguration = CustomDocNodes.configuration; - this._markdownEmitter = new CustomMarkdownEmitter(this._apiModel); + this.#apiModel = options.apiModel; + this.#documenterConfig = options.documenterConfig; + this.#outputFolder = options.outputFolder; + this.#tsdocConfiguration = CustomDocNodes.configuration; + this.#markdownEmitter = new CustomMarkdownEmitter(this.#apiModel); - this._pluginLoader = new PluginLoader(); + this.#pluginLoader = new PluginLoader(); } public generateFiles(): void { - if (this._documenterConfig) { - this._pluginLoader.load(this._documenterConfig, () => { + if (this.#documenterConfig) { + this.#pluginLoader.load(this.#documenterConfig, () => { return new MarkdownDocumenterFeatureContext({ - apiModel: this._apiModel, - outputFolder: this._outputFolder, + apiModel: this.#apiModel, + outputFolder: this.#outputFolder, documenter: new MarkdownDocumenterAccessor({ getLinkForApiItem: (apiItem: ApiItem) => { return this._getLinkFilenameForApiItem(apiItem); @@ -112,15 +112,15 @@ export class MarkdownDocumenter { console.log(); this._deleteOldOutputFiles(); - this._writeApiItemPage(this._apiModel); + this._writeApiItemPage(this.#apiModel); - if (this._pluginLoader.markdownDocumenterFeature) { - this._pluginLoader.markdownDocumenterFeature.onFinished({}); + if (this.#pluginLoader.markdownDocumenterFeature) { + this.#pluginLoader.markdownDocumenterFeature.onFinished({}); } } private _writeApiItemPage(apiItem: ApiItem): void { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; const output: DocSection = new DocSection({ configuration }); this._writeBreadcrumb(output, apiItem); @@ -302,14 +302,14 @@ export class MarkdownDocumenter { this._writeRemarksSection(output, apiItem); } - const filename: string = path.join(this._outputFolder, this._getFilenameForApiItem(apiItem)); + const filename: string = path.join(this.#outputFolder, this._getFilenameForApiItem(apiItem)); const stringBuilder: StringBuilder = new StringBuilder(); stringBuilder.append( '\n\n' ); - this._markdownEmitter.emit(stringBuilder, output, { + this.#markdownEmitter.emit(stringBuilder, output, { contextApiItem: apiItem, onGetFilenameForApiItem: (apiItemForFilename: ApiItem) => { return this._getLinkFilenameForApiItem(apiItemForFilename); @@ -318,24 +318,24 @@ export class MarkdownDocumenter { let pageContent: string = stringBuilder.toString(); - if (this._pluginLoader.markdownDocumenterFeature) { + if (this.#pluginLoader.markdownDocumenterFeature) { // Allow the plugin to customize the pageContent const eventArgs: IMarkdownDocumenterFeatureOnBeforeWritePageArgs = { apiItem: apiItem, outputFilename: filename, pageContent: pageContent }; - this._pluginLoader.markdownDocumenterFeature.onBeforeWritePage(eventArgs); + this.#pluginLoader.markdownDocumenterFeature.onBeforeWritePage(eventArgs); pageContent = eventArgs.pageContent; } FileSystem.writeFile(filename, pageContent, { - convertLineEndings: this._documenterConfig ? this._documenterConfig.newlineKind : NewlineKind.CrLf + convertLineEndings: this.#documenterConfig ? this.#documenterConfig.newlineKind : NewlineKind.CrLf }); } private _writeHeritageTypes(output: DocSection, apiItem: ApiDeclaredItem): void { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; if (apiItem instanceof ApiClass) { if (apiItem.extendsType) { @@ -389,7 +389,7 @@ export class MarkdownDocumenter { (token) => token.kind === ExcerptTokenKind.Reference && token.canonicalReference && - this._apiModel.resolveDeclarationReference(token.canonicalReference, undefined).resolvedApiItem + this.#apiModel.resolveDeclarationReference(token.canonicalReference, undefined).resolvedApiItem ); if (refs.length > 0) { const referencesParagraph: DocParagraph = new DocParagraph({ configuration }, [ @@ -418,7 +418,7 @@ export class MarkdownDocumenter { } private _writeRemarksSection(output: DocSection, apiItem: ApiItem): void { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; if (apiItem instanceof ApiDocumentedItem) { const tsdocComment: DocComment | undefined = apiItem.tsdocComment; @@ -450,7 +450,7 @@ export class MarkdownDocumenter { } private _writeThrowsSection(output: DocSection, apiItem: ApiItem): void { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; if (apiItem instanceof ApiDocumentedItem) { const tsdocComment: DocComment | undefined = apiItem.tsdocComment; @@ -474,7 +474,7 @@ export class MarkdownDocumenter { } private _writeDefaultValueSection(output: DocSection, apiItem: ApiItem): void { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; if (apiItem instanceof ApiDocumentedItem) { const tsdocComment: DocComment | undefined = apiItem.tsdocComment; @@ -501,7 +501,7 @@ export class MarkdownDocumenter { * GENERATE PAGE: MODEL */ private _writeModelTable(output: DocSection, apiModel: ApiModel): void { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; const packagesTable: DocTable = new DocTable({ configuration, @@ -532,7 +532,7 @@ export class MarkdownDocumenter { * GENERATE PAGE: PACKAGE or NAMESPACE */ private _writePackageOrNamespaceTables(output: DocSection, apiContainer: ApiPackage | ApiNamespace): void { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; const abstractClassesTable: DocTable = new DocTable({ configuration, @@ -671,7 +671,7 @@ export class MarkdownDocumenter { * GENERATE PAGE: CLASS */ private _writeClassTables(output: DocSection, apiClass: ApiClass): void { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; const eventsTable: DocTable = new DocTable({ configuration, @@ -773,7 +773,7 @@ export class MarkdownDocumenter { * GENERATE PAGE: ENUM */ private _writeEnumTables(output: DocSection, apiEnum: ApiEnum): void { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; const enumMembersTable: DocTable = new DocTable({ configuration, @@ -804,7 +804,7 @@ export class MarkdownDocumenter { * GENERATE PAGE: INTERFACE */ private _writeInterfaceTables(output: DocSection, apiInterface: ApiInterface): void { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; const eventsTable: DocTable = new DocTable({ configuration, @@ -884,7 +884,7 @@ export class MarkdownDocumenter { * GENERATE PAGE: FUNCTION-LIKE */ private _writeParameterTables(output: DocSection, apiParameterListMixin: ApiParameterListMixin): void { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; const parametersTable: DocTable = new DocTable({ configuration, @@ -947,7 +947,7 @@ export class MarkdownDocumenter { } private _createParagraphForTypeExcerpt(excerpt: Excerpt): DocParagraph { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; const paragraph: DocParagraph = new DocParagraph({ configuration }); @@ -967,7 +967,7 @@ export class MarkdownDocumenter { } private _appendExcerptTokenWithHyperlinks(docNodeContainer: DocNodeContainer, token: ExcerptToken): void { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; // Markdown doesn't provide a standardized syntax for hyperlinks inside code spans, so we will render // the type expression as DocPlainText. Instead of creating multiple DocParagraphs, we can simply @@ -976,7 +976,7 @@ export class MarkdownDocumenter { // If it's hyperlinkable, then append a DocLinkTag if (token.kind === ExcerptTokenKind.Reference && token.canonicalReference) { - const apiItemResult: IResolveDeclarationReferenceResult = this._apiModel.resolveDeclarationReference( + const apiItemResult: IResolveDeclarationReferenceResult = this.#apiModel.resolveDeclarationReference( token.canonicalReference, undefined ); @@ -999,7 +999,7 @@ export class MarkdownDocumenter { } private _createTitleCell(apiItem: ApiItem): DocTableCell { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; let linkText: string = Utilities.getConciseSignature(apiItem); if (ApiOptionalMixin.isBaseClassOf(apiItem) && apiItem.isOptional) { @@ -1026,7 +1026,7 @@ export class MarkdownDocumenter { * check than to have each caller perform a type cast. */ private _createDescriptionCell(apiItem: ApiItem, isInherited: boolean = false): DocTableCell { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; const section: DocSection = new DocSection({ configuration }); @@ -1078,7 +1078,7 @@ export class MarkdownDocumenter { } private _createModifiersCell(apiItem: ApiItem): DocTableCell { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; const section: DocSection = new DocSection({ configuration }); @@ -1122,7 +1122,7 @@ export class MarkdownDocumenter { } private _createPropertyTypeCell(apiItem: ApiItem): DocTableCell { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; const section: DocSection = new DocSection({ configuration }); @@ -1134,7 +1134,7 @@ export class MarkdownDocumenter { } private _createInitializerCell(apiItem: ApiItem): DocTableCell { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; const section: DocSection = new DocSection({ configuration }); @@ -1150,14 +1150,14 @@ export class MarkdownDocumenter { } private _writeBreadcrumb(output: DocSection, apiItem: ApiItem): void { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; output.appendNodeInParagraph( new DocLinkTag({ configuration, tagName: '@link', linkText: 'Home', - urlDestination: this._getLinkFilenameForApiItem(this._apiModel) + urlDestination: this._getLinkFilenameForApiItem(this.#apiModel) }) ); @@ -1187,7 +1187,7 @@ export class MarkdownDocumenter { } private _writeAlphaWarning(output: DocSection): void { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; const betaWarning: string = 'This API is provided as an alpha preview for developers and may change' + ' based on feedback that we receive. Do not use this API in a production environment.'; @@ -1199,7 +1199,7 @@ export class MarkdownDocumenter { } private _writeBetaWarning(output: DocSection): void { - const configuration: TSDocConfiguration = this._tsdocConfiguration; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; const betaWarning: string = 'This API is provided as a beta preview for developers and may change' + ' based on feedback that we receive. Do not use this API in a production environment.'; @@ -1236,8 +1236,8 @@ export class MarkdownDocumenter { apiClassOrInterface: ApiClass | ApiInterface, output: DocSection ): readonly ApiItem[] { - const configuration: TSDocConfiguration = this._tsdocConfiguration; - const showInheritedMembers: boolean = !!this._documenterConfig?.configFile.showInheritedMembers; + const configuration: TSDocConfiguration = this.#tsdocConfiguration; + const showInheritedMembers: boolean = !!this.#documenterConfig?.configFile.showInheritedMembers; if (!showInheritedMembers) { return apiClassOrInterface.members; } @@ -1303,7 +1303,7 @@ export class MarkdownDocumenter { } private _deleteOldOutputFiles(): void { - console.log('Deleting old output from ' + this._outputFolder); - FileSystem.ensureEmptyFolder(this._outputFolder); + console.log('Deleting old output from ' + this.#outputFolder); + FileSystem.ensureEmptyFolder(this.#outputFolder); } } diff --git a/apps/api-documenter/src/documenters/OfficeYamlDocumenter.ts b/apps/api-documenter/src/documenters/OfficeYamlDocumenter.ts index df82c0caa2b..9119f328931 100644 --- a/apps/api-documenter/src/documenters/OfficeYamlDocumenter.ts +++ b/apps/api-documenter/src/documenters/OfficeYamlDocumenter.ts @@ -25,14 +25,14 @@ interface ISnippetsFile { * Extends YamlDocumenter with some custom logic that is specific to Office Add-ins. */ export class OfficeYamlDocumenter extends YamlDocumenter { - private _snippets: ISnippetsFile; - private _snippetsAll: ISnippetsFile; + #snippets: ISnippetsFile; + #snippetsAll: ISnippetsFile; // Default API Set URL when no product match is found. - private _apiSetUrlDefault: string = '/office/dev/add-ins/reference/javascript-api-for-office'; + #apiSetUrlDefault: string = '/office/dev/add-ins/reference/javascript-api-for-office'; // Hash set of API Set URLs based on product. - private _apiSetUrls: Record = { + #apiSetUrls: Record = { Excel: '/javascript/api/requirement-sets/excel/excel-api-requirement-sets', OneNote: '/javascript/api/requirement-sets/onenote/onenote-api-requirement-sets', Outlook: '/javascript/api/requirement-sets/outlook/outlook-api-requirement-sets', @@ -49,8 +49,8 @@ export class OfficeYamlDocumenter extends YamlDocumenter { console.log('Loading snippets from ' + snippetsFilePath); const snippetsContent: string = FileSystem.readFile(snippetsFilePath); - this._snippets = yaml.load(snippetsContent, { filename: snippetsFilePath }) as ISnippetsFile; - this._snippetsAll = yaml.load(snippetsContent, { filename: snippetsFilePath }) as ISnippetsFile; + this.#snippets = yaml.load(snippetsContent, { filename: snippetsFilePath }) as ISnippetsFile; + this.#snippetsAll = yaml.load(snippetsContent, { filename: snippetsFilePath }) as ISnippetsFile; } public override generateFiles(outputFolder: string): void { @@ -58,7 +58,7 @@ export class OfficeYamlDocumenter extends YamlDocumenter { // After we generate everything, check for any unused snippets console.log(); - for (const apiName of Object.keys(this._snippets)) { + for (const apiName of Object.keys(this.#snippets)) { console.error(Colorize.yellow('Warning: Unused snippet ' + apiName)); } } @@ -80,9 +80,9 @@ export class OfficeYamlDocumenter extends YamlDocumenter { yamlItem.remarks = this._fixupApiSet(yamlItem.remarks, yamlItem.uid); } - const snippets: string[] | undefined = this._snippetsAll[nameWithoutPackage]; + const snippets: string[] | undefined = this.#snippetsAll[nameWithoutPackage]; if (snippets) { - delete this._snippets[nameWithoutPackage]; + delete this.#snippets[nameWithoutPackage]; const snippetText: string = this._generateExampleSnippetText(snippets); if (yamlItem.remarks) { yamlItem.remarks += snippetText; @@ -109,13 +109,13 @@ export class OfficeYamlDocumenter extends YamlDocumenter { // Gets the link to the API set based on product context. Seeks a case-insensitive match in the hash set. private _getApiSetUrl(uid: string): string { - for (const key of Object.keys(this._apiSetUrls)) { + for (const key of Object.keys(this.#apiSetUrls)) { const regexp: RegExp = new RegExp(key, 'i'); if (regexp.test(uid)) { - return this._apiSetUrls[key]; + return this.#apiSetUrls[key]; } } - return this._apiSetUrlDefault; // match not found. + return this.#apiSetUrlDefault; // match not found. } private _generateExampleSnippetText(snippets: string[]): string { diff --git a/apps/api-documenter/src/documenters/YamlDocumenter.ts b/apps/api-documenter/src/documenters/YamlDocumenter.ts index 73420328756..eeaf805633c 100644 --- a/apps/api-documenter/src/documenters/YamlDocumenter.ts +++ b/apps/api-documenter/src/documenters/YamlDocumenter.ts @@ -98,23 +98,23 @@ export type YamlFormat = 'udp' | 'sdp'; */ export class YamlDocumenter { protected readonly newDocfxNamespaces: boolean; - private readonly _yamlFormat: string; - private readonly _apiModel: ApiModel; - private readonly _markdownEmitter: CustomMarkdownEmitter; + readonly #yamlFormat: string; + readonly #apiModel: ApiModel; + readonly #markdownEmitter: CustomMarkdownEmitter; - private _apiItemsByCanonicalReference: Map; - private _yamlReferences: IYamlReferences | undefined; + #apiItemsByCanonicalReference: Map; + #yamlReferences: IYamlReferences | undefined; public constructor( apiModel: ApiModel, newDocfxNamespaces: boolean = false, yamlFormat: YamlFormat = 'sdp' ) { - this._apiModel = apiModel; + this.#apiModel = apiModel; this.newDocfxNamespaces = newDocfxNamespaces; - this._yamlFormat = yamlFormat; - this._markdownEmitter = new CustomMarkdownEmitter(this._apiModel); - this._apiItemsByCanonicalReference = new Map(); + this.#yamlFormat = yamlFormat; + this.#markdownEmitter = new CustomMarkdownEmitter(this.#apiModel); + this.#apiItemsByCanonicalReference = new Map(); this._initApiItems(); } @@ -124,16 +124,16 @@ export class YamlDocumenter { console.log(); this._deleteOldOutputFiles(outputFolder); - for (const apiPackage of this._apiModel.packages) { + for (const apiPackage of this.#apiModel.packages) { console.log(`Writing ${apiPackage.name} package`); this._visitApiItems(outputFolder, apiPackage, undefined); } - if (this._yamlFormat === 'sdp') { + if (this.#yamlFormat === 'sdp') { convertUDPYamlToSDP(outputFolder); } - this._writeTocFile(outputFolder, this._apiModel.packages); + this._writeTocFile(outputFolder, this.#apiModel.packages); } /** @virtual */ @@ -158,8 +158,8 @@ export class YamlDocumenter { ): boolean { let savedYamlReferences: IYamlReferences | undefined; if (!this._shouldEmbed(apiItem.kind)) { - savedYamlReferences = this._yamlReferences; - this._yamlReferences = undefined; + savedYamlReferences = this.#yamlReferences; + this.#yamlReferences = undefined; } const yamlItem: IYamlItem | undefined = this._generateYamlItem(apiItem); @@ -192,11 +192,11 @@ export class YamlDocumenter { } } - if (this._yamlReferences && this._yamlReferences.references.length > 0) { - newYamlFile.references = this._yamlReferences.references; + if (this.#yamlReferences && this.#yamlReferences.references.length > 0) { + newYamlFile.references = this.#yamlReferences.references; } - this._yamlReferences = savedYamlReferences; + this.#yamlReferences = savedYamlReferences; const yamlFilePath: string = this._getYamlFilePath(outputFolder, apiItem); @@ -741,7 +741,7 @@ export class YamlDocumenter { private _renderMarkdown(docSection: DocSection, contextApiItem: ApiItem): string { const stringBuilder: StringBuilder = new StringBuilder(); - this._markdownEmitter.emit(stringBuilder, docSection, { + this.#markdownEmitter.emit(stringBuilder, docSection, { contextApiItem, onGetFilenameForApiItem: (apiItem: ApiItem) => { // NOTE: GitHub's markdown renderer does not resolve relative hyperlinks correctly @@ -804,7 +804,7 @@ export class YamlDocumenter { * Initialize the _apiItemsByCanonicalReference data structure. */ private _initApiItems(): void { - this._initApiItemsRecursive(this._apiModel); + this._initApiItemsRecursive(this.#apiModel); } /** @@ -812,7 +812,7 @@ export class YamlDocumenter { */ private _initApiItemsRecursive(apiItem: ApiItem): void { if (apiItem.canonicalReference && !apiItem.canonicalReference.isEmpty) { - this._apiItemsByCanonicalReference.set(apiItem.canonicalReference.toString(), apiItem); + this.#apiItemsByCanonicalReference.set(apiItem.canonicalReference.toString(), apiItem); } // Recurse container members @@ -824,14 +824,14 @@ export class YamlDocumenter { } private _ensureYamlReferences(): IYamlReferences { - if (!this._yamlReferences) { - this._yamlReferences = { + if (!this.#yamlReferences) { + this.#yamlReferences = { references: [], typeNameToUid: new Map(), uidTypeReferenceCounters: new Map() }; } - return this._yamlReferences; + return this.#yamlReferences; } private _renderInheritance( @@ -842,7 +842,7 @@ export class YamlDocumenter { for (const heritageType of heritageTypes) { const type: string = this._renderType(contextUid, heritageType.excerpt); const yamlInheritance: IYamlInheritanceTree = { type }; - const apiItem: ApiItem | undefined = this._apiItemsByCanonicalReference.get(type); + const apiItem: ApiItem | undefined = this.#apiItemsByCanonicalReference.get(type); if (apiItem) { if (apiItem instanceof ApiClass) { if (apiItem.extendsType) { @@ -902,7 +902,7 @@ export class YamlDocumenter { excerptTokens[0].canonicalReference ) { const excerptRef: string = excerptTokens[0].canonicalReference.toString(); - const apiItem: ApiItem | undefined = this._apiItemsByCanonicalReference.get(excerptRef); + const apiItem: ApiItem | undefined = this.#apiItemsByCanonicalReference.get(excerptRef); return this._recordYamlReference( yamlReferences, excerptTokens[0].canonicalReference.toString(), @@ -948,7 +948,7 @@ export class YamlDocumenter { const spec: IYamlReferenceSpec = {}; const specUid: string | undefined = token.canonicalReference && token.canonicalReference.toString(); const apiItem: ApiItem | undefined = specUid - ? this._apiItemsByCanonicalReference.get(specUid) + ? this.#apiItemsByCanonicalReference.get(specUid) : undefined; if (specUid) { spec.uid = specUid; diff --git a/apps/api-documenter/src/markdown/CustomMarkdownEmitter.ts b/apps/api-documenter/src/markdown/CustomMarkdownEmitter.ts index fa6637733e9..00bb38b439c 100644 --- a/apps/api-documenter/src/markdown/CustomMarkdownEmitter.ts +++ b/apps/api-documenter/src/markdown/CustomMarkdownEmitter.ts @@ -25,12 +25,12 @@ export interface ICustomMarkdownEmitterOptions extends IMarkdownEmitterOptions { } export class CustomMarkdownEmitter extends MarkdownEmitter { - private _apiModel: ApiModel; + #apiModel: ApiModel; public constructor(apiModel: ApiModel) { super(); - this._apiModel = apiModel; + this.#apiModel = apiModel; } public override emit( @@ -165,7 +165,7 @@ export class CustomMarkdownEmitter extends MarkdownEmitter { ): void { const options: ICustomMarkdownEmitterOptions = context.options; - const result: IResolveDeclarationReferenceResult = this._apiModel.resolveDeclarationReference( + const result: IResolveDeclarationReferenceResult = this.#apiModel.resolveDeclarationReference( docLinkTag.codeDestination!, options.contextApiItem ); diff --git a/apps/api-documenter/src/nodes/DocTable.ts b/apps/api-documenter/src/nodes/DocTable.ts index 43da35b609b..e573bed7366 100644 --- a/apps/api-documenter/src/nodes/DocTable.ts +++ b/apps/api-documenter/src/nodes/DocTable.ts @@ -21,13 +21,13 @@ export interface IDocTableParameters extends IDocNodeParameters { export class DocTable extends DocNode { public readonly header: DocTableRow; - private _rows: DocTableRow[]; + #rows: DocTableRow[]; public constructor(parameters: IDocTableParameters, rows?: ReadonlyArray) { super(parameters); this.header = new DocTableRow({ configuration: this.configuration }); - this._rows = []; + this.#rows = []; if (parameters) { if (parameters.headerTitles) { @@ -59,11 +59,11 @@ export class DocTable extends DocNode { } public get rows(): ReadonlyArray { - return this._rows; + return this.#rows; } public addRow(row: DocTableRow): void { - this._rows.push(row); + this.#rows.push(row); } public createAndAddRow(): DocTableRow { @@ -73,6 +73,6 @@ export class DocTable extends DocNode { } protected override onGetChildNodes(): ReadonlyArray { - return [this.header, ...this._rows]; + return [this.header, ...this.#rows]; } } diff --git a/apps/api-documenter/src/nodes/DocTableRow.ts b/apps/api-documenter/src/nodes/DocTableRow.ts index bf215b7c6d1..d5ac6a12ad6 100644 --- a/apps/api-documenter/src/nodes/DocTableRow.ts +++ b/apps/api-documenter/src/nodes/DocTableRow.ts @@ -15,12 +15,12 @@ export interface IDocTableRowParameters extends IDocNodeParameters {} * Represents table row, similar to an HTML `` element. */ export class DocTableRow extends DocNode { - private readonly _cells: DocTableCell[]; + readonly #cells: DocTableCell[]; public constructor(parameters: IDocTableRowParameters, cells?: ReadonlyArray) { super(parameters); - this._cells = []; + this.#cells = []; if (cells) { for (const cell of cells) { this.addCell(cell); @@ -33,11 +33,11 @@ export class DocTableRow extends DocNode { } public get cells(): ReadonlyArray { - return this._cells; + return this.#cells; } public addCell(cell: DocTableCell): void { - this._cells.push(cell); + this.#cells.push(cell); } public createAndAddCell(): DocTableCell { @@ -58,6 +58,6 @@ export class DocTableRow extends DocNode { } protected override onGetChildNodes(): ReadonlyArray { - return this._cells; + return this.#cells; } } diff --git a/apps/api-documenter/src/plugin/MarkdownDocumenterAccessor.ts b/apps/api-documenter/src/plugin/MarkdownDocumenterAccessor.ts index 8f6c176e094..642e8fef334 100644 --- a/apps/api-documenter/src/plugin/MarkdownDocumenterAccessor.ts +++ b/apps/api-documenter/src/plugin/MarkdownDocumenterAccessor.ts @@ -18,11 +18,11 @@ export interface IMarkdownDocumenterAccessorImplementation { * @public */ export class MarkdownDocumenterAccessor { - private _implementation: IMarkdownDocumenterAccessorImplementation; + #implementation: IMarkdownDocumenterAccessorImplementation; /** @internal */ public constructor(implementation: IMarkdownDocumenterAccessorImplementation) { - this._implementation = implementation; + this.#implementation = implementation; } /** @@ -31,6 +31,6 @@ export class MarkdownDocumenterAccessor { * @returns The hyperlink, or `undefined` if the `ApiItem` object does not have a hyperlink. */ public getLinkForApiItem(apiItem: ApiItem): string | undefined { - return this._implementation.getLinkForApiItem(apiItem); + return this.#implementation.getLinkForApiItem(apiItem); } } diff --git a/apps/api-documenter/src/utils/IndentedWriter.ts b/apps/api-documenter/src/utils/IndentedWriter.ts index d751ac1682e..3b583118b19 100644 --- a/apps/api-documenter/src/utils/IndentedWriter.ts +++ b/apps/api-documenter/src/utils/IndentedWriter.ts @@ -37,37 +37,37 @@ export class IndentedWriter { */ public defaultIndentPrefix: string = ' '; - private readonly _builder: IStringBuilder; + readonly #builder: IStringBuilder; - private _latestChunk: string | undefined; - private _previousChunk: string | undefined; - private _atStartOfLine: boolean; + #latestChunk: string | undefined; + #previousChunk: string | undefined; + #atStartOfLine: boolean; - private readonly _indentStack: string[]; - private _indentText: string; + readonly #indentStack: string[]; + #indentText: string; - private _beforeStack: string[]; - private _isWritingBeforeStack: boolean; + #beforeStack: string[]; + #isWritingBeforeStack: boolean; public constructor(builder?: IStringBuilder) { - this._builder = builder === undefined ? new StringBuilder() : builder; + this.#builder = builder === undefined ? new StringBuilder() : builder; - this._latestChunk = undefined; - this._previousChunk = undefined; - this._atStartOfLine = true; + this.#latestChunk = undefined; + this.#previousChunk = undefined; + this.#atStartOfLine = true; - this._indentStack = []; - this._indentText = ''; + this.#indentStack = []; + this.#indentText = ''; - this._beforeStack = []; - this._isWritingBeforeStack = false; + this.#beforeStack = []; + this.#isWritingBeforeStack = false; } /** * Retrieves the output that was built so far. */ public getText(): string { - return this._builder.toString(); + return this.#builder.toString(); } public toString(): string { @@ -82,7 +82,7 @@ export class IndentedWriter { * corresponding call to IndentedWriter.decreaseIndent(). */ public increaseIndent(indentPrefix?: string): void { - this._indentStack.push(indentPrefix !== undefined ? indentPrefix : this.defaultIndentPrefix); + this.#indentStack.push(indentPrefix !== undefined ? indentPrefix : this.defaultIndentPrefix); this._updateIndentText(); } @@ -91,7 +91,7 @@ export class IndentedWriter { * to IndentedWriter.increaseIndent(). */ public decreaseIndent(): void { - this._indentStack.pop(); + this.#indentStack.pop(); this._updateIndentText(); } @@ -133,8 +133,8 @@ export class IndentedWriter { * Returns the last character that was written, or an empty string if no characters have been written yet. */ public peekLastCharacter(): string { - if (this._latestChunk !== undefined) { - return this._latestChunk.substr(-1, 1); + if (this.#latestChunk !== undefined) { + return this.#latestChunk.substr(-1, 1); } return ''; } @@ -144,12 +144,12 @@ export class IndentedWriter { * have been written yet. */ public peekSecondLastCharacter(): string { - if (this._latestChunk !== undefined) { - if (this._latestChunk.length > 1) { - return this._latestChunk.substr(-2, 1); + if (this.#latestChunk !== undefined) { + if (this.#latestChunk.length > 1) { + return this.#latestChunk.substr(-2, 1); } - if (this._previousChunk !== undefined) { - return this._previousChunk.substr(-1, 1); + if (this.#previousChunk !== undefined) { + return this.#previousChunk.substr(-1, 1); } } return ''; @@ -162,7 +162,7 @@ export class IndentedWriter { * If `mayWrite` writes nothing, this method will write nothing. */ public writeTentative(before: string, after: string, mayWrite: () => void): void { - this._beforeStack.push(before); + this.#beforeStack.push(before); // If this function writes anything, then _all_ messages in the "before stack" will also be // written. This means that the stack will be empty (as when we write a message from the stack, @@ -172,8 +172,8 @@ export class IndentedWriter { // If the stack is not empty, it means that `mayWrite` didn't write anything. Pop the last- // added message from the stack, we'll never write it. Otherwise, if the stack is empty, then // write the "after" message. - if (this._beforeStack.length > 0) { - this._beforeStack.pop(); + if (this.#beforeStack.length > 0) { + this.#beforeStack.pop(); } else { this.write(after); } @@ -189,7 +189,7 @@ export class IndentedWriter { return; } - if (!this._isWritingBeforeStack) { + if (!this.#isWritingBeforeStack) { this._writeBeforeStack(); } @@ -220,7 +220,7 @@ export class IndentedWriter { public writeLine(message: string = ''): void { if (message.length > 0) { this.write(message); - } else if (!this._isWritingBeforeStack) { + } else if (!this.#isWritingBeforeStack) { this._writeBeforeStack(); } @@ -232,27 +232,27 @@ export class IndentedWriter { */ private _writeLinePart(message: string): void { if (message.length > 0) { - if (this._atStartOfLine && this._indentText.length > 0) { - this._write(this._indentText); + if (this.#atStartOfLine && this.#indentText.length > 0) { + this._write(this.#indentText); } this._write(message); - this._atStartOfLine = false; + this.#atStartOfLine = false; } } private _writeNewLine(): void { - if (this._atStartOfLine && this._indentText.length > 0) { - this._write(this._indentText); + if (this.#atStartOfLine && this.#indentText.length > 0) { + this._write(this.#indentText); } this._write('\n'); - this._atStartOfLine = true; + this.#atStartOfLine = true; } private _write(s: string): void { - this._previousChunk = this._latestChunk; - this._latestChunk = s; - this._builder.append(s); + this.#previousChunk = this.#latestChunk; + this.#latestChunk = s; + this.#builder.append(s); } /** @@ -260,17 +260,17 @@ export class IndentedWriter { * populated by the `writeTentative` method. */ private _writeBeforeStack(): void { - this._isWritingBeforeStack = true; + this.#isWritingBeforeStack = true; - for (const message of this._beforeStack) { + for (const message of this.#beforeStack) { this.write(message); } - this._isWritingBeforeStack = false; - this._beforeStack = []; + this.#isWritingBeforeStack = false; + this.#beforeStack = []; } private _updateIndentText(): void { - this._indentText = this._indentStack.join(''); + this.#indentText = this.#indentStack.join(''); } } diff --git a/apps/api-extractor/src/analyzer/AstDeclaration.ts b/apps/api-extractor/src/analyzer/AstDeclaration.ts index 78cc4ed7337..0b7d4886f5f 100644 --- a/apps/api-extractor/src/analyzer/AstDeclaration.ts +++ b/apps/api-extractor/src/analyzer/AstDeclaration.ts @@ -65,12 +65,12 @@ export class AstDeclaration { public apiItemMetadata: unknown; // NOTE: This array becomes immutable after astSymbol.analyze() sets astSymbol.analyzed=true - private readonly _analyzedChildren: AstDeclaration[] = []; + readonly #analyzedChildren: AstDeclaration[] = []; - private readonly _analyzedReferencedAstEntitiesSet: Set = new Set(); + readonly #analyzedReferencedAstEntitiesSet: Set = new Set(); // Reverse lookup used by findChildrenWithName() - private _childrenByName: Map | undefined = undefined; + #childrenByName: Map | undefined = undefined; public constructor(options: IAstDeclarationOptions) { this.declaration = options.declaration; @@ -104,7 +104,7 @@ export class AstDeclaration { * The collection will be empty until AstSymbol.analyzed is true. */ public get children(): ReadonlyArray { - return this.astSymbol.analyzed ? this._analyzedChildren : []; + return this.astSymbol.analyzed ? this.#analyzedChildren : []; } /** @@ -122,7 +122,7 @@ export class AstDeclaration { * (e.g. if a method returns an enum, this doesn't imply that the method's class references that enum) */ public get referencedAstEntities(): ReadonlyArray { - return this.astSymbol.analyzed ? [...this._analyzedReferencedAstEntitiesSet] : []; + return this.astSymbol.analyzed ? [...this.#analyzedReferencedAstEntitiesSet] : []; } /** @@ -139,7 +139,7 @@ export class AstDeclaration { throw new InternalError('_notifyChildAttach() called after analysis is already complete'); } - this._analyzedChildren.push(child); + this.#analyzedChildren.push(child); } /** @@ -154,7 +154,7 @@ export class AstDeclaration { } result += '\n'; - for (const referencedAstEntity of this._analyzedReferencedAstEntitiesSet.values()) { + for (const referencedAstEntity of this.#analyzedReferencedAstEntitiesSet.values()) { result += indent + ` ref: ${referencedAstEntity.localName}\n`; } @@ -186,7 +186,7 @@ export class AstDeclaration { for (let current: AstDeclaration | undefined = this; current; current = current.parent) { // Don't add references to symbols that are already referenced by a parent - if (current._analyzedReferencedAstEntitiesSet.has(referencedAstEntity)) { + if (current.#analyzedReferencedAstEntitiesSet.has(referencedAstEntity)) { return; } // Don't add the symbols of parents either @@ -195,7 +195,7 @@ export class AstDeclaration { } } - this._analyzedReferencedAstEntitiesSet.add(referencedAstEntity); + this.#analyzedReferencedAstEntitiesSet.add(referencedAstEntity); } /** @@ -220,15 +220,15 @@ export class AstDeclaration { // // return this.astSymbol.analyzed ? this._analyzedChildren : []; // - if (!this.astSymbol.analyzed || this._analyzedChildren.length === 0) { + if (!this.astSymbol.analyzed || this.#analyzedChildren.length === 0) { return []; } - if (this._childrenByName === undefined) { + if (this.#childrenByName === undefined) { // Build the lookup table const childrenByName: Map = new Map(); - for (const child of this._analyzedChildren) { + for (const child of this.#analyzedChildren) { const childName: string = child.astSymbol.localName; let array: AstDeclaration[] | undefined = childrenByName.get(childName); if (array === undefined) { @@ -237,10 +237,10 @@ export class AstDeclaration { } array.push(child); } - this._childrenByName = childrenByName; + this.#childrenByName = childrenByName; } - return this._childrenByName.get(name) || []; + return this.#childrenByName.get(name) || []; } /** diff --git a/apps/api-extractor/src/analyzer/AstReferenceResolver.ts b/apps/api-extractor/src/analyzer/AstReferenceResolver.ts index e51de2f1934..91aa924f69b 100644 --- a/apps/api-extractor/src/analyzer/AstReferenceResolver.ts +++ b/apps/api-extractor/src/analyzer/AstReferenceResolver.ts @@ -42,21 +42,21 @@ export class ResolverFailure { * which resolves declaration references by walking the hierarchy loaded from an .api.json file. */ export class AstReferenceResolver { - private readonly _collector: Collector; - private readonly _astSymbolTable: AstSymbolTable; - private readonly _workingPackage: WorkingPackage; + readonly #collector: Collector; + readonly #astSymbolTable: AstSymbolTable; + readonly #workingPackage: WorkingPackage; public constructor(collector: Collector) { - this._collector = collector; - this._astSymbolTable = collector.astSymbolTable; - this._workingPackage = collector.workingPackage; + this.#collector = collector; + this.#astSymbolTable = collector.astSymbolTable; + this.#workingPackage = collector.workingPackage; } public resolve(declarationReference: tsdoc.DocDeclarationReference): AstDeclaration | ResolverFailure { // Is it referring to the working package? if ( declarationReference.packageName !== undefined && - declarationReference.packageName !== this._workingPackage.name + declarationReference.packageName !== this.#workingPackage.name ) { return new ResolverFailure('External package references are not supported'); } @@ -66,8 +66,8 @@ export class AstReferenceResolver { return new ResolverFailure('Import paths are not supported'); } - const astModule: AstModule = this._astSymbolTable.fetchAstModuleFromWorkingPackage( - this._workingPackage.entryPointSourceFile + const astModule: AstModule = this.#astSymbolTable.fetchAstModuleFromWorkingPackage( + this.#workingPackage.entryPointSourceFile ); if (declarationReference.memberReferences.length === 0) { @@ -81,14 +81,14 @@ export class AstReferenceResolver { return exportName; } - const rootAstEntity: AstEntity | undefined = this._astSymbolTable.tryGetExportOfAstModule( + const rootAstEntity: AstEntity | undefined = this.#astSymbolTable.tryGetExportOfAstModule( exportName, astModule ); if (rootAstEntity === undefined) { return new ResolverFailure( - `The package "${this._workingPackage.name}" does not have an export "${exportName}"` + `The package "${this.#workingPackage.name}" does not have an export "${exportName}"` ); } @@ -250,7 +250,7 @@ export class AstReferenceResolver { const matches: AstDeclaration[] = []; for (const astDeclaration of astDeclarations) { - const overloadIndex: number = this._collector.getOverloadIndex(astDeclaration); + const overloadIndex: number = this.#collector.getOverloadIndex(astDeclaration); if (overloadIndex === selectorOverloadIndex) { matches.push(astDeclaration); } @@ -288,7 +288,7 @@ export class AstReferenceResolver { let result: AstDeclaration | undefined = undefined; for (const match of matches) { - const declarationMetadata: DeclarationMetadata = this._collector.fetchDeclarationMetadata(match); + const declarationMetadata: DeclarationMetadata = this.#collector.fetchDeclarationMetadata(match); if (!declarationMetadata.isAncillary) { if (result) { return undefined; // more than one match diff --git a/apps/api-extractor/src/analyzer/AstSymbol.ts b/apps/api-extractor/src/analyzer/AstSymbol.ts index fb34e28efc2..bc1e1a8d78b 100644 --- a/apps/api-extractor/src/analyzer/AstSymbol.ts +++ b/apps/api-extractor/src/analyzer/AstSymbol.ts @@ -108,11 +108,11 @@ export class AstSymbol extends AstEntity { */ public symbolMetadata: unknown; - private readonly _astDeclarations: AstDeclaration[]; + readonly #astDeclarations: AstDeclaration[]; // This flag is unused if this is not the root symbol. // Being "analyzed" is a property of the root symbol. - private _analyzed: boolean = false; + #analyzed: boolean = false; public constructor(options: IAstSymbolOptions) { super(); @@ -131,7 +131,7 @@ export class AstSymbol extends AstEntity { this.nominalAnalysis = nominalAnalysis; this.parentAstSymbol = parentAstSymbol; this.rootAstSymbol = rootAstSymbol; - this._astDeclarations = []; + this.#astDeclarations = []; } /** @@ -143,7 +143,7 @@ export class AstSymbol extends AstEntity { * declaration merging. */ public get astDeclarations(): ReadonlyArray { - return this._astDeclarations; + return this.#astDeclarations; } /** @@ -154,7 +154,7 @@ export class AstSymbol extends AstEntity { * returns true if-and-only-if the root symbol was analyzed. */ public get analyzed(): boolean { - return this.rootAstSymbol._analyzed; + return this.rootAstSymbol.#analyzed; } /** @@ -166,7 +166,7 @@ export class AstSymbol extends AstEntity { if (this.analyzed) { throw new InternalError('_notifyDeclarationAttach() called after analysis is already complete'); } - this._astDeclarations.push(astDeclaration); + this.#astDeclarations.push(astDeclaration); } /** @@ -178,7 +178,7 @@ export class AstSymbol extends AstEntity { if (this.parentAstSymbol) { throw new InternalError('_notifyAnalyzed() called for an AstSymbol which is not the root'); } - this._analyzed = true; + this.#analyzed = true; } /** diff --git a/apps/api-extractor/src/analyzer/AstSymbolTable.ts b/apps/api-extractor/src/analyzer/AstSymbolTable.ts index 1bfa982b578..6f48e5bb2aa 100644 --- a/apps/api-extractor/src/analyzer/AstSymbolTable.ts +++ b/apps/api-extractor/src/analyzer/AstSymbolTable.ts @@ -62,13 +62,13 @@ export interface IFetchAstSymbolOptions { * are declared (i.e. the AstImport information needed to import them). */ export class AstSymbolTable { - private readonly _program: ts.Program; - private readonly _typeChecker: ts.TypeChecker; - private readonly _messageRouter: MessageRouter; - private readonly _globalVariableAnalyzer: IGlobalVariableAnalyzer; - private readonly _packageMetadataManager: PackageMetadataManager; - private readonly _exportAnalyzer: ExportAnalyzer; - private readonly _alreadyWarnedGlobalNames: Set; + readonly #program: ts.Program; + readonly #typeChecker: ts.TypeChecker; + readonly #messageRouter: MessageRouter; + readonly #globalVariableAnalyzer: IGlobalVariableAnalyzer; + readonly #packageMetadataManager: PackageMetadataManager; + readonly #exportAnalyzer: ExportAnalyzer; + readonly #alreadyWarnedGlobalNames: Set; /** * A mapping from ts.Symbol --> AstSymbol @@ -77,19 +77,19 @@ export class AstSymbolTable { * * After following type aliases, we use this map to look up the corresponding AstSymbol. */ - private readonly _astSymbolsBySymbol: Map = new Map(); + readonly #astSymbolsBySymbol: Map = new Map(); /** * A mapping from ts.Declaration --> AstDeclaration */ - private readonly _astDeclarationsByDeclaration: Map = new Map< + readonly #astDeclarationsByDeclaration: Map = new Map< ts.Node, AstDeclaration >(); // Note that this is a mapping from specific AST nodes that we analyzed, based on the underlying symbol // for that node. - private readonly _entitiesByNode: Map = new Map< + readonly #entitiesByNode: Map = new Map< ts.Identifier, AstEntity | undefined >(); @@ -101,32 +101,32 @@ export class AstSymbolTable { bundledPackageNames: ReadonlySet, messageRouter: MessageRouter ) { - this._program = program; - this._typeChecker = typeChecker; - this._messageRouter = messageRouter; - this._globalVariableAnalyzer = TypeScriptInternals.getGlobalVariableAnalyzer(program); - this._packageMetadataManager = new PackageMetadataManager(packageJsonLookup, messageRouter); + this.#program = program; + this.#typeChecker = typeChecker; + this.#messageRouter = messageRouter; + this.#globalVariableAnalyzer = TypeScriptInternals.getGlobalVariableAnalyzer(program); + this.#packageMetadataManager = new PackageMetadataManager(packageJsonLookup, messageRouter); - this._exportAnalyzer = new ExportAnalyzer(this._program, this._typeChecker, bundledPackageNames, { + this.#exportAnalyzer = new ExportAnalyzer(this.#program, this.#typeChecker, bundledPackageNames, { analyze: this.analyze.bind(this), fetchAstSymbol: this._fetchAstSymbol.bind(this) }); - this._alreadyWarnedGlobalNames = new Set(); + this.#alreadyWarnedGlobalNames = new Set(); } /** * Used to analyze an entry point that belongs to the working package. */ public fetchAstModuleFromWorkingPackage(sourceFile: ts.SourceFile): AstModule { - return this._exportAnalyzer.fetchAstModuleFromSourceFile(sourceFile, undefined, false); + return this.#exportAnalyzer.fetchAstModuleFromSourceFile(sourceFile, undefined, false); } /** * This crawls the specified entry point and collects the full set of exported AstSymbols. */ public fetchAstModuleExportInfo(astModule: AstModule): IAstModuleExportInfo { - return this._exportAnalyzer.fetchAstModuleExportInfo(astModule); + return this.#exportAnalyzer.fetchAstModuleExportInfo(astModule); } /** @@ -134,7 +134,7 @@ export class AstSymbolTable { * Returns undefined if no match was found. */ public tryGetExportOfAstModule(exportName: string, astModule: AstModule): AstEntity | undefined { - return this._exportAnalyzer.tryGetExportOfAstModule(exportName, astModule); + return this.#exportAnalyzer.tryGetExportOfAstModule(exportName, astModule); } /** @@ -171,7 +171,7 @@ export class AstSymbolTable { throw new Error('getChildDeclarationByNode() cannot be used for an AstSymbol that was not analyzed'); } - const childAstDeclaration: AstDeclaration | undefined = this._astDeclarationsByDeclaration.get(node); + const childAstDeclaration: AstDeclaration | undefined = this.#astDeclarationsByDeclaration.get(node); if (!childAstDeclaration) { throw new Error('Child declaration not found for the specified node'); } @@ -189,10 +189,10 @@ export class AstSymbolTable { * Throws an Error if the ts.Identifier is not part of node tree that was analyzed. */ public tryGetEntityForNode(identifier: ts.Identifier | ts.ImportTypeNode): AstEntity | undefined { - if (!this._entitiesByNode.has(identifier)) { + if (!this.#entitiesByNode.has(identifier)) { throw new InternalError('tryGetEntityForIdentifier() called for an identifier that was not analyzed'); } - return this._entitiesByNode.get(identifier); + return this.#entitiesByNode.get(identifier); } /** @@ -361,9 +361,9 @@ export class AstSymbolTable { ); if (identifierNode) { - let referencedAstEntity: AstEntity | undefined = this._entitiesByNode.get(identifierNode); + let referencedAstEntity: AstEntity | undefined = this.#entitiesByNode.get(identifierNode); if (!referencedAstEntity) { - const symbol: ts.Symbol | undefined = this._typeChecker.getSymbolAtLocation(identifierNode); + const symbol: ts.Symbol | undefined = this.#typeChecker.getSymbolAtLocation(identifierNode); if (!symbol) { throw new Error('Symbol not found for identifier: ' + identifierNode.getText()); } @@ -384,17 +384,17 @@ export class AstSymbolTable { } if (displacedSymbol) { - if (this._globalVariableAnalyzer.hasGlobalName(identifierNode.text)) { + if (this.#globalVariableAnalyzer.hasGlobalName(identifierNode.text)) { // If the displaced symbol is a global variable, then API Extractor simply ignores it. // Ambient declarations typically describe the runtime environment (provided by an API consumer), // so we don't bother analyzing them as an API contract. (There are probably some packages // that include interesting global variables in their API, but API Extractor doesn't support // that yet; it would be a feature request.) - if (this._messageRouter.showDiagnostics) { - if (!this._alreadyWarnedGlobalNames.has(identifierNode.text)) { - this._alreadyWarnedGlobalNames.add(identifierNode.text); - this._messageRouter.logDiagnostic( + if (this.#messageRouter.showDiagnostics) { + if (!this.#alreadyWarnedGlobalNames.has(identifierNode.text)) { + this.#alreadyWarnedGlobalNames.add(identifierNode.text); + this.#messageRouter.logDiagnostic( `Ignoring reference to global variable "${identifierNode.text}"` + ` in ` + SourceFileLocationFormatter.formatDeclaration(identifierNode) @@ -407,12 +407,12 @@ export class AstSymbolTable { throw new InternalError(`Unable to follow symbol for "${identifierNode.text}"`); } } else { - referencedAstEntity = this._exportAnalyzer.fetchReferencedAstEntity( + referencedAstEntity = this.#exportAnalyzer.fetchReferencedAstEntity( symbol, governingAstDeclaration.astSymbol.isExternal ); - this._entitiesByNode.set(identifierNode, referencedAstEntity); + this.#entitiesByNode.set(identifierNode, referencedAstEntity); } } @@ -427,8 +427,8 @@ export class AstSymbolTable { case ts.SyntaxKind.Identifier: { const identifierNode: ts.Identifier = node as ts.Identifier; - if (!this._entitiesByNode.has(identifierNode)) { - const symbol: ts.Symbol | undefined = this._typeChecker.getSymbolAtLocation(identifierNode); + if (!this.#entitiesByNode.has(identifierNode)) { + const symbol: ts.Symbol | undefined = this.#typeChecker.getSymbolAtLocation(identifierNode); let referencedAstEntity: AstEntity | undefined = undefined; @@ -436,7 +436,7 @@ export class AstSymbolTable { referencedAstEntity = this._fetchEntityForNode(identifierNode, governingAstDeclaration); } - this._entitiesByNode.set(identifierNode, referencedAstEntity); + this.#entitiesByNode.set(identifierNode, referencedAstEntity); } } break; @@ -444,9 +444,9 @@ export class AstSymbolTable { case ts.SyntaxKind.ImportType: { const importTypeNode: ts.ImportTypeNode = node as ts.ImportTypeNode; - let referencedAstEntity: AstEntity | undefined = this._entitiesByNode.get(importTypeNode); + let referencedAstEntity: AstEntity | undefined = this.#entitiesByNode.get(importTypeNode); - if (!this._entitiesByNode.has(importTypeNode)) { + if (!this.#entitiesByNode.has(importTypeNode)) { referencedAstEntity = this._fetchEntityForNode(importTypeNode, governingAstDeclaration); if (!referencedAstEntity) { @@ -454,7 +454,7 @@ export class AstSymbolTable { throw new Error('Failed to fetch entity for import() type node: ' + importTypeNode.getText()); } - this._entitiesByNode.set(importTypeNode, referencedAstEntity); + this.#entitiesByNode.set(importTypeNode, referencedAstEntity); } if (referencedAstEntity) { @@ -479,26 +479,26 @@ export class AstSymbolTable { node: ts.Identifier | ts.ImportTypeNode, governingAstDeclaration: AstDeclaration ): AstEntity | undefined { - let referencedAstEntity: AstEntity | undefined = this._entitiesByNode.get(node); + let referencedAstEntity: AstEntity | undefined = this.#entitiesByNode.get(node); if (!referencedAstEntity) { if (node.kind === ts.SyntaxKind.ImportType) { - referencedAstEntity = this._exportAnalyzer.fetchReferencedAstEntityFromImportTypeNode( + referencedAstEntity = this.#exportAnalyzer.fetchReferencedAstEntityFromImportTypeNode( node, governingAstDeclaration.astSymbol.isExternal ); } else { - const symbol: ts.Symbol | undefined = this._typeChecker.getSymbolAtLocation(node); + const symbol: ts.Symbol | undefined = this.#typeChecker.getSymbolAtLocation(node); if (!symbol) { throw new Error('Symbol not found for identifier: ' + node.getText()); } - referencedAstEntity = this._exportAnalyzer.fetchReferencedAstEntity( + referencedAstEntity = this.#exportAnalyzer.fetchReferencedAstEntity( symbol, governingAstDeclaration.astSymbol.isExternal ); } - this._entitiesByNode.set(node, referencedAstEntity); + this.#entitiesByNode.set(node, referencedAstEntity); } return referencedAstEntity; } @@ -510,7 +510,7 @@ export class AstSymbolTable { const symbol: ts.Symbol | undefined = TypeScriptHelpers.getSymbolForDeclaration( node as ts.Declaration, - this._typeChecker + this.#typeChecker ); if (!symbol) { throw new InternalError('Unable to find symbol for node'); @@ -527,7 +527,7 @@ export class AstSymbolTable { return undefined; } - const astDeclaration: AstDeclaration | undefined = this._astDeclarationsByDeclaration.get(node); + const astDeclaration: AstDeclaration | undefined = this.#astDeclarationsByDeclaration.get(node); if (!astDeclaration) { throw new InternalError('Unable to find constructed AstDeclaration'); @@ -556,21 +556,21 @@ export class AstSymbolTable { } // API Extractor doesn't analyze ambient declarations at all - if (TypeScriptHelpers.isAmbient(followedSymbol, this._typeChecker)) { + if (TypeScriptHelpers.isAmbient(followedSymbol, this.#typeChecker)) { // We make a special exemption for ambient declarations that appear in a source file containing // an "export=" declaration that allows them to be imported as non-ambient. - if (!this._exportAnalyzer.isImportableAmbientSourceFile(arbitraryDeclaration.getSourceFile())) { + if (!this.#exportAnalyzer.isImportableAmbientSourceFile(arbitraryDeclaration.getSourceFile())) { return undefined; } } // Make sure followedSymbol isn't an alias for something else - if (TypeScriptHelpers.isFollowableAlias(followedSymbol, this._typeChecker)) { + if (TypeScriptHelpers.isFollowableAlias(followedSymbol, this.#typeChecker)) { // We expect the caller to have already followed any aliases throw new InternalError('AstSymbolTable._fetchAstSymbol() cannot be called with a symbol alias'); } - let astSymbol: AstSymbol | undefined = this._astSymbolsBySymbol.get(followedSymbol); + let astSymbol: AstSymbol | undefined = this.#astSymbolsBySymbol.get(followedSymbol); if (!astSymbol) { // None of the above lookups worked, so create a new entry... @@ -582,7 +582,7 @@ export class AstSymbolTable { // represent it, but we don't need to analyze its sibling/children. const followedSymbolSourceFileName: string = arbitraryDeclaration.getSourceFile().fileName; - if (!this._packageMetadataManager.isAedocSupportedFor(followedSymbolSourceFileName)) { + if (!this.#packageMetadataManager.isAedocSupportedFor(followedSymbolSourceFileName)) { nominalAnalysis = true; if (!options.includeNominalAnalysis) { @@ -623,7 +623,7 @@ export class AstSymbolTable { if (arbitraryParentDeclaration) { const parentSymbol: ts.Symbol = TypeScriptHelpers.getSymbolForDeclaration( arbitraryParentDeclaration as ts.Declaration, - this._typeChecker + this.#typeChecker ); parentAstSymbol = this._fetchAstSymbol({ @@ -651,7 +651,7 @@ export class AstSymbolTable { rootAstSymbol: parentAstSymbol ? parentAstSymbol.rootAstSymbol : undefined }); - this._astSymbolsBySymbol.set(followedSymbol, astSymbol); + this.#astSymbolsBySymbol.set(followedSymbol, astSymbol); // Okay, now while creating the declarations we will wire them up to the // their corresponding parent declarations @@ -664,7 +664,7 @@ export class AstSymbolTable { throw new InternalError('Missing parent declaration'); } - parentAstDeclaration = this._astDeclarationsByDeclaration.get(parentDeclaration); + parentAstDeclaration = this.#astDeclarationsByDeclaration.get(parentDeclaration); if (!parentAstDeclaration) { throw new InternalError('Missing parent AstDeclaration'); } @@ -676,7 +676,7 @@ export class AstSymbolTable { parent: parentAstDeclaration }); - this._astDeclarationsByDeclaration.set(declaration, astDeclaration); + this.#astDeclarationsByDeclaration.set(declaration, astDeclaration); } } diff --git a/apps/api-extractor/src/analyzer/ExportAnalyzer.ts b/apps/api-extractor/src/analyzer/ExportAnalyzer.ts index 6870d3a1954..2d92e1c32c6 100644 --- a/apps/api-extractor/src/analyzer/ExportAnalyzer.ts +++ b/apps/api-extractor/src/analyzer/ExportAnalyzer.ts @@ -58,18 +58,18 @@ interface IAstModuleReference { * generating .d.ts rollups. */ export class ExportAnalyzer { - private readonly _program: ts.Program; - private readonly _typeChecker: ts.TypeChecker; - private readonly _bundledPackageNames: ReadonlySet; - private readonly _astSymbolTable: IAstSymbolTable; + readonly #program: ts.Program; + readonly #typeChecker: ts.TypeChecker; + readonly #bundledPackageNames: ReadonlySet; + readonly #astSymbolTable: IAstSymbolTable; - private readonly _astModulesByModuleSymbol: Map = new Map(); + readonly #astModulesByModuleSymbol: Map = new Map(); // Used with isImportableAmbientSourceFile() - private readonly _importableAmbientSourceFiles: Set = new Set(); + readonly #importableAmbientSourceFiles: Set = new Set(); - private readonly _astImportsByKey: Map = new Map(); - private readonly _astNamespaceImportByModule: Map = new Map(); + readonly #astImportsByKey: Map = new Map(); + readonly #astNamespaceImportByModule: Map = new Map(); public constructor( program: ts.Program, @@ -77,10 +77,10 @@ export class ExportAnalyzer { bundledPackageNames: ReadonlySet, astSymbolTable: IAstSymbolTable ) { - this._program = program; - this._typeChecker = typeChecker; - this._bundledPackageNames = bundledPackageNames; - this._astSymbolTable = astSymbolTable; + this.#program = program; + this.#typeChecker = typeChecker; + this.#bundledPackageNames = bundledPackageNames; + this.#astSymbolTable = astSymbolTable; } /** @@ -100,7 +100,7 @@ export class ExportAnalyzer { // Don't traverse into a module that we already processed before: // The compiler allows m1 to have "export * from 'm2'" and "export * from 'm3'", // even if m2 and m3 both have "export * from 'm4'". - let astModule: AstModule | undefined = this._astModulesByModuleSymbol.get(moduleSymbol); + let astModule: AstModule | undefined = this.#astModulesByModuleSymbol.get(moduleSymbol); if (!astModule) { // (If moduleReference === undefined, then this is the entry point of the local project being analyzed.) const externalModulePath: string | undefined = @@ -108,11 +108,11 @@ export class ExportAnalyzer { astModule = new AstModule({ sourceFile, moduleSymbol, externalModulePath }); - this._astModulesByModuleSymbol.set(moduleSymbol, astModule); + this.#astModulesByModuleSymbol.set(moduleSymbol, astModule); if (astModule.isExternal) { // It's an external package, so do the special simplified analysis that doesn't crawl into referenced modules - for (const exportedSymbol of this._typeChecker.getExportsOfModule(moduleSymbol)) { + for (const exportedSymbol of this.#typeChecker.getExportsOfModule(moduleSymbol)) { if (externalModulePath === undefined) { throw new InternalError( 'Failed assertion: externalModulePath=undefined but astModule.isExternal=true' @@ -121,14 +121,14 @@ export class ExportAnalyzer { const followedSymbol: ts.Symbol = TypeScriptHelpers.followAliases( exportedSymbol, - this._typeChecker + this.#typeChecker ); // Ignore virtual symbols that don't have any declarations const arbitraryDeclaration: ts.Declaration | undefined = TypeScriptHelpers.tryGetADeclaration(followedSymbol); if (arbitraryDeclaration) { - const astSymbol: AstSymbol | undefined = this._astSymbolTable.fetchAstSymbol({ + const astSymbol: AstSymbol | undefined = this.#astSymbolTable.fetchAstSymbol({ followedSymbol: followedSymbol, isExternal: astModule.isExternal, includeNominalAnalysis: true, @@ -192,7 +192,7 @@ export class ExportAnalyzer { ): ts.Symbol { const moduleSymbol: ts.Symbol | undefined = TypeScriptInternals.tryGetSymbolForDeclaration( sourceFile, - this._typeChecker + this.#typeChecker ); if (moduleSymbol !== undefined) { // This is the normal case. The SourceFile acts is a module and has a symbol. @@ -208,12 +208,12 @@ export class ExportAnalyzer { // Follow the import/export declaration to one hop the exported item inside the target module let followedSymbol: ts.Symbol | undefined = TypeScriptInternals.getImmediateAliasedSymbol( moduleReference.moduleSpecifierSymbol, - this._typeChecker + this.#typeChecker ); if (followedSymbol === undefined) { // This is a workaround for a compiler bug where getImmediateAliasedSymbol() sometimes returns undefined - followedSymbol = this._typeChecker.getAliasedSymbol(moduleReference.moduleSpecifierSymbol); + followedSymbol = this.#typeChecker.getAliasedSymbol(moduleReference.moduleSpecifierSymbol); } if (followedSymbol !== undefined && followedSymbol !== moduleReference.moduleSpecifierSymbol) { @@ -224,7 +224,7 @@ export class ExportAnalyzer { // eslint-disable-next-line no-bitwise if ((parent.flags & ts.SymbolFlags.ValueModule) !== 0) { // Record that that this is an ambient module that can also be imported from - this._importableAmbientSourceFiles.add(sourceFile); + this.#importableAmbientSourceFiles.add(sourceFile); return parent; } } @@ -276,12 +276,12 @@ export class ExportAnalyzer { ? TypeScriptInternals.getModeForUsageLocation( importOrExportDeclaration.getSourceFile(), specifier, - this._program.getCompilerOptions() + this.#program.getCompilerOptions() ) : undefined; const resolvedModule: ts.ResolvedModuleFull | undefined = TypeScriptInternals.getResolvedModule( - this._program, + this.#program, importOrExportDeclaration.getSourceFile(), moduleSpecifier, mode @@ -296,7 +296,7 @@ export class ExportAnalyzer { // Either something like `jquery` or `@microsoft/api-extractor`. const packageName: string | undefined = resolvedModule.packageId?.name; - if (packageName !== undefined && this._bundledPackageNames.has(packageName)) { + if (packageName !== undefined && this.#bundledPackageNames.has(packageName)) { return false; } @@ -319,7 +319,7 @@ export class ExportAnalyzer { * returns true. */ public isImportableAmbientSourceFile(sourceFile: ts.SourceFile): boolean { - return this._importableAmbientSourceFiles.has(sourceFile); + return this.#importableAmbientSourceFiles.has(sourceFile); } private _collectAllExportsRecursive(astModuleExportInfo: IAstModuleExportInfo, astModule: AstModule): void { @@ -346,11 +346,11 @@ export class ExportAnalyzer { const astEntity: AstEntity = this._getExportOfAstModule(exportSymbol.name, astModule); if (astEntity instanceof AstSymbol && !astEntity.isExternal) { - this._astSymbolTable.analyze(astEntity); + this.#astSymbolTable.analyze(astEntity); } if (astEntity instanceof AstNamespaceImport && !astEntity.astModule.isExternal) { - this._astSymbolTable.analyze(astEntity); + this.#astSymbolTable.analyze(astEntity); } exportedLocalEntities.set(exportSymbol.name, astEntity); @@ -390,7 +390,7 @@ export class ExportAnalyzer { let current: ts.Symbol = symbol; if (referringModuleIsExternal) { - current = TypeScriptHelpers.followAliases(symbol, this._typeChecker); + current = TypeScriptHelpers.followAliases(symbol, this.#typeChecker); } else { for (;;) { // Is this symbol an import/export that we need to follow to find the real declaration? @@ -413,7 +413,7 @@ export class ExportAnalyzer { const currentAlias: ts.Symbol = TypeScriptInternals.getImmediateAliasedSymbol( current, - this._typeChecker + this.#typeChecker ); // Stop if we reach the end of the chain if (!currentAlias || currentAlias === current) { @@ -425,7 +425,7 @@ export class ExportAnalyzer { } // Otherwise, assume it is a normal declaration - const astSymbol: AstSymbol | undefined = this._astSymbolTable.fetchAstSymbol({ + const astSymbol: AstSymbol | undefined = this.#astSymbolTable.fetchAstSymbol({ followedSymbol: current, isExternal: referringModuleIsExternal, includeNominalAnalysis: false, @@ -476,7 +476,7 @@ export class ExportAnalyzer { : node; // There is no symbol property in a ImportTypeNode, obtain the associated export symbol - const exportSymbol: ts.Symbol | undefined = this._typeChecker.getSymbolAtLocation(rightMostToken); + const exportSymbol: ts.Symbol | undefined = this.#typeChecker.getSymbolAtLocation(rightMostToken); if (!exportSymbol) { throw new InternalError( `Symbol not found for identifier: ${node.getText()}\n` + @@ -510,7 +510,7 @@ export class ExportAnalyzer { break; } - const currentAlias: ts.Symbol = this._typeChecker.getAliasedSymbol(followedSymbol); + const currentAlias: ts.Symbol = this.#typeChecker.getAliasedSymbol(followedSymbol); if (!currentAlias || currentAlias === followedSymbol) { break; } @@ -518,7 +518,7 @@ export class ExportAnalyzer { followedSymbol = currentAlias; } - const astSymbol: AstSymbol | undefined = this._astSymbolTable.fetchAstSymbol({ + const astSymbol: AstSymbol | undefined = this.#astSymbolTable.fetchAstSymbol({ followedSymbol: followedSymbol, isExternal: referringModuleIsExternal, includeNominalAnalysis: false, @@ -780,7 +780,7 @@ export class ExportAnalyzer { declarationSymbol: ts.Symbol, declaration: ts.Declaration ): AstNamespaceImport { - let namespaceImport: AstNamespaceImport | undefined = this._astNamespaceImportByModule.get(astModule); + let namespaceImport: AstNamespaceImport | undefined = this.#astNamespaceImportByModule.get(astModule); if (namespaceImport === undefined) { namespaceImport = new AstNamespaceImport({ namespaceName: declarationSymbol.name, @@ -788,7 +788,7 @@ export class ExportAnalyzer { declaration: declaration, symbol: declarationSymbol }); - this._astNamespaceImportByModule.set(astModule, namespaceImport); + this.#astNamespaceImportByModule.set(astModule, namespaceImport); } return namespaceImport; @@ -908,11 +908,11 @@ export class ExportAnalyzer { ? TypeScriptInternals.getModeForUsageLocation( importOrExportDeclaration.getSourceFile(), importOrExportDeclaration.moduleSpecifier, - this._program.getCompilerOptions() + this.#program.getCompilerOptions() ) : undefined; const resolvedModule: ts.ResolvedModuleFull | undefined = TypeScriptInternals.getResolvedModule( - this._program, + this.#program, importOrExportDeclaration.getSourceFile(), moduleSpecifier, mode @@ -932,7 +932,7 @@ export class ExportAnalyzer { // Map the filename back to the corresponding SourceFile. This circuitous approach is needed because // we have no way to access the compiler's internal resolveExternalModuleName() function - const moduleSourceFile: ts.SourceFile | undefined = this._program.getSourceFile( + const moduleSourceFile: ts.SourceFile | undefined = this.#program.getSourceFile( resolvedModule.resolvedFileName ); if (!moduleSourceFile) { @@ -961,16 +961,16 @@ export class ExportAnalyzer { private _fetchAstImport(importSymbol: ts.Symbol | undefined, options: IAstImportOptions): AstImport { const key: string = AstImport.getKey(options); - let astImport: AstImport | undefined = this._astImportsByKey.get(key); + let astImport: AstImport | undefined = this.#astImportsByKey.get(key); if (!astImport) { astImport = new AstImport(options); - this._astImportsByKey.set(key, astImport); + this.#astImportsByKey.set(key, astImport); if (importSymbol) { - const followedSymbol: ts.Symbol = TypeScriptHelpers.followAliases(importSymbol, this._typeChecker); + const followedSymbol: ts.Symbol = TypeScriptHelpers.followAliases(importSymbol, this.#typeChecker); - astImport.astSymbol = this._astSymbolTable.fetchAstSymbol({ + astImport.astSymbol = this.#astSymbolTable.fetchAstSymbol({ followedSymbol: followedSymbol, isExternal: true, includeNominalAnalysis: false, diff --git a/apps/api-extractor/src/analyzer/PackageMetadataManager.ts b/apps/api-extractor/src/analyzer/PackageMetadataManager.ts index a007664d3c4..9acd6f05f8a 100644 --- a/apps/api-extractor/src/analyzer/PackageMetadataManager.ts +++ b/apps/api-extractor/src/analyzer/PackageMetadataManager.ts @@ -217,16 +217,16 @@ function _resolveTsdocMetadataPathFromPackageJson( export class PackageMetadataManager { public static tsdocMetadataFilename: string = TSDOC_METADATA_FILENAME; - private readonly _packageJsonLookup: PackageJsonLookup; - private readonly _messageRouter: MessageRouter; - private readonly _packageMetadataByPackageJsonPath: Map = new Map< + readonly #packageJsonLookup: PackageJsonLookup; + readonly #messageRouter: MessageRouter; + readonly #packageMetadataByPackageJsonPath: Map = new Map< string, PackageMetadata >(); public constructor(packageJsonLookup: PackageJsonLookup, messageRouter: MessageRouter) { - this._packageJsonLookup = packageJsonLookup; - this._messageRouter = messageRouter; + this.#packageJsonLookup = packageJsonLookup; + this.#messageRouter = messageRouter; } /** @@ -278,15 +278,15 @@ export class PackageMetadataManager { */ public tryFetchPackageMetadata(sourceFilePath: string): PackageMetadata | undefined { const packageJsonFilePath: string | undefined = - this._packageJsonLookup.tryGetPackageJsonFilePathFor(sourceFilePath); + this.#packageJsonLookup.tryGetPackageJsonFilePathFor(sourceFilePath); if (!packageJsonFilePath) { return undefined; } let packageMetadata: PackageMetadata | undefined = - this._packageMetadataByPackageJsonPath.get(packageJsonFilePath); + this.#packageMetadataByPackageJsonPath.get(packageJsonFilePath); if (!packageMetadata) { - const packageJson: INodePackageJson = this._packageJsonLookup.loadNodePackageJson(packageJsonFilePath); + const packageJson: INodePackageJson = this.#packageJsonLookup.loadNodePackageJson(packageJsonFilePath); const packageJsonFolder: string = path.dirname(packageJsonFilePath); @@ -298,7 +298,7 @@ export class PackageMetadataManager { ); if (FileSystem.exists(tsdocMetadataPath)) { - this._messageRouter.logVerbose( + this.#messageRouter.logVerbose( ConsoleMessageId.FoundTSDocMetadata, 'Found metadata in ' + tsdocMetadataPath ); @@ -307,7 +307,7 @@ export class PackageMetadataManager { } packageMetadata = new PackageMetadata(packageJsonFilePath, packageJson, aedocSupported); - this._packageMetadataByPackageJsonPath.set(packageJsonFilePath, packageMetadata); + this.#packageMetadataByPackageJsonPath.set(packageJsonFilePath, packageMetadata); } return packageMetadata; diff --git a/apps/api-extractor/src/analyzer/Span.ts b/apps/api-extractor/src/analyzer/Span.ts index e4d1f2970ab..d033c62829c 100644 --- a/apps/api-extractor/src/analyzer/Span.ts +++ b/apps/api-extractor/src/analyzer/Span.ts @@ -95,12 +95,12 @@ export class SpanModification { */ public indentDocComment: IndentDocCommentScope = IndentDocCommentScope.None; - private readonly _span: Span; - private _prefix: string | undefined; - private _suffix: string | undefined; + readonly #span: Span; + #prefix: string | undefined; + #suffix: string | undefined; public constructor(span: Span) { - this._span = span; + this.#span = span; this.reset(); } @@ -108,22 +108,22 @@ export class SpanModification { * Allows the Span.prefix text to be changed. */ public get prefix(): string { - return this._prefix !== undefined ? this._prefix : this._span.prefix; + return this.#prefix !== undefined ? this.#prefix : this.#span.prefix; } public set prefix(value: string) { - this._prefix = value; + this.#prefix = value; } /** * Allows the Span.suffix text to be changed. */ public get suffix(): string { - return this._suffix !== undefined ? this._suffix : this._span.suffix; + return this.#suffix !== undefined ? this.#suffix : this.#span.suffix; } public set suffix(value: string) { - this._suffix = value; + this.#suffix = value; } /** @@ -134,9 +134,9 @@ export class SpanModification { this.omitSeparatorAfter = false; this.sortChildren = false; this.sortKey = undefined; - this._prefix = undefined; - this._suffix = undefined; - if (this._span.kind === ts.SyntaxKind.JSDocComment) { + this.#prefix = undefined; + this.#suffix = undefined; + if (this.#span.kind === ts.SyntaxKind.JSDocComment) { this.indentDocComment = IndentDocCommentScope.SpanAndChildren; } } @@ -189,19 +189,19 @@ export class Span { public readonly modification: SpanModification; - private _parent: Span | undefined; - private _previousSibling: Span | undefined; - private _nextSibling: Span | undefined; + #parent: Span | undefined; + #previousSibling: Span | undefined; + #nextSibling: Span | undefined; - private _separatorStartIndex: number; - private _separatorEndIndex: number; + #separatorStartIndex: number; + #separatorEndIndex: number; public constructor(node: ts.Node) { this.node = node; this.startIndex = node.kind === ts.SyntaxKind.SourceFile ? node.getFullStart() : node.getStart(); this.endIndex = node.end; - this._separatorStartIndex = 0; - this._separatorEndIndex = 0; + this.#separatorStartIndex = 0; + this.#separatorEndIndex = 0; this.children = []; this.modification = new SpanModification(this); @@ -209,11 +209,11 @@ export class Span { for (const childNode of this.node.getChildren() || []) { const childSpan: Span = new Span(childNode); - childSpan._parent = this; - childSpan._previousSibling = previousChildSpan; + childSpan.#parent = this; + childSpan.#previousSibling = previousChildSpan; if (previousChildSpan) { - previousChildSpan._nextSibling = childSpan; + previousChildSpan.#nextSibling = childSpan; } this.children.push(childSpan); @@ -245,8 +245,8 @@ export class Span { } separatorRecipient = lastChild; } - separatorRecipient._separatorStartIndex = previousChildSpan.endIndex; - separatorRecipient._separatorEndIndex = childSpan.startIndex; + separatorRecipient.#separatorStartIndex = previousChildSpan.endIndex; + separatorRecipient.#separatorEndIndex = childSpan.startIndex; } } @@ -264,7 +264,7 @@ export class Span { * may have a parent in the AST. */ public get parent(): Span | undefined { - return this._parent; + return this.#parent; } /** @@ -274,7 +274,7 @@ export class Span { * may have a previous sibling in the AST. */ public get previousSibling(): Span | undefined { - return this._previousSibling; + return this.#previousSibling; } /** @@ -284,7 +284,7 @@ export class Span { * may have a previous sibling in the AST. */ public get nextSibling(): Span | undefined { - return this._nextSibling; + return this.#nextSibling; } /** @@ -317,7 +317,7 @@ export class Span { * Here we mean "next" according to an inorder traversal, not necessarily a sibling. */ public get separator(): string { - return this._getSubstring(this._separatorStartIndex, this._separatorEndIndex); + return this._getSubstring(this.#separatorStartIndex, this.#separatorEndIndex); } /** diff --git a/apps/api-extractor/src/api/ExtractorMessage.ts b/apps/api-extractor/src/api/ExtractorMessage.ts index 60e9e95e274..55c627b4fe9 100644 --- a/apps/api-extractor/src/api/ExtractorMessage.ts +++ b/apps/api-extractor/src/api/ExtractorMessage.ts @@ -88,8 +88,8 @@ export interface IExtractorMessageOptions { * @public */ export class ExtractorMessage { - private _handled: boolean; - private _logLevel: ExtractorLogLevel; + #handled: boolean; + #logLevel: ExtractorLogLevel; /** * The category of issue. @@ -150,8 +150,8 @@ export class ExtractorMessage { this.sourceFileColumn = sourceFileColumn; this.properties = properties; - this._handled = false; - this._logLevel = logLevel; + this.#handled = false; + this.#logLevel = logLevel; } /** @@ -167,16 +167,16 @@ export class ExtractorMessage { * to discard a message entirely, instead assign `logLevel = none`. */ public get handled(): boolean { - return this._handled; + return this.#handled; } public set handled(value: boolean) { - if (this._handled && !value) { + if (this.#handled && !value) { throw new Error( 'One a message has been marked as handled, the "handled" property cannot be set to false' ); } - this._handled = value; + this.#handled = value; } /** @@ -193,7 +193,7 @@ export class ExtractorMessage { * To discard a message entirely, assign `logLevel = none`. */ public get logLevel(): ExtractorLogLevel { - return this._logLevel; + return this.#logLevel; } public set logLevel(value: ExtractorLogLevel) { @@ -207,7 +207,7 @@ export class ExtractorMessage { default: throw new Error('Invalid log level'); } - this._logLevel = value; + this.#logLevel = value; } /** diff --git a/apps/api-extractor/src/cli/ApiExtractorCommandLine.ts b/apps/api-extractor/src/cli/ApiExtractorCommandLine.ts index 2c434e32cec..8142d5166b1 100644 --- a/apps/api-extractor/src/cli/ApiExtractorCommandLine.ts +++ b/apps/api-extractor/src/cli/ApiExtractorCommandLine.ts @@ -11,7 +11,7 @@ import { RunAction } from './RunAction'; import { InitAction } from './InitAction'; export class ApiExtractorCommandLine extends CommandLineParser { - private readonly _debugParameter: CommandLineFlagParameter; + readonly #debugParameter: CommandLineFlagParameter; public constructor() { super({ @@ -25,7 +25,7 @@ export class ApiExtractorCommandLine extends CommandLineParser { }); this._populateActions(); - this._debugParameter = this.defineFlagParameter({ + this.#debugParameter = this.defineFlagParameter({ parameterLongName: '--debug', parameterShortName: '-d', description: 'Show the full call stack if an error occurs while executing the tool' @@ -33,7 +33,7 @@ export class ApiExtractorCommandLine extends CommandLineParser { } protected override async onExecuteAsync(): Promise { - if (this._debugParameter.value) { + if (this.#debugParameter.value) { InternalError.breakInDebugger = true; } @@ -43,7 +43,7 @@ export class ApiExtractorCommandLine extends CommandLineParser { process.exitCode = 0; } catch (error) { if (!(error instanceof AlreadyReportedError)) { - if (this._debugParameter.value) { + if (this.#debugParameter.value) { console.error(os.EOL + error.stack); } else { console.error(os.EOL + Colorize.red('ERROR: ' + error.message.trim())); diff --git a/apps/api-extractor/src/cli/RunAction.ts b/apps/api-extractor/src/cli/RunAction.ts index d0e60bb9326..407cb43cebb 100644 --- a/apps/api-extractor/src/cli/RunAction.ts +++ b/apps/api-extractor/src/cli/RunAction.ts @@ -23,12 +23,12 @@ import type { ApiExtractorCommandLine } from './ApiExtractorCommandLine'; import { ExtractorConfig, type IExtractorConfigPrepareOptions } from '../api/ExtractorConfig'; export class RunAction extends CommandLineAction { - private readonly _configFileParameter: CommandLineStringParameter; - private readonly _localFlag: CommandLineFlagParameter; - private readonly _verboseFlag: CommandLineFlagParameter; - private readonly _diagnosticsParameter: CommandLineFlagParameter; - private readonly _typescriptCompilerFolderParameter: CommandLineStringParameter; - private readonly _printApiReportDiffFlag: CommandLineFlagParameter; + readonly #configFileParameter: CommandLineStringParameter; + readonly #localFlag: CommandLineFlagParameter; + readonly #verboseFlag: CommandLineFlagParameter; + readonly #diagnosticsParameter: CommandLineFlagParameter; + readonly #typescriptCompilerFolderParameter: CommandLineStringParameter; + readonly #printApiReportDiffFlag: CommandLineFlagParameter; public constructor(parser: ApiExtractorCommandLine) { super({ @@ -37,14 +37,14 @@ export class RunAction extends CommandLineAction { documentation: 'Invoke API Extractor on a project' }); - this._configFileParameter = this.defineStringParameter({ + this.#configFileParameter = this.defineStringParameter({ parameterLongName: '--config', parameterShortName: '-c', argumentName: 'FILE', description: `Use the specified ${ExtractorConfig.FILENAME} file path, rather than guessing its location` }); - this._localFlag = this.defineFlagParameter({ + this.#localFlag = this.defineFlagParameter({ parameterLongName: '--local', parameterShortName: '-l', description: @@ -54,20 +54,20 @@ export class RunAction extends CommandLineAction { ' report file is automatically copied in a local build.' }); - this._verboseFlag = this.defineFlagParameter({ + this.#verboseFlag = this.defineFlagParameter({ parameterLongName: '--verbose', parameterShortName: '-v', description: 'Show additional informational messages in the output.' }); - this._diagnosticsParameter = this.defineFlagParameter({ + this.#diagnosticsParameter = this.defineFlagParameter({ parameterLongName: '--diagnostics', description: 'Show diagnostic messages used for troubleshooting problems with API Extractor.' + ' This flag also enables the "--verbose" flag.' }); - this._typescriptCompilerFolderParameter = this.defineStringParameter({ + this.#typescriptCompilerFolderParameter = this.defineStringParameter({ parameterLongName: '--typescript-compiler-folder', argumentName: 'PATH', description: @@ -78,7 +78,7 @@ export class RunAction extends CommandLineAction { " and API Extractor's compiler will use those system typings instead." }); - this._printApiReportDiffFlag = this.defineFlagParameter({ + this.#printApiReportDiffFlag = this.defineFlagParameter({ parameterLongName: '--print-api-report-diff', description: 'If provided, then any differences between the actual and expected API reports will be ' + @@ -91,7 +91,7 @@ export class RunAction extends CommandLineAction { const lookup: PackageJsonLookup = new PackageJsonLookup(); let configFilename: string; - let typescriptCompilerFolder: string | undefined = this._typescriptCompilerFolderParameter.value; + let typescriptCompilerFolder: string | undefined = this.#typescriptCompilerFolderParameter.value; if (typescriptCompilerFolder) { typescriptCompilerFolder = path.normalize(typescriptCompilerFolder); @@ -102,27 +102,27 @@ export class RunAction extends CommandLineAction { : undefined; if (!typescriptCompilerPackageJson) { throw new Error( - `The path specified in the ${this._typescriptCompilerFolderParameter.longName} parameter is not a package.` + `The path specified in the ${this.#typescriptCompilerFolderParameter.longName} parameter is not a package.` ); } else if (typescriptCompilerPackageJson.name !== 'typescript') { throw new Error( - `The path specified in the ${this._typescriptCompilerFolderParameter.longName} parameter is not a TypeScript` + + `The path specified in the ${this.#typescriptCompilerFolderParameter.longName} parameter is not a TypeScript` + ' compiler package.' ); } } else { throw new Error( - `The path specified in the ${this._typescriptCompilerFolderParameter.longName} parameter does not exist.` + `The path specified in the ${this.#typescriptCompilerFolderParameter.longName} parameter does not exist.` ); } } let extractorConfig: ExtractorConfig; - if (this._configFileParameter.value) { - configFilename = path.normalize(this._configFileParameter.value); + if (this.#configFileParameter.value) { + configFilename = path.normalize(this.#configFileParameter.value); if (!FileSystem.exists(configFilename)) { - throw new Error('Config file not found: ' + this._configFileParameter.value); + throw new Error('Config file not found: ' + this.#configFileParameter.value); } extractorConfig = ExtractorConfig.loadFileAndPrepare(configFilename); @@ -145,11 +145,11 @@ export class RunAction extends CommandLineAction { } const extractorResult: ExtractorResult = Extractor.invoke(extractorConfig, { - localBuild: this._localFlag.value, - showVerboseMessages: this._verboseFlag.value, - showDiagnostics: this._diagnosticsParameter.value, + localBuild: this.#localFlag.value, + showVerboseMessages: this.#verboseFlag.value, + showDiagnostics: this.#diagnosticsParameter.value, typescriptCompilerFolder: typescriptCompilerFolder, - printApiReportDiff: this._printApiReportDiffFlag.value + printApiReportDiff: this.#printApiReportDiffFlag.value }); if (extractorResult.succeeded) { diff --git a/apps/api-extractor/src/collector/Collector.ts b/apps/api-extractor/src/collector/Collector.ts index 2e6a374f11d..25e9dbe4d82 100644 --- a/apps/api-extractor/src/collector/Collector.ts +++ b/apps/api-extractor/src/collector/Collector.ts @@ -83,32 +83,32 @@ export class Collector { */ public readonly bundledPackageNames: ReadonlySet; - private readonly _program: ts.Program; + readonly #program: ts.Program; - private readonly _tsdocParser: tsdoc.TSDocParser; + readonly #tsdocParser: tsdoc.TSDocParser; - private _astEntryPoint: AstModule | undefined; + #astEntryPoint: AstModule | undefined; - private readonly _entities: CollectorEntity[] = []; - private readonly _entitiesByAstEntity: Map = new Map< + readonly #entities: CollectorEntity[] = []; + readonly #entitiesByAstEntity: Map = new Map< AstEntity, CollectorEntity >(); - private readonly _entitiesBySymbol: Map = new Map(); + readonly #entitiesBySymbol: Map = new Map(); - private readonly _starExportedExternalModulePaths: string[] = []; + readonly #starExportedExternalModulePaths: string[] = []; - private readonly _dtsTypeReferenceDirectives: Set = new Set(); - private readonly _dtsLibReferenceDirectives: Set = new Set(); + readonly #dtsTypeReferenceDirectives: Set = new Set(); + readonly #dtsLibReferenceDirectives: Set = new Set(); // Used by getOverloadIndex() - private readonly _cachedOverloadIndexesByDeclaration: Map; + readonly #cachedOverloadIndexesByDeclaration: Map; public constructor(options: ICollectorOptions) { this.packageJsonLookup = new PackageJsonLookup(); const { program, extractorConfig, sourceMapper, messageRouter } = options; - this._program = program; + this.#program = program; this.extractorConfig = extractorConfig; this.sourceMapper = sourceMapper; @@ -138,7 +138,7 @@ export class Collector { this.typeChecker = program.getTypeChecker(); this.globalVariableAnalyzer = TypeScriptInternals.getGlobalVariableAnalyzer(this.program); - this._tsdocParser = new tsdoc.TSDocParser(this.extractorConfig.tsdocConfiguration); + this.#tsdocParser = new tsdoc.TSDocParser(this.extractorConfig.tsdocConfiguration); // Resolve package name patterns and store concrete set of bundled package dependency names this.bundledPackageNames = _resolveBundledPackagePatterns( @@ -155,7 +155,7 @@ export class Collector { ); this.astReferenceResolver = new AstReferenceResolver(this); - this._cachedOverloadIndexesByDeclaration = new Map(); + this.#cachedOverloadIndexesByDeclaration = new Map(); } /**a @@ -166,7 +166,7 @@ export class Collector { * ``` */ public get dtsTypeReferenceDirectives(): ReadonlySet { - return this._dtsTypeReferenceDirectives; + return this.#dtsTypeReferenceDirectives; } /** @@ -177,11 +177,11 @@ export class Collector { * ``` */ public get dtsLibReferenceDirectives(): ReadonlySet { - return this._dtsLibReferenceDirectives; + return this.#dtsLibReferenceDirectives; } public get entities(): ReadonlyArray { - return this._entities; + return this.#entities; } /** @@ -189,21 +189,21 @@ export class Collector { * as star exports (e.g. `export * from "@rushstack/node-core-library/lib/FileSystem"`). */ public get starExportedExternalModulePaths(): ReadonlyArray { - return this._starExportedExternalModulePaths; + return this.#starExportedExternalModulePaths; } /** * Perform the analysis. */ public analyze(): void { - if (this._astEntryPoint) { + if (this.#astEntryPoint) { throw new Error('DtsRollupGenerator.analyze() was already called'); } // This runs a full type analysis, and then augments the Abstract Syntax Tree (i.e. declarations) // with semantic information (i.e. symbols). The "diagnostics" are a subset of the everyday // compile errors that would result from a full compilation. - for (const diagnostic of this._program.getSemanticDiagnostics()) { + for (const diagnostic of this.#program.getSemanticDiagnostics()) { this.messageRouter.addCompilerDiagnostic(diagnostic); } @@ -244,7 +244,7 @@ export class Collector { const astEntryPoint: AstModule = this.astSymbolTable.fetchAstModuleFromWorkingPackage(entryPointSourceFile); - this._astEntryPoint = astEntryPoint; + this.#astEntryPoint = astEntryPoint; const packageDocCommentTextRange: ts.TextRange | undefined = PackageDocComment.tryFindInSourceFile( entryPointSourceFile, @@ -258,7 +258,7 @@ export class Collector { packageDocCommentTextRange.end ); - this.workingPackage.tsdocParserContext = this._tsdocParser.parseRange(range); + this.workingPackage.tsdocParserContext = this.#tsdocParser.parseRange(range); this.messageRouter.addTsdocMessages(this.workingPackage.tsdocParserContext, entryPointSourceFile); @@ -313,14 +313,14 @@ export class Collector { for (const starExportedExternalModule of starExportedExternalModules) { if (starExportedExternalModule.externalModulePath !== undefined) { - this._starExportedExternalModulePaths.push(starExportedExternalModule.externalModulePath); + this.#starExportedExternalModulePaths.push(starExportedExternalModule.externalModulePath); } } - Sort.sortBy(this._entities, (x) => x.getSortKey()); - Sort.sortSet(this._dtsTypeReferenceDirectives); - Sort.sortSet(this._dtsLibReferenceDirectives); - this._starExportedExternalModulePaths.sort(); + Sort.sortBy(this.#entities, (x) => x.getSortKey()); + Sort.sortSet(this.#dtsTypeReferenceDirectives); + Sort.sortSet(this.#dtsLibReferenceDirectives); + this.#starExportedExternalModulePaths.sort(); } /** @@ -332,7 +332,7 @@ export class Collector { public tryGetEntityForNode(identifier: ts.Identifier | ts.ImportTypeNode): CollectorEntity | undefined { const astEntity: AstEntity | undefined = this.astSymbolTable.tryGetEntityForNode(identifier); if (astEntity) { - return this._entitiesByAstEntity.get(astEntity); + return this.#entitiesByAstEntity.get(astEntity); } return undefined; } @@ -342,14 +342,14 @@ export class Collector { * doesn't refer to anything interesting. */ public tryGetEntityForSymbol(symbol: ts.Symbol): CollectorEntity | undefined { - return this._entitiesBySymbol.get(symbol); + return this.#entitiesBySymbol.get(symbol); } /** * Returns the associated `CollectorEntity` for the given `astEntity`, if one was created during analysis. */ public tryGetCollectorEntity(astEntity: AstEntity): CollectorEntity | undefined { - return this._entitiesByAstEntity.get(astEntity); + return this.#entitiesByAstEntity.get(astEntity); } public fetchSymbolMetadata(astSymbol: AstSymbol): SymbolMetadata { @@ -436,7 +436,7 @@ export class Collector { return 1; // trivial case } - let overloadIndex: number | undefined = this._cachedOverloadIndexesByDeclaration.get(astDeclaration); + let overloadIndex: number | undefined = this.#cachedOverloadIndexesByDeclaration.get(astDeclaration); if (overloadIndex === undefined) { // TSDoc index selectors are positive integers counting from 1 @@ -445,11 +445,11 @@ export class Collector { // Filter out other declarations that are not overloads. For example, an overloaded function can also // be a namespace. if (other.declaration.kind === astDeclaration.declaration.kind) { - this._cachedOverloadIndexesByDeclaration.set(other, nextIndex); + this.#cachedOverloadIndexesByDeclaration.set(other, nextIndex); ++nextIndex; } } - overloadIndex = this._cachedOverloadIndexesByDeclaration.get(astDeclaration); + overloadIndex = this.#cachedOverloadIndexesByDeclaration.get(astDeclaration); } if (overloadIndex === undefined) { @@ -465,18 +465,18 @@ export class Collector { exportName?: string, parent?: CollectorEntity ): CollectorEntity { - let entity: CollectorEntity | undefined = this._entitiesByAstEntity.get(astEntity); + let entity: CollectorEntity | undefined = this.#entitiesByAstEntity.get(astEntity); if (!entity) { entity = new CollectorEntity(astEntity); - this._entitiesByAstEntity.set(astEntity, entity); + this.#entitiesByAstEntity.set(astEntity, entity); if (astEntity instanceof AstSymbol) { - this._entitiesBySymbol.set(astEntity.followedSymbol, entity); + this.#entitiesBySymbol.set(astEntity.followedSymbol, entity); } else if (astEntity instanceof AstNamespaceImport) { - this._entitiesBySymbol.set(astEntity.symbol, entity); + this.#entitiesBySymbol.set(astEntity.symbol, entity); } - this._entities.push(entity); + this.#entities.push(entity); this._collectReferenceDirectives(astEntity); } @@ -516,7 +516,7 @@ export class Collector { if (astEntity instanceof AstNamespaceImport) { const astModuleExportInfo: IAstModuleExportInfo = astEntity.fetchAstModuleExportInfo(this); - const parentEntity: CollectorEntity | undefined = this._entitiesByAstEntity.get(astEntity); + const parentEntity: CollectorEntity | undefined = this.#entitiesByAstEntity.get(astEntity); if (!parentEntity) { // This should never happen, as we've already created entities for all AstNamespaceImports. throw new InternalError( @@ -558,7 +558,7 @@ export class Collector { const usedNames: Set = new Set(); // First collect the names of explicit package exports, and perform a sanity check. - for (const entity of this._entities) { + for (const entity of this.#entities) { for (const exportName of entity.exportNames) { if (usedNames.has(exportName)) { // This should be impossible @@ -569,7 +569,7 @@ export class Collector { } // Ensure that each entity has a unique nameForEmit - for (const entity of this._entities) { + for (const entity of this.#entities) { // What name would we ideally want to emit it as? let idealNameForEmit: string; @@ -874,7 +874,7 @@ export class Collector { // Don't report missing release tags for forgotten exports (unless we're including forgotten exports // in either the API report or doc model). const astSymbol: AstSymbol = astDeclaration.astSymbol; - const entity: CollectorEntity | undefined = this._entitiesByAstEntity.get(astSymbol.rootAstSymbol); + const entity: CollectorEntity | undefined = this.#entitiesByAstEntity.get(astSymbol.rootAstSymbol); if ( entity && (entity.consumable || @@ -956,7 +956,7 @@ export class Collector { range.end ); - const parserContext: tsdoc.ParserContext = this._tsdocParser.parseRange(tsdocTextRange); + const parserContext: tsdoc.ParserContext = this.#tsdocParser.parseRange(tsdocTextRange); this.messageRouter.addTsdocMessages(parserContext, declaration.getSourceFile(), astDeclaration); @@ -1017,7 +1017,7 @@ export class Collector { onlyIncludeExplicitlyPreserved ); if (name) { - this._dtsTypeReferenceDirectives.add(name); + this.#dtsTypeReferenceDirectives.add(name); } } @@ -1028,7 +1028,7 @@ export class Collector { onlyIncludeExplicitlyPreserved ); if (reference) { - this._dtsLibReferenceDirectives.add(reference); + this.#dtsLibReferenceDirectives.add(reference); } } } diff --git a/apps/api-extractor/src/collector/CollectorEntity.ts b/apps/api-extractor/src/collector/CollectorEntity.ts index 36bb07353d9..9e33bd8f54e 100644 --- a/apps/api-extractor/src/collector/CollectorEntity.ts +++ b/apps/api-extractor/src/collector/CollectorEntity.ts @@ -25,14 +25,14 @@ export class CollectorEntity { */ public readonly astEntity: AstEntity; - private _exportNames: Set = new Set(); - private _exportNamesSorted: boolean = false; - private _singleExportName: string | undefined = undefined; - private _localExportNamesByParent: Map> = new Map(); + #exportNames: Set = new Set(); + #exportNamesSorted: boolean = false; + #singleExportName: string | undefined = undefined; + #localExportNamesByParent: Map> = new Map(); - private _nameForEmit: string | undefined = undefined; + #nameForEmit: string | undefined = undefined; - private _sortKey: string | undefined = undefined; + #sortKey: string | undefined = undefined; public constructor(astEntity: AstEntity) { this.astEntity = astEntity; @@ -44,12 +44,12 @@ export class CollectorEntity { * global names (e.g. `Promise`) and (2) if local, other local names across different files. */ public get nameForEmit(): string | undefined { - return this._nameForEmit; + return this.#nameForEmit; } public set nameForEmit(value: string | undefined) { - this._nameForEmit = value; - this._sortKey = undefined; // invalidate the cached value + this.#nameForEmit = value; + this.#sortKey = undefined; // invalidate the cached value } /** @@ -64,11 +64,11 @@ export class CollectorEntity { * ``` */ public get exportNames(): ReadonlySet { - if (!this._exportNamesSorted) { - Sort.sortSet(this._exportNames); - this._exportNamesSorted = true; + if (!this.#exportNamesSorted) { + Sort.sortSet(this.#exportNames); + this.#exportNamesSorted = true; } - return this._exportNames; + return this.#exportNames; } /** @@ -76,7 +76,7 @@ export class CollectorEntity { * In all other cases, it is undefined. */ public get singleExportName(): string | undefined { - return this._singleExportName; + return this.#singleExportName; } /** @@ -92,9 +92,9 @@ export class CollectorEntity { // We don't inline an AstImport if (this.astEntity instanceof AstSymbol) { // We don't inline a symbol with more than one exported name - if (this._singleExportName !== undefined && this._singleExportName !== ts.InternalSymbolName.Default) { + if (this.#singleExportName !== undefined && this.#singleExportName !== ts.InternalSymbolName.Default) { // We can't inline a symbol whose emitted name is different from the export name - if (this._nameForEmit === undefined || this._nameForEmit === this._singleExportName) { + if (this.#nameForEmit === undefined || this.#nameForEmit === this.#singleExportName) { return true; } } @@ -133,7 +133,7 @@ export class CollectorEntity { if (this.exportedFromEntryPoint) return true; // Exported from parent? - for (const localExportNames of this._localExportNamesByParent.values()) { + for (const localExportNames of this.#localExportNamesByParent.values()) { if (localExportNames.size > 0) { return true; } @@ -173,7 +173,7 @@ export class CollectorEntity { if (this.exportedFromEntryPoint) return true; // Exported from consumable parent? - for (const [parent, localExportNames] of this._localExportNamesByParent) { + for (const [parent, localExportNames] of this.#localExportNamesByParent) { if (localExportNames.size > 0 && parent.consumable) { return true; } @@ -187,7 +187,7 @@ export class CollectorEntity { * `undefined`. */ public getFirstExportingConsumableParent(): CollectorEntity | undefined { - for (const [parent, localExportNames] of this._localExportNamesByParent) { + for (const [parent, localExportNames] of this.#localExportNamesByParent) { if (parent.consumable && localExportNames.size > 0) { return parent; } @@ -199,14 +199,14 @@ export class CollectorEntity { * Adds a new export name to the entity. */ public addExportName(exportName: string): void { - if (!this._exportNames.has(exportName)) { - this._exportNamesSorted = false; - this._exportNames.add(exportName); + if (!this.#exportNames.has(exportName)) { + this.#exportNamesSorted = false; + this.#exportNames.add(exportName); - if (this._exportNames.size === 1) { - this._singleExportName = exportName; + if (this.#exportNames.size === 1) { + this.#singleExportName = exportName; } else { - this._singleExportName = undefined; + this.#singleExportName = undefined; } } } @@ -229,19 +229,19 @@ export class CollectorEntity { * `add` is the local export name for the `CollectorEntity` for `add`. */ public addLocalExportName(localExportName: string, parent: CollectorEntity): void { - const localExportNames: Set = this._localExportNamesByParent.get(parent) || new Set(); + const localExportNames: Set = this.#localExportNamesByParent.get(parent) || new Set(); localExportNames.add(localExportName); - this._localExportNamesByParent.set(parent, localExportNames); + this.#localExportNamesByParent.set(parent, localExportNames); } /** * A sorting key used by DtsRollupGenerator._makeUniqueNames() */ public getSortKey(): string { - if (!this._sortKey) { - this._sortKey = Collector.getSortKeyIgnoringUnderscore(this.nameForEmit || this.astEntity.localName); + if (!this.#sortKey) { + this.#sortKey = Collector.getSortKeyIgnoringUnderscore(this.nameForEmit || this.astEntity.localName); } - return this._sortKey; + return this.#sortKey; } } diff --git a/apps/api-extractor/src/collector/MessageRouter.ts b/apps/api-extractor/src/collector/MessageRouter.ts index fe13466fe31..9c0139905cd 100644 --- a/apps/api-extractor/src/collector/MessageRouter.ts +++ b/apps/api-extractor/src/collector/MessageRouter.ts @@ -47,30 +47,30 @@ export class MessageRouter { public static readonly DIAGNOSTICS_LINE: string = '============================================================'; - private readonly _workingPackageFolder: string | undefined; - private readonly _messageCallback: ((message: ExtractorMessage) => void) | undefined; + readonly #workingPackageFolder: string | undefined; + readonly #messageCallback: ((message: ExtractorMessage) => void) | undefined; // All messages - private readonly _messages: ExtractorMessage[]; + readonly #messages: ExtractorMessage[]; // For each AstDeclaration, the messages associated with it. This is used when addToApiReportFile=true - private readonly _associatedMessagesForAstDeclaration: Map; + readonly #associatedMessagesForAstDeclaration: Map; - private readonly _sourceMapper: SourceMapper; + readonly #sourceMapper: SourceMapper; - private readonly _tsdocConfiguration: tsdoc.TSDocConfiguration; + readonly #tsdocConfiguration: tsdoc.TSDocConfiguration; // Normalized representation of the routing rules from api-extractor.json - private _reportingRuleByMessageId: Map = new Map(); - private _compilerDefaultRule: IReportingRule = { + #reportingRuleByMessageId: Map = new Map(); + #compilerDefaultRule: IReportingRule = { logLevel: ExtractorLogLevel.None, addToApiReportFile: false }; - private _extractorDefaultRule: IReportingRule = { + #extractorDefaultRule: IReportingRule = { logLevel: ExtractorLogLevel.None, addToApiReportFile: false }; - private _tsdocDefaultRule: IReportingRule = { logLevel: ExtractorLogLevel.None, addToApiReportFile: false }; + #tsdocDefaultRule: IReportingRule = { logLevel: ExtractorLogLevel.None, addToApiReportFile: false }; public errorCount: number = 0; public warningCount: number = 0; @@ -95,13 +95,13 @@ export class MessageRouter { showDiagnostics, messagesConfig } = options; - this._workingPackageFolder = workingPackageFolder; - this._messageCallback = messageCallback; + this.#workingPackageFolder = workingPackageFolder; + this.#messageCallback = messageCallback; - this._messages = []; - this._associatedMessagesForAstDeclaration = new Map(); - this._sourceMapper = sourceMapper; - this._tsdocConfiguration = tsdocConfiguration; + this.#messages = []; + this.#associatedMessagesForAstDeclaration = new Map(); + this.#sourceMapper = sourceMapper; + this.#tsdocConfiguration = tsdocConfiguration; // showDiagnostics implies showVerboseMessages this.showVerboseMessages = showVerboseMessages || showDiagnostics; @@ -121,14 +121,14 @@ export class MessageRouter { ); if (messageId === 'default') { - this._compilerDefaultRule = reportingRule; + this.#compilerDefaultRule = reportingRule; } else if (!/^TS[0-9]+$/.test(messageId)) { throw new Error( `Error in API Extractor config: The messages.compilerMessageReporting table contains` + ` an invalid entry "${messageId}". The identifier format is "TS" followed by an integer.` ); } else { - this._reportingRuleByMessageId.set(messageId, reportingRule); + this.#reportingRuleByMessageId.set(messageId, reportingRule); } } } @@ -140,7 +140,7 @@ export class MessageRouter { ); if (messageId === 'default') { - this._extractorDefaultRule = reportingRule; + this.#extractorDefaultRule = reportingRule; } else if (!/^ae-/.test(messageId)) { throw new Error( `Error in API Extractor config: The messages.extractorMessageReporting table contains` + @@ -152,7 +152,7 @@ export class MessageRouter { ` an unrecognized identifier "${messageId}". Is it spelled correctly?` ); } else { - this._reportingRuleByMessageId.set(messageId, reportingRule); + this.#reportingRuleByMessageId.set(messageId, reportingRule); } } } @@ -164,26 +164,26 @@ export class MessageRouter { ); if (messageId === 'default') { - this._tsdocDefaultRule = reportingRule; + this.#tsdocDefaultRule = reportingRule; } else if (!/^tsdoc-/.test(messageId)) { throw new Error( `Error in API Extractor config: The messages.tsdocMessageReporting table contains` + ` an invalid entry "${messageId}". The name should begin with the "tsdoc-" prefix.` ); - } else if (!this._tsdocConfiguration.isKnownMessageId(messageId)) { + } else if (!this.#tsdocConfiguration.isKnownMessageId(messageId)) { throw new Error( `Error in API Extractor config: The messages.tsdocMessageReporting table contains` + ` an unrecognized identifier "${messageId}". Is it spelled correctly?` ); } else { - this._reportingRuleByMessageId.set(messageId, reportingRule); + this.#reportingRuleByMessageId.set(messageId, reportingRule); } } } } public get messages(): ReadonlyArray { - return this._messages; + return this.#messages; } /** @@ -207,7 +207,7 @@ export class MessageRouter { // NOTE: Since compiler errors pertain to issues specific to the .d.ts files, // we do not apply source mappings for them. const sourceFile: ts.SourceFile = diagnostic.file; - const sourceLocation: ISourceLocation = this._sourceMapper.getSourceLocation({ + const sourceLocation: ISourceLocation = this.#sourceMapper.getSourceLocation({ sourceFile, pos: diagnostic.start || 0, useDtsLocation: true @@ -217,7 +217,7 @@ export class MessageRouter { options.sourceFileColumn = sourceLocation.sourceFileColumn; } - this._messages.push(new ExtractorMessage(options)); + this.#messages.push(new ExtractorMessage(options)); } /** @@ -263,7 +263,7 @@ export class MessageRouter { text: message.unformattedText }; - const sourceLocation: ISourceLocation = this._sourceMapper.getSourceLocation({ + const sourceLocation: ISourceLocation = this.#sourceMapper.getSourceLocation({ sourceFile, pos: message.textRange.pos }); @@ -277,7 +277,7 @@ export class MessageRouter { this._associateMessageWithAstDeclaration(extractorMessage, astDeclaration); } - this._messages.push(extractorMessage); + this.#messages.push(extractorMessage); } } @@ -307,11 +307,11 @@ export class MessageRouter { astDeclaration: AstDeclaration ): void { let associatedMessages: ExtractorMessage[] | undefined = - this._associatedMessagesForAstDeclaration.get(astDeclaration); + this.#associatedMessagesForAstDeclaration.get(astDeclaration); if (!associatedMessages) { associatedMessages = []; - this._associatedMessagesForAstDeclaration.set(astDeclaration, associatedMessages); + this.#associatedMessagesForAstDeclaration.set(astDeclaration, associatedMessages); } associatedMessages.push(extractorMessage); } @@ -333,7 +333,7 @@ export class MessageRouter { properties }; - const sourceLocation: ISourceLocation = this._sourceMapper.getSourceLocation({ + const sourceLocation: ISourceLocation = this.#sourceMapper.getSourceLocation({ sourceFile, pos }); @@ -343,7 +343,7 @@ export class MessageRouter { const extractorMessage: ExtractorMessage = new ExtractorMessage(options); - this._messages.push(extractorMessage); + this.#messages.push(extractorMessage); return extractorMessage; } @@ -356,7 +356,7 @@ export class MessageRouter { const messagesForApiReportFile: ExtractorMessage[] = []; const associatedMessages: ExtractorMessage[] = - this._associatedMessagesForAstDeclaration.get(astDeclaration) || []; + this.#associatedMessagesForAstDeclaration.get(astDeclaration) || []; for (const associatedMessage of associatedMessages) { // Make sure we didn't already report this message for some reason if (!associatedMessage.handled) { @@ -518,8 +518,8 @@ export class MessageRouter { } // If there is a callback, allow it to modify and/or handle the message - if (this._messageCallback) { - this._messageCallback(message); + if (this.#messageCallback) { + this.#messageCallback(message); } // Update the statistics @@ -547,7 +547,7 @@ export class MessageRouter { if (message.category === ExtractorMessageCategory.Console) { messageText = message.text; } else { - messageText = message.formatMessageWithLocation(this._workingPackageFolder); + messageText = message.formatMessageWithLocation(this.#workingPackageFolder); } switch (message.logLevel) { @@ -574,17 +574,17 @@ export class MessageRouter { * For a given message, determine the IReportingRule based on the rule tables. */ private _getRuleForMessage(message: ExtractorMessage): IReportingRule { - const reportingRule: IReportingRule | undefined = this._reportingRuleByMessageId.get(message.messageId); + const reportingRule: IReportingRule | undefined = this.#reportingRuleByMessageId.get(message.messageId); if (reportingRule) { return reportingRule; } switch (message.category) { case ExtractorMessageCategory.Compiler: - return this._compilerDefaultRule; + return this.#compilerDefaultRule; case ExtractorMessageCategory.Extractor: - return this._extractorDefaultRule; + return this.#extractorDefaultRule; case ExtractorMessageCategory.TSDoc: - return this._tsdocDefaultRule; + return this.#tsdocDefaultRule; case ExtractorMessageCategory.Console: throw new InternalError('ExtractorMessageCategory.Console is not supported with IReportingRule'); } diff --git a/apps/api-extractor/src/collector/SourceMapper.ts b/apps/api-extractor/src/collector/SourceMapper.ts index d0859a4f395..109515a2bd7 100644 --- a/apps/api-extractor/src/collector/SourceMapper.ts +++ b/apps/api-extractor/src/collector/SourceMapper.ts @@ -67,10 +67,10 @@ export interface IGetSourceLocationOptions { export class SourceMapper { // Map from .d.ts file path --> ISourceMap if a source map was found, or null if not found - private _sourceMapByFilePath: Map = new Map(); + #sourceMapByFilePath: Map = new Map(); // Cache the FileSystem.exists() result for mapped .ts files - private _originalFileInfoByPath: Map = new Map(); + #originalFileInfoByPath: Map = new Map(); /** * Given a `.d.ts` source file and a specific position within the file, return the corresponding @@ -115,7 +115,7 @@ export class SourceMapper { const mappedFilePath: string = path.resolve(path.dirname(sourceFilePath), nearestMappingItem.source); // Does the mapped filename exist? Use a cache to remember the answer. - let originalFileInfo: IOriginalFileInfo | undefined = this._originalFileInfoByPath.get(mappedFilePath); + let originalFileInfo: IOriginalFileInfo | undefined = this.#originalFileInfoByPath.get(mappedFilePath); if (originalFileInfo === undefined) { originalFileInfo = { fileExists: FileSystem.exists(mappedFilePath), @@ -132,7 +132,7 @@ export class SourceMapper { originalFileInfo.maxColumnForLine.unshift(0); // Extra item since lines are 1-based } - this._originalFileInfoByPath.set(mappedFilePath, originalFileInfo); + this.#originalFileInfoByPath.set(mappedFilePath, originalFileInfo); } // Don't translate coordinates to a file that doesn't exist @@ -168,16 +168,16 @@ export class SourceMapper { } private _getSourceMap(sourceFilePath: string): ISourceMap | null { - let sourceMap: ISourceMap | null | undefined = this._sourceMapByFilePath.get(sourceFilePath); + let sourceMap: ISourceMap | null | undefined = this.#sourceMapByFilePath.get(sourceFilePath); if (sourceMap === undefined) { // Normalize the path and redo the lookup const normalizedPath: string = FileSystem.getRealPath(sourceFilePath); - sourceMap = this._sourceMapByFilePath.get(normalizedPath); + sourceMap = this.#sourceMapByFilePath.get(normalizedPath); if (sourceMap !== undefined) { // Copy the result from the normalized to the non-normalized key - this._sourceMapByFilePath.set(sourceFilePath, sourceMap); + this.#sourceMapByFilePath.set(sourceFilePath, sourceMap); } else { // Given "folder/file.d.ts", check for a corresponding "folder/file.d.ts.map" const sourceMapPath: string = normalizedPath + '.map'; @@ -209,10 +209,10 @@ export class SourceMapper { sourceMap = null; } - this._sourceMapByFilePath.set(normalizedPath, sourceMap); + this.#sourceMapByFilePath.set(normalizedPath, sourceMap); if (sourceFilePath !== normalizedPath) { // Add both keys to the map - this._sourceMapByFilePath.set(sourceFilePath, sourceMap); + this.#sourceMapByFilePath.set(sourceFilePath, sourceMap); } } } diff --git a/apps/api-extractor/src/enhancers/DocCommentEnhancer.ts b/apps/api-extractor/src/enhancers/DocCommentEnhancer.ts index 17b228afe35..3c235b96008 100644 --- a/apps/api-extractor/src/enhancers/DocCommentEnhancer.ts +++ b/apps/api-extractor/src/enhancers/DocCommentEnhancer.ts @@ -15,10 +15,10 @@ import { VisitorState } from '../collector/VisitorState'; import { ResolverFailure } from '../analyzer/AstReferenceResolver'; export class DocCommentEnhancer { - private readonly _collector: Collector; + readonly #collector: Collector; public constructor(collector: Collector) { - this._collector = collector; + this.#collector = collector; } public static analyze(collector: Collector): void { @@ -27,12 +27,12 @@ export class DocCommentEnhancer { } public analyze(): void { - for (const entity of this._collector.entities) { + for (const entity of this.#collector.entities) { if (entity.astEntity instanceof AstSymbol) { if ( entity.consumable || - this._collector.extractorConfig.apiReportIncludeForgottenExports || - this._collector.extractorConfig.docModelIncludeForgottenExports + this.#collector.extractorConfig.apiReportIncludeForgottenExports || + this.#collector.extractorConfig.docModelIncludeForgottenExports ) { entity.astEntity.forEachDeclarationRecursive((astDeclaration: AstDeclaration) => { this._analyzeApiItem(astDeclaration); @@ -43,13 +43,13 @@ export class DocCommentEnhancer { } private _analyzeApiItem(astDeclaration: AstDeclaration): void { - const metadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const metadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); if (metadata.docCommentEnhancerVisitorState === VisitorState.Visited) { return; } if (metadata.docCommentEnhancerVisitorState === VisitorState.Visiting) { - this._collector.messageRouter.addAnalyzerIssue( + this.#collector.messageRouter.addAnalyzerIssue( ExtractorMessageId.CyclicInheritDoc, `The @inheritDoc tag for "${astDeclaration.astSymbol.localName}" refers to its own declaration`, astDeclaration @@ -79,7 +79,7 @@ export class DocCommentEnhancer { // The class that contains this constructor const classDeclaration: AstDeclaration = astDeclaration.parent!; - const configuration: tsdoc.TSDocConfiguration = this._collector.extractorConfig.tsdocConfiguration; + const configuration: tsdoc.TSDocConfiguration = this.#collector.extractorConfig.tsdocConfiguration; if (!metadata.tsdocComment) { metadata.tsdocComment = new tsdoc.DocComment({ configuration }); @@ -96,10 +96,10 @@ export class DocCommentEnhancer { ]); } - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); if (apiItemMetadata.effectiveReleaseTag === ReleaseTag.Internal) { // If the constructor is marked as internal, then add a boilerplate notice for the containing class - const classMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(classDeclaration); + const classMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(classDeclaration); if (!classMetadata.tsdocComment) { classMetadata.tsdocComment = new tsdoc.DocComment({ configuration }); @@ -187,10 +187,10 @@ export class DocCommentEnhancer { // Tracked by: https://github.com/microsoft/rushstack/issues/1195 if (this._refersToDeclarationInWorkingPackage(node.codeDestination)) { const referencedAstDeclaration: AstDeclaration | ResolverFailure = - this._collector.astReferenceResolver.resolve(node.codeDestination); + this.#collector.astReferenceResolver.resolve(node.codeDestination); if (referencedAstDeclaration instanceof ResolverFailure) { - this._collector.messageRouter.addAnalyzerIssue( + this.#collector.messageRouter.addAnalyzerIssue( ExtractorMessageId.UnresolvedLink, 'The @link reference could not be resolved: ' + referencedAstDeclaration.reason, astDeclaration @@ -213,7 +213,7 @@ export class DocCommentEnhancer { inheritDocTag: tsdoc.DocInheritDocTag ): void { if (!inheritDocTag.declarationReference) { - this._collector.messageRouter.addAnalyzerIssue( + this.#collector.messageRouter.addAnalyzerIssue( ExtractorMessageId.UnresolvedInheritDocBase, 'The @inheritDoc tag needs a TSDoc declaration reference; signature matching is not supported yet', astDeclaration @@ -229,10 +229,10 @@ export class DocCommentEnhancer { } const referencedAstDeclaration: AstDeclaration | ResolverFailure = - this._collector.astReferenceResolver.resolve(inheritDocTag.declarationReference); + this.#collector.astReferenceResolver.resolve(inheritDocTag.declarationReference); if (referencedAstDeclaration instanceof ResolverFailure) { - this._collector.messageRouter.addAnalyzerIssue( + this.#collector.messageRouter.addAnalyzerIssue( ExtractorMessageId.UnresolvedInheritDocReference, 'The @inheritDoc reference could not be resolved: ' + referencedAstDeclaration.reason, astDeclaration @@ -243,7 +243,7 @@ export class DocCommentEnhancer { this._analyzeApiItem(referencedAstDeclaration); const referencedMetadata: ApiItemMetadata = - this._collector.fetchApiItemMetadata(referencedAstDeclaration); + this.#collector.fetchApiItemMetadata(referencedAstDeclaration); if (referencedMetadata.tsdocComment) { this._copyInheritedDocs(docComment, referencedMetadata.tsdocComment); @@ -277,7 +277,7 @@ export class DocCommentEnhancer { ): boolean { return ( declarationReference?.packageName === undefined || - declarationReference.packageName === this._collector.workingPackage.name + declarationReference.packageName === this.#collector.workingPackage.name ); } } diff --git a/apps/api-extractor/src/generators/ApiModelGenerator.ts b/apps/api-extractor/src/generators/ApiModelGenerator.ts index e03cfab218e..85766192889 100644 --- a/apps/api-extractor/src/generators/ApiModelGenerator.ts +++ b/apps/api-extractor/src/generators/ApiModelGenerator.ts @@ -70,22 +70,22 @@ export interface IApiModelGenerationOptions { } export class ApiModelGenerator { - private readonly _collector: Collector; - private readonly _apiModel: ApiModel; - private readonly _referenceGenerator: DeclarationReferenceGenerator; - private readonly _releaseTagsToTrim: Set | undefined; + readonly #collector: Collector; + readonly #apiModel: ApiModel; + readonly #referenceGenerator: DeclarationReferenceGenerator; + readonly #releaseTagsToTrim: Set | undefined; public readonly docModelEnabled: boolean; public constructor(collector: Collector, extractorConfig: ExtractorConfig) { - this._collector = collector; - this._apiModel = new ApiModel(); - this._referenceGenerator = new DeclarationReferenceGenerator(collector); + this.#collector = collector; + this.#apiModel = new ApiModel(); + this.#referenceGenerator = new DeclarationReferenceGenerator(collector); const apiModelGenerationOptions: IApiModelGenerationOptions | undefined = extractorConfig.docModelGenerationOptions; if (apiModelGenerationOptions) { - this._releaseTagsToTrim = apiModelGenerationOptions.releaseTagsToTrim; + this.#releaseTagsToTrim = apiModelGenerationOptions.releaseTagsToTrim; this.docModelEnabled = true; } else { this.docModelEnabled = false; @@ -93,28 +93,28 @@ export class ApiModelGenerator { } public get apiModel(): ApiModel { - return this._apiModel; + return this.#apiModel; } public buildApiPackage(): ApiPackage { - const packageDocComment: tsdoc.DocComment | undefined = this._collector.workingPackage.tsdocComment; + const packageDocComment: tsdoc.DocComment | undefined = this.#collector.workingPackage.tsdocComment; const apiPackage: ApiPackage = new ApiPackage({ - name: this._collector.workingPackage.name, + name: this.#collector.workingPackage.name, docComment: packageDocComment, - tsdocConfiguration: this._collector.extractorConfig.tsdocConfiguration, - projectFolderUrl: this._collector.extractorConfig.projectFolderUrl + tsdocConfiguration: this.#collector.extractorConfig.tsdocConfiguration, + projectFolderUrl: this.#collector.extractorConfig.projectFolderUrl }); - this._apiModel.addMember(apiPackage); + this.#apiModel.addMember(apiPackage); const apiEntryPoint: ApiEntryPoint = new ApiEntryPoint({ name: '' }); apiPackage.addMember(apiEntryPoint); - for (const entity of this._collector.entities) { + for (const entity of this.#collector.entities) { // Only process entities that are exported from the entry point. Entities that are exported from // `AstNamespaceImport` entities will be processed by `_processAstNamespaceImport`. However, if // we are including forgotten exports, then process everything. - if (entity.exportedFromEntryPoint || this._collector.extractorConfig.docModelIncludeForgottenExports) { + if (entity.exportedFromEntryPoint || this.#collector.extractorConfig.docModelIncludeForgottenExports) { this._processAstEntity(entity.astEntity, { name: entity.nameForEmit!, isExported: entity.exportedFromEntryPoint, @@ -129,7 +129,7 @@ export class ApiModelGenerator { private _processAstEntity(astEntity: AstEntity, context: IProcessAstEntityContext): void { if (astEntity instanceof AstSymbol) { // Skip ancillary declarations; we will process them with the main declaration - for (const astDeclaration of this._collector.getNonAncillaryDeclarations(astEntity)) { + for (const astDeclaration of this.#collector.getNonAncillaryDeclarations(astEntity)) { this._processDeclaration(astDeclaration, context); } return; @@ -200,9 +200,9 @@ export class ApiModelGenerator { return; // trim out private declarations } - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; - if (this._releaseTagsToTrim?.has(releaseTag)) { + if (this.#releaseTagsToTrim?.has(releaseTag)) { return; } @@ -309,7 +309,7 @@ export class ApiModelGenerator { private _processApiCallSignature(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { parentApiItem } = context; - const overloadIndex: number = this._collector.getOverloadIndex(astDeclaration); + const overloadIndex: number = this.#collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiCallSignature.getContainerKey(overloadIndex); let apiCallSignature: ApiCallSignature | undefined = parentApiItem.tryGetMemberByKey( @@ -338,7 +338,7 @@ export class ApiModelGenerator { ); const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const fileUrlPath: string = this._getFileUrlPath(callSignature); @@ -360,7 +360,7 @@ export class ApiModelGenerator { private _processApiConstructor(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { parentApiItem } = context; - const overloadIndex: number = this._collector.getOverloadIndex(astDeclaration); + const overloadIndex: number = this.#collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiConstructor.getContainerKey(overloadIndex); let apiConstructor: ApiConstructor | undefined = parentApiItem.tryGetMemberByKey( @@ -379,7 +379,7 @@ export class ApiModelGenerator { ); const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const isProtected: boolean = (astDeclaration.modifierFlags & ts.ModifierFlags.Protected) !== 0; @@ -434,7 +434,7 @@ export class ApiModelGenerator { } const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const isAbstract: boolean = @@ -468,7 +468,7 @@ export class ApiModelGenerator { context: IProcessAstEntityContext ): void { const { parentApiItem } = context; - const overloadIndex: number = this._collector.getOverloadIndex(astDeclaration); + const overloadIndex: number = this.#collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiConstructSignature.getContainerKey(overloadIndex); let apiConstructSignature: ApiConstructSignature | undefined = parentApiItem.tryGetMemberByKey( @@ -497,7 +497,7 @@ export class ApiModelGenerator { ); const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const fileUrlPath: string = this._getFileUrlPath(constructSignature); @@ -525,11 +525,11 @@ export class ApiModelGenerator { if (apiEnum === undefined) { const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, []); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const preserveMemberOrder: boolean = - this._collector.extractorConfig.enumMemberOrder === EnumMemberOrder.Preserve; + this.#collector.extractorConfig.enumMemberOrder === EnumMemberOrder.Preserve; const fileUrlPath: string = this._getFileUrlPath(astDeclaration.declaration); apiEnum = new ApiEnum({ @@ -570,7 +570,7 @@ export class ApiModelGenerator { } const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const fileUrlPath: string = this._getFileUrlPath(enumMember); @@ -595,7 +595,7 @@ export class ApiModelGenerator { ): void { const { name, isExported, parentApiItem } = context; - const overloadIndex: number = this._collector.getOverloadIndex(astDeclaration); + const overloadIndex: number = this.#collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiFunction.getContainerKey(name, overloadIndex); let apiFunction: ApiFunction | undefined = parentApiItem.tryGetMemberByKey(containerKey) as ApiFunction; @@ -622,7 +622,7 @@ export class ApiModelGenerator { ); const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const fileUrlPath: string = this._getFileUrlPath(functionDeclaration); @@ -646,7 +646,7 @@ export class ApiModelGenerator { private _processApiIndexSignature(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { parentApiItem } = context; - const overloadIndex: number = this._collector.getOverloadIndex(astDeclaration); + const overloadIndex: number = this.#collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiIndexSignature.getContainerKey(overloadIndex); let apiIndexSignature: ApiIndexSignature | undefined = parentApiItem.tryGetMemberByKey( @@ -668,7 +668,7 @@ export class ApiModelGenerator { ); const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const isReadonly: boolean = this._isReadonly(astDeclaration); @@ -721,7 +721,7 @@ export class ApiModelGenerator { } const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const fileUrlPath: string = this._getFileUrlPath(interfaceDeclaration); @@ -749,7 +749,7 @@ export class ApiModelGenerator { private _processApiMethod(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { name, parentApiItem } = context; const isStatic: boolean = (astDeclaration.modifierFlags & ts.ModifierFlags.Static) !== 0; - const overloadIndex: number = this._collector.getOverloadIndex(astDeclaration); + const overloadIndex: number = this.#collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiMethod.getContainerKey(name, isStatic, overloadIndex); let apiMethod: ApiMethod | undefined = parentApiItem.tryGetMemberByKey(containerKey) as ApiMethod; @@ -775,7 +775,7 @@ export class ApiModelGenerator { ); const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; if (releaseTag === ReleaseTag.Internal || releaseTag === ReleaseTag.Alpha) { @@ -812,7 +812,7 @@ export class ApiModelGenerator { context: IProcessAstEntityContext ): void { const { name, parentApiItem } = context; - const overloadIndex: number = this._collector.getOverloadIndex(astDeclaration); + const overloadIndex: number = this.#collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiMethodSignature.getContainerKey(name, overloadIndex); let apiMethodSignature: ApiMethodSignature | undefined = parentApiItem.tryGetMemberByKey( @@ -840,7 +840,7 @@ export class ApiModelGenerator { ); const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const isOptional: boolean = @@ -874,7 +874,7 @@ export class ApiModelGenerator { if (apiNamespace === undefined) { const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, []); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const fileUrlPath: string = this._getFileUrlPath(astDeclaration.declaration); @@ -930,7 +930,7 @@ export class ApiModelGenerator { } const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const isOptional: boolean = @@ -983,7 +983,7 @@ export class ApiModelGenerator { } const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const isOptional: boolean = @@ -1033,7 +1033,7 @@ export class ApiModelGenerator { nodeTransforms.push({ node: typeAliasDeclaration.type, captureTokenRange: typeTokenRange }); const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const fileUrlPath: string = this._getFileUrlPath(typeAliasDeclaration); @@ -1081,7 +1081,7 @@ export class ApiModelGenerator { } const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const isReadonly: boolean = this._isReadonly(astDeclaration); @@ -1113,9 +1113,9 @@ export class ApiModelGenerator { const excerptTokens: IExcerptToken[] = []; // Build the main declaration - ExcerptBuilder.addDeclaration(excerptTokens, astDeclaration, nodeTransforms, this._referenceGenerator); + ExcerptBuilder.addDeclaration(excerptTokens, astDeclaration, nodeTransforms, this.#referenceGenerator); - const declarationMetadata: DeclarationMetadata = this._collector.fetchDeclarationMetadata(astDeclaration); + const declarationMetadata: DeclarationMetadata = this.#collector.fetchDeclarationMetadata(astDeclaration); // Add any ancillary declarations for (const ancillaryDeclaration of declarationMetadata.ancillaryDeclarations) { @@ -1124,7 +1124,7 @@ export class ApiModelGenerator { excerptTokens, ancillaryDeclaration, nodeTransforms, - this._referenceGenerator + this.#referenceGenerator ); } @@ -1174,7 +1174,7 @@ export class ApiModelGenerator { parameters.push({ parameterName: syntheticName ?? parameter.name.getText().trim(), parameterTypeTokenRange, - isOptional: this._collector.typeChecker.isOptionalParameter(parameter) + isOptional: this.#collector.typeChecker.isOptionalParameter(parameter) }); if (syntheticName !== undefined) { @@ -1195,10 +1195,10 @@ export class ApiModelGenerator { case ts.SyntaxKind.PropertySignature: case ts.SyntaxKind.SetAccessor: case ts.SyntaxKind.VariableDeclaration: { - const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); + const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const declarationMetadata: DeclarationMetadata = - this._collector.fetchDeclarationMetadata(astDeclaration); + this.#collector.fetchDeclarationMetadata(astDeclaration); const hasReadonlyModifier: boolean = (astDeclaration.modifierFlags & ts.ModifierFlags.Readonly) !== 0; const hasReadonlyDocTag: boolean = !!docComment?.modifierTagSet?.hasTagName('@readonly'); @@ -1220,13 +1220,13 @@ export class ApiModelGenerator { private _getFileUrlPath(declaration: ts.Declaration): string { const sourceFile: ts.SourceFile = declaration.getSourceFile(); - const sourceLocation: ISourceLocation = this._collector.sourceMapper.getSourceLocation({ + const sourceLocation: ISourceLocation = this.#collector.sourceMapper.getSourceLocation({ sourceFile, pos: declaration.pos }); let result: string = path.relative( - this._collector.extractorConfig.projectFolder, + this.#collector.extractorConfig.projectFolder, sourceLocation.sourceFilePath ); result = Path.convertToSlashes(result); diff --git a/apps/api-extractor/src/generators/DeclarationReferenceGenerator.ts b/apps/api-extractor/src/generators/DeclarationReferenceGenerator.ts index bb81031afe4..047cd77a92e 100644 --- a/apps/api-extractor/src/generators/DeclarationReferenceGenerator.ts +++ b/apps/api-extractor/src/generators/DeclarationReferenceGenerator.ts @@ -22,17 +22,17 @@ import { AstNamespaceImport } from '../analyzer/AstNamespaceImport'; export class DeclarationReferenceGenerator { public static readonly unknownReference: string = '?'; - private _collector: Collector; + #collector: Collector; public constructor(collector: Collector) { - this._collector = collector; + this.#collector = collector; } /** * Gets the UID for a TypeScript Identifier that references a type. */ public getDeclarationReferenceForIdentifier(node: ts.Identifier): DeclarationReference | undefined { - const symbol: ts.Symbol | undefined = this._collector.typeChecker.getSymbolAtLocation(node); + const symbol: ts.Symbol | undefined = this.#collector.typeChecker.getSymbolAtLocation(node); if (symbol !== undefined) { const isExpression: boolean = _isInExpressionContext(node); return ( @@ -68,7 +68,7 @@ export class DeclarationReferenceGenerator { // global symbols or external library symbols to be Locals. const isGlobal: boolean = !!sourceFile && !ts.isExternalModule(sourceFile); const isFromExternalLibrary: boolean = - !!sourceFile && this._collector.program.isSourceFileFromExternalLibrary(sourceFile); + !!sourceFile && this.#collector.program.isSourceFileFromExternalLibrary(sourceFile); if (isGlobal || isFromExternalLibrary) { if (parent && parent.members && _isSameSymbol(parent.members.get(symbol.escapedName), symbol)) { return Navigation.Members; @@ -81,7 +81,7 @@ export class DeclarationReferenceGenerator { // `CollectorEntity`, then use Exports. We use `consumable` here instead of `exported` because // if the symbol is exported from a non-consumable `AstNamespaceImport`, we don't want to use // Exports. We should use Locals instead. - const entity: CollectorEntity | undefined = this._collector.tryGetEntityForSymbol(symbol); + const entity: CollectorEntity | undefined = this.#collector.tryGetEntityForSymbol(symbol); if (entity?.consumable) { return Navigation.Exports; } @@ -114,10 +114,10 @@ export class DeclarationReferenceGenerator { let followedSymbol: ts.Symbol = symbol; if (followedSymbol.flags & ts.SymbolFlags.ExportValue) { - followedSymbol = this._collector.typeChecker.getExportSymbolOfSymbol(followedSymbol); + followedSymbol = this.#collector.typeChecker.getExportSymbolOfSymbol(followedSymbol); } if (followedSymbol.flags & ts.SymbolFlags.Alias) { - followedSymbol = this._collector.typeChecker.getAliasedSymbol(followedSymbol); + followedSymbol = this.#collector.typeChecker.getAliasedSymbol(followedSymbol); // Without this logic, we end up following the symbol `ns` in `import * as ns from './file'` to // the actual file `file.ts`. We don't want to do this, so revert to the original symbol. @@ -144,7 +144,7 @@ export class DeclarationReferenceGenerator { } let localName: string = followedSymbol.name; - const entity: CollectorEntity | undefined = this._collector.tryGetEntityForSymbol(followedSymbol); + const entity: CollectorEntity | undefined = this.#collector.tryGetEntityForSymbol(followedSymbol); if (entity?.nameForEmit) { localName = entity.nameForEmit; } @@ -192,7 +192,7 @@ export class DeclarationReferenceGenerator { // Note that it's possible for a symbol to be exported from an entry point as well as one or more // namespaces. In that case, it's not clear what to choose as its parent. Today's logic is neither // perfect nor particularly stable to API items being renamed and shuffled around. - const entity: CollectorEntity | undefined = this._collector.tryGetEntityForSymbol(symbol); + const entity: CollectorEntity | undefined = this.#collector.tryGetEntityForSymbol(symbol); if (entity) { if (entity.exportedFromEntryPoint) { return new DeclarationReference(this._sourceFileToModuleSource(sourceFile)); @@ -206,7 +206,7 @@ export class DeclarationReferenceGenerator { ) { const parentSymbol: ts.Symbol | undefined = TypeScriptInternals.tryGetSymbolForDeclaration( firstExportingConsumableParent.astEntity.declaration, - this._collector.typeChecker + this.#collector.typeChecker ); if (parentSymbol) { return this._symbolToDeclarationReference( @@ -244,7 +244,7 @@ export class DeclarationReferenceGenerator { if (grandParent && ts.isModuleDeclaration(grandParent)) { const grandParentSymbol: ts.Symbol | undefined = TypeScriptInternals.tryGetSymbolForDeclaration( grandParent, - this._collector.typeChecker + this.#collector.typeChecker ); if (grandParentSymbol) { return this._symbolToDeclarationReference( @@ -264,27 +264,27 @@ export class DeclarationReferenceGenerator { } private _getPackageName(sourceFile: ts.SourceFile): string { - if (this._collector.program.isSourceFileFromExternalLibrary(sourceFile)) { + if (this.#collector.program.isSourceFileFromExternalLibrary(sourceFile)) { const packageJson: INodePackageJson | undefined = - this._collector.packageJsonLookup.tryLoadNodePackageJsonFor(sourceFile.fileName); + this.#collector.packageJsonLookup.tryLoadNodePackageJsonFor(sourceFile.fileName); if (packageJson && packageJson.name) { return packageJson.name; } return DeclarationReferenceGenerator.unknownReference; } - return this._collector.workingPackage.name; + return this.#collector.workingPackage.name; } private _sourceFileToModuleSource(sourceFile: ts.SourceFile | undefined): GlobalSource | ModuleSource { if (sourceFile && ts.isExternalModule(sourceFile)) { const packageName: string = this._getPackageName(sourceFile); - if (this._collector.bundledPackageNames.has(packageName)) { + if (this.#collector.bundledPackageNames.has(packageName)) { // The api-extractor.json config file has a "bundledPackages" setting, which causes imports from // certain NPM packages to be treated as part of the working project. In this case, we need to // substitute the working package name. - return new ModuleSource(this._collector.workingPackage.name); + return new ModuleSource(this.#collector.workingPackage.name); } else { return new ModuleSource(packageName); } diff --git a/apps/api-extractor/src/generators/IndentedWriter.ts b/apps/api-extractor/src/generators/IndentedWriter.ts index 84c2a91e35b..32661a47e02 100644 --- a/apps/api-extractor/src/generators/IndentedWriter.ts +++ b/apps/api-extractor/src/generators/IndentedWriter.ts @@ -70,35 +70,35 @@ export class IndentedWriter { */ public trimLeadingSpaces: boolean = false; - private readonly _builder: IStringBuilder; + readonly #builder: IStringBuilder; - private _latestChunk: string | undefined; - private _previousChunk: string | undefined; - private _atStartOfLine: boolean; + #latestChunk: string | undefined; + #previousChunk: string | undefined; + #atStartOfLine: boolean; - private readonly _indentStack: string[]; - private _indentText: string; + readonly #indentStack: string[]; + #indentText: string; - private _previousLineIsBlank: boolean; - private _currentLineIsBlank: boolean; + #previousLineIsBlank: boolean; + #currentLineIsBlank: boolean; public constructor(builder?: IStringBuilder) { - this._builder = builder === undefined ? new StringBuilder() : builder; - this._latestChunk = undefined; - this._previousChunk = undefined; - this._atStartOfLine = true; - this._previousLineIsBlank = true; - this._currentLineIsBlank = true; + this.#builder = builder === undefined ? new StringBuilder() : builder; + this.#latestChunk = undefined; + this.#previousChunk = undefined; + this.#atStartOfLine = true; + this.#previousLineIsBlank = true; + this.#currentLineIsBlank = true; - this._indentStack = []; - this._indentText = ''; + this.#indentStack = []; + this.#indentText = ''; } /** * Retrieves the output that was built so far. */ public getText(): string { - return this._builder.toString(); + return this.#builder.toString(); } public toString(): string { @@ -113,7 +113,7 @@ export class IndentedWriter { * corresponding call to IndentedWriter.decreaseIndent(). */ public increaseIndent(indentPrefix?: string): void { - this._indentStack.push(indentPrefix !== undefined ? indentPrefix : this.defaultIndentPrefix); + this.#indentStack.push(indentPrefix !== undefined ? indentPrefix : this.defaultIndentPrefix); this._updateIndentText(); } @@ -122,7 +122,7 @@ export class IndentedWriter { * to IndentedWriter.increaseIndent(). */ public decreaseIndent(): void { - this._indentStack.pop(); + this.#indentStack.pop(); this._updateIndentText(); } @@ -153,7 +153,7 @@ export class IndentedWriter { */ public ensureSkippedLine(): void { this.ensureNewLine(); - if (!this._previousLineIsBlank) { + if (!this.#previousLineIsBlank) { this._writeNewLine(); } } @@ -162,8 +162,8 @@ export class IndentedWriter { * Returns the last character that was written, or an empty string if no characters have been written yet. */ public peekLastCharacter(): string { - if (this._latestChunk !== undefined) { - return this._latestChunk.substr(-1, 1); + if (this.#latestChunk !== undefined) { + return this.#latestChunk.substr(-1, 1); } return ''; } @@ -173,12 +173,12 @@ export class IndentedWriter { * have been written yet. */ public peekSecondLastCharacter(): string { - if (this._latestChunk !== undefined) { - if (this._latestChunk.length > 1) { - return this._latestChunk.substr(-2, 1); + if (this.#latestChunk !== undefined) { + if (this.#latestChunk.length > 1) { + return this.#latestChunk.substr(-2, 1); } - if (this._previousChunk !== undefined) { - return this._previousChunk.substr(-1, 1); + if (this.#previousChunk !== undefined) { + return this.#previousChunk.substr(-1, 1); } } return ''; @@ -231,44 +231,44 @@ export class IndentedWriter { private _writeLinePart(message: string): void { let trimmedMessage: string = message; - if (this.trimLeadingSpaces && this._atStartOfLine) { + if (this.trimLeadingSpaces && this.#atStartOfLine) { trimmedMessage = message.replace(/^ +/, ''); } if (trimmedMessage.length > 0) { - if (this._atStartOfLine && this._indentText.length > 0) { - this._write(this._indentText); + if (this.#atStartOfLine && this.#indentText.length > 0) { + this._write(this.#indentText); } this._write(trimmedMessage); - if (this._currentLineIsBlank) { + if (this.#currentLineIsBlank) { if (/\S/.test(trimmedMessage)) { - this._currentLineIsBlank = false; + this.#currentLineIsBlank = false; } } - this._atStartOfLine = false; + this.#atStartOfLine = false; } } private _writeNewLine(): void { if (this.indentBlankLines) { - if (this._atStartOfLine && this._indentText.length > 0) { - this._write(this._indentText); + if (this.#atStartOfLine && this.#indentText.length > 0) { + this._write(this.#indentText); } } - this._previousLineIsBlank = this._currentLineIsBlank; + this.#previousLineIsBlank = this.#currentLineIsBlank; this._write('\n'); - this._currentLineIsBlank = true; - this._atStartOfLine = true; + this.#currentLineIsBlank = true; + this.#atStartOfLine = true; } private _write(s: string): void { - this._previousChunk = this._latestChunk; - this._latestChunk = s; - this._builder.append(s); + this.#previousChunk = this.#latestChunk; + this.#latestChunk = s; + this.#builder.append(s); } private _updateIndentText(): void { - this._indentText = this._indentStack.join(''); + this.#indentText = this.#indentStack.join(''); } } diff --git a/libraries/api-extractor-model/src/items/ApiDeclaredItem.ts b/libraries/api-extractor-model/src/items/ApiDeclaredItem.ts index aa4fba36e63..caabb784e1d 100644 --- a/libraries/api-extractor-model/src/items/ApiDeclaredItem.ts +++ b/libraries/api-extractor-model/src/items/ApiDeclaredItem.ts @@ -41,23 +41,23 @@ export interface IApiDeclaredItemJson extends IApiDocumentedItemJson { * @public */ export class ApiDeclaredItem extends ApiDocumentedItem { - private _excerptTokens: ExcerptToken[]; - private _excerpt: Excerpt; - private _fileUrlPath?: string; - private _sourceLocation?: SourceLocation; + #excerptTokens: ExcerptToken[]; + #excerpt: Excerpt; + #fileUrlPath?: string; + #sourceLocation?: SourceLocation; public constructor(options: IApiDeclaredItemOptions) { super(options); - this._excerptTokens = options.excerptTokens.map((token) => { + this.#excerptTokens = options.excerptTokens.map((token) => { const canonicalReference: DeclarationReference | undefined = token.canonicalReference === undefined ? undefined : DeclarationReference.parse(token.canonicalReference); return new ExcerptToken(token.kind, token.text, canonicalReference); }); - this._excerpt = new Excerpt(this.excerptTokens, { startIndex: 0, endIndex: this.excerptTokens.length }); - this._fileUrlPath = options.fileUrlPath; + this.#excerpt = new Excerpt(this.excerptTokens, { startIndex: 0, endIndex: this.excerptTokens.length }); + this.#fileUrlPath = options.fileUrlPath; } public static override onDeserializeInto( @@ -75,14 +75,14 @@ export class ApiDeclaredItem extends ApiDocumentedItem { * The source code excerpt where the API item is declared. */ public get excerpt(): Excerpt { - return this._excerpt; + return this.#excerpt; } /** * The individual source code tokens that comprise the main excerpt. */ public get excerptTokens(): ReadonlyArray { - return this._excerptTokens; + return this.#excerptTokens; } /** @@ -91,17 +91,17 @@ export class ApiDeclaredItem extends ApiDocumentedItem { * the same as the parent API item's. */ public get fileUrlPath(): string | undefined { - return this._fileUrlPath; + return this.#fileUrlPath; } /** * Returns the source location where the API item is declared. */ public get sourceLocation(): SourceLocation { - if (!this._sourceLocation) { - this._sourceLocation = this._buildSourceLocation(); + if (!this.#sourceLocation) { + this.#sourceLocation = this._buildSourceLocation(); } - return this._sourceLocation; + return this.#sourceLocation; } /** diff --git a/libraries/api-extractor-model/src/items/ApiDocumentedItem.ts b/libraries/api-extractor-model/src/items/ApiDocumentedItem.ts index 3fdce63f3a7..8fbc29cf377 100644 --- a/libraries/api-extractor-model/src/items/ApiDocumentedItem.ts +++ b/libraries/api-extractor-model/src/items/ApiDocumentedItem.ts @@ -29,11 +29,11 @@ export interface IApiDocumentedItemJson extends IApiItemJson { * @public */ export class ApiDocumentedItem extends ApiItem { - private _tsdocComment: tsdoc.DocComment | undefined; + #tsdocComment: tsdoc.DocComment | undefined; public constructor(options: IApiDocumentedItemOptions) { super(options); - this._tsdocComment = options.docComment; + this.#tsdocComment = options.docComment; } public static override onDeserializeInto( @@ -59,7 +59,7 @@ export class ApiDocumentedItem extends ApiItem { } public get tsdocComment(): tsdoc.DocComment | undefined { - return this._tsdocComment; + return this.#tsdocComment; } public override serializeInto(jsonObject: Partial): void { diff --git a/libraries/api-extractor-model/src/items/ApiItem.ts b/libraries/api-extractor-model/src/items/ApiItem.ts index 1eb7fb014c6..81988eba990 100644 --- a/libraries/api-extractor-model/src/items/ApiItem.ts +++ b/libraries/api-extractor-model/src/items/ApiItem.ts @@ -64,8 +64,8 @@ export const apiItem_onParentChanged: unique symbol = Symbol('ApiItem._onAddToCo * @public */ export class ApiItem { - private _canonicalReference: DeclarationReference | undefined; - private _parent: ApiItem | undefined; + #canonicalReference: DeclarationReference | undefined; + #parent: ApiItem | undefined; public constructor(options: IApiItemOptions) { // ("options" is not used here, but part of the inheritance pattern) @@ -111,15 +111,15 @@ export class ApiItem { * @beta */ public get canonicalReference(): DeclarationReference { - if (!this._canonicalReference) { + if (!this.#canonicalReference) { try { - this._canonicalReference = this.buildCanonicalReference(); + this.#canonicalReference = this.buildCanonicalReference(); } catch (e) { const name: string = this.getScopedNameWithinPackage() || this.displayName; throw new InternalError(`Error building canonical reference for ${name}:\n` + (e as Error).message); } } - return this._canonicalReference; + return this.#canonicalReference; } /** @@ -168,7 +168,7 @@ export class ApiItem { * @virtual */ public get parent(): ApiItem | undefined { - return this._parent; + return this.#parent; } /** @@ -192,7 +192,7 @@ export class ApiItem { * item of its name/kind, then the result is an array containing only this item. */ public getMergedSiblings(): ReadonlyArray { - const parent: ApiItem | undefined = this._parent; + const parent: ApiItem | undefined = this.#parent; if (parent && ApiItemContainerMixin.isBaseClassOf(parent)) { return parent._getMergedSiblingsForMember(this); } @@ -301,8 +301,8 @@ export class ApiItem { * @internal */ public [apiItem_onParentChanged](parent: ApiItem | undefined): void { - this._parent = parent; - this._canonicalReference = undefined; + this.#parent = parent; + this.#canonicalReference = undefined; } /** diff --git a/libraries/api-extractor-model/src/mixins/Excerpt.ts b/libraries/api-extractor-model/src/mixins/Excerpt.ts index c6060a8448b..18e9bfc6961 100644 --- a/libraries/api-extractor-model/src/mixins/Excerpt.ts +++ b/libraries/api-extractor-model/src/mixins/Excerpt.ts @@ -51,32 +51,32 @@ export interface IExcerptToken { * @public */ export class ExcerptToken { - private readonly _kind: ExcerptTokenKind; - private readonly _text: string; - private readonly _canonicalReference: DeclarationReference | undefined; + readonly #kind: ExcerptTokenKind; + readonly #text: string; + readonly #canonicalReference: DeclarationReference | undefined; public constructor(kind: ExcerptTokenKind, text: string, canonicalReference?: DeclarationReference) { - this._kind = kind; + this.#kind = kind; // Standardize the newlines across operating systems. Even though this may deviate from the actual // input source file that was parsed, it's useful because the newline gets serialized inside // a string literal in .api.json, which cannot be automatically normalized by Git. - this._text = Text.convertToLf(text); - this._canonicalReference = canonicalReference; + this.#text = Text.convertToLf(text); + this.#canonicalReference = canonicalReference; } /** * Indicates the kind of token. */ public get kind(): ExcerptTokenKind { - return this._kind; + return this.#kind; } /** * The text fragment. */ public get text(): string { - return this._text; + return this.#text; } /** @@ -84,7 +84,7 @@ export class ExcerptToken { * this property will be `undefined`. */ public get canonicalReference(): DeclarationReference | undefined { - return this._canonicalReference; + return this.#canonicalReference; } } @@ -131,7 +131,7 @@ export class Excerpt { */ public readonly spannedTokens: ReadonlyArray; - private _text: string | undefined; + #text: string | undefined; public constructor(tokens: ReadonlyArray, tokenRange: IExcerptTokenRange) { this.tokens = tokens; @@ -152,10 +152,10 @@ export class Excerpt { * The excerpted text, formed by concatenating the text of the `spannedTokens` strings. */ public get text(): string { - if (this._text === undefined) { - this._text = this.spannedTokens.map((x) => x.text).join(''); + if (this.#text === undefined) { + this.#text = this.spannedTokens.map((x) => x.text).join(''); } - return this._text; + return this.#text; } /** diff --git a/libraries/api-extractor-model/src/model/ApiClass.ts b/libraries/api-extractor-model/src/model/ApiClass.ts index 8b260e7d052..737b37ffe9f 100644 --- a/libraries/api-extractor-model/src/model/ApiClass.ts +++ b/libraries/api-extractor-model/src/model/ApiClass.ts @@ -87,7 +87,7 @@ export class ApiClass extends ApiItemContainerMixin( */ public readonly extendsType: HeritageType | undefined; - private readonly _implementsTypes: HeritageType[] = []; + readonly #implementsTypes: HeritageType[] = []; public constructor(options: IApiClassOptions) { super(options); @@ -99,7 +99,7 @@ export class ApiClass extends ApiItemContainerMixin( } for (const implementsTokenRange of options.implementsTokenRanges) { - this._implementsTypes.push(new HeritageType(this.buildExcerpt(implementsTokenRange))); + this.#implementsTypes.push(new HeritageType(this.buildExcerpt(implementsTokenRange))); } } @@ -130,7 +130,7 @@ export class ApiClass extends ApiItemContainerMixin( * The list of interfaces that this class implements using the `implements` keyword. */ public get implementsTypes(): ReadonlyArray { - return this._implementsTypes; + return this.#implementsTypes; } public override serializeInto(jsonObject: Partial): void { diff --git a/libraries/api-extractor-model/src/model/ApiInterface.ts b/libraries/api-extractor-model/src/model/ApiInterface.ts index d327c00e3d8..cc040557dc9 100644 --- a/libraries/api-extractor-model/src/model/ApiInterface.ts +++ b/libraries/api-extractor-model/src/model/ApiInterface.ts @@ -83,13 +83,13 @@ export interface IApiInterfaceJson export class ApiInterface extends ApiItemContainerMixin( ApiNameMixin(ApiTypeParameterListMixin(ApiReleaseTagMixin(ApiExportedMixin(ApiDeclaredItem)))) ) { - private readonly _extendsTypes: HeritageType[] = []; + readonly #extendsTypes: HeritageType[] = []; public constructor(options: IApiInterfaceOptions) { super(options); for (const extendsTokenRange of options.extendsTokenRanges) { - this._extendsTypes.push(new HeritageType(this.buildExcerpt(extendsTokenRange))); + this.#extendsTypes.push(new HeritageType(this.buildExcerpt(extendsTokenRange))); } } @@ -119,7 +119,7 @@ export class ApiInterface extends ApiItemContainerMixin( * The list of base interfaces that this interface inherits from using the `extends` keyword. */ public get extendsTypes(): ReadonlyArray { - return this._extendsTypes; + return this.#extendsTypes; } public override serializeInto(jsonObject: Partial): void { diff --git a/libraries/api-extractor-model/src/model/ApiModel.ts b/libraries/api-extractor-model/src/model/ApiModel.ts index 2e7da02319a..337b982c3ba 100644 --- a/libraries/api-extractor-model/src/model/ApiModel.ts +++ b/libraries/api-extractor-model/src/model/ApiModel.ts @@ -51,14 +51,14 @@ import { ModelReferenceResolver, type IResolveDeclarationReferenceResult } from * @public */ export class ApiModel extends ApiItemContainerMixin(ApiItem) { - private readonly _resolver: ModelReferenceResolver; + readonly #resolver: ModelReferenceResolver; - private _packagesByName: Map | undefined = undefined; - private _apiItemsByCanonicalReference: Map | undefined = undefined; + #packagesByName: Map | undefined = undefined; + #apiItemsByCanonicalReference: Map | undefined = undefined; public constructor() { super({}); - this._resolver = new ModelReferenceResolver(this); + this.#resolver = new ModelReferenceResolver(this); } public loadPackage(apiJsonFilename: string): ApiPackage { @@ -84,8 +84,8 @@ export class ApiModel extends ApiItemContainerMixin(ApiItem) { throw new Error('Only items of type ApiPackage may be added to an ApiModel'); } super.addMember(member); - this._packagesByName = undefined; // invalidate the cache - this._apiItemsByCanonicalReference = undefined; // invalidate the cache + this.#packagesByName = undefined; // invalidate the cache + this.#apiItemsByCanonicalReference = undefined; // invalidate the cache } /** @@ -99,18 +99,18 @@ export class ApiModel extends ApiItemContainerMixin(ApiItem) { */ public tryGetPackageByName(packageName: string): ApiPackage | undefined { // Build the lookup on demand - if (this._packagesByName === undefined) { - this._packagesByName = new Map(); + if (this.#packagesByName === undefined) { + this.#packagesByName = new Map(); const unscopedMap: Map = new Map(); for (const apiPackage of this.packages) { - if (this._packagesByName.get(apiPackage.name)) { + if (this.#packagesByName.get(apiPackage.name)) { // This should not happen throw new Error(`The model contains multiple packages with the name ${apiPackage.name}`); } - this._packagesByName.set(apiPackage.name, apiPackage); + this.#packagesByName.set(apiPackage.name, apiPackage); const unscopedName: string = PackageName.parse(apiPackage.name).unscopedName; @@ -124,15 +124,15 @@ export class ApiModel extends ApiItemContainerMixin(ApiItem) { for (const [unscopedName, apiPackage] of unscopedMap) { if (apiPackage) { - if (!this._packagesByName.has(unscopedName)) { + if (!this.#packagesByName.has(unscopedName)) { // If the unscoped name is unambiguous, then we can also use it as a lookup - this._packagesByName.set(unscopedName, apiPackage); + this.#packagesByName.set(unscopedName, apiPackage); } } } } - return this._packagesByName.get(packageName); + return this.#packagesByName.get(packageName); } public resolveDeclarationReference( @@ -140,16 +140,16 @@ export class ApiModel extends ApiItemContainerMixin(ApiItem) { contextApiItem: ApiItem | undefined ): IResolveDeclarationReferenceResult { if (declarationReference instanceof DocDeclarationReference) { - return this._resolver.resolve(declarationReference, contextApiItem); + return this.#resolver.resolve(declarationReference, contextApiItem); } else if (declarationReference instanceof DeclarationReference) { // use this._apiItemsByCanonicalReference to look up ApiItem // Build the lookup on demand - if (!this._apiItemsByCanonicalReference) { - this._apiItemsByCanonicalReference = new Map(); + if (!this.#apiItemsByCanonicalReference) { + this.#apiItemsByCanonicalReference = new Map(); for (const apiPackage of this.packages) { - this._initApiItemsRecursive(apiPackage, this._apiItemsByCanonicalReference); + this._initApiItemsRecursive(apiPackage, this.#apiItemsByCanonicalReference); } } @@ -158,7 +158,7 @@ export class ApiModel extends ApiItemContainerMixin(ApiItem) { errorMessage: undefined }; - const apiItem: ApiItem | undefined = this._apiItemsByCanonicalReference.get( + const apiItem: ApiItem | undefined = this.#apiItemsByCanonicalReference.get( declarationReference.toString() ); diff --git a/libraries/api-extractor-model/src/model/ApiPackage.ts b/libraries/api-extractor-model/src/model/ApiPackage.ts index aa9dc373cd6..dfec4985b47 100644 --- a/libraries/api-extractor-model/src/model/ApiPackage.ts +++ b/libraries/api-extractor-model/src/model/ApiPackage.ts @@ -130,14 +130,14 @@ export interface IApiPackageSaveOptions extends IJsonFileSaveOptions { * @public */ export class ApiPackage extends ApiItemContainerMixin(ApiNameMixin(ApiDocumentedItem)) { - private readonly _tsdocConfiguration: TSDocConfiguration; - private readonly _projectFolderUrl?: string; + readonly #tsdocConfiguration: TSDocConfiguration; + readonly #projectFolderUrl?: string; public constructor(options: IApiPackageOptions) { super(options); - this._tsdocConfiguration = options.tsdocConfiguration; - this._projectFolderUrl = options.projectFolderUrl; + this.#tsdocConfiguration = options.tsdocConfiguration; + this.#projectFolderUrl = options.projectFolderUrl; } public static override onDeserializeInto( @@ -244,11 +244,11 @@ export class ApiPackage extends ApiItemContainerMixin(ApiNameMixin(ApiDocumented * in the .api.json file so that doc comments can be parsed accurately when loading the file. */ public get tsdocConfiguration(): TSDocConfiguration { - return this._tsdocConfiguration; + return this.#tsdocConfiguration; } public get projectFolderUrl(): string | undefined { - return this._projectFolderUrl; + return this.#projectFolderUrl; } public override addMember(member: ApiEntryPoint): void { diff --git a/libraries/api-extractor-model/src/model/ModelReferenceResolver.ts b/libraries/api-extractor-model/src/model/ModelReferenceResolver.ts index e8282dedaab..4c0334a1ba8 100644 --- a/libraries/api-extractor-model/src/model/ModelReferenceResolver.ts +++ b/libraries/api-extractor-model/src/model/ModelReferenceResolver.ts @@ -37,10 +37,10 @@ export interface IResolveDeclarationReferenceResult { * which resolves declaration references by walking the compiler state. */ export class ModelReferenceResolver { - private readonly _apiModel: ApiModel; + readonly #apiModel: ApiModel; public constructor(apiModel: ApiModel) { - this._apiModel = apiModel; + this.#apiModel = apiModel; } public resolve( @@ -56,7 +56,7 @@ export class ModelReferenceResolver { // Is this an absolute reference? if (declarationReference.packageName !== undefined) { - apiPackage = this._apiModel.tryGetPackageByName(declarationReference.packageName); + apiPackage = this.#apiModel.tryGetPackageByName(declarationReference.packageName); if (apiPackage === undefined) { result.errorMessage = `The package "${declarationReference.packageName}" could not be located`; return result; diff --git a/libraries/api-extractor-model/src/model/Parameter.ts b/libraries/api-extractor-model/src/model/Parameter.ts index d802380c443..6481574acd5 100644 --- a/libraries/api-extractor-model/src/model/Parameter.ts +++ b/libraries/api-extractor-model/src/model/Parameter.ts @@ -51,22 +51,22 @@ export class Parameter { */ public isOptional: boolean; - private _parent: ApiParameterListMixin; + #parent: ApiParameterListMixin; public constructor(options: IParameterOptions) { this.name = options.name; this.parameterTypeExcerpt = options.parameterTypeExcerpt; this.isOptional = options.isOptional; - this._parent = options.parent; + this.#parent = options.parent; } /** * Returns the `@param` documentation for this parameter, if present. */ public get tsdocParamBlock(): tsdoc.DocParamBlock | undefined { - if (this._parent instanceof ApiDocumentedItem) { - if (this._parent.tsdocComment) { - return this._parent.tsdocComment.params.tryGetBlockByName(this.name); + if (this.#parent instanceof ApiDocumentedItem) { + if (this.#parent.tsdocComment) { + return this.#parent.tsdocComment.params.tryGetBlockByName(this.name); } } } diff --git a/libraries/api-extractor-model/src/model/SourceLocation.ts b/libraries/api-extractor-model/src/model/SourceLocation.ts index 4d92a07c66c..412062348ad 100644 --- a/libraries/api-extractor-model/src/model/SourceLocation.ts +++ b/libraries/api-extractor-model/src/model/SourceLocation.ts @@ -32,12 +32,12 @@ export interface ISourceLocationOptions { * @public */ export class SourceLocation { - private readonly _projectFolderUrl?: string; - private readonly _fileUrlPath?: string; + readonly #projectFolderUrl?: string; + readonly #fileUrlPath?: string; public constructor(options: ISourceLocationOptions) { - this._projectFolderUrl = options.projectFolderUrl; - this._fileUrlPath = options.fileUrlPath; + this.#projectFolderUrl = options.projectFolderUrl; + this.#fileUrlPath = options.fileUrlPath; } /** @@ -45,16 +45,16 @@ export class SourceLocation { * cannot be determined. */ public get fileUrl(): string | undefined { - if (this._projectFolderUrl === undefined || this._fileUrlPath === undefined) { + if (this.#projectFolderUrl === undefined || this.#fileUrlPath === undefined) { return undefined; } - let projectFolderUrl: string = this._projectFolderUrl; + let projectFolderUrl: string = this.#projectFolderUrl; if (!projectFolderUrl.endsWith('/')) { projectFolderUrl += '/'; } - const url: URL = new URL(this._fileUrlPath, projectFolderUrl); + const url: URL = new URL(this.#fileUrlPath, projectFolderUrl); return url.href; } } diff --git a/libraries/api-extractor-model/src/model/TypeParameter.ts b/libraries/api-extractor-model/src/model/TypeParameter.ts index 55fd019fdca..1c4edb41163 100644 --- a/libraries/api-extractor-model/src/model/TypeParameter.ts +++ b/libraries/api-extractor-model/src/model/TypeParameter.ts @@ -84,7 +84,7 @@ export class TypeParameter { */ public isOptional: boolean; - private _parent: ApiTypeParameterListMixin; + #parent: ApiTypeParameterListMixin; public constructor(options: ITypeParameterOptions) { const { name, constraintExcerpt, defaultTypeExcerpt, isOptional, parent } = options; @@ -92,16 +92,16 @@ export class TypeParameter { this.constraintExcerpt = constraintExcerpt; this.defaultTypeExcerpt = defaultTypeExcerpt; this.isOptional = isOptional; - this._parent = parent; + this.#parent = parent; } /** * Returns the `@typeParam` documentation for this parameter, if present. */ public get tsdocTypeParamBlock(): tsdoc.DocParamBlock | undefined { - if (this._parent instanceof ApiDocumentedItem) { - if (this._parent.tsdocComment) { - return this._parent.tsdocComment.typeParams.tryGetBlockByName(this.name); + if (this.#parent instanceof ApiDocumentedItem) { + if (this.#parent.tsdocComment) { + return this.#parent.tsdocComment.typeParams.tryGetBlockByName(this.name); } } } diff --git a/libraries/credential-cache/src/CredentialCache.ts b/libraries/credential-cache/src/CredentialCache.ts index 198887c25fd..d71d3594beb 100644 --- a/libraries/credential-cache/src/CredentialCache.ts +++ b/libraries/credential-cache/src/CredentialCache.ts @@ -50,12 +50,12 @@ export interface ICredentialCacheOptions { * @public */ export class CredentialCache implements Disposable { - private readonly _cacheFilePath: string; - private readonly _cacheEntries: Map; - private _modified: boolean = false; - private _disposed: boolean = false; - private readonly _supportsEditing: boolean; - private readonly _lockfile: LockFile | undefined; + readonly #cacheFilePath: string; + readonly #cacheEntries: Map; + #modified: boolean = false; + #disposed: boolean = false; + readonly #supportsEditing: boolean; + readonly #lockfile: LockFile | undefined; private constructor( cacheFilePath: string, @@ -66,10 +66,10 @@ export class CredentialCache implements Disposable { throw new Error(`Unexpected ${cacheFilePath} file version: ${loadedJson.version}`); } - this._cacheFilePath = cacheFilePath; - this._cacheEntries = new Map(Object.entries(loadedJson?.cacheEntries || {})); - this._supportsEditing = !!lockfile; - this._lockfile = lockfile; + this.#cacheFilePath = cacheFilePath; + this.#cacheEntries = new Map(Object.entries(loadedJson?.cacheEntries || {})); + this.#supportsEditing = !!lockfile; + this.#lockfile = lockfile; } public static async initializeAsync(options: ICredentialCacheOptions): Promise { @@ -121,14 +121,14 @@ export class CredentialCache implements Disposable { const { expires, credential, credentialMetadata } = entry; const expiresMilliseconds: number = expires?.getTime() || 0; - const existingCacheEntry: ICacheEntryJson | undefined = this._cacheEntries.get(cacheId); + const existingCacheEntry: ICacheEntryJson | undefined = this.#cacheEntries.get(cacheId); if ( existingCacheEntry?.credential !== credential || existingCacheEntry?.expires !== expiresMilliseconds || !Objects.areDeepEqual(existingCacheEntry?.credentialMetadata, credentialMetadata) ) { - this._modified = true; - this._cacheEntries.set(cacheId, { + this.#modified = true; + this.#cacheEntries.set(cacheId, { expires: expiresMilliseconds, credential, credentialMetadata @@ -139,7 +139,7 @@ export class CredentialCache implements Disposable { public tryGetCacheEntry(cacheId: string): ICredentialCacheEntry | undefined { this._validate(false); - const cacheEntry: ICacheEntryJson | undefined = this._cacheEntries.get(cacheId); + const cacheEntry: ICacheEntryJson | undefined = this.#cacheEntries.get(cacheId); if (cacheEntry) { const result: ICredentialCacheEntry = { expires: cacheEntry.expires ? new Date(cacheEntry.expires) : undefined, @@ -156,9 +156,9 @@ export class CredentialCache implements Disposable { public deleteCacheEntry(cacheId: string): void { this._validate(true); - if (this._cacheEntries.has(cacheId)) { - this._modified = true; - this._cacheEntries.delete(cacheId); + if (this.#cacheEntries.has(cacheId)) { + this.#modified = true; + this.#cacheEntries.delete(cacheId); } } @@ -166,10 +166,10 @@ export class CredentialCache implements Disposable { this._validate(true); const now: number = Date.now(); - for (const [cacheId, cacheEntry] of this._cacheEntries.entries()) { + for (const [cacheId, cacheEntry] of this.#cacheEntries.entries()) { if (cacheEntry.expires < now) { - this._cacheEntries.delete(cacheId); - this._modified = true; + this.#cacheEntries.delete(cacheId); + this.#modified = true; } } } @@ -177,9 +177,9 @@ export class CredentialCache implements Disposable { public async saveIfModifiedAsync(): Promise { this._validate(true); - if (this._modified) { + if (this.#modified) { const cacheEntriesJson: { [cacheId: string]: ICacheEntryJson } = {}; - for (const [cacheId, cacheEntry] of this._cacheEntries.entries()) { + for (const [cacheId, cacheEntry] of this.#cacheEntries.entries()) { cacheEntriesJson[cacheId] = cacheEntry; } @@ -187,13 +187,13 @@ export class CredentialCache implements Disposable { version: LATEST_CREDENTIALS_JSON_VERSION, cacheEntries: cacheEntriesJson }; - await JsonFile.saveAsync(newJson, this._cacheFilePath, { + await JsonFile.saveAsync(newJson, this.#cacheFilePath, { ensureFolderExists: true, updateExistingFile: true, ignoreUndefinedValues: true }); - this._modified = false; + this.#modified = false; } } @@ -202,16 +202,16 @@ export class CredentialCache implements Disposable { } public dispose(): void { - this._lockfile?.release(); - this._disposed = true; + this.#lockfile?.release(); + this.#disposed = true; } private _validate(requiresEditing: boolean): void { - if (!this._supportsEditing && requiresEditing) { + if (!this.#supportsEditing && requiresEditing) { throw new Error(`This instance of ${CredentialCache.name} does not support editing.`); } - if (this._disposed) { + if (this.#disposed) { throw new Error(`This instance of ${CredentialCache.name} has been disposed.`); } } diff --git a/libraries/debug-certificate-manager/src/CertificateStore.ts b/libraries/debug-certificate-manager/src/CertificateStore.ts index 4f3ff73d1fa..19de34b38d1 100644 --- a/libraries/debug-certificate-manager/src/CertificateStore.ts +++ b/libraries/debug-certificate-manager/src/CertificateStore.ts @@ -38,14 +38,14 @@ export interface ICertificateStoreOptions { * @public */ export class CertificateStore { - private readonly _caCertificatePath: string; - private readonly _certificatePath: string; - private readonly _keyPath: string; - private readonly _storePath: string; + readonly #caCertificatePath: string; + readonly #certificatePath: string; + readonly #keyPath: string; + readonly #storePath: string; - private _caCertificateData: string | undefined; - private _certificateData: string | undefined; - private _keyData: string | undefined; + #caCertificateData: string | undefined; + #certificateData: string | undefined; + #keyData: string | undefined; public constructor(options: ICertificateStoreOptions = {}) { const requestedStorePath: string | undefined = options.storePath; @@ -113,47 +113,47 @@ export class CertificateStore { options.keyFilename ?? debugCertificateManagerConfig?.keyFilename ?? 'rushstack-serve.key' ); - this._storePath = storePath; - this._caCertificatePath = caCertificatePath; - this._certificatePath = certificatePath; - this._keyPath = keyPath; + this.#storePath = storePath; + this.#caCertificatePath = caCertificatePath; + this.#certificatePath = certificatePath; + this.#keyPath = keyPath; } /** * Path to the directory where the debug certificates are stored. */ public get storePath(): string { - return this._storePath; + return this.#storePath; } /** * Path to the saved debug CA certificate */ public get caCertificatePath(): string { - return this._caCertificatePath; + return this.#caCertificatePath; } /** * Path to the saved debug TLS certificate */ public get certificatePath(): string { - return this._certificatePath; + return this.#certificatePath; } /** * Path to the saved debug TLS key */ public get keyPath(): string { - return this._keyPath; + return this.#keyPath; } /** * Debug Certificate Authority certificate pem file contents. */ public get caCertificateData(): string | undefined { - if (!this._caCertificateData) { + if (!this.#caCertificateData) { try { - this._caCertificateData = FileSystem.readFile(this._caCertificatePath); + this.#caCertificateData = FileSystem.readFile(this.#caCertificatePath); } catch (err) { if (!FileSystem.isNotExistError(err)) { throw err; @@ -161,26 +161,26 @@ export class CertificateStore { } } - return this._caCertificateData; + return this.#caCertificateData; } public set caCertificateData(certificate: string | undefined) { if (certificate) { - FileSystem.writeFile(this._caCertificatePath, certificate); - } else if (FileSystem.exists(this._caCertificatePath)) { - FileSystem.deleteFile(this._caCertificatePath); + FileSystem.writeFile(this.#caCertificatePath, certificate); + } else if (FileSystem.exists(this.#caCertificatePath)) { + FileSystem.deleteFile(this.#caCertificatePath); } - this._caCertificateData = certificate; + this.#caCertificateData = certificate; } /** * Debug TLS Server certificate pem file contents. */ public get certificateData(): string | undefined { - if (!this._certificateData) { + if (!this.#certificateData) { try { - this._certificateData = FileSystem.readFile(this._certificatePath); + this.#certificateData = FileSystem.readFile(this.#certificatePath); } catch (err) { if (!FileSystem.isNotExistError(err)) { throw err; @@ -188,26 +188,26 @@ export class CertificateStore { } } - return this._certificateData; + return this.#certificateData; } public set certificateData(certificate: string | undefined) { if (certificate) { - FileSystem.writeFile(this._certificatePath, certificate); - } else if (FileSystem.exists(this._certificatePath)) { - FileSystem.deleteFile(this._certificatePath); + FileSystem.writeFile(this.#certificatePath, certificate); + } else if (FileSystem.exists(this.#certificatePath)) { + FileSystem.deleteFile(this.#certificatePath); } - this._certificateData = certificate; + this.#certificateData = certificate; } /** * Key used to sign the debug pem certificate. */ public get keyData(): string | undefined { - if (!this._keyData) { + if (!this.#keyData) { try { - this._keyData = FileSystem.readFile(this._keyPath); + this.#keyData = FileSystem.readFile(this.#keyPath); } catch (err) { if (!FileSystem.isNotExistError(err)) { throw err; @@ -215,16 +215,16 @@ export class CertificateStore { } } - return this._keyData; + return this.#keyData; } public set keyData(key: string | undefined) { if (key) { - FileSystem.writeFile(this._keyPath, key); - } else if (FileSystem.exists(this._keyPath)) { - FileSystem.deleteFile(this._keyPath); + FileSystem.writeFile(this.#keyPath, key); + } else if (FileSystem.exists(this.#keyPath)) { + FileSystem.deleteFile(this.#keyPath); } - this._keyData = key; + this.#keyData = key; } } diff --git a/libraries/heft-config-file/src/ConfigurationFileBase.ts b/libraries/heft-config-file/src/ConfigurationFileBase.ts index 6f484f6fded..b3e2b41ee49 100644 --- a/libraries/heft-config-file/src/ConfigurationFileBase.ts +++ b/libraries/heft-config-file/src/ConfigurationFileBase.ts @@ -425,23 +425,23 @@ export type IOnConfigurationFileNotFoundCallback = ( * @beta */ export abstract class ConfigurationFileBase { - private readonly _getSchema: () => JsonSchema; + readonly #getSchema: () => JsonSchema; - private readonly _jsonPathMetadata: readonly [string, IJsonPathMetadata][]; - private readonly _propertyInheritanceTypes: IPropertiesInheritance; - private readonly _defaultPropertyInheritance: IPropertyInheritanceDefaults; - private readonly _customValidationFunction: CustomValidationFunction | undefined; - private __schema: JsonSchema | undefined; + readonly #jsonPathMetadata: readonly [string, IJsonPathMetadata][]; + readonly #propertyInheritanceTypes: IPropertiesInheritance; + readonly #defaultPropertyInheritance: IPropertyInheritanceDefaults; + readonly #customValidationFunction: CustomValidationFunction | undefined; + #_schema: JsonSchema | undefined; private get _schema(): JsonSchema { - if (!this.__schema) { - this.__schema = this._getSchema(); + if (!this.#_schema) { + this.#_schema = this.#getSchema(); } - return this.__schema; + return this.#_schema; } - private readonly _configCache: Map> = new Map(); - private readonly _configPromiseCache: Map< + readonly #configCache: Map> = new Map(); + readonly #configPromiseCache: Map< string, Promise> > = new Map(); @@ -456,15 +456,15 @@ export abstract class ConfigurationFileBase JsonSchema.fromLoadedObject(jsonSchemaObject); + this.#getSchema = () => JsonSchema.fromLoadedObject(jsonSchemaObject); } else { - this._getSchema = () => JsonSchema.fromFile(jsonSchemaPath); + this.#getSchema = () => JsonSchema.fromFile(jsonSchemaPath); } - this._jsonPathMetadata = Object.entries(jsonPathMetadata); - this._propertyInheritanceTypes = propertyInheritance; - this._defaultPropertyInheritance = propertyInheritanceDefaults; - this._customValidationFunction = customValidationFunction; + this.#jsonPathMetadata = Object.entries(jsonPathMetadata); + this.#propertyInheritanceTypes = propertyInheritance; + this.#defaultPropertyInheritance = propertyInheritanceDefaults; + this.#customValidationFunction = customValidationFunction; } /** @@ -569,7 +569,7 @@ export abstract class ConfigurationFileBase | undefined = this._configCache.get( + let cacheEntry: IConfigurationFileCacheEntry | undefined = this.#configCache.get( resolvedConfigurationFilePath ); if (!cacheEntry) { @@ -579,7 +579,7 @@ export abstract class ConfigurationFileBase> | undefined = - this._configPromiseCache.get(resolvedConfigurationFilePath); + this.#configPromiseCache.get(resolvedConfigurationFilePath); if (!cacheEntryPromise) { cacheEntryPromise = this._loadConfigurationFileEntryAsync( terminal, @@ -611,10 +611,10 @@ export abstract class ConfigurationFileBase) => { - this._configCache.set(resolvedConfigurationFilePath, value); + this.#configCache.set(resolvedConfigurationFilePath, value); return value; }); - this._configPromiseCache.set(resolvedConfigurationFilePath, cacheEntryPromise); + this.#configPromiseCache.set(resolvedConfigurationFilePath, cacheEntryPromise); } return await cacheEntryPromise; @@ -659,7 +659,7 @@ export abstract class ConfigurationFileBase, + this.#defaultPropertyInheritance, + this.#propertyInheritanceTypes as IPropertiesInheritance<{ [key: string]: unknown }>, ignoreProperties ) as Partial; diff --git a/libraries/lookup-by-path/src/LookupByPath.ts b/libraries/lookup-by-path/src/LookupByPath.ts index 638cf7274e2..6673296d85e 100644 --- a/libraries/lookup-by-path/src/LookupByPath.ts +++ b/libraries/lookup-by-path/src/LookupByPath.ts @@ -285,12 +285,12 @@ export class LookupByPath implements IReadonlyLookupByPath; + readonly #root: IPathTrieNode; /** * The number of entries in this trie. */ - private _size: number; + #size: number; /** * Constructs a new `LookupByPath` @@ -298,13 +298,13 @@ export class LookupByPath implements IReadonlyLookupByPath, delimiter?: string) { - this._root = { + this.#root = { value: undefined, children: undefined }; this.delimiter = delimiter ?? '/'; - this._size = 0; + this.#size = 0; if (entries) { for (const [path, item] of entries) { @@ -332,14 +332,14 @@ export class LookupByPath implements IReadonlyLookupByPath { - return this._root; + return this.#root; } /** @@ -348,9 +348,9 @@ export class LookupByPath implements IReadonlyLookupByPath implements IReadonlyLookupByPath | undefined = this._findNodeAtPrefix(query, delimeter); if (node?.value !== undefined) { node.value = undefined; - this._size--; + this.#size--; return true; } @@ -411,7 +411,7 @@ export class LookupByPath implements IReadonlyLookupByPath 0; } @@ -422,7 +422,7 @@ export class LookupByPath implements IReadonlyLookupByPath, value: TItem): this { - let node: IPathTrieNode = this._root; + let node: IPathTrieNode = this.#root; for (const segment of pathSegments) { if (!node.children) { node.children = new Map(); @@ -440,7 +440,7 @@ export class LookupByPath implements IReadonlyLookupByPath implements IReadonlyLookupByPath): TItem | undefined { - let node: IPathTrieNode = this._root; + let node: IPathTrieNode = this.#root; let best: TItem | undefined = node.value; // Trivial cases if (node.children) { @@ -540,7 +540,7 @@ export class LookupByPath implements IReadonlyLookupByPath][] = [[query ?? '', root]]; @@ -617,7 +617,7 @@ export class LookupByPath implements IReadonlyLookupByPath implements IReadonlyLookupByPath { if (jsonNode.valueIndex !== undefined) { targetNode.value = deserializedValues[jsonNode.valueIndex]; - result._size++; + result.#size++; } if (jsonNode.children) { @@ -664,7 +664,7 @@ export class LookupByPath implements IReadonlyLookupByPath implements IReadonlyLookupByPath): IPrefixMatch | undefined { - let node: IPathTrieNode = this._root; + let node: IPathTrieNode = this.#root; let best: IPrefixMatch | undefined = node.value ? { value: node.value, @@ -720,7 +720,7 @@ export class LookupByPath implements IReadonlyLookupByPath | undefined { - let node: IPathTrieNode = this._root; + let node: IPathTrieNode = this.#root; for (const { prefix } of _iteratePrefixes(query, delimiter)) { if (!node.children) { return undefined; diff --git a/libraries/module-minifier/src/LocalMinifier.ts b/libraries/module-minifier/src/LocalMinifier.ts index 9f64006cc0f..1d0bed697a1 100644 --- a/libraries/module-minifier/src/LocalMinifier.ts +++ b/libraries/module-minifier/src/LocalMinifier.ts @@ -28,15 +28,15 @@ export interface ILocalMinifierOptions { * @public */ export class LocalMinifier implements IModuleMinifier { - private readonly _terserOptions: MinifyOptions; + readonly #terserOptions: MinifyOptions; - private readonly _resultCache: Map; - private readonly _configHash: string; + readonly #resultCache: Map; + readonly #configHash: string; public constructor(options: ILocalMinifierOptions) { const { terserOptions = {} } = options || {}; - this._terserOptions = { + this.#terserOptions = { ...terserOptions, output: terserOptions.output ? { @@ -47,13 +47,13 @@ export class LocalMinifier implements IModuleMinifier { const { version: terserVersion } = require('terser/package.json'); - this._configHash = createHash('sha256') + this.#configHash = createHash('sha256') .update(LocalMinifier.name, 'utf8') .update(`terser@${terserVersion}`) .update(serialize(terserOptions)) .digest('base64'); - this._resultCache = new Map(); + this.#resultCache = new Map(); } /** @@ -64,14 +64,14 @@ export class LocalMinifier implements IModuleMinifier { public minify(request: IModuleMinificationRequest, callback: IModuleMinificationCallback): void { const { hash } = request; - const cached: IModuleMinificationResult | undefined = this._resultCache.get(hash); + const cached: IModuleMinificationResult | undefined = this.#resultCache.get(hash); if (cached) { return callback(cached); } - minifySingleFileAsync(request, this._terserOptions) + minifySingleFileAsync(request, this.#terserOptions) .then((result: IModuleMinificationResult) => { - this._resultCache.set(hash, result); + this.#resultCache.set(hash, result); callback(result); }) .catch((error) => { @@ -93,7 +93,7 @@ export class LocalMinifier implements IModuleMinifier { // Do nothing. }; return { - configHash: this._configHash, + configHash: this.#configHash, disconnectAsync, disconnect: disconnectAsync }; diff --git a/libraries/module-minifier/src/MessagePortMinifier.ts b/libraries/module-minifier/src/MessagePortMinifier.ts index 45259e90665..e727ef8c9cb 100644 --- a/libraries/module-minifier/src/MessagePortMinifier.ts +++ b/libraries/module-minifier/src/MessagePortMinifier.ts @@ -19,11 +19,11 @@ import type { export class MessagePortMinifier implements IModuleMinifier { public readonly port: WorkerThreads.MessagePort; - private readonly _callbacks: Map; + readonly #callbacks: Map; public constructor(port: WorkerThreads.MessagePort) { this.port = port; - this._callbacks = new Map(); + this.#callbacks = new Map(); } /** @@ -34,13 +34,13 @@ export class MessagePortMinifier implements IModuleMinifier { public minify(request: IModuleMinificationRequest, callback: IModuleMinificationCallback): void { const { hash } = request; - const callbacks: IModuleMinificationCallback[] | undefined = this._callbacks.get(hash); + const callbacks: IModuleMinificationCallback[] | undefined = this.#callbacks.get(hash); if (callbacks) { callbacks.push(callback); return; } - this._callbacks.set(hash, [callback]); + this.#callbacks.set(hash, [callback]); this.port.postMessage(request); } @@ -53,7 +53,7 @@ export class MessagePortMinifier implements IModuleMinifier { this.port.postMessage('initialize'); const configHash: string = await configHashPromise; - const callbacks: Map = this._callbacks; + const callbacks: Map = this.#callbacks; function handler(message: IModuleMinificationResult | number | false): void { if (typeof message === 'object') { diff --git a/libraries/module-minifier/src/WorkerPoolMinifier.ts b/libraries/module-minifier/src/WorkerPoolMinifier.ts index 4a81fbc75a0..4d76d234229 100644 --- a/libraries/module-minifier/src/WorkerPoolMinifier.ts +++ b/libraries/module-minifier/src/WorkerPoolMinifier.ts @@ -50,16 +50,16 @@ export interface IWorkerPoolMinifierOptions { * @public */ export class WorkerPoolMinifier implements IModuleMinifier { - private readonly _pool: WorkerPool; - private readonly _verbose: boolean; - private readonly _configHash: string; + readonly #pool: WorkerPool; + readonly #verbose: boolean; + readonly #configHash: string; - private _refCount: number; - private _deduped: number; - private _minified: number; + #refCount: number; + #deduped: number; + #minified: number; - private readonly _resultCache: Map; - private readonly _activeRequests: Map; + readonly #resultCache: Map; + readonly #activeRequests: Map; public constructor(options: IWorkerPoolMinifierOptions) { const { @@ -81,28 +81,28 @@ export class WorkerPoolMinifier implements IModuleMinifier { const { version: terserVersion } = require('terser/package.json'); - this._configHash = createHash('sha256') + this.#configHash = createHash('sha256') .update(WorkerPoolMinifier.name, 'utf8') .update(`terser@${terserVersion}`) .update(serialize(terserOptions)) .digest('base64'); - this._activeRequests = activeRequests; - this._refCount = 0; - this._resultCache = resultCache; - this._pool = terserPool; - this._verbose = verbose; + this.#activeRequests = activeRequests; + this.#refCount = 0; + this.#resultCache = resultCache; + this.#pool = terserPool; + this.#verbose = verbose; - this._deduped = 0; - this._minified = 0; + this.#deduped = 0; + this.#minified = 0; } public get maxThreads(): number { - return this._pool.maxWorkers; + return this.#pool.maxWorkers; } public set maxThreads(threads: number) { - this._pool.maxWorkers = threads; + this.#pool.maxWorkers = threads; } /** @@ -113,47 +113,46 @@ export class WorkerPoolMinifier implements IModuleMinifier { public minify(request: IModuleMinificationRequest, callback: IModuleMinificationCallback): void { const { hash } = request; - const cached: IModuleMinificationResult | undefined = this._resultCache.get(hash); + const cached: IModuleMinificationResult | undefined = this.#resultCache.get(hash); if (cached) { - ++this._deduped; + ++this.#deduped; return callback(cached); } - const { _activeRequests: activeRequests } = this; - const callbacks: IModuleMinificationCallback[] | undefined = activeRequests.get(hash); + const callbacks: IModuleMinificationCallback[] | undefined = this.#activeRequests.get(hash); if (callbacks) { - ++this._deduped; + ++this.#deduped; callbacks.push(callback); return; } - activeRequests.set(hash, [callback]); - ++this._minified; + this.#activeRequests.set(hash, [callback]); + ++this.#minified; - this._pool + this.#pool .checkoutWorkerAsync(true) .then((worker) => { const cb: (message: IModuleMinificationResult) => void = ( message: IModuleMinificationResult ): void => { worker.off('message', cb); - const workerCallbacks: IModuleMinificationCallback[] | undefined = activeRequests.get( + const workerCallbacks: IModuleMinificationCallback[] | undefined = this.#activeRequests.get( message.hash )!; - activeRequests.delete(message.hash); - this._resultCache.set(message.hash, message); + this.#activeRequests.delete(message.hash); + this.#resultCache.set(message.hash, message); for (const workerCallback of workerCallbacks) { workerCallback(message); } // This should always be the last thing done with the worker - this._pool.checkinWorker(worker); + this.#pool.checkinWorker(worker); }; worker.on('message', cb); worker.postMessage(request); }) .catch((error: Error) => { - const errorCallbacks: IModuleMinificationCallback[] = activeRequests.get(hash)!; + const errorCallbacks: IModuleMinificationCallback[] = this.#activeRequests.get(hash)!; for (const errorCallback of errorCallbacks) { errorCallback({ hash, @@ -169,30 +168,30 @@ export class WorkerPoolMinifier implements IModuleMinifier { * {@inheritdoc IModuleMinifier.connectAsync} */ public async connectAsync(): Promise { - if (++this._refCount === 1) { - this._pool.reset(); + if (++this.#refCount === 1) { + this.#pool.reset(); } const disconnectAsync: IMinifierConnection['disconnectAsync'] = async () => { - if (--this._refCount === 0) { - if (this._verbose) { + if (--this.#refCount === 0) { + if (this.#verbose) { // eslint-disable-next-line no-console console.log(`Shutting down minifier worker pool`); } - await this._pool.finishAsync(); - this._resultCache.clear(); - this._activeRequests.clear(); - if (this._verbose) { + await this.#pool.finishAsync(); + this.#resultCache.clear(); + this.#activeRequests.clear(); + if (this.#verbose) { // eslint-disable-next-line no-console - console.log(`Module minification: ${this._deduped} Deduped, ${this._minified} Processed`); + console.log(`Module minification: ${this.#deduped} Deduped, ${this.#minified} Processed`); } } - this._deduped = 0; - this._minified = 0; + this.#deduped = 0; + this.#minified = 0; }; return { - configHash: this._configHash, + configHash: this.#configHash, disconnectAsync, disconnect: disconnectAsync diff --git a/libraries/npm-check-fork/src/NpmRegistryClient.ts b/libraries/npm-check-fork/src/NpmRegistryClient.ts index b8a000b2e1f..62068f1b16d 100644 --- a/libraries/npm-check-fork/src/NpmRegistryClient.ts +++ b/libraries/npm-check-fork/src/NpmRegistryClient.ts @@ -62,16 +62,16 @@ const DEFAULT_TIMEOUT_MS: number = 30000; * @public */ export class NpmRegistryClient { - private readonly _registryUrl: string; - private readonly _userAgent: string; - private readonly _timeoutMs: number; + readonly #registryUrl: string; + readonly #userAgent: string; + readonly #timeoutMs: number; public constructor(options?: INpmRegistryClientOptions) { // trim trailing slash if one was provided - this._registryUrl = (options?.registryUrl ?? DEFAULT_REGISTRY_URL).replace(/\/$/, ''); - this._userAgent = + this.#registryUrl = (options?.registryUrl ?? DEFAULT_REGISTRY_URL).replace(/\/$/, ''); + this.#userAgent = options?.userAgent ?? `npm-check-fork node/${process.version} ${os.platform()} ${os.arch()}`; - this._timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS; + this.#timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS; } /** @@ -88,7 +88,7 @@ export class NpmRegistryClient { // Scoped packages need the slash encoded // @scope/name -> @scope%2Fname const encodedName: string = packageName.replace(/\//g, '%2F'); - return `${this._registryUrl}/${encodedName}`; + return `${this.#registryUrl}/${encodedName}`; } /** @@ -121,11 +121,11 @@ export class NpmRegistryClient { port: parsedUrl.port || (isHttps ? 443 : 80), path: parsedUrl.pathname + parsedUrl.search, method: 'GET', - timeout: this._timeoutMs, + timeout: this.#timeoutMs, headers: { Accept: 'application/json', 'Accept-Encoding': 'gzip, deflate', - 'User-Agent': this._userAgent + 'User-Agent': this.#userAgent } }; @@ -191,7 +191,7 @@ export class NpmRegistryClient { request.on('timeout', () => { request.destroy(); - resolve({ error: `Request timed out after ${this._timeoutMs}ms` }); + resolve({ error: `Request timed out after ${this.#timeoutMs}ms` }); }); request.end(); diff --git a/libraries/operation-graph/src/Operation.ts b/libraries/operation-graph/src/Operation.ts index 23fb6749709..0b3434ab5e4 100644 --- a/libraries/operation-graph/src/Operation.ts +++ b/libraries/operation-graph/src/Operation.ts @@ -187,13 +187,13 @@ export class Operation | undefined = undefined; + #promise: Promise | undefined = undefined; /** * If true, then a run of this operation is currently wanted. * This is used to track state from the `requestRun` callback passed to the runner. */ - private _runPending: boolean = true; + #runPending: boolean = true; public readonly metadata: TMetadata; @@ -231,8 +231,8 @@ export class Operation[]; + readonly #operations: Operation[]; /** * The total number of non-silent operations in the graph. * Silent operations are generally used to simplify the construction of the graph. */ - private readonly _trackedOperationCount: number; + readonly #trackedOperationCount: number; - private readonly _groupRecords: Set>; + readonly #groupRecords: Set>; public constructor(operations: ReadonlySet>) { let trackedOperationCount: number = 0; @@ -62,11 +62,11 @@ export class OperationExecutionManager e.group).filter((e) => e !== undefined)); + this.#groupRecords = new Set(Array.from(this.#operations, (e) => e.group).filter((e) => e !== undefined)); for (const consumer of operations) { for (const dependency of consumer.dependencies) { @@ -98,13 +98,13 @@ export class OperationExecutionManager = new Set(); const finishedGroups: Set = new Set(); - const maxParallelism: number = Math.min(this._operations.length, parallelism); + const maxParallelism: number = Math.min(this.#operations.length, parallelism); - for (const groupRecord of this._groupRecords) { + for (const groupRecord of this.#groupRecords) { groupRecord.reset(); } - for (const operation of this._operations) { + for (const operation of this.#operations) { operation.reset(); } @@ -192,7 +192,7 @@ export class OperationExecutionManager record._executeAsync(executionContext))); + await Promise.all(this.#operations.map((record: Operation) => record._executeAsync(executionContext))); // Terminate queue execution. workQueueAbortController.abort(); @@ -203,7 +203,7 @@ export class OperationExecutionManager { - private readonly _operations: Set = new Set(); - private _remainingOperations: Set = new Set(); + readonly #operations: Set = new Set(); + #remainingOperations: Set = new Set(); - private _groupStopwatch: Stopwatch = new Stopwatch(); - private _hasCancellations: boolean = false; - private _hasFailures: boolean = false; + #groupStopwatch: Stopwatch = new Stopwatch(); + #hasCancellations: boolean = false; + #hasFailures: boolean = false; public readonly name: string; public readonly metadata: TMetadata; public get duration(): number { - return this._groupStopwatch ? this._groupStopwatch.duration : 0; + return this.#groupStopwatch ? this.#groupStopwatch.duration : 0; } public get finished(): boolean { - return this._remainingOperations.size === 0; + return this.#remainingOperations.size === 0; } public get hasCancellations(): boolean { - return this._hasCancellations; + return this.#hasCancellations; } public get hasFailures(): boolean { - return this._hasFailures; + return this.#hasFailures; } public constructor(name: string, metadata: TMetadata = {} as TMetadata) { @@ -46,35 +46,35 @@ export class OperationGroupRecord { } public addOperation(operation: Operation): void { - this._operations.add(operation); + this.#operations.add(operation); } public startTimer(): void { // Keep this undefined until needed, then start to avoid subsequent calls to startTimer() - this._groupStopwatch.start(); + this.#groupStopwatch.start(); } public setOperationAsComplete(operation: Operation, state: IOperationState): void { - if (!this._remainingOperations.has(operation)) { + if (!this.#remainingOperations.has(operation)) { throw new InternalError(`Operation ${operation.name} is not in the group ${this.name}`); } if (state.status === OperationStatus.Aborted) { - this._hasCancellations = true; + this.#hasCancellations = true; } else if (state.status === OperationStatus.Failure) { - this._hasFailures = true; + this.#hasFailures = true; } - this._remainingOperations.delete(operation); - if (this._remainingOperations.size === 0) { - this._groupStopwatch.stop(); + this.#remainingOperations.delete(operation); + if (this.#remainingOperations.size === 0) { + this.#groupStopwatch.stop(); } } public reset(): void { - this._remainingOperations = new Set(this._operations); - this._groupStopwatch.reset(); - this._hasCancellations = false; - this._hasFailures = false; + this.#remainingOperations = new Set(this.#operations); + this.#groupStopwatch.reset(); + this.#hasCancellations = false; + this.#hasFailures = false; } } diff --git a/libraries/operation-graph/src/Stopwatch.ts b/libraries/operation-graph/src/Stopwatch.ts index ed1591d731a..360d790c0df 100644 --- a/libraries/operation-graph/src/Stopwatch.ts +++ b/libraries/operation-graph/src/Stopwatch.ts @@ -8,14 +8,14 @@ * @public */ export class Stopwatch { - private _startTime: number | undefined; - private _endTime: number | undefined; - private _running: boolean; + #startTime: number | undefined; + #endTime: number | undefined; + #running: boolean; public constructor() { - this._startTime = undefined; - this._endTime = undefined; - this._running = false; + this.#startTime = undefined; + this.#endTime = undefined; + this.#running = false; } /** @@ -26,7 +26,7 @@ export class Stopwatch { } public get isRunning(): boolean { - return this._running; + return this.#running; } /** @@ -34,12 +34,12 @@ export class Stopwatch { * reset() should be called before calling start() again. */ public start(): Stopwatch { - if (this._startTime !== undefined) { + if (this.#startTime !== undefined) { throw new Error('Call reset() before starting the Stopwatch'); } - this._startTime = performance.now(); - this._endTime = undefined; - this._running = true; + this.#startTime = performance.now(); + this.#endTime = undefined; + this.#running = true; return this; } @@ -47,8 +47,8 @@ export class Stopwatch { * Stops executing the stopwatch and saves the current timestamp */ public stop(): Stopwatch { - this._endTime = this._startTime !== undefined ? performance.now() : undefined; - this._running = false; + this.#endTime = this.#startTime !== undefined ? performance.now() : undefined; + this.#running = false; return this; } @@ -56,8 +56,8 @@ export class Stopwatch { * Resets all values of the stopwatch back to the original */ public reset(): Stopwatch { - this._endTime = this._startTime = undefined; - this._running = false; + this.#endTime = this.#startTime = undefined; + this.#running = false; return this; } @@ -65,7 +65,7 @@ export class Stopwatch { * Displays how long the stopwatch has been executing in a human readable format. */ public toString(): string { - if (!this._running && this._startTime === undefined) { + if (!this.#running && this.#startTime === undefined) { return '0.00 seconds (stopped)'; } const totalSeconds: number = this.duration; @@ -84,25 +84,25 @@ export class Stopwatch { * Get the duration in seconds. */ public get duration(): number { - if (this._startTime === undefined) { + if (this.#startTime === undefined) { return 0; } - const curTime: number = this._endTime !== undefined ? this._endTime : performance.now(); + const curTime: number = this.#endTime !== undefined ? this.#endTime : performance.now(); - return (curTime - this._startTime) / 1000.0; + return (curTime - this.#startTime) / 1000.0; } /** * Return the start time of the most recent stopwatch run. */ public get startTime(): number | undefined { - return this._startTime; + return this.#startTime; } /** * Return the end time of the most recent stopwatch run. */ public get endTime(): number | undefined { - return this._endTime; + return this.#endTime; } } diff --git a/libraries/operation-graph/src/WatchLoop.ts b/libraries/operation-graph/src/WatchLoop.ts index 43ff6b32c7c..8a50f720634 100644 --- a/libraries/operation-graph/src/WatchLoop.ts +++ b/libraries/operation-graph/src/WatchLoop.ts @@ -58,23 +58,23 @@ export interface IWatchLoopState { * @beta */ export class WatchLoop implements IWatchLoopState { - private readonly _options: Readonly; + readonly #options: Readonly; - private _abortController: AbortController; - private _isRunning: boolean; - private _runRequested: boolean; - private _requestRunPromise: Promise<[string, string?]>; - private _resolveRequestRun!: (value: [string, string?]) => void; + #abortController: AbortController; + #isRunning: boolean; + #runRequested: boolean; + #requestRunPromise: Promise<[string, string?]>; + #resolveRequestRun!: (value: [string, string?]) => void; public constructor(options: IWatchLoopOptions) { - this._options = options; + this.#options = options; - this._abortController = new AbortController(); - this._isRunning = false; + this.#abortController = new AbortController(); + this.#isRunning = false; // Always start as true, so that any requests prior to first run are silenced. - this._runRequested = true; - this._requestRunPromise = new Promise<[string, string?]>((resolve) => { - this._resolveRequestRun = resolve; + this.#runRequested = true; + this.#requestRunPromise = new Promise<[string, string?]>((resolve) => { + this.#resolveRequestRun = resolve; }); } @@ -86,7 +86,7 @@ export class WatchLoop implements IWatchLoopState { return OperationStatus.Aborted; } - abortSignal.addEventListener('abort', this._abortCurrent, { once: true }); + abortSignal.addEventListener('abort', this.#abortCurrent, { once: true }); try { let result: OperationStatus = OperationStatus.Ready; @@ -98,12 +98,12 @@ export class WatchLoop implements IWatchLoopState { } result = await this._runIterationAsync(); - } while (this._runRequested); + } while (this.#runRequested); // Even if the run has finished, if the abort signal was aborted, we should return `Aborted` just in case. return abortSignal.aborted ? OperationStatus.Aborted : result; } finally { - abortSignal.removeEventListener('abort', this._abortCurrent); + abortSignal.removeEventListener('abort', this.#abortCurrent); } } @@ -121,7 +121,7 @@ export class WatchLoop implements IWatchLoopState { await this.runUntilStableAsync(abortSignal); onWaiting(); - await Promise.race([this._requestRunPromise, abortPromise]); + await Promise.race([this.#requestRunPromise, abortPromise]); } } @@ -181,7 +181,7 @@ export class WatchLoop implements IWatchLoopState { } case 'cancel': { - if (this._isRunning) { + if (this.#isRunning) { abortController.abort(); abortController = new AbortController(); // This will terminate the currently executing `runUntilStableAsync` call. @@ -197,7 +197,7 @@ export class WatchLoop implements IWatchLoopState { try { status = await this.runUntilStableAsync(abortController.signal); // ESLINT: "Promises must be awaited, end with a call to .catch, end with a call to .then ..." - this._requestRunPromise.then( + this.#requestRunPromise.then( ([requestor, detail]) => requestRunFromHost(requestor, detail), (error: Error) => { // Unreachable code. The promise will never be rejected. @@ -234,43 +234,43 @@ export class WatchLoop implements IWatchLoopState { * Requests that a new run occur. */ public requestRun: OperationRequestRunCallback = (requestor: string, detail?: string) => { - if (!this._runRequested) { - this._options.onRequestRun(requestor, detail); - this._runRequested = true; - if (this._isRunning) { - this._options.onAbort(); - this._abortCurrent(); + if (!this.#runRequested) { + this.#options.onRequestRun(requestor, detail); + this.#runRequested = true; + if (this.#isRunning) { + this.#options.onAbort(); + this.#abortCurrent(); } } - this._resolveRequestRun([requestor, detail]); + this.#resolveRequestRun([requestor, detail]); }; /** * The abort signal for the current iteration. */ public get abortSignal(): AbortSignal { - return this._abortController.signal; + return this.#abortController.signal; } /** * Cancels the current iteration (if possible). */ - private _abortCurrent = (): void => { - this._abortController.abort(); + #abortCurrent = (): void => { + this.#abortController.abort(); }; /** * Resets the abort signal and run request state. */ private _reset(): void { - if (this._abortController.signal.aborted) { - this._abortController = new AbortController(); + if (this.#abortController.signal.aborted) { + this.#abortController = new AbortController(); } - if (this._runRequested) { - this._runRequested = false; - this._requestRunPromise = new Promise<[string, string?]>((resolve) => { - this._resolveRequestRun = resolve; + if (this.#runRequested) { + this.#runRequested = false; + this.#requestRunPromise = new Promise<[string, string?]>((resolve) => { + this.#resolveRequestRun = resolve; }); } } @@ -282,10 +282,10 @@ export class WatchLoop implements IWatchLoopState { private async _runIterationAsync(): Promise { this._reset(); - this._options.onBeforeExecute(); + this.#options.onBeforeExecute(); try { - this._isRunning = true; - return await this._options.executeAsync(this); + this.#isRunning = true; + return await this.#options.executeAsync(this); } catch (err) { if (!(err instanceof AlreadyReportedError)) { throw err; @@ -293,7 +293,7 @@ export class WatchLoop implements IWatchLoopState { return OperationStatus.Failure; } } finally { - this._isRunning = false; + this.#isRunning = false; } } } diff --git a/libraries/operation-graph/src/WorkQueue.ts b/libraries/operation-graph/src/WorkQueue.ts index 114eae665e8..d9b6dd89a40 100644 --- a/libraries/operation-graph/src/WorkQueue.ts +++ b/libraries/operation-graph/src/WorkQueue.ts @@ -11,61 +11,61 @@ interface IQueueItem { } export class WorkQueue { - private readonly _queue: MinimumHeap; - private readonly _abortSignal: AbortSignal; - private readonly _abortPromise: Promise; + readonly #queue: MinimumHeap; + readonly #abortSignal: AbortSignal; + readonly #abortPromise: Promise; - private _pushPromise: Promise; - private _resolvePush: () => void; - private _resolvePushTimeout: NodeJS.Timeout | undefined; + #pushPromise: Promise; + #resolvePush: () => void; + #resolvePushTimeout: NodeJS.Timeout | undefined; public constructor(abortSignal: AbortSignal) { // Sort by priority descending. Thus the comparator returns a negative number if a has higher priority than b. - this._queue = new MinimumHeap((a: IQueueItem, b: IQueueItem) => b.priority - a.priority); - this._abortSignal = abortSignal; - this._abortPromise = abortSignal.aborted + this.#queue = new MinimumHeap((a: IQueueItem, b: IQueueItem) => b.priority - a.priority); + this.#abortSignal = abortSignal; + this.#abortPromise = abortSignal.aborted ? Promise.resolve() : new Promise((resolve) => { abortSignal.addEventListener('abort', () => resolve(), { once: true }); }); - [this._pushPromise, this._resolvePush] = Async.getSignal(); - this._resolvePushTimeout = undefined; + [this.#pushPromise, this.#resolvePush] = Async.getSignal(); + this.#resolvePushTimeout = undefined; } public async *[Symbol.asyncIterator](): AsyncIterableIterator<() => Promise> { - while (!this._abortSignal.aborted) { - while (this._queue.size > 0) { - const item: IQueueItem = this._queue.poll()!; + while (!this.#abortSignal.aborted) { + while (this.#queue.size > 0) { + const item: IQueueItem = this.#queue.poll()!; yield item.task; } - await Promise.race([this._pushPromise, this._abortPromise]); + await Promise.race([this.#pushPromise, this.#abortPromise]); } } public pushAsync(task: () => Promise, priority: number): Promise { return new Promise((resolve, reject) => { - this._queue.push({ + this.#queue.push({ task: () => task().then(resolve, reject), priority }); // ESLINT: "Promises must be awaited, end with a call to .catch, end with a call to .then ..." // eslint-disable-next-line @typescript-eslint/no-floating-promises - this._abortPromise.finally(() => resolve(OperationStatus.Aborted)); + this.#abortPromise.finally(() => resolve(OperationStatus.Aborted)); this._resolvePushDebounced(); }); } private _resolvePushDebounced(): void { - if (!this._resolvePushTimeout) { - this._resolvePushTimeout = setTimeout(() => { - this._resolvePushTimeout = undefined; - this._resolvePush(); + if (!this.#resolvePushTimeout) { + this.#resolvePushTimeout = setTimeout(() => { + this.#resolvePushTimeout = undefined; + this.#resolvePush(); - [this._pushPromise, this._resolvePush] = Async.getSignal(); + [this.#pushPromise, this.#resolvePush] = Async.getSignal(); }); } } diff --git a/libraries/package-extractor/src/ArchiveManager.ts b/libraries/package-extractor/src/ArchiveManager.ts index a463fbe45af..69a7d1360c2 100644 --- a/libraries/package-extractor/src/ArchiveManager.ts +++ b/libraries/package-extractor/src/ArchiveManager.ts @@ -21,7 +21,7 @@ export interface IAddToArchiveOptions { } export class ArchiveManager { - private _zip: JSZip = new JSZip(); + #zip: JSZip = new JSZip(); public async addToArchiveAsync(options: IAddToArchiveOptions): Promise { const { filePath, fileData, archivePath } = options; @@ -48,14 +48,14 @@ export class ArchiveManager { // Replace backslashes for Unix compat const addPath: string = Path.convertToSlashes(archivePath); - this._zip.file(addPath, data, { + this.#zip.file(addPath, data, { unixPermissions: permissions, dir: false }); } public async createArchiveAsync(archiveFilePath: string): Promise { - const zipContent: Buffer = await this._zip.generateAsync({ + const zipContent: Buffer = await this.#zip.generateAsync({ type: 'nodebuffer', platform: 'UNIX' }); diff --git a/libraries/package-extractor/src/AssetHandler.ts b/libraries/package-extractor/src/AssetHandler.ts index e177c009067..ef8e0db02c4 100644 --- a/libraries/package-extractor/src/AssetHandler.ts +++ b/libraries/package-extractor/src/AssetHandler.ts @@ -45,16 +45,16 @@ export interface IFinalizeOptions { } export class AssetHandler { - private readonly _terminal: ITerminal; - private readonly _sourceRootFolder: string; - private readonly _targetRootFolder: string; - private readonly _createArchiveOnly: boolean; - private readonly _symlinkAnalyzer: SymlinkAnalyzer; - private readonly _archiveManager: ArchiveManager | undefined; - private readonly _archiveFilePath: string | undefined; - private readonly _linkCreationMode: LinkCreationMode; - private readonly _includedAssetPaths: Set = new Set(); - private _isFinalized: boolean = false; + readonly #terminal: ITerminal; + readonly #sourceRootFolder: string; + readonly #targetRootFolder: string; + readonly #createArchiveOnly: boolean; + readonly #symlinkAnalyzer: SymlinkAnalyzer; + readonly #archiveManager: ArchiveManager | undefined; + readonly #archiveFilePath: string | undefined; + readonly #linkCreationMode: LinkCreationMode; + readonly #includedAssetPaths: Set = new Set(); + #isFinalized: boolean = false; public constructor(options: IAssetHandlerOptions) { const { @@ -66,22 +66,22 @@ export class AssetHandler { createArchiveFilePath, createArchiveOnly = false } = options; - this._terminal = terminal; - this._sourceRootFolder = sourceRootFolder; - this._targetRootFolder = targetRootFolder; - this._symlinkAnalyzer = symlinkAnalyzer; + this.#terminal = terminal; + this.#sourceRootFolder = sourceRootFolder; + this.#targetRootFolder = targetRootFolder; + this.#symlinkAnalyzer = symlinkAnalyzer; if (createArchiveFilePath) { if (path.extname(createArchiveFilePath) !== '.zip') { throw new Error('Only archives with the .zip file extension are currently supported.'); } - this._archiveFilePath = path.resolve(targetRootFolder, createArchiveFilePath); - this._archiveManager = new ArchiveManager(); + this.#archiveFilePath = path.resolve(targetRootFolder, createArchiveFilePath); + this.#archiveManager = new ArchiveManager(); } - if (createArchiveOnly && !this._archiveManager) { + if (createArchiveOnly && !this.#archiveManager) { throw new Error('createArchiveOnly cannot be true if createArchiveFilePath is not provided'); } - this._createArchiveOnly = createArchiveOnly; - this._linkCreationMode = linkCreation || 'default'; + this.#createArchiveOnly = createArchiveOnly; + this.#linkCreationMode = linkCreation || 'default'; } public async includeAssetAsync(options: IIncludeAssetPathOptions): Promise; @@ -91,11 +91,11 @@ export class AssetHandler { const { sourceFileContent, targetFilePath, ignoreIfExisting = false } = options; let { sourceFilePath } = options; - if (this._isFinalized) { + if (this.#isFinalized) { throw new Error('includeAssetAsync() cannot be called after finalizeAsync()'); } if (!sourceFilePath && !sourceFileContent) { - if (!Path.isUnder(targetFilePath, this._targetRootFolder)) { + if (!Path.isUnder(targetFilePath, this.#targetRootFolder)) { throw new Error('The existing asset path must be under the target root folder'); } sourceFilePath = targetFilePath; @@ -103,14 +103,14 @@ export class AssetHandler { if (sourceFilePath && sourceFileContent) { throw new Error('Either sourceFilePath or sourceFileContent must be provided, but not both'); } - if (this._includedAssetPaths.has(targetFilePath)) { + if (this.#includedAssetPaths.has(targetFilePath)) { if (ignoreIfExisting) { return; } throw new Error(`The asset at path "${targetFilePath}" has already been included`); } - if (!this._createArchiveOnly) { + if (!this.#createArchiveOnly) { // Ignore when the source file is the same as the target file, as it's a no-op if (sourceFilePath && sourceFilePath !== targetFilePath) { // Use the fs.copyFile API instead of FileSystem.copyFileAsync() since copyFileAsync performs @@ -132,38 +132,38 @@ export class AssetHandler { } } - if (this._archiveManager) { - const targetRelativeFilePath: string = path.relative(this._targetRootFolder, targetFilePath); + if (this.#archiveManager) { + const targetRelativeFilePath: string = path.relative(this.#targetRootFolder, targetFilePath); if (sourceFilePath) { - await this._archiveManager.addToArchiveAsync({ + await this.#archiveManager.addToArchiveAsync({ filePath: sourceFilePath, archivePath: targetRelativeFilePath }); } else if (sourceFileContent) { - await this._archiveManager.addToArchiveAsync({ + await this.#archiveManager.addToArchiveAsync({ fileData: sourceFileContent, archivePath: targetRelativeFilePath }); } } - this._includedAssetPaths.add(targetFilePath); + this.#includedAssetPaths.add(targetFilePath); } public get assetPaths(): string[] { - return [...this._includedAssetPaths]; + return [...this.#includedAssetPaths]; } public async finalizeAsync(options?: IFinalizeOptions): Promise { const { onAfterExtractSymlinksAsync } = options ?? {}; - if (this._isFinalized) { + if (this.#isFinalized) { throw new Error('finalizeAsync() has already been called'); } - if (this._linkCreationMode === 'default') { - this._terminal.writeLine('Creating symlinks'); - const linksToCopy: ILinkInfo[] = this._symlinkAnalyzer.reportSymlinks(); + if (this.#linkCreationMode === 'default') { + this.#terminal.writeLine('Creating symlinks'); + const linksToCopy: ILinkInfo[] = this.#symlinkAnalyzer.reportSymlinks(); await Async.forEachAsync(linksToCopy, async (linkToCopy: ILinkInfo) => { await this._extractSymlinkAsync(linkToCopy); }); @@ -171,12 +171,12 @@ export class AssetHandler { await onAfterExtractSymlinksAsync?.(); - if (this._archiveManager && this._archiveFilePath) { - this._terminal.writeLine(`Creating archive at "${this._archiveFilePath}"`); - await this._archiveManager.createArchiveAsync(this._archiveFilePath); + if (this.#archiveManager && this.#archiveFilePath) { + this.#terminal.writeLine(`Creating archive at "${this.#archiveFilePath}"`); + await this.#archiveManager.createArchiveAsync(this.#archiveFilePath); } - this._isFinalized = true; + this.#isFinalized = true; } /** @@ -186,13 +186,13 @@ export class AssetHandler { const { kind, linkPath, targetPath } = { ...linkInfo, linkPath: remapSourcePathForTargetFolder({ - sourceRootFolder: this._sourceRootFolder, - targetRootFolder: this._targetRootFolder, + sourceRootFolder: this.#sourceRootFolder, + targetRootFolder: this.#targetRootFolder, sourcePath: linkInfo.linkPath }), targetPath: remapSourcePathForTargetFolder({ - sourceRootFolder: this._sourceRootFolder, - targetRootFolder: this._targetRootFolder, + sourceRootFolder: this.#sourceRootFolder, + targetRootFolder: this.#targetRootFolder, sourcePath: linkInfo.targetPath }) }; diff --git a/libraries/package-extractor/src/SymlinkAnalyzer.ts b/libraries/package-extractor/src/SymlinkAnalyzer.ts index 36eaff95481..7a889c2016c 100644 --- a/libraries/package-extractor/src/SymlinkAnalyzer.ts +++ b/libraries/package-extractor/src/SymlinkAnalyzer.ts @@ -72,16 +72,16 @@ export interface IAnalyzePathOptions { } export class SymlinkAnalyzer { - private readonly _requiredSourceParentPath: string | undefined; + readonly #requiredSourceParentPath: string | undefined; // The directory tree discovered so far - private readonly _nodesByPath: Map = new Map(); + readonly #nodesByPath: Map = new Map(); // The symlinks that we encountered while building the directory tree - private readonly _linkInfosByPath: Map = new Map(); + readonly #linkInfosByPath: Map = new Map(); public constructor(options: ISymlinkAnalyzerOptions = {}) { - this._requiredSourceParentPath = options.requiredSourceParentPath; + this.#requiredSourceParentPath = options.requiredSourceParentPath; } public async analyzePathAsync( @@ -95,7 +95,7 @@ export class SymlinkAnalyzer { // First, try to short-circuit the analysis if we've already analyzed this path const resolvedPath: string = path.resolve(inputPath); - const existingNode: PathNode | undefined = this._nodesByPath.get(resolvedPath); + const existingNode: PathNode | undefined = this.#nodesByPath.get(resolvedPath); if (existingNode) { return existingNode; } @@ -113,7 +113,7 @@ export class SymlinkAnalyzer { } const currentPath: string = targetPath.slice(0, targetPathIndex); - currentNode = this._nodesByPath.get(currentPath); + currentNode = this.#nodesByPath.get(currentPath); if (currentNode === undefined) { const linkStats: FileSystemStats = await FileSystem.getLinkStatisticsAsync(currentPath); if (linkStats.isSymbolicLink()) { @@ -122,9 +122,9 @@ export class SymlinkAnalyzer { const resolvedLinkTargetPath: string = path.resolve(path.dirname(currentPath), linkTargetPath); // Do a check to make sure that the link target path is not outside the source folder - if (this._requiredSourceParentPath) { + if (this.#requiredSourceParentPath) { const relativeLinkTargetPath: string = path.relative( - this._requiredSourceParentPath, + this.#requiredSourceParentPath, resolvedLinkTargetPath ); if (relativeLinkTargetPath.startsWith('..')) { @@ -134,7 +134,7 @@ export class SymlinkAnalyzer { return undefined; } throw new Error( - `Symlink targets not under folder "${this._requiredSourceParentPath}": ` + + `Symlink targets not under folder "${this.#requiredSourceParentPath}": ` + `${currentPath} -> ${resolvedLinkTargetPath}` ); } @@ -161,7 +161,7 @@ export class SymlinkAnalyzer { } else { throw new Error('Unknown object type: ' + currentPath); } - this._nodesByPath.set(currentPath, currentNode); + this.#nodesByPath.set(currentPath, currentNode); } if (!preserveLinks) { @@ -172,7 +172,7 @@ export class SymlinkAnalyzer { }); // Have we created an ILinkInfo for this link yet? - if (!this._linkInfosByPath.has(currentNode.nodePath)) { + if (!this.#linkInfosByPath.has(currentNode.nodePath)) { // Follow any symbolic links to determine whether the final target is a directory const targetStats: FileSystemStats = await FileSystem.getStatisticsAsync(targetNode.nodePath); const targetIsDirectory: boolean = targetStats.isDirectory(); @@ -181,7 +181,7 @@ export class SymlinkAnalyzer { linkPath: currentNode.nodePath, targetPath: targetNode.nodePath }; - this._linkInfosByPath.set(currentNode.nodePath, linkInfo); + this.#linkInfosByPath.set(currentNode.nodePath, linkInfo); } const nodeTargetPath: string = targetNode.nodePath; @@ -209,7 +209,7 @@ export class SymlinkAnalyzer { * Returns a summary of all the symbolic links encountered by {@link SymlinkAnalyzer.analyzePathAsync}. */ public reportSymlinks(): ILinkInfo[] { - const list: ILinkInfo[] = [...this._linkInfosByPath.values()]; + const list: ILinkInfo[] = [...this.#linkInfosByPath.values()]; Sort.sortBy(list, (x) => x.linkPath); return list; } diff --git a/libraries/package-extractor/src/scripts/createLinks/cli/CreateLinksCommandLineParser.ts b/libraries/package-extractor/src/scripts/createLinks/cli/CreateLinksCommandLineParser.ts index 10b64a2ed7f..25c366f77e0 100644 --- a/libraries/package-extractor/src/scripts/createLinks/cli/CreateLinksCommandLineParser.ts +++ b/libraries/package-extractor/src/scripts/createLinks/cli/CreateLinksCommandLineParser.ts @@ -9,7 +9,7 @@ import { CreateLinksAction } from './actions/CreateLinksAction'; import { RemoveLinksAction } from './actions/RemoveLinksAction'; export class CreateLinksCommandLineParser extends CommandLineParser { - private readonly _terminal: ITerminal; + readonly #terminal: ITerminal; public constructor(terminal: ITerminal) { super({ @@ -17,10 +17,10 @@ export class CreateLinksCommandLineParser extends CommandLineParser { toolDescription: 'Create or remove symlinks for the extracted packages' }); - this._terminal = terminal; + this.#terminal = terminal; - this.addAction(new CreateLinksAction(this._terminal)); - this.addAction(new RemoveLinksAction(this._terminal)); + this.addAction(new CreateLinksAction(this.#terminal)); + this.addAction(new RemoveLinksAction(this.#terminal)); } protected override async onExecuteAsync(): Promise { @@ -31,8 +31,8 @@ export class CreateLinksCommandLineParser extends CommandLineParser { process.exitCode = 0; } catch (error) { if (!(error instanceof AlreadyReportedError)) { - this._terminal.writeErrorLine(); - this._terminal.writeErrorLine('ERROR: ' + error.message.trim()); + this.#terminal.writeErrorLine(); + this.#terminal.writeErrorLine('ERROR: ' + error.message.trim()); } } } diff --git a/libraries/package-extractor/src/scripts/createLinks/cli/actions/CreateLinksAction.ts b/libraries/package-extractor/src/scripts/createLinks/cli/actions/CreateLinksAction.ts index 146bb76b46c..cd0491b4cf6 100644 --- a/libraries/package-extractor/src/scripts/createLinks/cli/actions/CreateLinksAction.ts +++ b/libraries/package-extractor/src/scripts/createLinks/cli/actions/CreateLinksAction.ts @@ -76,9 +76,9 @@ async function realizeFilesAsync( } export class CreateLinksAction extends CommandLineAction { - private _terminal: ITerminal; - private _realizeFilesParameter: CommandLineFlagParameter; - private _linkBinsParameter: CommandLineFlagParameter; + #terminal: ITerminal; + #realizeFilesParameter: CommandLineFlagParameter; + #linkBinsParameter: CommandLineFlagParameter; public constructor(terminal: ITerminal) { super({ @@ -87,14 +87,14 @@ export class CreateLinksAction extends CommandLineAction { documentation: 'This action creates symlinks for the extraction process.' }); - this._terminal = terminal; + this.#terminal = terminal; - this._realizeFilesParameter = this.defineFlagParameter({ + this.#realizeFilesParameter = this.defineFlagParameter({ parameterLongName: REALIZE_FILES_PARAMETER_NAME, description: 'Realize files instead of creating symlinks' }); - this._linkBinsParameter = this.defineFlagParameter({ + this.#linkBinsParameter = this.defineFlagParameter({ parameterLongName: LINK_BINS_PARAMETER_NAME, description: 'Create the .bin files for extracted packages' }); @@ -102,24 +102,24 @@ export class CreateLinksAction extends CommandLineAction { protected override async onExecuteAsync(): Promise { const extractorMetadataObject: IExtractorMetadataJson = await getExtractorMetadataAsync(); - const realizeFiles: boolean = this._realizeFilesParameter.value; - const linkBins: boolean = this._linkBinsParameter.value; + const realizeFiles: boolean = this.#realizeFilesParameter.value; + const linkBins: boolean = this.#linkBinsParameter.value; - this._terminal.writeLine(`Creating links for extraction at path "${TARGET_ROOT_FOLDER}"`); - await removeLinksAsync(this._terminal, TARGET_ROOT_FOLDER, extractorMetadataObject); - await createLinksAsync(this._terminal, TARGET_ROOT_FOLDER, extractorMetadataObject); + this.#terminal.writeLine(`Creating links for extraction at path "${TARGET_ROOT_FOLDER}"`); + await removeLinksAsync(this.#terminal, TARGET_ROOT_FOLDER, extractorMetadataObject); + await createLinksAsync(this.#terminal, TARGET_ROOT_FOLDER, extractorMetadataObject); if (realizeFiles) { - this._terminal.writeLine(`Realizing files for extraction at path "${TARGET_ROOT_FOLDER}"`); - await realizeFilesAsync(this._terminal, TARGET_ROOT_FOLDER, extractorMetadataObject); + this.#terminal.writeLine(`Realizing files for extraction at path "${TARGET_ROOT_FOLDER}"`); + await realizeFilesAsync(this.#terminal, TARGET_ROOT_FOLDER, extractorMetadataObject); } if (linkBins) { - this._terminal.writeLine(`Linking bins for extraction at path "${TARGET_ROOT_FOLDER}"`); + this.#terminal.writeLine(`Linking bins for extraction at path "${TARGET_ROOT_FOLDER}"`); const extractedProjectFolderPaths: string[] = extractorMetadataObject.projects.map( (project: IProjectInfoJson) => path.join(TARGET_ROOT_FOLDER, project.path) ); - await makeBinLinksAsync(this._terminal, extractedProjectFolderPaths); + await makeBinLinksAsync(this.#terminal, extractedProjectFolderPaths); } } } diff --git a/libraries/package-extractor/src/scripts/createLinks/cli/actions/RemoveLinksAction.ts b/libraries/package-extractor/src/scripts/createLinks/cli/actions/RemoveLinksAction.ts index bea0e60f9e4..3f12c2bcef3 100644 --- a/libraries/package-extractor/src/scripts/createLinks/cli/actions/RemoveLinksAction.ts +++ b/libraries/package-extractor/src/scripts/createLinks/cli/actions/RemoveLinksAction.ts @@ -28,7 +28,7 @@ export async function removeLinksAsync( } export class RemoveLinksAction extends CommandLineAction { - private _terminal: ITerminal; + #terminal: ITerminal; public constructor(terminal: ITerminal) { super({ @@ -37,13 +37,13 @@ export class RemoveLinksAction extends CommandLineAction { documentation: 'This action removes the symlinks created by the "create" action.' }); - this._terminal = terminal; + this.#terminal = terminal; } protected override async onExecuteAsync(): Promise { const extractorMetadataObject: IExtractorMetadataJson = await getExtractorMetadataAsync(); - this._terminal.writeLine(`Removing links for extraction at path "${TARGET_ROOT_FOLDER}"`); - await removeLinksAsync(this._terminal, TARGET_ROOT_FOLDER, extractorMetadataObject); + this.#terminal.writeLine(`Removing links for extraction at path "${TARGET_ROOT_FOLDER}"`); + await removeLinksAsync(this.#terminal, TARGET_ROOT_FOLDER, extractorMetadataObject); } } diff --git a/libraries/rig-package/src/RigConfig.ts b/libraries/rig-package/src/RigConfig.ts index 28cdf252338..e3b5e928477 100644 --- a/libraries/rig-package/src/RigConfig.ts +++ b/libraries/rig-package/src/RigConfig.ts @@ -244,11 +244,11 @@ export class RigConfig implements IRigConfig { // Example: /path/to/your-project/node_modules/example-rig/ // If the value is `undefined`, then getResolvedProfileFolder() has not calculated it yet - private _resolvedRigPackageFolder: string | undefined; + #resolvedRigPackageFolder: string | undefined; // Example: /path/to/your-project/node_modules/example-rig/profiles/example-profile // If the value is `undefined`, then getResolvedProfileFolder() has not calculated it yet - private _resolvedProfileFolder: string | undefined; + #resolvedProfileFolder: string | undefined; private constructor(options: IRigConfigOptions) { const { projectFolderPath, rigFound, filePath, rigPackageName, rigProfile = 'default' } = options; @@ -381,7 +381,7 @@ export class RigConfig implements IRigConfig { * {@inheritdoc IRigConfig.getResolvedProfileFolder} */ public getResolvedProfileFolder(): string { - if (this._resolvedRigPackageFolder === undefined) { + if (this.#resolvedRigPackageFolder === undefined) { if (!this.rigFound) { throw new Error('Cannot resolve the rig package because no rig was specified for this project'); } @@ -393,13 +393,13 @@ export class RigConfig implements IRigConfig { resolveOptions ); - this._resolvedRigPackageFolder = path.dirname(resolvedRigPackageJsonPath); + this.#resolvedRigPackageFolder = path.dirname(resolvedRigPackageJsonPath); } - if (this._resolvedProfileFolder === undefined) { - this._resolvedProfileFolder = path.join(this._resolvedRigPackageFolder, this.relativeProfileFolderPath); + if (this.#resolvedProfileFolder === undefined) { + this.#resolvedProfileFolder = path.join(this.#resolvedRigPackageFolder, this.relativeProfileFolderPath); - if (!fs.existsSync(this._resolvedProfileFolder)) { + if (!fs.existsSync(this.#resolvedProfileFolder)) { throw new Error( `The rig profile "${this.rigProfile}" is not defined` + ` by the rig package "${this.rigPackageName}"` @@ -407,14 +407,14 @@ export class RigConfig implements IRigConfig { } } - return this._resolvedProfileFolder; + return this.#resolvedProfileFolder; } /** * {@inheritdoc IRigConfig.getResolvedProfileFolderAsync} */ public async getResolvedProfileFolderAsync(): Promise { - if (this._resolvedRigPackageFolder === undefined) { + if (this.#resolvedRigPackageFolder === undefined) { if (!this.rigFound) { throw new Error('Cannot resolve the rig package because no rig was specified for this project'); } @@ -426,13 +426,13 @@ export class RigConfig implements IRigConfig { resolveOptions ); - this._resolvedRigPackageFolder = path.dirname(resolvedRigPackageJsonPath); + this.#resolvedRigPackageFolder = path.dirname(resolvedRigPackageJsonPath); } - if (this._resolvedProfileFolder === undefined) { - this._resolvedProfileFolder = path.join(this._resolvedRigPackageFolder, this.relativeProfileFolderPath); + if (this.#resolvedProfileFolder === undefined) { + this.#resolvedProfileFolder = path.join(this.#resolvedRigPackageFolder, this.relativeProfileFolderPath); - if (!(await Helpers.fsExistsAsync(this._resolvedProfileFolder))) { + if (!(await Helpers.fsExistsAsync(this.#resolvedProfileFolder))) { throw new Error( `The rig profile "${this.rigProfile}" is not defined` + ` by the rig package "${this.rigPackageName}"` @@ -440,7 +440,7 @@ export class RigConfig implements IRigConfig { } } - return this._resolvedProfileFolder; + return this.#resolvedProfileFolder; } /** diff --git a/libraries/stream-collator/src/CollatedTerminal.ts b/libraries/stream-collator/src/CollatedTerminal.ts index 2e969a21729..e1e07cc0a10 100644 --- a/libraries/stream-collator/src/CollatedTerminal.ts +++ b/libraries/stream-collator/src/CollatedTerminal.ts @@ -9,21 +9,21 @@ import { type ITerminalChunk, TerminalChunkKind, type TerminalWritable } from '@ * @beta */ export class CollatedTerminal { - private readonly _destination: TerminalWritable; + readonly #destination: TerminalWritable; public constructor(destination: TerminalWritable) { - this._destination = destination; + this.#destination = destination; } public writeChunk(chunk: ITerminalChunk): void { - this._destination.writeChunk(chunk); + this.#destination.writeChunk(chunk); } public writeStdoutLine(message: string): void { - this._destination.writeChunk({ text: message + '\n', kind: TerminalChunkKind.Stdout }); + this.#destination.writeChunk({ text: message + '\n', kind: TerminalChunkKind.Stdout }); } public writeStderrLine(message: string): void { - this._destination.writeChunk({ text: message + '\n', kind: TerminalChunkKind.Stderr }); + this.#destination.writeChunk({ text: message + '\n', kind: TerminalChunkKind.Stderr }); } } diff --git a/libraries/stream-collator/src/CollatedWriter.ts b/libraries/stream-collator/src/CollatedWriter.ts index 8b062676db6..ad936dad8f0 100644 --- a/libraries/stream-collator/src/CollatedWriter.ts +++ b/libraries/stream-collator/src/CollatedWriter.ts @@ -12,8 +12,8 @@ import { CollatedTerminal } from './CollatedTerminal'; * @beta */ export class CollatedWriter extends TerminalWritable { - private readonly _collator: StreamCollator; - private readonly _bufferedChunks: ITerminalChunk[]; + readonly #collator: StreamCollator; + readonly #bufferedChunks: ITerminalChunk[]; public readonly taskName: string; public readonly terminal: CollatedTerminal; @@ -24,16 +24,16 @@ export class CollatedWriter extends TerminalWritable { this.taskName = taskName; this.terminal = new CollatedTerminal(this); - this._collator = collator; + this.#collator = collator; - this._bufferedChunks = []; + this.#bufferedChunks = []; } /** * Returns true if this is the active writer for its associated {@link StreamCollator}. */ public get isActive(): boolean { - return this._collator.activeWriter === this; + return this.#collator.activeWriter === this; } /** @@ -41,24 +41,24 @@ export class CollatedWriter extends TerminalWritable { * not become active yet, they can be inspected via this property. */ public get bufferedChunks(): ReadonlyArray { - return this._bufferedChunks; + return this.#bufferedChunks; } /** {@inheritDoc @rushstack/terminal#TerminalWritable.onWriteChunk} */ public onWriteChunk(chunk: ITerminalChunk): void { - this._collator._writerWriteChunk(this, chunk, this._bufferedChunks); + this.#collator._writerWriteChunk(this, chunk, this.#bufferedChunks); } /** {@inheritDoc @rushstack/terminal#TerminalWritable.onClose} */ public override onClose(): void { - this._collator._writerClose(this, this._bufferedChunks); + this.#collator._writerClose(this, this.#bufferedChunks); } /** @internal */ public _flushBufferedChunks(): void { - for (const chunk of this._bufferedChunks) { - this._collator.destination.writeChunk(chunk); + for (const chunk of this.#bufferedChunks) { + this.#collator.destination.writeChunk(chunk); } - this._bufferedChunks.length = 0; + this.#bufferedChunks.length = 0; } } diff --git a/libraries/stream-collator/src/StreamCollator.ts b/libraries/stream-collator/src/StreamCollator.ts index 3cd51ac3d1b..9931ce01c55 100644 --- a/libraries/stream-collator/src/StreamCollator.ts +++ b/libraries/stream-collator/src/StreamCollator.ts @@ -37,21 +37,21 @@ export interface IStreamCollatorOptions { * @beta */ export class StreamCollator { - private _taskNames: Set = new Set(); - private _writers: Set = new Set(); + #taskNames: Set = new Set(); + #writers: Set = new Set(); // The writer whose output is being shown in realtime, or undefined if none - private _activeWriter: CollatedWriter | undefined = undefined; + #activeWriter: CollatedWriter | undefined = undefined; // Writers that are not closed yet, and have never been active - private _openInactiveWriters: Set = new Set(); + #openInactiveWriters: Set = new Set(); // Writers that are now closed, but have accumulated buffered chunks, and have never been active - private _closedInactiveWriters: Set = new Set(); + #closedInactiveWriters: Set = new Set(); - private _onWriterActive: ((writer: CollatedWriter) => void) | undefined; + #onWriterActive: ((writer: CollatedWriter) => void) | undefined; - private _preventReentrantCall: boolean = false; + #preventReentrantCall: boolean = false; public readonly destination: TerminalWritable; public readonly terminal: CollatedTerminal; @@ -59,7 +59,7 @@ export class StreamCollator { public constructor(options: IStreamCollatorOptions) { this.destination = options.destination; this.terminal = new CollatedTerminal(this.destination); - this._onWriterActive = options.onWriterActive; + this.#onWriterActive = options.onWriterActive; } /** @@ -67,7 +67,7 @@ export class StreamCollator { * is active yet. */ public get activeWriter(): CollatedWriter | undefined { - return this._activeWriter; + return this.#activeWriter; } /** @@ -75,8 +75,8 @@ export class StreamCollator { * currently active writer, or an empty string if no writer is active. */ public get activeTaskName(): string { - if (this._activeWriter) { - return this._activeWriter.taskName; + if (this.#activeWriter) { + return this.#activeWriter.taskName; } return ''; } @@ -86,7 +86,7 @@ export class StreamCollator { * in the order that they were registered. */ public get writers(): ReadonlySet { - return this._writers; + return this.#writers; } /** @@ -94,19 +94,19 @@ export class StreamCollator { * to receive its input. */ public registerTask(taskName: string): CollatedWriter { - if (this._taskNames.has(taskName)) { + if (this.#taskNames.has(taskName)) { throw new Error('A task with that name has already been registered'); } const writer: CollatedWriter = new CollatedWriter(taskName, this); - this._writers.add(writer); - this._taskNames.add(writer.taskName); + this.#writers.add(writer); + this.#taskNames.add(writer.taskName); // When a task is initially registered, it is open and has not accumulated any buffered chunks - this._openInactiveWriters.add(writer); + this.#openInactiveWriters.add(writer); - if (this._activeWriter === undefined) { + if (this.#activeWriter === undefined) { // If there is no active writer, then the first one to be registered becomes active. this._assignActiveWriter(writer); } @@ -122,7 +122,7 @@ export class StreamCollator { ): void { this._checkForReentrantCall(); - if (this._activeWriter === undefined) { + if (this.#activeWriter === undefined) { // If no writer is currently active, then the first one to write something becomes active this._assignActiveWriter(writer); } @@ -141,22 +141,22 @@ export class StreamCollator { if (writer.isActive) { writer._flushBufferedChunks(); - this._activeWriter = undefined; + this.#activeWriter = undefined; // If any buffered writers are already closed, activate them each immediately // We copy the set, since _assignActiveWriter() will be deleting from it. - for (const closedInactiveWriter of [...this._closedInactiveWriters]) { + for (const closedInactiveWriter of [...this.#closedInactiveWriters]) { try { this._assignActiveWriter(closedInactiveWriter); } finally { - this._activeWriter = undefined; + this.#activeWriter = undefined; } } let writerToActivate: CollatedWriter | undefined = undefined; // Try to activate a writer that already accumulated some data - for (const openInactiveWriter of this._openInactiveWriters) { + for (const openInactiveWriter of this.#openInactiveWriters) { if (openInactiveWriter.bufferedChunks.length > 0) { writerToActivate = openInactiveWriter; break; @@ -164,7 +164,7 @@ export class StreamCollator { } if (!writerToActivate) { // Otherwise just take the first one - for (const openInactiveWriter of this._openInactiveWriters) { + for (const openInactiveWriter of this.#openInactiveWriters) { writerToActivate = openInactiveWriter; break; } @@ -174,23 +174,23 @@ export class StreamCollator { this._assignActiveWriter(writerToActivate); } } else { - this._openInactiveWriters.delete(writer); - this._closedInactiveWriters.add(writer); + this.#openInactiveWriters.delete(writer); + this.#closedInactiveWriters.add(writer); } } private _assignActiveWriter(writer: CollatedWriter): void { - this._activeWriter = writer; + this.#activeWriter = writer; - this._closedInactiveWriters.delete(writer); - this._openInactiveWriters.delete(writer); + this.#closedInactiveWriters.delete(writer); + this.#openInactiveWriters.delete(writer); - if (this._onWriterActive) { - this._preventReentrantCall = true; + if (this.#onWriterActive) { + this.#preventReentrantCall = true; try { - this._onWriterActive(writer); + this.#onWriterActive(writer); } finally { - this._preventReentrantCall = false; + this.#preventReentrantCall = false; } } @@ -198,7 +198,7 @@ export class StreamCollator { } private _checkForReentrantCall(): void { - if (this._preventReentrantCall) { + if (this.#preventReentrantCall) { throw new InternalError('Reentrant call to StreamCollator'); } } diff --git a/libraries/terminal/src/CallbackWritable.ts b/libraries/terminal/src/CallbackWritable.ts index 0b5bb7afc77..4bf336d02b9 100644 --- a/libraries/terminal/src/CallbackWritable.ts +++ b/libraries/terminal/src/CallbackWritable.ts @@ -27,14 +27,14 @@ export interface ICallbackWritableOptions { * @public */ export class CallbackWritable extends TerminalWritable { - private readonly _callback: (chunk: ITerminalChunk) => void; + readonly #callback: (chunk: ITerminalChunk) => void; public constructor(options: ICallbackWritableOptions) { super(); - this._callback = options.onWriteChunk; + this.#callback = options.onWriteChunk; } protected onWriteChunk(chunk: ITerminalChunk): void { - this._callback(chunk); + this.#callback(chunk); } } diff --git a/libraries/terminal/src/DiscardStdoutTransform.ts b/libraries/terminal/src/DiscardStdoutTransform.ts index 7dda773674e..dd9cdbc0b0c 100644 --- a/libraries/terminal/src/DiscardStdoutTransform.ts +++ b/libraries/terminal/src/DiscardStdoutTransform.ts @@ -58,12 +58,12 @@ enum State { * @beta */ export class DiscardStdoutTransform extends TerminalTransform { - private _state: State; + #state: State; public constructor(options: IDiscardStdoutTransformOptions) { super(options); - this._state = State.Okay; + this.#state = State.Okay; } protected onWriteChunk(chunk: ITerminalChunk): void { @@ -72,14 +72,14 @@ export class DiscardStdoutTransform extends TerminalTransform { } if (chunk.kind === TerminalChunkKind.Stdout) { - if (this._state === State.StderrFragment) { + if (this.#state === State.StderrFragment) { if (chunk.text.indexOf('\n') >= 0) { - this._state = State.InsertLinefeed; + this.#state = State.InsertLinefeed; } } } else if (chunk.kind === TerminalChunkKind.Stderr) { let correctedText: string; - if (this._state === State.InsertLinefeed) { + if (this.#state === State.InsertLinefeed) { correctedText = '\n' + chunk.text; } else { correctedText = chunk.text; @@ -89,9 +89,9 @@ export class DiscardStdoutTransform extends TerminalTransform { if (correctedText.length > 0) { if (correctedText[correctedText.length - 1] === '\n') { - this._state = State.Okay; + this.#state = State.Okay; } else { - this._state = State.StderrFragment; + this.#state = State.StderrFragment; } } } else { diff --git a/libraries/terminal/src/PrefixProxyTerminalProvider.ts b/libraries/terminal/src/PrefixProxyTerminalProvider.ts index c33d247e285..552ef868839 100644 --- a/libraries/terminal/src/PrefixProxyTerminalProvider.ts +++ b/libraries/terminal/src/PrefixProxyTerminalProvider.ts @@ -54,35 +54,35 @@ export type IPrefixProxyTerminalProviderOptions = * @beta */ export class PrefixProxyTerminalProvider implements ITerminalProvider { - private readonly _parentTerminalProvider: ITerminalProvider; - private readonly _getPrefix: () => string; - private readonly _newlineRegex: RegExp; - private _isOnNewline: boolean; + readonly #parentTerminalProvider: ITerminalProvider; + readonly #getPrefix: () => string; + readonly #newlineRegex: RegExp; + #isOnNewline: boolean; public constructor(options: IPrefixProxyTerminalProviderOptions) { const { terminalProvider } = options; - this._parentTerminalProvider = terminalProvider; + this.#parentTerminalProvider = terminalProvider; if ((options as IStaticPrefixProxyTerminalProviderOptions).prefix !== undefined) { const { prefix } = options as IStaticPrefixProxyTerminalProviderOptions; - this._getPrefix = () => prefix; + this.#getPrefix = () => prefix; } else { const { getPrefix } = options as IDynamicPrefixProxyTerminalProviderOptions; - this._getPrefix = getPrefix; + this.#getPrefix = getPrefix; } - this._isOnNewline = true; + this.#isOnNewline = true; - this._newlineRegex = new RegExp(`${Text.escapeRegExp(terminalProvider.eolCharacter)}|\\n`, 'g'); + this.#newlineRegex = new RegExp(`${Text.escapeRegExp(terminalProvider.eolCharacter)}|\\n`, 'g'); } public get supportsColor(): boolean { - return this._parentTerminalProvider.supportsColor; + return this.#parentTerminalProvider.supportsColor; } public get eolCharacter(): string { - return this._parentTerminalProvider.eolCharacter; + return this.#parentTerminalProvider.eolCharacter; } public write(data: string, severity: TerminalProviderSeverity): void { @@ -90,24 +90,24 @@ export class PrefixProxyTerminalProvider implements ITerminalProvider { let currentIndex: number = 0; let newlineMatch: RegExpExecArray | null; - while ((newlineMatch = this._newlineRegex.exec(data))) { + while ((newlineMatch = this.#newlineRegex.exec(data))) { // Extract the line, add the prefix, and write it out with the newline const newlineIndex: number = newlineMatch.index; const newIndex: number = newlineIndex + newlineMatch[0].length; - const prefix: string = this._isOnNewline ? this._getPrefix() : ''; + const prefix: string = this.#isOnNewline ? this.#getPrefix() : ''; const dataToWrite: string = `${prefix}${data.substring(currentIndex, newIndex)}`; - this._parentTerminalProvider.write(dataToWrite, severity); + this.#parentTerminalProvider.write(dataToWrite, severity); // Update the currentIndex to start the search from the char after the newline currentIndex = newIndex; - this._isOnNewline = true; + this.#isOnNewline = true; } // The remaining data is not postfixed by a newline, so write out the data and set _isNewline to false const remainingData: string = data.substring(currentIndex); if (remainingData.length) { - const prefix: string = this._isOnNewline ? this._getPrefix() : ''; - this._parentTerminalProvider.write(`${prefix}${remainingData}`, severity); - this._isOnNewline = false; + const prefix: string = this.#isOnNewline ? this.#getPrefix() : ''; + this.#parentTerminalProvider.write(`${prefix}${remainingData}`, severity); + this.#isOnNewline = false; } } } diff --git a/libraries/terminal/src/ProblemCollector.ts b/libraries/terminal/src/ProblemCollector.ts index 0425109153b..f1c9a30a943 100644 --- a/libraries/terminal/src/ProblemCollector.ts +++ b/libraries/terminal/src/ProblemCollector.ts @@ -40,28 +40,28 @@ export interface IProblemCollectorOptions extends ITerminalWritableOptions { * @beta */ export class ProblemCollector extends TerminalWritable implements IProblemCollector { - private readonly _matchers: IProblemMatcher[]; - private readonly _problems: Set = new Set(); - private readonly _onProblem: ((problem: IProblem) => void) | undefined; + readonly #matchers: IProblemMatcher[]; + readonly #problems: Set = new Set(); + readonly #onProblem: ((problem: IProblem) => void) | undefined; public constructor(options: IProblemCollectorOptions) { super(options); const { matchers = [], matcherJson = [], onProblem } = options; const fromJson: IProblemMatcher[] = matcherJson.length !== 0 ? parseProblemMatchersJson(matcherJson) : []; - this._matchers = [...matchers, ...fromJson]; - if (this._matchers.length === 0) { + this.#matchers = [...matchers, ...fromJson]; + if (this.#matchers.length === 0) { throw new Error('ProblemCollector requires at least one problem matcher.'); } - this._onProblem = onProblem; + this.#onProblem = onProblem; } /** * {@inheritdoc IProblemCollector} */ public get problems(): ReadonlySet { - return this._problems; + return this.#problems; } /** @@ -77,15 +77,15 @@ export class ProblemCollector extends TerminalWritable implements IProblemCollec ); } - for (const matcher of this._matchers) { + for (const matcher of this.#matchers) { const problem: IProblem | false = matcher.exec(text); if (problem) { const finalized: IProblem = { ...problem, matcherName: matcher.name }; - this._problems.add(finalized); - this._onProblem?.(finalized); + this.#problems.add(finalized); + this.#onProblem?.(finalized); } } } @@ -94,7 +94,7 @@ export class ProblemCollector extends TerminalWritable implements IProblemCollec * {@inheritdoc TerminalWritable} */ protected onClose(): void { - for (const matcher of this._matchers) { + for (const matcher of this.#matchers) { if (matcher.flush) { const flushed: IProblem[] = matcher.flush(); if (flushed && flushed.length > 0) { @@ -103,8 +103,8 @@ export class ProblemCollector extends TerminalWritable implements IProblemCollec ...problem, matcherName: matcher.name }; - this._problems.add(finalized); - this._onProblem?.(finalized); + this.#problems.add(finalized); + this.#onProblem?.(finalized); } } } diff --git a/libraries/terminal/src/SplitterTransform.ts b/libraries/terminal/src/SplitterTransform.ts index cce5a428ffe..c3a165076df 100644 --- a/libraries/terminal/src/SplitterTransform.ts +++ b/libraries/terminal/src/SplitterTransform.ts @@ -29,15 +29,15 @@ export interface ISplitterTransformOptions extends ITerminalWritableOptions { * @public */ export class SplitterTransform extends TerminalWritable { - private readonly _destinations: Set; + readonly #destinations: Set; public constructor(options: ISplitterTransformOptions) { super(); - this._destinations = new Set(options.destinations); + this.#destinations = new Set(options.destinations); } public get destinations(): ReadonlySet { - return this._destinations; + return this.#destinations; } /** @@ -46,7 +46,7 @@ export class SplitterTransform extends TerminalWritable { * @param destination - The destination to add. */ public addDestination(destination: TerminalWritable): void { - this._destinations.add(destination); + this.#destinations.add(destination); } /** @@ -59,7 +59,7 @@ export class SplitterTransform extends TerminalWritable { * If the destination is not found, it will not be closed. */ public removeDestination(destination: TerminalWritable, close: boolean = true): boolean { - if (this._destinations.delete(destination)) { + if (this.#destinations.delete(destination)) { if (close && !destination.preventAutoclose) { destination.close(); } @@ -69,7 +69,7 @@ export class SplitterTransform extends TerminalWritable { } protected onWriteChunk(chunk: ITerminalChunk): void { - for (const destination of this._destinations) { + for (const destination of this.#destinations) { destination.writeChunk(chunk); } } @@ -78,7 +78,7 @@ export class SplitterTransform extends TerminalWritable { const errors: Error[] = []; // If an exception is thrown, try to ensure that the other destinations get closed properly - for (const destination of this._destinations) { + for (const destination of this.#destinations) { if (!destination.preventAutoclose) { try { destination.close(); @@ -88,7 +88,7 @@ export class SplitterTransform extends TerminalWritable { } } - this._destinations.clear(); + this.#destinations.clear(); if (errors.length > 0) { throw errors[0]; diff --git a/libraries/terminal/src/StdioLineTransform.ts b/libraries/terminal/src/StdioLineTransform.ts index af02fdfe6f9..7574b92cd9e 100644 --- a/libraries/terminal/src/StdioLineTransform.ts +++ b/libraries/terminal/src/StdioLineTransform.ts @@ -67,16 +67,16 @@ export interface IStdioLineTransformOptions extends ITerminalTransformOptions { * @beta */ export class StderrLineTransform extends TerminalTransform { - private _accumulatedLine: string; - private _accumulatedStderr: boolean; + #accumulatedLine: string; + #accumulatedStderr: boolean; public readonly newline: string; public constructor(options: IStdioLineTransformOptions) { super(options); - this._accumulatedLine = ''; - this._accumulatedStderr = false; + this.#accumulatedLine = ''; + this.#accumulatedStderr = false; this.newline = Text.getNewline(options.newlineKind || NewlineKind.Lf); } @@ -93,18 +93,18 @@ export class StderrLineTransform extends TerminalTransform { while (startIndex < text.length) { if (chunk.kind === TerminalChunkKind.Stderr) { - this._accumulatedStderr = true; + this.#accumulatedStderr = true; } const endIndex: number = text.indexOf('\n', startIndex); if (endIndex < 0) { // we did not find \n, so simply append - this._accumulatedLine += text.substring(startIndex); + this.#accumulatedLine += text.substring(startIndex); break; } // append everything up to \n - this._accumulatedLine += text.substring(startIndex, endIndex); + this.#accumulatedLine += text.substring(startIndex, endIndex); this._processAccumulatedLine(); @@ -114,28 +114,28 @@ export class StderrLineTransform extends TerminalTransform { } protected onClose(): void { - if (this._accumulatedLine.length > 0) { + if (this.#accumulatedLine.length > 0) { this._processAccumulatedLine(); } this.autocloseDestination(); } private _processAccumulatedLine(): void { - this._accumulatedLine += this.newline; + this.#accumulatedLine += this.newline; - if (this._accumulatedStderr) { + if (this.#accumulatedStderr) { this.destination.writeChunk({ kind: TerminalChunkKind.Stderr, - text: this._accumulatedLine + text: this.#accumulatedLine }); } else { this.destination.writeChunk({ kind: TerminalChunkKind.Stdout, - text: this._accumulatedLine + text: this.#accumulatedLine }); } - this._accumulatedLine = ''; - this._accumulatedStderr = false; + this.#accumulatedLine = ''; + this.#accumulatedStderr = false; } } diff --git a/libraries/terminal/src/StdioSummarizer.ts b/libraries/terminal/src/StdioSummarizer.ts index 12c3bf18c50..4ca14558d42 100644 --- a/libraries/terminal/src/StdioSummarizer.ts +++ b/libraries/terminal/src/StdioSummarizer.ts @@ -51,15 +51,15 @@ export interface IStdioSummarizerOptions extends ITerminalWritableOptions { */ export class StdioSummarizer extends TerminalWritable { // Capture up to this many leading lines - private _leadingLines: number; + #leadingLines: number; // Capture up to this many trailing lines - private _trailingLines: number; + #trailingLines: number; - private readonly _abridgedLeading: string[]; - private readonly _abridgedTrailing: string[]; - private _abridgedOmittedLines: number = 0; - private _abridgedStderr: boolean; + readonly #abridgedLeading: string[]; + readonly #abridgedTrailing: string[]; + #abridgedOmittedLines: number = 0; + #abridgedStderr: boolean; public constructor(options?: IStdioSummarizerOptions) { super(options); @@ -68,12 +68,12 @@ export class StdioSummarizer extends TerminalWritable { options = {}; } - this._leadingLines = options.leadingLines !== undefined ? options.leadingLines : 10; - this._trailingLines = options.trailingLines !== undefined ? options.trailingLines : 10; + this.#leadingLines = options.leadingLines !== undefined ? options.leadingLines : 10; + this.#trailingLines = options.trailingLines !== undefined ? options.trailingLines : 10; - this._abridgedLeading = []; - this._abridgedTrailing = []; - this._abridgedStderr = false; + this.#abridgedLeading = []; + this.#abridgedTrailing = []; + this.#abridgedStderr = false; } /** @@ -86,14 +86,14 @@ export class StdioSummarizer extends TerminalWritable { if (this.isOpen) { throw new Error('The summary cannot be prepared until after close() is called.'); } - const report: string[] = [...this._abridgedLeading]; - if (this._abridgedOmittedLines === 1) { - report.push(` ...${this._abridgedOmittedLines} line omitted...\n`); + const report: string[] = [...this.#abridgedLeading]; + if (this.#abridgedOmittedLines === 1) { + report.push(` ...${this.#abridgedOmittedLines} line omitted...\n`); } - if (this._abridgedOmittedLines > 1) { - report.push(` ...${this._abridgedOmittedLines} lines omitted...\n`); + if (this.#abridgedOmittedLines > 1) { + report.push(` ...${this.#abridgedOmittedLines} lines omitted...\n`); } - report.push(...this._abridgedTrailing); + report.push(...this.#abridgedTrailing); return report.join(''); } @@ -106,29 +106,29 @@ export class StdioSummarizer extends TerminalWritable { ); } - if (chunk.kind === TerminalChunkKind.Stderr && !this._abridgedStderr) { + if (chunk.kind === TerminalChunkKind.Stderr && !this.#abridgedStderr) { // The first time we see stderr, switch to capturing stderr - this._abridgedStderr = true; - this._abridgedLeading.length = 0; - this._abridgedTrailing.length = 0; - this._abridgedOmittedLines = 0; - } else if (this._abridgedStderr && chunk.kind !== TerminalChunkKind.Stderr) { + this.#abridgedStderr = true; + this.#abridgedLeading.length = 0; + this.#abridgedTrailing.length = 0; + this.#abridgedOmittedLines = 0; + } else if (this.#abridgedStderr && chunk.kind !== TerminalChunkKind.Stderr) { // If we're capturing stderr, then ignore non-stderr input return; } // Did we capture enough leading lines? - if (this._abridgedLeading.length < this._leadingLines) { - this._abridgedLeading.push(chunk.text); + if (this.#abridgedLeading.length < this.#leadingLines) { + this.#abridgedLeading.push(chunk.text); return; } - this._abridgedTrailing.push(chunk.text); + this.#abridgedTrailing.push(chunk.text); // If we captured to many trailing lines, omit the extras - while (this._abridgedTrailing.length > this._trailingLines) { - this._abridgedTrailing.shift(); - ++this._abridgedOmittedLines; + while (this.#abridgedTrailing.length > this.#trailingLines) { + this.#abridgedTrailing.shift(); + ++this.#abridgedOmittedLines; } } } diff --git a/libraries/terminal/src/StringBufferTerminalProvider.ts b/libraries/terminal/src/StringBufferTerminalProvider.ts index 34eb4d50cac..50fd1536eab 100644 --- a/libraries/terminal/src/StringBufferTerminalProvider.ts +++ b/libraries/terminal/src/StringBufferTerminalProvider.ts @@ -90,12 +90,12 @@ const LONGEST_SEVERITY_NAME_LENGTH: number = Object.keys(TerminalProviderSeverit * @beta */ export class StringBufferTerminalProvider implements ITerminalProvider { - private _standardBuffer: StringBuilder = new StringBuilder(); - private _verboseBuffer: StringBuilder = new StringBuilder(); - private _debugBuffer: StringBuilder = new StringBuilder(); - private _warningBuffer: StringBuilder = new StringBuilder(); - private _errorBuffer: StringBuilder = new StringBuilder(); - private _allOutputChunks: IOutputChunk[] = []; + #standardBuffer: StringBuilder = new StringBuilder(); + #verboseBuffer: StringBuilder = new StringBuilder(); + #debugBuffer: StringBuilder = new StringBuilder(); + #warningBuffer: StringBuilder = new StringBuilder(); + #errorBuffer: StringBuilder = new StringBuilder(); + #allOutputChunks: IOutputChunk[] = []; /** * {@inheritDoc ITerminalProvider.supportsColor} @@ -114,11 +114,11 @@ export class StringBufferTerminalProvider implements ITerminalProvider { severity ] as TerminalProviderSeverityName; - const lastChunk: IOutputChunk | undefined = this._allOutputChunks[this._allOutputChunks.length - 1]; + const lastChunk: IOutputChunk | undefined = this.#allOutputChunks[this.#allOutputChunks.length - 1]; if (lastChunk && lastChunk.severity === severityName) { lastChunk.text += text; } else { - this._allOutputChunks.push({ + this.#allOutputChunks.push({ text, severity: severityName }); @@ -126,28 +126,28 @@ export class StringBufferTerminalProvider implements ITerminalProvider { switch (severity) { case TerminalProviderSeverity.warning: { - this._warningBuffer.append(text); + this.#warningBuffer.append(text); break; } case TerminalProviderSeverity.error: { - this._errorBuffer.append(text); + this.#errorBuffer.append(text); break; } case TerminalProviderSeverity.verbose: { - this._verboseBuffer.append(text); + this.#verboseBuffer.append(text); break; } case TerminalProviderSeverity.debug: { - this._debugBuffer.append(text); + this.#debugBuffer.append(text); break; } case TerminalProviderSeverity.log: default: { - this._standardBuffer.append(text); + this.#standardBuffer.append(text); break; } } @@ -164,7 +164,7 @@ export class StringBufferTerminalProvider implements ITerminalProvider { * Get everything that has been written at log-level severity. */ public getOutput(options?: IStringBufferOutputOptions): string { - return _normalizeOutput(this._standardBuffer.toString(), options); + return _normalizeOutput(this.#standardBuffer.toString(), options); } /** @@ -178,28 +178,28 @@ export class StringBufferTerminalProvider implements ITerminalProvider { * Get everything that has been written at verbose-level severity. */ public getVerboseOutput(options?: IStringBufferOutputOptions): string { - return _normalizeOutput(this._verboseBuffer.toString(), options); + return _normalizeOutput(this.#verboseBuffer.toString(), options); } /** * Get everything that has been written at debug-level severity. */ public getDebugOutput(options?: IStringBufferOutputOptions): string { - return _normalizeOutput(this._debugBuffer.toString(), options); + return _normalizeOutput(this.#debugBuffer.toString(), options); } /** * Get everything that has been written at error-level severity. */ public getErrorOutput(options?: IStringBufferOutputOptions): string { - return _normalizeOutput(this._errorBuffer.toString(), options); + return _normalizeOutput(this.#errorBuffer.toString(), options); } /** * Get everything that has been written at warning-level severity. */ public getWarningOutput(options?: IStringBufferOutputOptions): string { - return _normalizeOutput(this._warningBuffer.toString(), options); + return _normalizeOutput(this.#warningBuffer.toString(), options); } /** @@ -255,7 +255,7 @@ export class StringBufferTerminalProvider implements ITerminalProvider { if (asLines) { const lines: `[${string}] ${string}`[] = []; - for (const { text: rawText, severity: rawSeverity } of this._allOutputChunks) { + for (const { text: rawText, severity: rawSeverity } of this.#allOutputChunks) { const severity: string = (rawSeverity as TerminalProviderSeverityName).padStart( LONGEST_SEVERITY_NAME_LENGTH, ' ' @@ -287,7 +287,7 @@ export class StringBufferTerminalProvider implements ITerminalProvider { return lines; } else { - return this._allOutputChunks.map(({ text: rawText, severity }) => { + return this.#allOutputChunks.map(({ text: rawText, severity }) => { const text: string = _normalizeOutputInner(rawText, normalizeSpecialCharacters); return { text, diff --git a/libraries/terminal/src/Terminal.ts b/libraries/terminal/src/Terminal.ts index d888fee5dc9..39421234a36 100644 --- a/libraries/terminal/src/Terminal.ts +++ b/libraries/terminal/src/Terminal.ts @@ -12,24 +12,24 @@ import { AnsiEscape } from './AnsiEscape'; * @beta */ export class Terminal implements ITerminal { - private readonly _providers: Set; + readonly #providers: Set; public constructor(provider: ITerminalProvider) { - this._providers = new Set([provider]); + this.#providers = new Set([provider]); } /** * {@inheritdoc ITerminal.registerProvider} */ public registerProvider(provider: ITerminalProvider): void { - this._providers.add(provider); + this.#providers.add(provider); } /** * {@inheritdoc ITerminal.unregisterProvider} */ public unregisterProvider(provider: ITerminalProvider): void { - this._providers.delete(provider); + this.#providers.delete(provider); } /** @@ -158,7 +158,7 @@ export class Terminal implements ITerminal { const concatenatedLinesWithColorByNewlineChar: Map = new Map(); const concatenatedLinesWithoutColorByNewlineChar: Map = new Map(); - for (const provider of this._providers) { + for (const provider of this.#providers) { let textToWrite: string | undefined; const eol: string = provider.eolCharacter; if (provider.supportsColor) { diff --git a/libraries/terminal/src/TerminalStreamWritable.ts b/libraries/terminal/src/TerminalStreamWritable.ts index 8b84a1bcdf3..f015111a58d 100644 --- a/libraries/terminal/src/TerminalStreamWritable.ts +++ b/libraries/terminal/src/TerminalStreamWritable.ts @@ -32,7 +32,7 @@ export interface ITerminalStreamWritableOptions { * @beta */ export class TerminalStreamWritable extends Writable { - private _writeMethod: (data: string) => void; + #writeMethod: (data: string) => void; public constructor(options: ITerminalStreamWritableOptions) { const { terminal, severity, writableOptions } = options; @@ -41,19 +41,19 @@ export class TerminalStreamWritable extends Writable { this._writev = undefined; switch (severity) { case TerminalProviderSeverity.log: - this._writeMethod = terminal.write.bind(terminal); + this.#writeMethod = terminal.write.bind(terminal); break; case TerminalProviderSeverity.verbose: - this._writeMethod = terminal.writeVerbose.bind(terminal); + this.#writeMethod = terminal.writeVerbose.bind(terminal); break; case TerminalProviderSeverity.debug: - this._writeMethod = terminal.writeDebug.bind(terminal); + this.#writeMethod = terminal.writeDebug.bind(terminal); break; case TerminalProviderSeverity.warning: - this._writeMethod = terminal.writeWarning.bind(terminal); + this.#writeMethod = terminal.writeWarning.bind(terminal); break; case TerminalProviderSeverity.error: - this._writeMethod = terminal.writeError.bind(terminal); + this.#writeMethod = terminal.writeError.bind(terminal); break; default: throw new Error(`Unknown severity: ${severity}`); @@ -68,7 +68,7 @@ export class TerminalStreamWritable extends Writable { ): void { try { const chunkData: string | Buffer = typeof chunk === 'string' ? chunk : Buffer.from(chunk); - this._writeMethod(chunkData.toString()); + this.#writeMethod(chunkData.toString()); } catch (e: unknown) { callback(e as Error); return; diff --git a/libraries/terminal/src/TerminalTable.ts b/libraries/terminal/src/TerminalTable.ts index 6f1d94645ab..801521eebec 100644 --- a/libraries/terminal/src/TerminalTable.ts +++ b/libraries/terminal/src/TerminalTable.ts @@ -156,24 +156,24 @@ const DEFAULT_CHARS: ITerminalTableChars = { * @public */ export class TerminalTable { - private readonly _head: string[]; - private readonly _specifiedColWidths: (number | undefined)[]; - private readonly _borderCharacters: ITerminalTableChars; - private readonly _borderColor: ((text: string) => string) | undefined; - private readonly _headingColor: ((text: string) => string) | undefined; - private readonly _rows: string[][]; + readonly #head: string[]; + readonly #specifiedColWidths: (number | undefined)[]; + readonly #borderCharacters: ITerminalTableChars; + readonly #borderColor: ((text: string) => string) | undefined; + readonly #headingColor: ((text: string) => string) | undefined; + readonly #rows: string[][]; public constructor(options: ITerminalTableOptions = {}) { const { head, colWidths, borderless, borderCharacters, borderColor, headingColor } = options; - this._head = head ?? []; - this._specifiedColWidths = colWidths ?? []; - this._borderCharacters = { + this.#head = head ?? []; + this.#specifiedColWidths = colWidths ?? []; + this.#borderCharacters = { ...(borderless ? BORDERLESS_CHARS : DEFAULT_CHARS), ...borderCharacters }; - this._borderColor = borderColor; - this._headingColor = headingColor; - this._rows = []; + this.#borderColor = borderColor; + this.#headingColor = headingColor; + this.#rows = []; } /** @@ -181,35 +181,33 @@ export class TerminalTable { */ public push(...rows: string[][]): void { for (const row of rows) { - this._rows.push(row); + this.#rows.push(row); } } public getLines(): string[] { + const head: string[] = this.#head; + const rows: string[][] = this.#rows; + const specifiedColWidths: (number | undefined)[] = this.#specifiedColWidths; + const borderColor: ((text: string) => string) | undefined = this.#borderColor; + const headingColor: ((text: string) => string) | undefined = this.#headingColor; const { - _head: head, - _rows: rows, - _specifiedColWidths: specifiedColWidths, - _borderColor: borderColor, - _headingColor: headingColor, - _borderCharacters: { - top: topSeparator, - topCenter: topCenterSeparator, - topLeft: topLeftSeparator, - topRight: topRightSeparator, - bottom: bottomSeparator, - bottomCenter: bottomCenterSeparator, - bottomLeft: bottomLeftSeparator, - bottomRight: bottomRightSeparator, - left: leftSeparator, - leftCenter: leftCenterSeparator, - horizontalCenter: horizontalCenterSeparator, - centerCenter: centerCenterSeparator, - right: rightSeparator, - rightCenter: rightCenterSeparator, - verticalCenter: verticalCenterSeparator - } - } = this; + top: topSeparator, + topCenter: topCenterSeparator, + topLeft: topLeftSeparator, + topRight: topRightSeparator, + bottom: bottomSeparator, + bottomCenter: bottomCenterSeparator, + bottomLeft: bottomLeftSeparator, + bottomRight: bottomRightSeparator, + left: leftSeparator, + leftCenter: leftCenterSeparator, + horizontalCenter: horizontalCenterSeparator, + centerCenter: centerCenterSeparator, + right: rightSeparator, + rightCenter: rightCenterSeparator, + verticalCenter: verticalCenterSeparator + } = this.#borderCharacters; const allRows: string[][] = [head, ...rows]; const columnCount: number = Math.max(0, ...allRows.map((r) => r.length)); @@ -306,9 +304,9 @@ export class TerminalTable { } } - for (let i: number = 0; i < this._rows.length; i++) { - lines.push(renderRow(this._rows[i])); - if (i < this._rows.length - 1 && centerLine !== undefined) { + for (let i: number = 0; i < this.#rows.length; i++) { + lines.push(renderRow(this.#rows[i])); + if (i < this.#rows.length - 1 && centerLine !== undefined) { lines.push(centerLine); } } diff --git a/libraries/terminal/src/TerminalWritable.ts b/libraries/terminal/src/TerminalWritable.ts index 22f20f72263..2dbcb8ea28d 100644 --- a/libraries/terminal/src/TerminalWritable.ts +++ b/libraries/terminal/src/TerminalWritable.ts @@ -74,12 +74,12 @@ export interface ITerminalWritableOptions { * @public */ export abstract class TerminalWritable { - private _isOpen: boolean; + #isOpen: boolean; public readonly preventAutoclose: boolean; public constructor(options?: ITerminalWritableOptions) { - this._isOpen = true; + this.#isOpen = true; if (!options) { options = {}; @@ -94,7 +94,7 @@ export abstract class TerminalWritable { * @sealed */ public get isOpen(): boolean { - return this._isOpen; + return this.#isOpen; } /** @@ -111,7 +111,7 @@ export abstract class TerminalWritable { * @sealed */ public writeChunk(chunk: ITerminalChunk): void { - if (!this._isOpen) { + if (!this.#isOpen) { throw new Error('Writer was already closed'); } this.onWriteChunk(chunk); @@ -136,9 +136,9 @@ export abstract class TerminalWritable { * @sealed */ public close(): void { - if (this._isOpen) { + if (this.#isOpen) { this.onClose(); - this._isOpen = false; + this.#isOpen = false; } } diff --git a/libraries/terminal/src/TextRewriterTransform.ts b/libraries/terminal/src/TextRewriterTransform.ts index 1377f806ba8..727fda0a548 100644 --- a/libraries/terminal/src/TextRewriterTransform.ts +++ b/libraries/terminal/src/TextRewriterTransform.ts @@ -60,8 +60,8 @@ export interface ITextRewriterTransformOptions extends ITerminalTransformOptions * @public */ export class TextRewriterTransform extends TerminalTransform { - private readonly _stderrStates: TextRewriterState[]; - private readonly _stdoutStates: TextRewriterState[]; + readonly #stderrStates: TextRewriterState[]; + readonly #stdoutStates: TextRewriterState[]; public readonly textRewriters: ReadonlyArray; @@ -95,15 +95,15 @@ export class TextRewriterTransform extends TerminalTransform { this.textRewriters = textRewriters; - this._stderrStates = this.textRewriters.map((x) => x.initialize()); - this._stdoutStates = this.textRewriters.map((x) => x.initialize()); + this.#stderrStates = this.textRewriters.map((x) => x.initialize()); + this.#stdoutStates = this.textRewriters.map((x) => x.initialize()); } protected onWriteChunk(chunk: ITerminalChunk): void { if (chunk.kind === TerminalChunkKind.Stderr) { - this._processText(chunk, this._stderrStates); + this._processText(chunk, this.#stderrStates); } else if (chunk.kind === TerminalChunkKind.Stdout) { - this._processText(chunk, this._stdoutStates); + this._processText(chunk, this.#stdoutStates); } else { this.destination.writeChunk(chunk); } @@ -146,8 +146,8 @@ export class TextRewriterTransform extends TerminalTransform { } protected onClose(): void { - this._closeRewriters(this._stderrStates, TerminalChunkKind.Stderr); - this._closeRewriters(this._stdoutStates, TerminalChunkKind.Stdout); + this._closeRewriters(this.#stderrStates, TerminalChunkKind.Stderr); + this._closeRewriters(this.#stdoutStates, TerminalChunkKind.Stdout); this.autocloseDestination(); } diff --git a/libraries/terminal/src/test/ProblemCollector.test.ts b/libraries/terminal/src/test/ProblemCollector.test.ts index 363080df07c..870d04be970 100644 --- a/libraries/terminal/src/test/ProblemCollector.test.ts +++ b/libraries/terminal/src/test/ProblemCollector.test.ts @@ -12,9 +12,9 @@ import { TerminalChunkKind } from '../ITerminalChunk'; class ErrorLineMatcher implements IProblemMatcher { public readonly name: string = 'errorLine'; - private readonly _regex: RegExp = /^ERROR:\s*(.*)\n$/; + readonly #regex: RegExp = /^ERROR:\s*(.*)\n$/; public exec(line: string): IProblem | false { - const match: RegExpExecArray | null = this._regex.exec(line); + const match: RegExpExecArray | null = this.#regex.exec(line); if (match) { return { matcherName: this.name, diff --git a/libraries/tree-pattern/src/TreePattern.ts b/libraries/tree-pattern/src/TreePattern.ts index 4876f30e28d..4ecd396ce97 100644 --- a/libraries/tree-pattern/src/TreePattern.ts +++ b/libraries/tree-pattern/src/TreePattern.ts @@ -54,10 +54,10 @@ export type ITreePatternCaptureSet = * @public */ export class TreePattern { - private readonly _pattern: TreeNode; + readonly #pattern: TreeNode; public constructor(pattern: TreeNode) { - this._pattern = pattern; + this.#pattern = pattern; } /** @@ -128,7 +128,7 @@ export class TreePattern { * @returns `true` if `root` matches the pattern, or `false` otherwise */ public match(root: TreeNode, captures: ITreePatternCaptureSet = {}): boolean { - return _matchTreeRecursive(root, this._pattern, captures, 'root'); + return _matchTreeRecursive(root, this.#pattern, captures, 'root'); } } diff --git a/libraries/ts-command-line/src/parameters/BaseClasses.ts b/libraries/ts-command-line/src/parameters/BaseClasses.ts index 0f5a0a1e0de..911c67fad34 100644 --- a/libraries/ts-command-line/src/parameters/BaseClasses.ts +++ b/libraries/ts-command-line/src/parameters/BaseClasses.ts @@ -81,7 +81,7 @@ export type CommandLineParameter = * @public */ export abstract class CommandLineParameterBase { - private _shortNameValue: string | undefined; + #shortNameValue: string | undefined; /** * A unique internal key used to retrieve the value from the parser's dictionary. @@ -137,7 +137,7 @@ export abstract class CommandLineParameterBase { /** @internal */ public constructor(definition: IBaseCommandLineDefinition) { this.longName = definition.parameterLongName; - this._shortNameValue = definition.parameterShortName; + this.#shortNameValue = definition.parameterShortName; this.parameterGroup = definition.parameterGroup; this.parameterScope = definition.parameterScope; this.description = definition.description; @@ -205,7 +205,7 @@ export abstract class CommandLineParameterBase { /** {@inheritDoc IBaseCommandLineDefinition.parameterShortName} */ public get shortName(): string | undefined { - return this._shortNameValue; + return this.#shortNameValue; } /** diff --git a/libraries/ts-command-line/src/parameters/CommandLineChoiceListParameter.ts b/libraries/ts-command-line/src/parameters/CommandLineChoiceListParameter.ts index 64a03318af2..8babe39f16e 100644 --- a/libraries/ts-command-line/src/parameters/CommandLineChoiceListParameter.ts +++ b/libraries/ts-command-line/src/parameters/CommandLineChoiceListParameter.ts @@ -15,7 +15,7 @@ export class CommandLineChoiceListParameter< /** {@inheritDoc ICommandLineChoiceListDefinition.alternatives} */ public readonly alternatives: ReadonlySet; - private _values: TChoice[] = []; + #values: TChoice[] = []; /** {@inheritDoc ICommandLineChoiceListDefinition.completions} */ public readonly completions: (() => Promise | ReadonlySet>) | undefined; @@ -54,7 +54,7 @@ export class CommandLineChoiceListParameter< this.reportInvalidData(data); } } - this._values = data; + this.#values = data; return; } @@ -71,14 +71,14 @@ export class CommandLineChoiceListParameter< } } - this._values = values as TChoice[]; + this.#values = values as TChoice[]; return; } } // (No default value for choice lists) - this._values = []; + this.#values = []; } /** @@ -89,7 +89,7 @@ export class CommandLineChoiceListParameter< * or if the parameter was omitted and has no default value. */ public get values(): ReadonlyArray { - return this._values; + return this.#values; } /** {@inheritDoc CommandLineParameterBase.appendToArgList} */ diff --git a/libraries/ts-command-line/src/parameters/CommandLineChoiceParameter.ts b/libraries/ts-command-line/src/parameters/CommandLineChoiceParameter.ts index 1b2d6179008..d65996cf9d2 100644 --- a/libraries/ts-command-line/src/parameters/CommandLineChoiceParameter.ts +++ b/libraries/ts-command-line/src/parameters/CommandLineChoiceParameter.ts @@ -24,7 +24,7 @@ export class CommandLineChoiceParameter extends /** {@inheritDoc ICommandLineStringDefinition.defaultValue} */ public readonly defaultValue: TChoice | undefined; - private _value: TChoice | undefined = undefined; + #value: TChoice | undefined = undefined; /** {@inheritDoc ICommandLineChoiceDefinition.completions} */ public readonly completions: (() => Promise | ReadonlySet>) | undefined; @@ -66,7 +66,7 @@ export class CommandLineChoiceParameter extends if (typeof data !== 'string') { this.reportInvalidData(data); } - this._value = data as TChoice; + this.#value = data as TChoice; return; } @@ -82,17 +82,17 @@ export class CommandLineChoiceParameter extends ); } - this._value = environmentValue as TChoice; + this.#value = environmentValue as TChoice; return; } } if (this.defaultValue !== undefined) { - this._value = this.defaultValue; + this.#value = this.defaultValue; return; } - this._value = undefined; + this.#value = undefined; } /** @@ -115,7 +115,7 @@ export class CommandLineChoiceParameter extends * or if the parameter was omitted and has no default value. */ public get value(): TChoice | undefined { - return this._value; + return this.#value; } /** {@inheritDoc CommandLineParameterBase.appendToArgList} */ diff --git a/libraries/ts-command-line/src/parameters/CommandLineFlagParameter.ts b/libraries/ts-command-line/src/parameters/CommandLineFlagParameter.ts index 607280a9305..e3b7330a2d9 100644 --- a/libraries/ts-command-line/src/parameters/CommandLineFlagParameter.ts +++ b/libraries/ts-command-line/src/parameters/CommandLineFlagParameter.ts @@ -9,7 +9,7 @@ import { CommandLineParameterBase, CommandLineParameterKind } from './BaseClasse * @public */ export class CommandLineFlagParameter extends CommandLineParameterBase { - private _value: boolean = false; + #value: boolean = false; /** {@inheritDoc CommandLineParameterBase.kind} */ public readonly kind: CommandLineParameterKind.Flag = CommandLineParameterKind.Flag; @@ -34,7 +34,7 @@ export class CommandLineFlagParameter extends CommandLineParameterBase { // This design prevents a syntax such as "--flag=false", probably because argparse prefers "--no-flag". // If we switch to a new CLI parser, we should try to add support for "--flag=false". if (data) { - this._value = data; + this.#value = data; return; } } @@ -49,12 +49,12 @@ export class CommandLineFlagParameter extends CommandLineParameterBase { ` ${this.environmentVariable}. Valid choices are 0 or 1.` ); } - this._value = environmentValue === '1'; + this.#value = environmentValue === '1'; return; } } - this._value = false; + this.#value = false; } /** @@ -65,7 +65,7 @@ export class CommandLineFlagParameter extends CommandLineParameterBase { * or if the flag was not used. */ public get value(): boolean { - return this._value; + return this.#value; } /** {@inheritDoc CommandLineParameterBase.appendToArgList} */ diff --git a/libraries/ts-command-line/src/parameters/CommandLineIntegerListParameter.ts b/libraries/ts-command-line/src/parameters/CommandLineIntegerListParameter.ts index 5fd23a989b9..7052548dc2f 100644 --- a/libraries/ts-command-line/src/parameters/CommandLineIntegerListParameter.ts +++ b/libraries/ts-command-line/src/parameters/CommandLineIntegerListParameter.ts @@ -10,7 +10,7 @@ import { EnvironmentVariableParser } from './EnvironmentVariableParser'; * @public */ export class CommandLineIntegerListParameter extends CommandLineParameterWithArgument { - private _values: number[] = []; + #values: number[] = []; /** {@inheritDoc CommandLineParameterBase.kind} */ public readonly kind: CommandLineParameterKind.IntegerList = CommandLineParameterKind.IntegerList; @@ -35,7 +35,7 @@ export class CommandLineIntegerListParameter extends CommandLineParameterWithArg this.reportInvalidData(data); } } - this._values = data; + this.#values = data; return; } @@ -54,14 +54,14 @@ export class CommandLineIntegerListParameter extends CommandLineParameterWithArg } parsedValues.push(parsed); } - this._values = parsedValues; + this.#values = parsedValues; return; } } // (No default value for integer lists) - this._values = []; + this.#values = []; } /** @@ -72,7 +72,7 @@ export class CommandLineIntegerListParameter extends CommandLineParameterWithArg * or if the parameter was omitted and has no default value. */ public get values(): ReadonlyArray { - return this._values; + return this.#values; } /** {@inheritDoc CommandLineParameterBase.appendToArgList} */ diff --git a/libraries/ts-command-line/src/parameters/CommandLineIntegerParameter.ts b/libraries/ts-command-line/src/parameters/CommandLineIntegerParameter.ts index 8af7493e309..e5c881bc53a 100644 --- a/libraries/ts-command-line/src/parameters/CommandLineIntegerParameter.ts +++ b/libraries/ts-command-line/src/parameters/CommandLineIntegerParameter.ts @@ -20,7 +20,7 @@ export class CommandLineIntegerParameter extends CommandLineParameterWithArgumen /** {@inheritDoc ICommandLineStringDefinition.defaultValue} */ public readonly defaultValue: number | undefined; - private _value: number | undefined = undefined; + #value: number | undefined = undefined; /** {@inheritDoc CommandLineParameterBase.kind} */ public readonly kind: CommandLineParameterKind.Integer = CommandLineParameterKind.Integer; @@ -42,7 +42,7 @@ export class CommandLineIntegerParameter extends CommandLineParameterWithArgumen if (typeof data !== 'number') { this.reportInvalidData(data); } - this._value = data; + this.#value = data; return; } @@ -57,17 +57,17 @@ export class CommandLineIntegerParameter extends CommandLineParameterWithArgumen ` ${this.environmentVariable}. It must be an integer value.` ); } - this._value = parsed; + this.#value = parsed; return; } } if (this.defaultValue !== undefined) { - this._value = this.defaultValue; + this.#value = this.defaultValue; return; } - this._value = undefined; + this.#value = undefined; } /** @@ -90,7 +90,7 @@ export class CommandLineIntegerParameter extends CommandLineParameterWithArgumen * or if the parameter was omitted and has no default value. */ public get value(): number | undefined { - return this._value; + return this.#value; } /** {@inheritDoc CommandLineParameterBase.appendToArgList} */ diff --git a/libraries/ts-command-line/src/parameters/CommandLineRemainder.ts b/libraries/ts-command-line/src/parameters/CommandLineRemainder.ts index 9af7c5b7f83..33eed89885e 100644 --- a/libraries/ts-command-line/src/parameters/CommandLineRemainder.ts +++ b/libraries/ts-command-line/src/parameters/CommandLineRemainder.ts @@ -8,7 +8,7 @@ import type { ICommandLineRemainderDefinition } from './CommandLineDefinition'; * @public */ export class CommandLineRemainder { - private _values: string[] = []; + #values: string[] = []; /** {@inheritDoc IBaseCommandLineDefinition.description} */ public readonly description: string; @@ -26,7 +26,7 @@ export class CommandLineRemainder { * The array will be empty if the command-line has not been parsed yet. */ public get values(): ReadonlyArray { - return this._values; + return this.#values; } /** @@ -39,7 +39,7 @@ export class CommandLineRemainder { throw new Error(`Unexpected data object for remainder: ` + JSON.stringify(data)); } - this._values.push(...data); + this.#values.push(...data); } /** {@inheritDoc CommandLineParameterBase.appendToArgList} */ diff --git a/libraries/ts-command-line/src/parameters/CommandLineStringListParameter.ts b/libraries/ts-command-line/src/parameters/CommandLineStringListParameter.ts index bf57de5992c..4485be752d9 100644 --- a/libraries/ts-command-line/src/parameters/CommandLineStringListParameter.ts +++ b/libraries/ts-command-line/src/parameters/CommandLineStringListParameter.ts @@ -10,7 +10,7 @@ import { EnvironmentVariableParser } from './EnvironmentVariableParser'; * @public */ export class CommandLineStringListParameter extends CommandLineParameterWithArgument { - private _values: string[] = []; + #values: string[] = []; /** {@inheritDoc CommandLineParameterBase.kind} */ public readonly kind: CommandLineParameterKind.StringList = CommandLineParameterKind.StringList; @@ -35,7 +35,7 @@ export class CommandLineStringListParameter extends CommandLineParameterWithArgu this.reportInvalidData(data); } } - this._values = data; + this.#values = data; return; } @@ -43,14 +43,14 @@ export class CommandLineStringListParameter extends CommandLineParameterWithArgu if (this.environmentVariable !== undefined) { const values: string[] | undefined = EnvironmentVariableParser.parseAsList(this.environmentVariable); if (values) { - this._values = values; + this.#values = values; return; } } // (No default value for string lists) - this._values = []; + this.#values = []; } /** @@ -61,7 +61,7 @@ export class CommandLineStringListParameter extends CommandLineParameterWithArgu * or if the parameter was omitted and has no default value. */ public get values(): ReadonlyArray { - return this._values; + return this.#values; } /** {@inheritDoc CommandLineParameterBase.appendToArgList} */ diff --git a/libraries/ts-command-line/src/parameters/CommandLineStringParameter.ts b/libraries/ts-command-line/src/parameters/CommandLineStringParameter.ts index 3b2f0c5c9ad..c0827276780 100644 --- a/libraries/ts-command-line/src/parameters/CommandLineStringParameter.ts +++ b/libraries/ts-command-line/src/parameters/CommandLineStringParameter.ts @@ -20,7 +20,7 @@ export class CommandLineStringParameter extends CommandLineParameterWithArgument /** {@inheritDoc ICommandLineStringDefinition.defaultValue} */ public readonly defaultValue: string | undefined; - private _value: string | undefined = undefined; + #value: string | undefined = undefined; /** {@inheritDoc CommandLineParameterBase.kind} */ public readonly kind: CommandLineParameterKind.String = CommandLineParameterKind.String; @@ -43,7 +43,7 @@ export class CommandLineStringParameter extends CommandLineParameterWithArgument if (typeof data !== 'string') { this.reportInvalidData(data); } - this._value = data; + this.#value = data; return; } @@ -53,17 +53,17 @@ export class CommandLineStringParameter extends CommandLineParameterWithArgument if (environmentValue !== undefined) { // NOTE: If the environment variable is defined as an empty string, // here we will accept the empty string as our value. (For number/flag we don't do that.) - this._value = environmentValue; + this.#value = environmentValue; return; } } if (this.defaultValue !== undefined) { - this._value = this.defaultValue; + this.#value = this.defaultValue; return; } - this._value = undefined; + this.#value = undefined; } /** @@ -88,7 +88,7 @@ export class CommandLineStringParameter extends CommandLineParameterWithArgument * or if the parameter was omitted and has no default value. */ public get value(): string | undefined { - return this._value; + return this.#value; } /** {@inheritDoc CommandLineParameterBase.appendToArgList} */ diff --git a/libraries/ts-command-line/src/providers/AliasCommandLineAction.ts b/libraries/ts-command-line/src/providers/AliasCommandLineAction.ts index e0aecd52e37..1b45553ff59 100644 --- a/libraries/ts-command-line/src/providers/AliasCommandLineAction.ts +++ b/libraries/ts-command-line/src/providers/AliasCommandLineAction.ts @@ -60,7 +60,7 @@ export class AliasCommandLineAction extends CommandLineAction { */ public readonly defaultParameters: ReadonlyArray; - private _parameterKeyMap: Map = new Map(); + #parameterKeyMap: Map = new Map(); public constructor(options: IAliasCommandLineActionOptions) { const { toolFilename, targetAction, defaultParameters: defaultParams = [], aliasName } = options; @@ -130,14 +130,14 @@ export class AliasCommandLineAction extends CommandLineAction { // We know the parserKey is defined because the underlying _defineParameter method sets it, // and all parameters that we have access to have already been defined. - this._parameterKeyMap.set(aliasParameter._parserKey!, parameter._parserKey!); + this.#parameterKeyMap.set(aliasParameter._parserKey!, parameter._parserKey!); } // We also need to register the remainder parameter if the target action has one. The parser // key for this parameter is constant. if (this.targetAction.remainder) { this.defineCommandLineRemainder(this.targetAction.remainder); - this._parameterKeyMap.set(argparse.Const.REMAINDER, argparse.Const.REMAINDER); + this.#parameterKeyMap.set(argparse.Const.REMAINDER, argparse.Const.REMAINDER); } // Finally, register the parameters with the parser. We need to make sure that the target action @@ -154,7 +154,7 @@ export class AliasCommandLineAction extends CommandLineAction { // If we have a mapping for the specified key, then use it. Otherwise, use the key as-is. if (targetParserKey) { - this._parameterKeyMap.set(parserKey, targetParserKey); + this.#parameterKeyMap.set(parserKey, targetParserKey); } } } @@ -176,7 +176,7 @@ export class AliasCommandLineAction extends CommandLineAction { if (key === 'action') { continue; } - const targetKey: string | undefined = this._parameterKeyMap.get(key); + const targetKey: string | undefined = this.#parameterKeyMap.get(key); targetData[targetKey ?? key] = value; } this.targetAction._processParsedData(parserOptions, targetData); diff --git a/libraries/ts-command-line/src/providers/CommandLineAction.ts b/libraries/ts-command-line/src/providers/CommandLineAction.ts index acfa54d9739..72d67cbcdd9 100644 --- a/libraries/ts-command-line/src/providers/CommandLineAction.ts +++ b/libraries/ts-command-line/src/providers/CommandLineAction.ts @@ -59,7 +59,7 @@ export abstract class CommandLineAction extends CommandLineParameterProvider { /** {@inheritDoc ICommandLineActionOptions.documentation} */ public readonly documentation: string; - private _argumentParser: argparse.ArgumentParser | undefined; + #argumentParser: argparse.ArgumentParser | undefined; public constructor(options: ICommandLineActionOptions) { super(); @@ -76,7 +76,7 @@ export abstract class CommandLineAction extends CommandLineParameterProvider { this.summary = summary; this.documentation = documentation; - this._argumentParser = undefined; + this.#argumentParser = undefined; } /** @@ -84,19 +84,19 @@ export abstract class CommandLineAction extends CommandLineParameterProvider { * @internal */ public _buildParser(actionsSubParser: argparse.SubParser): void { - this._argumentParser = actionsSubParser.addParser(this.actionName, { + this.#argumentParser = actionsSubParser.addParser(this.actionName, { help: escapeSprintf(this.summary), description: escapeSprintf(this.documentation) }); // Monkey-patch the error handling for the action parser - this._argumentParser.exit = (status: number, message: string) => { + this.#argumentParser.exit = (status: number, message: string) => { throw new CommandLineParserExitError(status, message); }; - const originalArgumentParserErrorFn: (err: Error | string) => void = this._argumentParser.error.bind( - this._argumentParser + const originalArgumentParserErrorFn: (err: Error | string) => void = this.#argumentParser.error.bind( + this.#argumentParser ); - this._argumentParser.error = (err: Error | string) => { + this.#argumentParser.error = (err: Error | string) => { // Ensure the ParserExitError bubbles up to the top without any special processing if (err instanceof CommandLineParserExitError) { throw err; @@ -118,12 +118,12 @@ export abstract class CommandLineAction extends CommandLineParameterProvider { * @internal */ public override _getArgumentParser(): argparse.ArgumentParser { - if (!this._argumentParser) { + if (!this.#argumentParser) { // We will improve this in the future throw new Error('The CommandLineAction must be added to a CommandLineParser before it can be used'); } - return this._argumentParser; + return this.#argumentParser; } /** diff --git a/libraries/ts-command-line/src/providers/CommandLineParameterProvider.ts b/libraries/ts-command-line/src/providers/CommandLineParameterProvider.ts index e7fd003f678..d85aafac399 100644 --- a/libraries/ts-command-line/src/providers/CommandLineParameterProvider.ts +++ b/libraries/ts-command-line/src/providers/CommandLineParameterProvider.ts @@ -114,42 +114,42 @@ export abstract class CommandLineParameterProvider { /** @internal */ protected readonly _registeredParameterParserKeysByName: Map; - private readonly _parameters: CommandLineParameter[]; - private readonly _parametersByLongName: Map; - private readonly _parametersByShortName: Map; - private readonly _parameterGroupsByName: Map< + readonly #parameters: CommandLineParameter[]; + readonly #parametersByLongName: Map; + readonly #parametersByShortName: Map; + readonly #parameterGroupsByName: Map< string | typeof SCOPING_PARAMETER_GROUP, argparse.ArgumentGroup >; - private _parametersHaveBeenRegistered: boolean; - private _parametersHaveBeenProcessed: boolean; - private _remainder: CommandLineRemainder | undefined; + #parametersHaveBeenRegistered: boolean; + #parametersHaveBeenProcessed: boolean; + #remainder: CommandLineRemainder | undefined; /** @internal */ // Third party code should not inherit subclasses or call this constructor public constructor() { - this._parameters = []; - this._parametersByLongName = new Map(); - this._parametersByShortName = new Map(); - this._parameterGroupsByName = new Map(); + this.#parameters = []; + this.#parametersByLongName = new Map(); + this.#parametersByShortName = new Map(); + this.#parameterGroupsByName = new Map(); this._ambiguousParameterParserKeysByName = new Map(); this._registeredParameterParserKeysByName = new Map(); - this._parametersHaveBeenRegistered = false; - this._parametersHaveBeenProcessed = false; + this.#parametersHaveBeenRegistered = false; + this.#parametersHaveBeenProcessed = false; } /** * Returns a collection of the parameters that were defined for this object. */ public get parameters(): ReadonlyArray { - return this._parameters; + return this.#parameters; } /** * Informs the caller if the argparse data has been processed into parameters. */ public get parametersProcessed(): boolean { - return this._parametersHaveBeenProcessed; + return this.#parametersHaveBeenProcessed; } /** @@ -157,7 +157,7 @@ export abstract class CommandLineParameterProvider { * this object captures any remaining command line arguments after the recognized portion. */ public get remainder(): CommandLineRemainder | undefined { - return this._remainder; + return this.#remainder; } /** @@ -420,11 +420,11 @@ export abstract class CommandLineParameterProvider { * In the "--help" documentation, the remainder rule will be represented as "...". */ public defineCommandLineRemainder(definition: ICommandLineRemainderDefinition): CommandLineRemainder { - if (this._remainder) { + if (this.#remainder) { throw new Error('defineRemainingArguments() has already been called for this provider'); } - this._remainder = new CommandLineRemainder(definition); - return this._remainder; + this.#remainder = new CommandLineRemainder(definition); + return this.#remainder; } /** @@ -517,7 +517,7 @@ export abstract class CommandLineParameterProvider { /** @internal */ public _registerDefinedParameters(state: IRegisterDefinedParametersState): void { - if (this._parametersHaveBeenRegistered) { + if (this.#parametersHaveBeenRegistered) { // We prevent new parameters from being defined after the first call to _registerDefinedParameters, // so we can already ensure that all parameters were registered. return; @@ -527,7 +527,7 @@ export abstract class CommandLineParameterProvider { // since we can't prefix scopes to short names in order to deduplicate them. The duplicate short names will // be reported as errors if the user attempts to use them. const parametersWithDuplicateShortNames: Set = new Set(); - for (const [shortName, shortNameParameters] of this._parametersByShortName.entries()) { + for (const [shortName, shortNameParameters] of this.#parametersByShortName.entries()) { if (shortNameParameters.length > 1) { for (const parameter of shortNameParameters) { this._defineAmbiguousParameter(shortName); @@ -539,7 +539,7 @@ export abstract class CommandLineParameterProvider { // Then, loop through all parameters and register them. If there are any duplicates, ensure that they have // provided a scope and register them with the scope. The duplicate long names will be reported as an error // if the user attempts to use them. - for (const longNameParameters of this._parametersByLongName.values()) { + for (const longNameParameters of this.#parametersByLongName.values()) { const useScopedLongName: boolean = longNameParameters.length > 1; for (const parameter of longNameParameters) { if (useScopedLongName) { @@ -576,9 +576,9 @@ export abstract class CommandLineParameterProvider { } // Need to add the remainder parameter last - if (this._remainder) { + if (this.#remainder) { const argparseOptions: argparse.ArgumentOptions = { - help: this._remainder.description, + help: this.#remainder.description, nargs: argparse.Const.REMAINDER, metavar: '"..."' }; @@ -586,7 +586,7 @@ export abstract class CommandLineParameterProvider { this._getArgumentParser().addArgument(argparse.Const.REMAINDER, argparseOptions); } - this._parametersHaveBeenRegistered = true; + this.#parametersHaveBeenRegistered = true; } /** @@ -600,7 +600,7 @@ export abstract class CommandLineParameterProvider { * @internal */ public _preParse(): void { - for (const parameter of this._parameters) { + for (const parameter of this.#parameters) { parameter._preParse?.(); } } @@ -610,7 +610,7 @@ export abstract class CommandLineParameterProvider { * @internal */ public _postParse(): void { - for (const parameter of this._parameters) { + for (const parameter of this.#parameters) { parameter._postParse?.(); } } @@ -620,11 +620,11 @@ export abstract class CommandLineParameterProvider { * @internal */ public _processParsedData(parserOptions: ICommandLineParserOptions, data: ICommandLineParserData): void { - if (!this._parametersHaveBeenRegistered) { + if (!this.#parametersHaveBeenRegistered) { throw new Error('Parameters have not been registered'); } - if (this._parametersHaveBeenProcessed) { + if (this.#parametersHaveBeenProcessed) { throw new Error('Command Line Parser Data was already processed'); } @@ -640,14 +640,14 @@ export abstract class CommandLineParameterProvider { // Determine if the ambiguous parameter is a short name or a long name, since the process of finding // the non-ambiguous name is different for each. const duplicateShortNameParameters: CommandLineParameterBase[] | undefined = - this._parametersByShortName.get(parameterName); + this.#parametersByShortName.get(parameterName); if (duplicateShortNameParameters) { // We also need to make sure we get the non-ambiguous long name for the parameter, since it is // possible for that the long name is ambiguous as well. const nonAmbiguousLongNames: string[] = []; for (const parameter of duplicateShortNameParameters) { const matchingLongNameParameters: CommandLineParameterBase[] | undefined = - this._parametersByLongName.get(parameter.longName); + this.#parametersByLongName.get(parameter.longName); if (!matchingLongNameParameters?.length) { // This should never happen throw new Error( @@ -681,7 +681,7 @@ export abstract class CommandLineParameterProvider { } const duplicateLongNameParameters: CommandLineParameterBase[] | undefined = - this._parametersByLongName.get(parameterName); + this.#parametersByLongName.get(parameterName); if (duplicateLongNameParameters) { const nonAmbiguousLongNames: string[] = duplicateLongNameParameters.map( (p: CommandLineParameterBase) => { @@ -713,7 +713,7 @@ export abstract class CommandLineParameterProvider { } // Fill in the values for the parameters - for (const parameter of this._parameters) { + for (const parameter of this.#parameters) { const value: unknown = data[parameter._parserKey!]; parameter._setValue(value); parameter._validateValue?.(); @@ -723,38 +723,38 @@ export abstract class CommandLineParameterProvider { this.remainder._setValue(data[argparse.Const.REMAINDER]); } - this._parametersHaveBeenProcessed = true; + this.#parametersHaveBeenProcessed = true; } /** @internal */ protected _defineParameter(parameter: CommandLineParameter): void { - if (this._parametersHaveBeenRegistered) { + if (this.#parametersHaveBeenRegistered) { throw new Error('Parameters have already been registered for this provider'); } // Generate and set the parser key at definition time parameter._parserKey = this._generateKey(); - this._parameters.push(parameter); + this.#parameters.push(parameter); // Collect all parameters with the same long name. We will perform conflict resolution at registration. - let longNameParameters: CommandLineParameter[] | undefined = this._parametersByLongName.get( + let longNameParameters: CommandLineParameter[] | undefined = this.#parametersByLongName.get( parameter.longName ); if (!longNameParameters) { longNameParameters = []; - this._parametersByLongName.set(parameter.longName, longNameParameters); + this.#parametersByLongName.set(parameter.longName, longNameParameters); } longNameParameters.push(parameter); // Collect all parameters with the same short name. We will perform conflict resolution at registration. if (parameter.shortName) { - let shortNameParameters: CommandLineParameter[] | undefined = this._parametersByShortName.get( + let shortNameParameters: CommandLineParameter[] | undefined = this.#parametersByShortName.get( parameter.shortName ); if (!shortNameParameters) { shortNameParameters = []; - this._parametersByShortName.set(parameter.shortName, shortNameParameters); + this.#parametersByShortName.set(parameter.shortName, shortNameParameters); } shortNameParameters.push(parameter); } @@ -762,7 +762,7 @@ export abstract class CommandLineParameterProvider { /** @internal */ protected _defineAmbiguousParameter(name: string): string { - if (this._parametersHaveBeenRegistered) { + if (this.#parametersHaveBeenRegistered) { throw new Error('Parameters have already been registered for this provider'); } @@ -871,7 +871,7 @@ export abstract class CommandLineParameterProvider { const argumentParser: IExtendedArgumentParser = this._getArgumentParser() as IExtendedArgumentParser; let argumentGroup: argparse.ArgumentGroup | undefined; if (parameterGroup) { - argumentGroup = this._parameterGroupsByName.get(parameterGroup); + argumentGroup = this.#parameterGroupsByName.get(parameterGroup); if (!argumentGroup) { let parameterGroupName: string; if (typeof parameterGroup === 'string') { @@ -885,7 +885,7 @@ export abstract class CommandLineParameterProvider { argumentGroup = argumentParser.addArgumentGroup({ title: `Optional ${parameterGroupName} arguments` }); - this._parameterGroupsByName.set(parameterGroup, argumentGroup); + this.#parameterGroupsByName.set(parameterGroup, argumentGroup); } } else { argumentGroup = argumentParser; @@ -985,7 +985,7 @@ export abstract class CommandLineParameterProvider { parameterScope = scope || parameterScope; const parameters: CommandLineParameterBase[] | undefined = - this._parametersByLongName.get(parameterLongName); + this.#parametersByLongName.get(parameterLongName); if (!parameters) { throw new Error(`The parameter "${parameterLongName}" is not defined`); } diff --git a/libraries/ts-command-line/src/providers/CommandLineParser.ts b/libraries/ts-command-line/src/providers/CommandLineParser.ts index 26e3b1037d1..b469d84c34f 100644 --- a/libraries/ts-command-line/src/providers/CommandLineParser.ts +++ b/libraries/ts-command-line/src/providers/CommandLineParser.ts @@ -62,22 +62,22 @@ export class CommandLineParser extends CommandLineParameterProvider { */ public selectedAction: CommandLineAction | undefined; - private readonly _argumentParser: argparse.ArgumentParser; - private _actionsSubParser: argparse.SubParser | undefined; - private readonly _options: ICommandLineParserOptions; - private readonly _actionsByName: Map; - private _executed: boolean = false; - private _tabCompleteActionWasAdded: boolean = false; + readonly #argumentParser: argparse.ArgumentParser; + #actionsSubParser: argparse.SubParser | undefined; + readonly #options: ICommandLineParserOptions; + readonly #actionsByName: Map; + #executed: boolean = false; + #tabCompleteActionWasAdded: boolean = false; public constructor(options: ICommandLineParserOptions) { super(); - this._options = options; - this._actionsByName = new Map(); + this.#options = options; + this.#actionsByName = new Map(); const { toolFilename, toolDescription, toolEpilog } = options; - this._argumentParser = new CustomArgumentParser({ + this.#argumentParser = new CustomArgumentParser({ addHelp: true, prog: toolFilename, description: escapeSprintf(toolDescription), @@ -93,22 +93,22 @@ export class CommandLineParser extends CommandLineParameterProvider { * Returns the list of actions that were defined for this CommandLineParser object. */ public get actions(): ReadonlyArray { - return Array.from(this._actionsByName.values()); + return Array.from(this.#actionsByName.values()); } /** * Defines a new action that can be used with the CommandLineParser instance. */ public addAction(action: CommandLineAction): void { - if (!this._actionsSubParser) { - this._actionsSubParser = this._argumentParser.addSubparsers({ + if (!this.#actionsSubParser) { + this.#actionsSubParser = this.#argumentParser.addSubparsers({ metavar: '', dest: 'action' }); } - action._buildParser(this._actionsSubParser); - this._actionsByName.set(action.actionName, action); + action._buildParser(this.#actionsSubParser); + this.#actionsByName.set(action.actionName, action); } /** @@ -128,7 +128,7 @@ export class CommandLineParser extends CommandLineParameterProvider { * undefined is returned. */ public tryGetAction(actionName: string): CommandLineAction | undefined { - return this._actionsByName.get(actionName); + return this.#actionsByName.get(actionName); } /** @@ -149,9 +149,9 @@ export class CommandLineParser extends CommandLineParameterProvider { * the process.argv will be used */ public async executeAsync(args?: string[]): Promise { - if (this._options.enableTabCompletionAction && !this._tabCompleteActionWasAdded) { + if (this.#options.enableTabCompletionAction && !this.#tabCompleteActionWasAdded) { this.addAction(new TabCompleteAction(this.actions, this.parameters)); - this._tabCompleteActionWasAdded = true; + this.#tabCompleteActionWasAdded = true; } try { @@ -201,13 +201,13 @@ export class CommandLineParser extends CommandLineParameterProvider { */ public async executeWithoutErrorHandlingAsync(args?: string[]): Promise { try { - if (this._executed) { + if (this.#executed) { // In the future we could allow the same parser to be invoked multiple times // with different arguments. We'll do that work as soon as someone encounters // a real world need for it. throw new Error('executeAsync() was already called for this parser instance'); } - this._executed = true; + this.#executed = true; this._validateDefinitions(); @@ -225,7 +225,7 @@ export class CommandLineParser extends CommandLineParameterProvider { if (args.length === 0) { // Parsers that use actions should print help when 0 args are provided. Allow // actionless parsers to continue on zero args. - this._argumentParser.printHelp(); + this.#argumentParser.printHelp(); return; } // Alias actions may provide a list of default params to add after the action name. @@ -261,16 +261,16 @@ export class CommandLineParser extends CommandLineParameterProvider { } this._preParse(); - patchFormatUsageForArgumentParser(this._argumentParser); + patchFormatUsageForArgumentParser(this.#argumentParser); for (const action of this.actions) { action._preParse(); patchFormatUsageForArgumentParser(action._getArgumentParser()); } - const data: ICommandLineParserData = this._argumentParser.parseArgs(args); + const data: ICommandLineParserData = this.#argumentParser.parseArgs(args); postParse(); - this._processParsedData(this._options, data); + this._processParsedData(this.#options, data); this.selectedAction = this.tryGetAction(data.action); if (this.actions.length > 0 && !this.selectedAction) { @@ -278,7 +278,7 @@ export class CommandLineParser extends CommandLineParameterProvider { throw new Error(`An action must be specified (${actions.join(', ')})`); } - this.selectedAction?._processParsedData(this._options, data); + this.selectedAction?._processParsedData(this.#options, data); await this.onExecuteAsync(); } catch (err) { if (err instanceof CommandLineParserExitError) { @@ -311,7 +311,7 @@ export class CommandLineParser extends CommandLineParameterProvider { ...state, parentParameterNames: updatedParentParameterNames }; - for (const action of this._actionsByName.values()) { + for (const action of this.#actionsByName.values()) { action._registerDefinedParameters(parentState); } } @@ -328,7 +328,7 @@ export class CommandLineParser extends CommandLineParameterProvider { * @internal */ protected override _getArgumentParser(): argparse.ArgumentParser { - return this._argumentParser; + return this.#argumentParser; } /** diff --git a/libraries/ts-command-line/src/providers/ScopedCommandLineAction.ts b/libraries/ts-command-line/src/providers/ScopedCommandLineAction.ts index a75d582142f..15e6b231e46 100644 --- a/libraries/ts-command-line/src/providers/ScopedCommandLineAction.ts +++ b/libraries/ts-command-line/src/providers/ScopedCommandLineAction.ts @@ -26,11 +26,11 @@ interface IInternalScopedCommandLineParserOptions extends ICommandLineParserOpti * for a ScopedCommandLineAction. */ class InternalScopedCommandLineParser extends CommandLineParser { - private _canExecute: boolean; - private readonly _internalOptions: IInternalScopedCommandLineParserOptions; + #canExecute: boolean; + readonly #internalOptions: IInternalScopedCommandLineParserOptions; public get canExecute(): boolean { - return this._canExecute; + return this.#canExecute; } public constructor(options: IInternalScopedCommandLineParserOptions) { @@ -58,21 +58,21 @@ class InternalScopedCommandLineParser extends CommandLineParser { }; super(scopedCommandLineParserOptions); - this._canExecute = false; - this._internalOptions = options; - this._internalOptions.onDefineScopedParameters(this); + this.#canExecute = false; + this.#internalOptions = options; + this.#internalOptions.onDefineScopedParameters(this); } public _registerDefinedParameters(state: IRegisterDefinedParametersState): void { // Since we are in a separate parser, we need to register the parameters using the state // from the parent parser. - super._registerDefinedParameters(this._internalOptions.registerDefinedParametersState); + super._registerDefinedParameters(this.#internalOptions.registerDefinedParametersState); } protected override async onExecuteAsync(): Promise { // Only set if we made it this far, which may not be the case if an error occurred or // if '--help' was specified. - this._canExecute = true; + this.#canExecute = true; } } @@ -98,11 +98,11 @@ class InternalScopedCommandLineParser extends CommandLineParser { * @public */ export abstract class ScopedCommandLineAction extends CommandLineAction { - private _options: ICommandLineActionOptions; - private _scopingParameters: CommandLineParameter[]; - private _unscopedParserOptions: ICommandLineParserOptions | undefined; - private _scopedCommandLineParser: InternalScopedCommandLineParser | undefined; - private _subparserState: IRegisterDefinedParametersState | undefined; + #options: ICommandLineActionOptions; + #scopingParameters: CommandLineParameter[]; + #unscopedParserOptions: ICommandLineParserOptions | undefined; + #scopedCommandLineParser: InternalScopedCommandLineParser | undefined; + #subparserState: IRegisterDefinedParametersState | undefined; /** * The required group name to apply to all scoping parameters. At least one parameter @@ -113,8 +113,8 @@ export abstract class ScopedCommandLineAction extends CommandLineAction { public constructor(options: ICommandLineActionOptions) { super(options); - this._options = options; - this._scopingParameters = []; + this.#options = options; + this.#scopingParameters = []; // Consume the remainder of the command-line, which will later be passed the scoped parser. // This will also prevent developers from calling this.defineCommandLineRemainder(...) since @@ -130,8 +130,8 @@ export abstract class ScopedCommandLineAction extends CommandLineAction { * {@inheritDoc CommandLineParameterProvider.parameters} */ public get parameters(): ReadonlyArray { - if (this._scopedCommandLineParser) { - return [...super.parameters, ...this._scopedCommandLineParser.parameters]; + if (this.#scopedCommandLineParser) { + return [...super.parameters, ...this.#scopedCommandLineParser.parameters]; } else { return super.parameters; } @@ -149,21 +149,21 @@ export abstract class ScopedCommandLineAction extends CommandLineAction { // This should never happen because the super method should throw if parameters haven't been registered, // but guard against this just in-case. - if (this._subparserState === undefined) { + if (this.#subparserState === undefined) { throw new Error('Parameters have not been registered'); } - this._unscopedParserOptions = parserOptions; + this.#unscopedParserOptions = parserOptions; // Generate the scoped parser using the parent parser information. We can only create this after we // have parsed the data, since the parameter values are used during construction. - this._scopedCommandLineParser = new InternalScopedCommandLineParser({ + this.#scopedCommandLineParser = new InternalScopedCommandLineParser({ ...parserOptions, - actionOptions: this._options, + actionOptions: this.#options, aliasAction: data.aliasAction, aliasDocumentation: data.aliasDocumentation, unscopedActionParameters: this.parameters as CommandLineParameter[], - registerDefinedParametersState: this._subparserState, + registerDefinedParametersState: this.#subparserState, onDefineScopedParameters: this.onDefineScopedParameters.bind(this) }); } @@ -173,7 +173,7 @@ export abstract class ScopedCommandLineAction extends CommandLineAction { * @internal */ public override async _executeAsync(): Promise { - if (!this._unscopedParserOptions || !this._scopedCommandLineParser) { + if (!this.#unscopedParserOptions || !this.#scopedCommandLineParser) { throw new Error('The CommandLineAction parameters must be processed before execution.'); } if (!this.remainder) { @@ -189,7 +189,7 @@ export abstract class ScopedCommandLineAction extends CommandLineAction { // argparse sets exit code 2 for invalid arguments 2, // model the message off of the built-in "unrecognized arguments" message - `${this.renderUsageText()}\n${this._unscopedParserOptions.toolFilename} ${this.actionName}: ` + + `${this.renderUsageText()}\n${this.#unscopedParserOptions.toolFilename} ${this.actionName}: ` + `error: Unrecognized arguments: ${this.remainder.values[0]}.\n` ); } @@ -199,11 +199,11 @@ export abstract class ScopedCommandLineAction extends CommandLineAction { } // Call the scoped parser using only the scoped args to handle parsing - await this._scopedCommandLineParser.executeWithoutErrorHandlingAsync(scopedArgs); + await this.#scopedCommandLineParser.executeWithoutErrorHandlingAsync(scopedArgs); // Only call execute if the parser reached the execute stage. This may not be true if // the parser exited early due to a specified '--help' parameter. - if (this._scopedCommandLineParser.canExecute) { + if (this.#scopedCommandLineParser.canExecute) { await super._executeAsync(); } @@ -212,7 +212,7 @@ export abstract class ScopedCommandLineAction extends CommandLineAction { /** @internal */ public _registerDefinedParameters(state: IRegisterDefinedParametersState): void { - if (!this._scopingParameters.length) { + if (!this.#scopingParameters.length) { throw new Error( 'No scoping parameters defined. At least one scoping parameter must be defined. ' + 'Scoping parameters are defined by setting the parameterGroupName to ' + @@ -228,7 +228,7 @@ export abstract class ScopedCommandLineAction extends CommandLineAction { ...this._registeredParameterParserKeysByName.keys() ]); - this._subparserState = { + this.#subparserState = { ...state, parentParameterNames: updatedParentParameterNames }; @@ -239,17 +239,17 @@ export abstract class ScopedCommandLineAction extends CommandLineAction { * @internal */ protected _getScopedCommandLineParser(): CommandLineParser { - if (!this._scopedCommandLineParser) { + if (!this.#scopedCommandLineParser) { throw new Error('The scoped CommandLineParser is only populated after the action is executed.'); } - return this._scopedCommandLineParser; + return this.#scopedCommandLineParser; } /** @internal */ protected _defineParameter(parameter: CommandLineParameter): void { super._defineParameter(parameter); if (parameter.parameterGroup === ScopedCommandLineAction.ScopingParameterGroup) { - this._scopingParameters.push(parameter); + this.#scopingParameters.push(parameter); } } diff --git a/libraries/ts-command-line/src/providers/TabCompletionAction.ts b/libraries/ts-command-line/src/providers/TabCompletionAction.ts index 9ec089eb14b..8461fcf7d45 100644 --- a/libraries/ts-command-line/src/providers/TabCompletionAction.ts +++ b/libraries/ts-command-line/src/providers/TabCompletionAction.ts @@ -19,10 +19,10 @@ const DEFAULT_WORD_TO_AUTOCOMPLETE: string = ''; const DEFAULT_POSITION: number = 0; export class TabCompleteAction extends CommandLineAction { - private readonly _wordToCompleteParameter: IRequiredCommandLineStringParameter; - private readonly _positionParameter: IRequiredCommandLineIntegerParameter; - private readonly _actions: Map>; - private readonly _globalParameters: Map; + readonly #wordToCompleteParameter: IRequiredCommandLineStringParameter; + readonly #positionParameter: IRequiredCommandLineIntegerParameter; + readonly #actions: Map>; + readonly #globalParameters: Map; public constructor( actions: ReadonlyArray, @@ -34,7 +34,7 @@ export class TabCompleteAction extends CommandLineAction { documentation: 'Provides tab completion.' }); - this._actions = new Map(); + this.#actions = new Map(); for (const action of actions) { const parameterNameToParameterInfoMap: Map = new Map(); for (const parameter of action.parameters) { @@ -43,25 +43,25 @@ export class TabCompleteAction extends CommandLineAction { parameterNameToParameterInfoMap.set(parameter.shortName, parameter as CommandLineParameter); } } - this._actions.set(action.actionName, parameterNameToParameterInfoMap); + this.#actions.set(action.actionName, parameterNameToParameterInfoMap); } - this._globalParameters = new Map(); + this.#globalParameters = new Map(); for (const parameter of globalParameters) { - this._globalParameters.set(parameter.longName, parameter as CommandLineParameter); + this.#globalParameters.set(parameter.longName, parameter as CommandLineParameter); if (parameter.shortName) { - this._globalParameters.set(parameter.shortName, parameter as CommandLineParameter); + this.#globalParameters.set(parameter.shortName, parameter as CommandLineParameter); } } - this._wordToCompleteParameter = this.defineStringParameter({ + this.#wordToCompleteParameter = this.defineStringParameter({ parameterLongName: '--word', argumentName: 'WORD', description: `The word to complete.`, defaultValue: DEFAULT_WORD_TO_AUTOCOMPLETE }); - this._positionParameter = this.defineIntegerParameter({ + this.#positionParameter = this.defineIntegerParameter({ parameterLongName: '--position', argumentName: 'INDEX', description: `The position in the word to be completed.`, @@ -70,8 +70,8 @@ export class TabCompleteAction extends CommandLineAction { } protected override async onExecuteAsync(): Promise { - const commandLine: string = this._wordToCompleteParameter.value; - const caretPosition: number = this._positionParameter.value || commandLine.length; + const commandLine: string = this.#wordToCompleteParameter.value; + const caretPosition: number = this.#positionParameter.value || commandLine.length; for await (const value of this.getCompletionsAsync(commandLine, caretPosition)) { // eslint-disable-next-line no-console @@ -83,7 +83,7 @@ export class TabCompleteAction extends CommandLineAction { commandLine: string, caretPosition: number = commandLine.length ): AsyncIterable { - const actions: Map> = this._actions; + const actions: Map> = this.#actions; if (!commandLine || !caretPosition) { yield* this._getAllActions(); @@ -164,8 +164,8 @@ export class TabCompleteAction extends CommandLineAction { } private *_getAllActions(): IterableIterator { - yield* this._actions.keys(); - yield* this._globalParameters.keys(); + yield* this.#actions.keys(); + yield* this.#globalParameters.keys(); } public tokenizeCommandLine(commandLine: string): string[] { @@ -199,7 +199,7 @@ export class TabCompleteAction extends CommandLineAction { } private _getGlobalParameterOffset(tokens: string[]): number { - const globalParameters: Map = this._globalParameters; + const globalParameters: Map = this.#globalParameters; let count: number = 0; outer: for (let i: number = 1; i < tokens.length; i++) { diff --git a/libraries/ts-command-line/src/test/AliasedCommandLineAction.test.ts b/libraries/ts-command-line/src/test/AliasedCommandLineAction.test.ts index 1534f638a9e..19ed2da92b9 100644 --- a/libraries/ts-command-line/src/test/AliasedCommandLineAction.test.ts +++ b/libraries/ts-command-line/src/test/AliasedCommandLineAction.test.ts @@ -25,7 +25,7 @@ class TestAliasAction extends AliasCommandLineAction { class TestAction extends CommandLineAction { public done: boolean = false; - private _flag!: CommandLineFlagParameter; + #flag!: CommandLineFlagParameter; public constructor() { super({ @@ -34,14 +34,14 @@ class TestAction extends CommandLineAction { documentation: 'a longer description' }); - this._flag = this.defineFlagParameter({ + this.#flag = this.defineFlagParameter({ parameterLongName: '--flag', description: 'The flag' }); } protected override async onExecuteAsync(): Promise { - expect(this._flag.value).toEqual(true); + expect(this.#flag.value).toEqual(true); this.done = true; } } @@ -49,9 +49,9 @@ class TestAction extends CommandLineAction { class TestScopedAction extends ScopedCommandLineAction { public done: boolean = false; public scopedValue: string | undefined; - private readonly _verboseArg: CommandLineFlagParameter; - private readonly _scopeArg: CommandLineStringParameter; - private _scopedArg: CommandLineStringParameter | undefined; + readonly #verboseArg: CommandLineFlagParameter; + readonly #scopeArg: CommandLineStringParameter; + #scopedArg: CommandLineStringParameter | undefined; public constructor() { super({ @@ -60,12 +60,12 @@ class TestScopedAction extends ScopedCommandLineAction { documentation: 'a longer description' }); - this._verboseArg = this.defineFlagParameter({ + this.#verboseArg = this.defineFlagParameter({ parameterLongName: '--verbose', description: 'A flag parameter.' }); - this._scopeArg = this.defineStringParameter({ + this.#scopeArg = this.defineStringParameter({ parameterLongName: '--scope', parameterGroup: ScopedCommandLineAction.ScopingParameterGroup, argumentName: 'SCOPE', @@ -74,17 +74,17 @@ class TestScopedAction extends ScopedCommandLineAction { } protected override async onExecuteAsync(): Promise { - if (this._scopedArg) { - expect(this._scopedArg.longName).toBe(`--scoped-${this._scopeArg.value}`); - this.scopedValue = this._scopedArg.value; + if (this.#scopedArg) { + expect(this.#scopedArg.longName).toBe(`--scoped-${this.#scopeArg.value}`); + this.scopedValue = this.#scopedArg.value; } this.done = true; } protected onDefineScopedParameters(scopedParameterProvider: CommandLineParameterProvider): void { - if (this._scopeArg.value) { - this._scopedArg = scopedParameterProvider.defineStringParameter({ - parameterLongName: `--scoped-${this._scopeArg.value}`, + if (this.#scopeArg.value) { + this.#scopedArg = scopedParameterProvider.defineStringParameter({ + parameterLongName: `--scoped-${this.#scopeArg.value}`, argumentName: 'SCOPED', description: 'The scoped argument.' }); diff --git a/libraries/ts-command-line/src/test/AmbiguousCommandLineParser.test.ts b/libraries/ts-command-line/src/test/AmbiguousCommandLineParser.test.ts index a487e9ad848..c6445201fc1 100644 --- a/libraries/ts-command-line/src/test/AmbiguousCommandLineParser.test.ts +++ b/libraries/ts-command-line/src/test/AmbiguousCommandLineParser.test.ts @@ -25,11 +25,11 @@ class GenericCommandLine extends CommandLineParser { class AmbiguousAction extends CommandLineAction { public done: boolean = false; - private _short1Arg: CommandLineStringParameter; - private _shortArg2: CommandLineStringParameter; - private _scope1Arg: CommandLineStringParameter; - private _scope2Arg: CommandLineStringParameter; - private _nonConflictingArg: CommandLineStringParameter; + #short1Arg: CommandLineStringParameter; + #shortArg2: CommandLineStringParameter; + #scope1Arg: CommandLineStringParameter; + #scope2Arg: CommandLineStringParameter; + #nonConflictingArg: CommandLineStringParameter; public constructor() { super({ @@ -38,31 +38,31 @@ class AmbiguousAction extends CommandLineAction { documentation: 'a longer description' }); - this._short1Arg = this.defineStringParameter({ + this.#short1Arg = this.defineStringParameter({ parameterLongName: '--short1', parameterShortName: '-s', argumentName: 'ARG', description: 'The argument' }); - this._shortArg2 = this.defineStringParameter({ + this.#shortArg2 = this.defineStringParameter({ parameterLongName: '--short2', parameterShortName: '-s', argumentName: 'ARG', description: 'The argument' }); - this._scope1Arg = this.defineStringParameter({ + this.#scope1Arg = this.defineStringParameter({ parameterLongName: '--arg', parameterScope: 'scope1', argumentName: 'ARG', description: 'The argument' }); - this._scope2Arg = this.defineStringParameter({ + this.#scope2Arg = this.defineStringParameter({ parameterLongName: '--arg', parameterScope: 'scope2', argumentName: 'ARG', description: 'The argument' }); - this._nonConflictingArg = this.defineStringParameter({ + this.#nonConflictingArg = this.defineStringParameter({ parameterLongName: '--non-conflicting-arg', parameterScope: 'scope', argumentName: 'ARG', @@ -71,11 +71,11 @@ class AmbiguousAction extends CommandLineAction { } protected override async onExecuteAsync(): Promise { - expect(this._short1Arg.value).toEqual('short1value'); - expect(this._shortArg2.value).toEqual('short2value'); - expect(this._scope1Arg.value).toEqual('scope1value'); - expect(this._scope2Arg.value).toEqual('scope2value'); - expect(this._nonConflictingArg.value).toEqual('nonconflictingvalue'); + expect(this.#short1Arg.value).toEqual('short1value'); + expect(this.#shortArg2.value).toEqual('short2value'); + expect(this.#scope1Arg.value).toEqual('scope1value'); + expect(this.#scope2Arg.value).toEqual('scope2value'); + expect(this.#nonConflictingArg.value).toEqual('nonconflictingvalue'); this.done = true; } } @@ -119,12 +119,12 @@ class AmbiguousScopedAction extends ScopedCommandLineAction { public scope1Value: string | undefined; public scope2Value: string | undefined; public nonConflictingValue: string | undefined; - private _scopingArg: CommandLineFlagParameter | undefined; - private _short1Arg: CommandLineStringParameter | undefined; - private _short2Arg: CommandLineStringParameter | undefined; - private _scope1Arg: CommandLineStringParameter | undefined; - private _scope2Arg: CommandLineStringParameter | undefined; - private _nonConflictingArg: CommandLineStringParameter | undefined; + #scopingArg: CommandLineFlagParameter | undefined; + #short1Arg: CommandLineStringParameter | undefined; + #short2Arg: CommandLineStringParameter | undefined; + #scope1Arg: CommandLineStringParameter | undefined; + #scope2Arg: CommandLineStringParameter | undefined; + #nonConflictingArg: CommandLineStringParameter | undefined; public constructor() { super({ @@ -134,7 +134,7 @@ class AmbiguousScopedAction extends ScopedCommandLineAction { }); // At least one scoping parameter is required to be defined on a scoped action - this._scopingArg = this.defineFlagParameter({ + this.#scopingArg = this.defineFlagParameter({ parameterLongName: '--scoping', description: 'The scoping parameter', parameterGroup: SCOPING_PARAMETER_GROUP @@ -142,53 +142,53 @@ class AmbiguousScopedAction extends ScopedCommandLineAction { } protected override async onExecuteAsync(): Promise { - expect(this._scopingArg?.value).toEqual(true); - if (this._short1Arg?.value) { - this.short1Value = this._short1Arg.value; + expect(this.#scopingArg?.value).toEqual(true); + if (this.#short1Arg?.value) { + this.short1Value = this.#short1Arg.value; } - if (this._short2Arg?.value) { - this.short2Value = this._short2Arg.value; + if (this.#short2Arg?.value) { + this.short2Value = this.#short2Arg.value; } - if (this._scope1Arg?.value) { - this.scope1Value = this._scope1Arg.value; + if (this.#scope1Arg?.value) { + this.scope1Value = this.#scope1Arg.value; } - if (this._scope2Arg?.value) { - this.scope2Value = this._scope2Arg.value; + if (this.#scope2Arg?.value) { + this.scope2Value = this.#scope2Arg.value; } - if (this._nonConflictingArg?.value) { - this.nonConflictingValue = this._nonConflictingArg.value; + if (this.#nonConflictingArg?.value) { + this.nonConflictingValue = this.#nonConflictingArg.value; } this.done = true; } protected onDefineScopedParameters(scopedParameterProvider: CommandLineParameterProvider): void { - this._short1Arg = scopedParameterProvider.defineStringParameter({ + this.#short1Arg = scopedParameterProvider.defineStringParameter({ parameterLongName: '--short1', parameterShortName: '-s', argumentName: 'ARG', description: 'The argument' }); - this._short2Arg = scopedParameterProvider.defineStringParameter({ + this.#short2Arg = scopedParameterProvider.defineStringParameter({ parameterLongName: '--short2', parameterShortName: '-s', argumentName: 'ARG', description: 'The argument' }); - this._scope1Arg = scopedParameterProvider.defineStringParameter({ + this.#scope1Arg = scopedParameterProvider.defineStringParameter({ parameterLongName: '--arg', parameterShortName: '-a', parameterScope: 'scope1', argumentName: 'ARG', description: 'The argument' }); - this._scope2Arg = scopedParameterProvider.defineStringParameter({ + this.#scope2Arg = scopedParameterProvider.defineStringParameter({ parameterLongName: '--arg', parameterShortName: '-a', parameterScope: 'scope2', argumentName: 'ARG', description: 'The argument' }); - this._nonConflictingArg = scopedParameterProvider.defineStringParameter({ + this.#nonConflictingArg = scopedParameterProvider.defineStringParameter({ parameterLongName: '--non-conflicting-arg', parameterShortName: '-a', parameterScope: 'scope', @@ -208,8 +208,8 @@ class AbbreviationScopedAction extends ScopedCommandLineAction { public unscopedAbbreviationFlag: CommandLineFlagParameter | undefined; public scopedAbbreviationFlag: CommandLineFlagParameter | undefined; - private readonly _scopingArg: CommandLineFlagParameter; - private _includeScopedAbbreviationFlag: boolean; + readonly #scopingArg: CommandLineFlagParameter; + #includeScopedAbbreviationFlag: boolean; public constructor(options: IAbbreviationScopedActionOptions) { super({ @@ -225,10 +225,10 @@ class AbbreviationScopedAction extends ScopedCommandLineAction { }); } - this._includeScopedAbbreviationFlag = !!options?.includeScopedAbbreviationFlag; + this.#includeScopedAbbreviationFlag = !!options?.includeScopedAbbreviationFlag; // At least one scoping parameter is required to be defined on a scoped action - this._scopingArg = this.defineFlagParameter({ + this.#scopingArg = this.defineFlagParameter({ parameterLongName: '--scoping', description: 'The scoping parameter', parameterGroup: SCOPING_PARAMETER_GROUP @@ -236,12 +236,12 @@ class AbbreviationScopedAction extends ScopedCommandLineAction { } protected override async onExecuteAsync(): Promise { - expect(this._scopingArg.value).toEqual(true); + expect(this.#scopingArg.value).toEqual(true); this.done = true; } protected onDefineScopedParameters(scopedParameterProvider: CommandLineParameterProvider): void { - if (this._includeScopedAbbreviationFlag) { + if (this.#includeScopedAbbreviationFlag) { this.scopedAbbreviationFlag = scopedParameterProvider.defineFlagParameter({ parameterLongName: '--abbreviation-flag', description: 'A flag used to test abbreviation logic' diff --git a/libraries/ts-command-line/src/test/CommandLineParser.test.ts b/libraries/ts-command-line/src/test/CommandLineParser.test.ts index 4fffb15bafa..ecb74195c19 100644 --- a/libraries/ts-command-line/src/test/CommandLineParser.test.ts +++ b/libraries/ts-command-line/src/test/CommandLineParser.test.ts @@ -8,7 +8,7 @@ import { ensureHelpTextMatchesSnapshot } from './helpTestUtilities'; class TestAction extends CommandLineAction { public done: boolean = false; - private _flag: CommandLineFlagParameter; + #flag: CommandLineFlagParameter; public constructor() { super({ @@ -17,14 +17,14 @@ class TestAction extends CommandLineAction { documentation: 'a longer description with sprintf-style escape characters, 100%' }); - this._flag = this.defineFlagParameter({ + this.#flag = this.defineFlagParameter({ parameterLongName: '--flag', description: 'The flag' }); } protected override async onExecuteAsync(): Promise { - expect(this._flag.value).toEqual(true); + expect(this.#flag.value).toEqual(true); this.done = true; } } diff --git a/libraries/ts-command-line/src/test/ConflictingCommandLineParser.test.ts b/libraries/ts-command-line/src/test/ConflictingCommandLineParser.test.ts index 9f33a9c6278..8022b4b5546 100644 --- a/libraries/ts-command-line/src/test/ConflictingCommandLineParser.test.ts +++ b/libraries/ts-command-line/src/test/ConflictingCommandLineParser.test.ts @@ -20,9 +20,9 @@ class GenericCommandLine extends CommandLineParser { class TestAction extends CommandLineAction { public done: boolean = false; - private _scope1Arg: CommandLineStringParameter; - private _scope2Arg: CommandLineStringParameter; - private _nonConflictingArg: CommandLineStringParameter; + #scope1Arg: CommandLineStringParameter; + #scope2Arg: CommandLineStringParameter; + #nonConflictingArg: CommandLineStringParameter; public constructor() { super({ @@ -32,14 +32,14 @@ class TestAction extends CommandLineAction { }); // Used to validate that conflicting parameters with different scopes return different values - this._scope1Arg = this.defineStringParameter({ + this.#scope1Arg = this.defineStringParameter({ parameterLongName: '--arg', parameterScope: 'scope1', argumentName: 'ARG', description: 'The argument' }); // Used to validate that conflicting parameters with different scopes return different values - this._scope2Arg = this.defineStringParameter({ + this.#scope2Arg = this.defineStringParameter({ parameterLongName: '--arg', parameterScope: 'scope2', argumentName: 'ARG', @@ -47,7 +47,7 @@ class TestAction extends CommandLineAction { }); // Used to validate that non-conflicting args can be reference by both the unscoped and the // scoped parameter names - this._nonConflictingArg = this.defineStringParameter({ + this.#nonConflictingArg = this.defineStringParameter({ parameterLongName: '--non-conflicting-arg', parameterScope: 'scope3', argumentName: 'ARG', @@ -56,9 +56,9 @@ class TestAction extends CommandLineAction { } protected override async onExecuteAsync(): Promise { - expect(this._scope1Arg.value).toEqual('scope1value'); - expect(this._scope2Arg.value).toEqual('scope2value'); - expect(this._nonConflictingArg.value).toEqual('nonconflictingvalue'); + expect(this.#scope1Arg.value).toEqual('scope1value'); + expect(this.#scope2Arg.value).toEqual('scope2value'); + expect(this.#nonConflictingArg.value).toEqual('nonconflictingvalue'); this.done = true; } } diff --git a/libraries/ts-command-line/src/test/ScopedCommandLineAction.test.ts b/libraries/ts-command-line/src/test/ScopedCommandLineAction.test.ts index a535c1e77cc..565435e6846 100644 --- a/libraries/ts-command-line/src/test/ScopedCommandLineAction.test.ts +++ b/libraries/ts-command-line/src/test/ScopedCommandLineAction.test.ts @@ -13,9 +13,9 @@ import { ensureHelpTextMatchesSnapshot } from './helpTestUtilities'; class TestScopedAction extends ScopedCommandLineAction { public done: boolean = false; public scopedValue: string | undefined; - private _verboseArg: CommandLineFlagParameter; - private _scopeArg: CommandLineStringParameter; - private _scopedArg: CommandLineStringParameter | undefined; + #verboseArg: CommandLineFlagParameter; + #scopeArg: CommandLineStringParameter; + #scopedArg: CommandLineStringParameter | undefined; public constructor() { super({ @@ -24,12 +24,12 @@ class TestScopedAction extends ScopedCommandLineAction { documentation: 'a longer description' }); - this._verboseArg = this.defineFlagParameter({ + this.#verboseArg = this.defineFlagParameter({ parameterLongName: '--verbose', description: 'A flag parameter.' }); - this._scopeArg = this.defineStringParameter({ + this.#scopeArg = this.defineStringParameter({ parameterLongName: '--scope', parameterGroup: ScopedCommandLineAction.ScopingParameterGroup, argumentName: 'SCOPE', @@ -38,17 +38,17 @@ class TestScopedAction extends ScopedCommandLineAction { } protected override async onExecuteAsync(): Promise { - if (this._scopedArg) { - expect(this._scopedArg.longName).toBe(`--scoped-${this._scopeArg.value}`); - this.scopedValue = this._scopedArg.value; + if (this.#scopedArg) { + expect(this.#scopedArg.longName).toBe(`--scoped-${this.#scopeArg.value}`); + this.scopedValue = this.#scopedArg.value; } this.done = true; } protected onDefineScopedParameters(scopedParameterProvider: CommandLineParameterProvider): void { - if (this._scopeArg.value) { - this._scopedArg = scopedParameterProvider.defineStringParameter({ - parameterLongName: `--scoped-${this._scopeArg.value}`, + if (this.#scopeArg.value) { + this.#scopedArg = scopedParameterProvider.defineStringParameter({ + parameterLongName: `--scoped-${this.#scopeArg.value}`, argumentName: 'SCOPED', description: 'The scoped argument.' }); diff --git a/libraries/ts-command-line/src/test/test-cli/PushAction.ts b/libraries/ts-command-line/src/test/test-cli/PushAction.ts index 7d10156b368..1106daeeaaf 100644 --- a/libraries/ts-command-line/src/test/test-cli/PushAction.ts +++ b/libraries/ts-command-line/src/test/test-cli/PushAction.ts @@ -12,8 +12,8 @@ import { BusinessLogic } from './BusinessLogic'; type Protocol = 'ftp' | 'webdav' | 'scp'; export class PushAction extends CommandLineAction { - private readonly _force: CommandLineFlagParameter; - private readonly _protocol: IRequiredCommandLineChoiceParameter; + readonly #force: CommandLineFlagParameter; + readonly #protocol: IRequiredCommandLineChoiceParameter; public constructor() { super({ @@ -22,13 +22,13 @@ export class PushAction extends CommandLineAction { documentation: 'Here we provide a longer description of how our action works.' }); - this._force = this.defineFlagParameter({ + this.#force = this.defineFlagParameter({ parameterLongName: '--force', parameterShortName: '-f', description: 'Push and overwrite any existing state' }); - this._protocol = this.defineChoiceParameter({ + this.#protocol = this.defineChoiceParameter({ parameterLongName: '--protocol', description: 'Specify the protocol to use', alternatives: ['ftp', 'webdav', 'scp'], @@ -39,6 +39,6 @@ export class PushAction extends CommandLineAction { protected onExecuteAsync(): Promise { // abstract - return BusinessLogic.doTheWorkAsync(this._force.value, this._protocol.value); + return BusinessLogic.doTheWorkAsync(this.#force.value, this.#protocol.value); } } diff --git a/libraries/ts-command-line/src/test/test-cli/RunAction.ts b/libraries/ts-command-line/src/test/test-cli/RunAction.ts index 00a6e22c4ff..6139218894e 100644 --- a/libraries/ts-command-line/src/test/test-cli/RunAction.ts +++ b/libraries/ts-command-line/src/test/test-cli/RunAction.ts @@ -4,7 +4,7 @@ import { CommandLineAction, type CommandLineStringParameter } from '../../index'; export class RunAction extends CommandLineAction { - private readonly _title: CommandLineStringParameter; + readonly #title: CommandLineStringParameter; public constructor() { super({ @@ -13,7 +13,7 @@ export class RunAction extends CommandLineAction { documentation: 'This demonstrates how to use the defineCommandLineRemainder() API.' }); - this._title = this.defineStringParameter({ + this.#title = this.defineStringParameter({ parameterLongName: '--title', argumentName: 'TITLE', environmentVariable: 'WIDGET_TITLE', @@ -28,7 +28,7 @@ export class RunAction extends CommandLineAction { protected override async onExecuteAsync(): Promise { // abstract // eslint-disable-next-line no-console - console.log(`Console Title: ${this._title.value || '(none)'}`); + console.log(`Console Title: ${this.#title.value || '(none)'}`); // eslint-disable-next-line no-console console.log('Arguments to be executed: ' + JSON.stringify(this.remainder!.values)); } diff --git a/libraries/ts-command-line/src/test/test-cli/WidgetCommandLine.ts b/libraries/ts-command-line/src/test/test-cli/WidgetCommandLine.ts index 192814b952f..fd7ce0b5d7e 100644 --- a/libraries/ts-command-line/src/test/test-cli/WidgetCommandLine.ts +++ b/libraries/ts-command-line/src/test/test-cli/WidgetCommandLine.ts @@ -8,7 +8,7 @@ import { RunAction } from './RunAction'; import { BusinessLogic } from './BusinessLogic'; export class WidgetCommandLine extends CommandLineParser { - private readonly _verbose: CommandLineFlagParameter; + readonly #verbose: CommandLineFlagParameter; public constructor() { super({ @@ -19,7 +19,7 @@ export class WidgetCommandLine extends CommandLineParser { this.addAction(new PushAction()); this.addAction(new RunAction()); - this._verbose = this.defineFlagParameter({ + this.#verbose = this.defineFlagParameter({ parameterLongName: '--verbose', parameterShortName: '-v', description: 'Show extra logging detail' @@ -27,7 +27,7 @@ export class WidgetCommandLine extends CommandLineParser { } protected override async onExecuteAsync(): Promise { - BusinessLogic.configureLogger(this._verbose.value); + BusinessLogic.configureLogger(this.#verbose.value); return await super.onExecuteAsync(); } } diff --git a/libraries/typings-generator/src/TypingsGenerator.ts b/libraries/typings-generator/src/TypingsGenerator.ts index 7d55c0ce88d..cdc962e4ce2 100644 --- a/libraries/typings-generator/src/TypingsGenerator.ts +++ b/libraries/typings-generator/src/TypingsGenerator.ts @@ -104,13 +104,13 @@ export interface ITypingsGeneratorOptionsWithCustomReadFile< */ export class TypingsGenerator { // Map of resolved consumer file path -> Set - private readonly _dependenciesOfFile: Map>; + readonly #dependenciesOfFile: Map>; // Map of resolved dependency file path -> Set - private readonly _consumersOfFile: Map>; + readonly #consumersOfFile: Map>; // Map of resolved file path -> relative file path - private readonly _relativePaths: Map; + readonly #relativePaths: Map; protected readonly _options: ITypingsGeneratorOptionsWithCustomReadFile< string | IGeneratedTypings | undefined, @@ -186,9 +186,9 @@ export class TypingsGenerator { this._options.fileExtensions = this._normalizeFileExtensions(fileExtensions); - this._dependenciesOfFile = new Map(); - this._consumersOfFile = new Map(); - this._relativePaths = new Map(); + this.#dependenciesOfFile = new Map(); + this.#consumersOfFile = new Map(); + this.#relativePaths = new Map(); this.inputFileGlob = `**/*+(${this._options.fileExtensions.join('|')})`; } @@ -288,17 +288,17 @@ export class TypingsGenerator { // Need to normalize slashes in the dependency path const dependency: string = path.resolve(this._options.srcFolder, rawDependency); - let dependencies: Set | undefined = this._dependenciesOfFile.get(consumer); + let dependencies: Set | undefined = this.#dependenciesOfFile.get(consumer); if (!dependencies) { dependencies = new Set(); - this._dependenciesOfFile.set(consumer, dependencies); + this.#dependenciesOfFile.set(consumer, dependencies); } dependencies.add(dependency); - let consumers: Set | undefined = this._consumersOfFile.get(dependency); + let consumers: Set | undefined = this.#consumersOfFile.get(dependency); if (!consumers) { consumers = new Set(); - this._consumersOfFile.set(dependency, consumers); + this.#consumersOfFile.set(dependency, consumers); } consumers.add(consumer); } @@ -330,13 +330,13 @@ export class TypingsGenerator { const relativePath: string = Path.convertToSlashes(rawPath); const resolvedPath: string = path.resolve(this._options.srcFolder, rawPath); - this._relativePaths.set(resolvedPath, relativePath); + this.#relativePaths.set(resolvedPath, relativePath); toProcess.add(resolvedPath); } // Expand out all registered consumers, according to the current dependency graph for (const file of toProcess) { - const consumers: Set | undefined = this._consumersOfFile.get(file); + const consumers: Set | undefined = this.#consumersOfFile.get(file); if (consumers) { for (const consumer of consumers) { toProcess.add(consumer); @@ -348,7 +348,7 @@ export class TypingsGenerator { await Async.forEachAsync( toProcess, async (resolvedPath: string) => { - const relativePath: string | undefined = this._relativePaths.get(resolvedPath); + const relativePath: string | undefined = this.#relativePaths.get(resolvedPath); if (!relativePath) { throw new Error(`Missing relative path for file ${resolvedPath}`); } @@ -427,10 +427,10 @@ export class TypingsGenerator { * Removes the consumer from all extant dependencies */ private _clearDependencies(consumer: string): void { - const dependencies: Set | undefined = this._dependenciesOfFile.get(consumer); + const dependencies: Set | undefined = this.#dependenciesOfFile.get(consumer); if (dependencies) { for (const dependency of dependencies) { - this._consumersOfFile.get(dependency)!.delete(consumer); + this.#consumersOfFile.get(dependency)!.delete(consumer); } dependencies.clear(); } diff --git a/libraries/worker-pool/src/WorkerPool.ts b/libraries/worker-pool/src/WorkerPool.ts index d47274673fd..09f04ec3a6c 100644 --- a/libraries/worker-pool/src/WorkerPool.ts +++ b/libraries/worker-pool/src/WorkerPool.ts @@ -54,18 +54,18 @@ export class WorkerPool { public id: string; public maxWorkers: number; - private readonly _alive: Worker[]; - private _error: Error | undefined; - private _finishing: boolean; - private readonly _idle: Worker[]; - private _nextId: number; - private readonly _onComplete: [() => void, (error: Error) => void][]; - private readonly _onWorkerDestroyed: (() => void) | undefined; - private readonly _pending: [(worker: Worker) => void, (error: Error) => void][]; - private readonly _prepare: ((worker: Worker) => void) | undefined; - private readonly _workerData: unknown; - private readonly _workerScript: string; - private readonly _workerResourceLimits: ResourceLimits | undefined; + readonly #alive: Worker[]; + #error: Error | undefined; + #finishing: boolean; + readonly #idle: Worker[]; + #nextId: number; + readonly #onComplete: [() => void, (error: Error) => void][]; + readonly #onWorkerDestroyed: (() => void) | undefined; + readonly #pending: [(worker: Worker) => void, (error: Error) => void][]; + readonly #prepare: ((worker: Worker) => void) | undefined; + readonly #workerData: unknown; + readonly #workerScript: string; + readonly #workerResourceLimits: ResourceLimits | undefined; public constructor(options: IWorkerPoolOptions) { const { @@ -80,39 +80,39 @@ export class WorkerPool { this.id = id; this.maxWorkers = maxWorkers; - this._alive = []; - this._error = undefined; - this._finishing = false; - this._idle = []; - this._nextId = 0; - this._onComplete = []; - this._onWorkerDestroyed = onWorkerDestroyed; - this._pending = []; - this._prepare = prepareWorker; - this._workerData = workerData; - this._workerScript = workerScriptPath; - this._workerResourceLimits = workerResourceLimits; + this.#alive = []; + this.#error = undefined; + this.#finishing = false; + this.#idle = []; + this.#nextId = 0; + this.#onComplete = []; + this.#onWorkerDestroyed = onWorkerDestroyed; + this.#pending = []; + this.#prepare = prepareWorker; + this.#workerData = workerData; + this.#workerScript = workerScriptPath; + this.#workerResourceLimits = workerResourceLimits; } /** * Gets the count of active workers. */ public getActiveCount(): number { - return this._alive.length - this._idle.length; + return this.#alive.length - this.#idle.length; } /** * Gets the count of idle workers. */ public getIdleCount(): number { - return this._idle.length; + return this.#idle.length; } /** * Gets the count of live workers. */ public getLiveCount(): number { - return this._alive.length; + return this.#alive.length; } /** @@ -120,32 +120,32 @@ export class WorkerPool { * Returns a promise that will be fulfilled if all workers finish successfully, or reject with the first error. */ public async finishAsync(): Promise { - this._finishing = true; + this.#finishing = true; - if (this._error) { - throw this._error; + if (this.#error) { + throw this.#error; } - if (!this._alive.length) { + if (!this.#alive.length) { // The pool has no live workers, this is a no-op return; } // Clean up all idle workers - for (const worker of this._idle.splice(0)) { + for (const worker of this.#idle.splice(0)) { worker.postMessage(false); } // There are still active workers, wait for them to clean up. - await new Promise((resolve, reject) => this._onComplete.push([resolve, reject])); + await new Promise((resolve, reject) => this.#onComplete.push([resolve, reject])); } /** * Resets the pool and allows more work */ public reset(): void { - this._finishing = false; - this._error = undefined; + this.#finishing = false; + this.#error = undefined; } /** @@ -153,23 +153,23 @@ export class WorkerPool { * @param worker - The worker to free */ public checkinWorker(worker: Worker): void { - if (this._error) { + if (this.#error) { // Shut down the worker (failure) worker.postMessage(false); return; } - const next: [(worker: Worker) => void, unknown] | undefined = this._pending.shift(); + const next: [(worker: Worker) => void, unknown] | undefined = this.#pending.shift(); if (next) { // Perform the next unit of work; next[0](worker); - } else if (this._finishing) { + } else if (this.#finishing) { // Shut down the worker (success) worker.postMessage(false); } else { // No pending work, idle the workers - this._idle.push(worker); + this.#idle.push(worker); } } @@ -178,11 +178,11 @@ export class WorkerPool { * @param allowCreate - If creating new workers is allowed (subject to maxSize) */ public async checkoutWorkerAsync(allowCreate: boolean): Promise { - if (this._error) { - throw this._error; + if (this.#error) { + throw this.#error; } - let worker: Worker | undefined = this._idle.shift(); + let worker: Worker | undefined = this.#idle.shift(); if (!worker && allowCreate) { worker = this._createWorker(); } @@ -192,7 +192,7 @@ export class WorkerPool { } return await new Promise((resolve: (worker: Worker) => void, reject: (error: Error) => void) => { - this._pending.push([resolve, reject]); + this.#pending.push([resolve, reject]); }); } @@ -200,22 +200,22 @@ export class WorkerPool { * Creates a new worker if allowed by maxSize. */ private _createWorker(): Worker | undefined { - if (this._alive.length >= this.maxWorkers) { + if (this.#alive.length >= this.maxWorkers) { return; } const worker: Worker & { [WORKER_ID_SYMBOL]?: string; - } = new Worker(this._workerScript, { + } = new Worker(this.#workerScript, { eval: false, - workerData: this._workerData, - resourceLimits: this._workerResourceLimits + workerData: this.#workerData, + resourceLimits: this.#workerResourceLimits }); - const id: string = `${this.id}#${++this._nextId}`; + const id: string = `${this.id}#${++this.#nextId}`; worker[WORKER_ID_SYMBOL] = id; - this._alive.push(worker); + this.#alive.push(worker); worker.on('error', (err) => { this._onError(err); @@ -229,8 +229,8 @@ export class WorkerPool { this._destroyWorker(worker); }); - if (this._prepare) { - this._prepare(worker); + if (this.#prepare) { + this.#prepare(worker); } return worker; @@ -240,24 +240,24 @@ export class WorkerPool { * Cleans up a worker */ private _destroyWorker(worker: Worker): void { - const aliveIndex: number = this._alive.indexOf(worker); + const aliveIndex: number = this.#alive.indexOf(worker); if (aliveIndex >= 0) { - this._alive.splice(aliveIndex, 1); + this.#alive.splice(aliveIndex, 1); } - const freeIndex: number = this._idle.indexOf(worker); + const freeIndex: number = this.#idle.indexOf(worker); if (freeIndex >= 0) { - this._idle.splice(freeIndex, 1); + this.#idle.splice(freeIndex, 1); } worker.unref(); - if (this._onWorkerDestroyed) { - this._onWorkerDestroyed(); + if (this.#onWorkerDestroyed) { + this.#onWorkerDestroyed(); } - if (!this._alive.length && !this._error) { - for (const [resolve] of this._onComplete.splice(0)) { + if (!this.#alive.length && !this.#error) { + for (const [resolve] of this.#onComplete.splice(0)) { resolve(); } } @@ -267,14 +267,14 @@ export class WorkerPool { * Notifies all pending callbacks that an error has occurred and switches this pool into error state. */ private _onError(error: Error): void { - this._error = error; + this.#error = error; - for (const [, reject] of this._pending.splice(0)) { - reject(this._error); + for (const [, reject] of this.#pending.splice(0)) { + reject(this.#error); } - for (const [, reject] of this._onComplete.splice(0)) { - reject(this._error); + for (const [, reject] of this.#onComplete.splice(0)) { + reject(this.#error); } } } diff --git a/repo-scripts/doc-plugin-rush-stack/src/RushStackFeature.ts b/repo-scripts/doc-plugin-rush-stack/src/RushStackFeature.ts index 8ecdee8f0d9..1e781f6232a 100644 --- a/repo-scripts/doc-plugin-rush-stack/src/RushStackFeature.ts +++ b/repo-scripts/doc-plugin-rush-stack/src/RushStackFeature.ts @@ -23,7 +23,7 @@ interface INavigationFile { } export class RushStackFeature extends MarkdownDocumenterFeature { - private _apiItemsWithPages: Set = new Set(); + #apiItemsWithPages: Set = new Set(); public override onInitialized(): void { // eslint-disable-next-line no-console @@ -42,7 +42,7 @@ export class RushStackFeature extends MarkdownDocumenterFeature { ].join('\n'); eventArgs.pageContent = header + eventArgs.pageContent; - this._apiItemsWithPages.add(eventArgs.apiItem); + this.#apiItemsWithPages.add(eventArgs.apiItem); } public override onFinished(eventArgs: IMarkdownDocumenterFeatureOnFinishedArgs): void { @@ -64,7 +64,7 @@ export class RushStackFeature extends MarkdownDocumenterFeature { private _buildNavigation(parentNodes: INavigationNode[], parentApiItem: ApiItem): void { for (const apiItem of parentApiItem.members) { - if (this._apiItemsWithPages.has(apiItem)) { + if (this.#apiItemsWithPages.has(apiItem)) { const newNode: INavigationNode = { title: apiItem.displayName, url: path.posix From bb9f15cc05a8d81b0ca699794b6f408828d56396 Mon Sep 17 00:00:00 2001 From: Bharat Middha <5100938+bmiddha@users.noreply.github.com> Date: Wed, 19 Aug 2026 15:02:32 -0700 Subject: [PATCH 2/4] fix(api-extractor): suppress private null warning Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8ebd5bf2-c44b-42d5-be25-e7936d4b0a14 --- apps/api-extractor/src/collector/SourceMapper.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/api-extractor/src/collector/SourceMapper.ts b/apps/api-extractor/src/collector/SourceMapper.ts index 109515a2bd7..a54f95ae90a 100644 --- a/apps/api-extractor/src/collector/SourceMapper.ts +++ b/apps/api-extractor/src/collector/SourceMapper.ts @@ -67,6 +67,7 @@ export interface IGetSourceLocationOptions { export class SourceMapper { // Map from .d.ts file path --> ISourceMap if a source map was found, or null if not found + // eslint-disable-next-line @rushstack/no-new-null -- The decoupled ESLint plugin does not recognize native private fields yet. #sourceMapByFilePath: Map = new Map(); // Cache the FileSystem.exists() result for mapped .ts files From 1ba2fc0ec1134347e78ee7c81cce31e5d252394a Mon Sep 17 00:00:00 2001 From: Bharat Middha <5100938+bmiddha@users.noreply.github.com> Date: Wed, 19 Aug 2026 15:36:21 -0700 Subject: [PATCH 3/4] refactor: use ECMAScript #private methods and accessors Convert TypeScript private method and getter/setter declarations to native #private syntax across api-documenter, api-extractor, api-extractor-model, credential-cache, debug-certificate-manager, heft-config-file, lookup-by-path, npm-check-fork, operation-graph, package-extractor, stream-collator, terminal, ts-command-line, typings-generator, worker-pool, and doc-plugin-rush-stack, stripping the conventional leading underscore. Extends the prior #private field conversion to methods and accessors using the same symbol-aware tool. Adds an eslint-disable-next-line @rushstack/no-new-null suppression to SourceMapper#getSourceMap, matching the existing suppression on its sibling private field, since converting the method to native #private syntax exposed it to the same decoupled-lint-rule gap. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8ebd5bf2-c44b-42d5-be25-e7936d4b0a14 --- .../src/cli/ApiDocumenterCommandLine.ts | 4 +- apps/api-documenter/src/cli/BaseAction.ts | 10 +- .../documenters/ExperimentalYamlDocumenter.ts | 26 +- .../src/documenters/MarkdownDocumenter.ts | 238 +++++++++--------- .../src/documenters/OfficeYamlDocumenter.ts | 14 +- .../src/documenters/YamlDocumenter.ts | 168 ++++++------- .../src/utils/IndentedWriter.ts | 40 +-- .../src/analyzer/AstReferenceResolver.ts | 28 +-- .../src/analyzer/AstSymbolTable.ts | 42 ++-- .../src/analyzer/ExportAnalyzer.ts | 96 +++---- apps/api-extractor/src/analyzer/Span.ts | 58 ++--- apps/api-extractor/src/api/ExtractorConfig.ts | 6 +- .../src/cli/ApiExtractorCommandLine.ts | 4 +- apps/api-extractor/src/collector/Collector.ts | 66 ++--- .../src/collector/MessageRouter.ts | 38 +-- .../src/collector/SourceMapper.ts | 9 +- .../src/enhancers/DocCommentEnhancer.ts | 36 +-- .../src/generators/ApiModelGenerator.ts | 214 ++++++++-------- .../DeclarationReferenceGenerator.ts | 30 +-- .../src/generators/IndentedWriter.ts | 32 +-- .../src/items/ApiDeclaredItem.ts | 4 +- .../api-extractor-model/src/model/ApiModel.ts | 6 +- .../src/model/ModelReferenceResolver.ts | 8 +- .../credential-cache/src/CredentialCache.ts | 12 +- .../src/CertificateManager.ts | 32 +-- .../src/ConfigurationFileBase.ts | 68 ++--- .../src/ProjectConfigurationFile.ts | 12 +- libraries/lookup-by-path/src/LookupByPath.ts | 14 +- .../npm-check-fork/src/NpmRegistryClient.ts | 4 +- libraries/operation-graph/src/Operation.ts | 4 +- libraries/operation-graph/src/WatchLoop.ts | 8 +- libraries/operation-graph/src/WorkQueue.ts | 4 +- .../package-extractor/src/AssetHandler.ts | 4 +- .../package-extractor/src/PackageExtractor.ts | 30 +-- .../stream-collator/src/StreamCollator.ts | 16 +- libraries/terminal/src/StdioLineTransform.ts | 6 +- libraries/terminal/src/Terminal.ts | 44 ++-- .../terminal/src/TextRewriterTransform.ts | 12 +- .../providers/CommandLineParameterProvider.ts | 32 +-- .../src/providers/CommandLineParser.ts | 4 +- .../src/providers/TabCompletionAction.ts | 22 +- .../typings-generator/src/TypingsGenerator.ts | 30 +-- libraries/worker-pool/src/WorkerPool.ts | 16 +- .../src/RushStackFeature.ts | 8 +- 44 files changed, 780 insertions(+), 779 deletions(-) diff --git a/apps/api-documenter/src/cli/ApiDocumenterCommandLine.ts b/apps/api-documenter/src/cli/ApiDocumenterCommandLine.ts index cc6c6774111..6d421ddfde4 100644 --- a/apps/api-documenter/src/cli/ApiDocumenterCommandLine.ts +++ b/apps/api-documenter/src/cli/ApiDocumenterCommandLine.ts @@ -15,10 +15,10 @@ export class ApiDocumenterCommandLine extends CommandLineParser { 'Reads *.api.json files produced by api-extractor, ' + ' and generates API documentation in various output formats.' }); - this._populateActions(); + this.#populateActions(); } - private _populateActions(): void { + #populateActions(): void { this.addAction(new MarkdownAction(this)); this.addAction(new YamlAction(this)); this.addAction(new GenerateAction(this)); diff --git a/apps/api-documenter/src/cli/BaseAction.ts b/apps/api-documenter/src/cli/BaseAction.ts index 3e8303f0f76..d17316bafcf 100644 --- a/apps/api-documenter/src/cli/BaseAction.ts +++ b/apps/api-documenter/src/cli/BaseAction.ts @@ -71,7 +71,7 @@ export abstract class BaseAction extends CommandLineAction { } } - this._applyInheritDoc(apiModel, apiModel); + this.#applyInheritDoc(apiModel, apiModel); return { apiModel, inputFolder, outputFolder }; } @@ -79,7 +79,7 @@ export abstract class BaseAction extends CommandLineAction { // TODO: This is a temporary workaround. The long term plan is for API Extractor's DocCommentEnhancer // to apply all @inheritDoc tags before the .api.json file is written. // See DocCommentEnhancer._applyInheritDoc() for more info. - private _applyInheritDoc(apiItem: ApiItem, apiModel: ApiModel): void { + #applyInheritDoc(apiItem: ApiItem, apiModel: ApiModel): void { if (apiItem instanceof ApiDocumentedItem) { if (apiItem.tsdocComment) { const inheritDocTag: tsdoc.DocInheritDocTag | undefined = apiItem.tsdocComment.inheritDocTag; @@ -103,7 +103,7 @@ export abstract class BaseAction extends CommandLineAction { result.resolvedApiItem.tsdocComment && result.resolvedApiItem !== apiItem ) { - this._copyInheritedDocs(apiItem.tsdocComment, result.resolvedApiItem.tsdocComment); + this.#copyInheritedDocs(apiItem.tsdocComment, result.resolvedApiItem.tsdocComment); } } } @@ -113,7 +113,7 @@ export abstract class BaseAction extends CommandLineAction { // Recurse members if (ApiItemContainerMixin.isBaseClassOf(apiItem)) { for (const member of apiItem.members) { - this._applyInheritDoc(member, apiModel); + this.#applyInheritDoc(member, apiModel); } } } @@ -122,7 +122,7 @@ export abstract class BaseAction extends CommandLineAction { * Copy the content from `sourceDocComment` to `targetDocComment`. * This code is borrowed from DocCommentEnhancer as a temporary workaround. */ - private _copyInheritedDocs(targetDocComment: tsdoc.DocComment, sourceDocComment: tsdoc.DocComment): void { + #copyInheritedDocs(targetDocComment: tsdoc.DocComment, sourceDocComment: tsdoc.DocComment): void { targetDocComment.summarySection = sourceDocComment.summarySection; targetDocComment.remarksBlock = sourceDocComment.remarksBlock; diff --git a/apps/api-documenter/src/documenters/ExperimentalYamlDocumenter.ts b/apps/api-documenter/src/documenters/ExperimentalYamlDocumenter.ts index 58bf457ec26..b017bc30a56 100644 --- a/apps/api-documenter/src/documenters/ExperimentalYamlDocumenter.ts +++ b/apps/api-documenter/src/documenters/ExperimentalYamlDocumenter.ts @@ -24,15 +24,15 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { this.#tocPointerMap = {}; - this._generateTocPointersMap(this.#config.tocConfig); + this.#generateTocPointersMap(this.#config.tocConfig); } protected override buildYamlTocFile(apiItems: ReadonlyArray): IYamlTocFile { - this._buildTocItems2(apiItems); + this.#buildTocItems2(apiItems); return this.#config.tocConfig; } - private _buildTocItems2(apiItems: ReadonlyArray): IYamlTocItem[] { + #buildTocItems2(apiItems: ReadonlyArray): IYamlTocItem[] { const tocItems: IYamlTocItem[] = []; for (const apiItem of apiItems) { let tocItem: IYamlTocItem; @@ -52,14 +52,14 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { }; if (apiItem.kind !== ApiItemKind.Package) { - this._filterItem(apiItem, tocItem); + this.#filterItem(apiItem, tocItem); } } tocItems.push(tocItem); const children: ApiItem[] = this._getLogicalChildren(apiItem); - const childItems: IYamlTocItem[] = this._buildTocItems2(children); + const childItems: IYamlTocItem[] = this.#buildTocItems2(children); if (childItems.length > 0) { tocItem.items = childItems; } @@ -68,13 +68,13 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { } // Parses the tocConfig object to build a pointers map of nodes where we want to sort out the API items - private _generateTocPointersMap(tocConfig: IYamlTocFile | IYamlTocItem): void { + #generateTocPointersMap(tocConfig: IYamlTocFile | IYamlTocItem): void { const { catchAllCategory } = this.#config; if (tocConfig.items) { for (const tocItem of tocConfig.items) { - if (tocItem.items && tocItem.items.length > 0 && this._shouldNotIncludeInPointersMap(tocItem)) { - this._generateTocPointersMap(tocItem); + if (tocItem.items && tocItem.items.length > 0 && this.#shouldNotIncludeInPointersMap(tocItem)) { + this.#generateTocPointersMap(tocItem); } else { // check for presence of the `catchAllCategory` config option if (catchAllCategory && tocItem.name === catchAllCategory) { @@ -90,7 +90,7 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { /** * Filtering out the api-item by inlineTags or category name presence in the item name. */ - private _filterItem(apiItem: ApiItem, tocItem: IYamlTocItem): void { + #filterItem(apiItem: ApiItem, tocItem: IYamlTocItem): void { const { categoryInlineTag, categorizeByName } = this.#config; const { name: itemName } = tocItem; let filtered: boolean = false; @@ -98,7 +98,7 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { // First we attempt to filter by inline tag if provided. if (apiItem instanceof ApiDocumentedItem) { const docInlineTag: DocInlineTag | undefined = categoryInlineTag - ? this._findInlineTagByName(categoryInlineTag, apiItem.tsdocComment) + ? this.#findInlineTagByName(categoryInlineTag, apiItem.tsdocComment) : undefined; const tagContent: string | undefined = @@ -132,7 +132,7 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { // This is a direct copy of a @docCategory inline tag finder in office-ui-fabric-react, // but is generic enough to be used for any inline tag - private _findInlineTagByName( + #findInlineTagByName( tagName: string, docComment: DocComment | undefined ): DocInlineTag | undefined { @@ -145,7 +145,7 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { } if (docComment) { for (const childNode of docComment.getChildNodes()) { - const result: DocInlineTag | undefined = this._findInlineTagByName(tagName, childNode as DocComment); + const result: DocInlineTag | undefined = this.#findInlineTagByName(tagName, childNode as DocComment); if (result !== undefined) { return result; } @@ -154,7 +154,7 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { return undefined; } - private _shouldNotIncludeInPointersMap(item: IYamlTocItem): boolean { + #shouldNotIncludeInPointersMap(item: IYamlTocItem): boolean { const { nonEmptyCategoryNodeNames } = this.#config; if (nonEmptyCategoryNodeNames && nonEmptyCategoryNodeNames.length) { return nonEmptyCategoryNodeNames.indexOf(item.name) === -1; diff --git a/apps/api-documenter/src/documenters/MarkdownDocumenter.ts b/apps/api-documenter/src/documenters/MarkdownDocumenter.ts index 8094e4d0e63..c5a17ed113c 100644 --- a/apps/api-documenter/src/documenters/MarkdownDocumenter.ts +++ b/apps/api-documenter/src/documenters/MarkdownDocumenter.ts @@ -102,7 +102,7 @@ export class MarkdownDocumenter { outputFolder: this.#outputFolder, documenter: new MarkdownDocumenterAccessor({ getLinkForApiItem: (apiItem: ApiItem) => { - return this._getLinkFilenameForApiItem(apiItem); + return this.#getLinkFilenameForApiItem(apiItem); } }) }); @@ -110,20 +110,20 @@ export class MarkdownDocumenter { } console.log(); - this._deleteOldOutputFiles(); + this.#deleteOldOutputFiles(); - this._writeApiItemPage(this.#apiModel); + this.#writeApiItemPage(this.#apiModel); if (this.#pluginLoader.markdownDocumenterFeature) { this.#pluginLoader.markdownDocumenterFeature.onFinished({}); } } - private _writeApiItemPage(apiItem: ApiItem): void { + #writeApiItemPage(apiItem: ApiItem): void { const configuration: TSDocConfiguration = this.#tsdocConfiguration; const output: DocSection = new DocSection({ configuration }); - this._writeBreadcrumb(output, apiItem); + this.#writeBreadcrumb(output, apiItem); const scopedName: string = apiItem.getScopedNameWithinPackage(); @@ -175,9 +175,9 @@ export class MarkdownDocumenter { if (ApiReleaseTagMixin.isBaseClassOf(apiItem)) { if (apiItem.releaseTag === ReleaseTag.Alpha) { - this._writeAlphaWarning(output); + this.#writeAlphaWarning(output); } else if (apiItem.releaseTag === ReleaseTag.Beta) { - this._writeBetaWarning(output); + this.#writeBetaWarning(output); } } @@ -207,7 +207,7 @@ export class MarkdownDocumenter { ); } - this._appendSection(output, tsdocComment.summarySection); + this.#appendSection(output, tsdocComment.summarySection); } } @@ -229,7 +229,7 @@ export class MarkdownDocumenter { ); } - this._writeHeritageTypes(output, apiItem); + this.#writeHeritageTypes(output, apiItem); } if (decoratorBlocks.length > 0) { @@ -251,58 +251,58 @@ export class MarkdownDocumenter { case ApiItemKind.Interface: case ApiItemKind.Namespace: case ApiItemKind.Package: - this._writeRemarksSection(output, apiItem); + this.#writeRemarksSection(output, apiItem); appendRemarks = false; break; } switch (apiItem.kind) { case ApiItemKind.Class: - this._writeClassTables(output, apiItem as ApiClass); + this.#writeClassTables(output, apiItem as ApiClass); break; case ApiItemKind.Enum: - this._writeEnumTables(output, apiItem as ApiEnum); + this.#writeEnumTables(output, apiItem as ApiEnum); break; case ApiItemKind.Interface: - this._writeInterfaceTables(output, apiItem as ApiInterface); + this.#writeInterfaceTables(output, apiItem as ApiInterface); break; case ApiItemKind.Constructor: case ApiItemKind.ConstructSignature: case ApiItemKind.Method: case ApiItemKind.MethodSignature: case ApiItemKind.Function: - this._writeParameterTables(output, apiItem as ApiParameterListMixin); - this._writeThrowsSection(output, apiItem); - this._writeDefaultValueSection(output, apiItem); + this.#writeParameterTables(output, apiItem as ApiParameterListMixin); + this.#writeThrowsSection(output, apiItem); + this.#writeDefaultValueSection(output, apiItem); break; case ApiItemKind.Namespace: - this._writePackageOrNamespaceTables(output, apiItem as ApiNamespace); + this.#writePackageOrNamespaceTables(output, apiItem as ApiNamespace); break; case ApiItemKind.Model: - this._writeModelTable(output, apiItem as ApiModel); + this.#writeModelTable(output, apiItem as ApiModel); break; case ApiItemKind.Package: - this._writePackageOrNamespaceTables(output, apiItem as ApiPackage); + this.#writePackageOrNamespaceTables(output, apiItem as ApiPackage); break; case ApiItemKind.Property: case ApiItemKind.PropertySignature: - this._writeDefaultValueSection(output, apiItem); + this.#writeDefaultValueSection(output, apiItem); break; case ApiItemKind.TypeAlias: - this._writeDefaultValueSection(output, apiItem); + this.#writeDefaultValueSection(output, apiItem); break; case ApiItemKind.Variable: - this._writeDefaultValueSection(output, apiItem); + this.#writeDefaultValueSection(output, apiItem); break; default: throw new Error('Unsupported API item kind: ' + apiItem.kind); } if (appendRemarks) { - this._writeRemarksSection(output, apiItem); + this.#writeRemarksSection(output, apiItem); } - const filename: string = path.join(this.#outputFolder, this._getFilenameForApiItem(apiItem)); + const filename: string = path.join(this.#outputFolder, this.#getFilenameForApiItem(apiItem)); const stringBuilder: StringBuilder = new StringBuilder(); stringBuilder.append( @@ -312,7 +312,7 @@ export class MarkdownDocumenter { this.#markdownEmitter.emit(stringBuilder, output, { contextApiItem: apiItem, onGetFilenameForApiItem: (apiItemForFilename: ApiItem) => { - return this._getLinkFilenameForApiItem(apiItemForFilename); + return this.#getLinkFilenameForApiItem(apiItemForFilename); } }); @@ -334,7 +334,7 @@ export class MarkdownDocumenter { }); } - private _writeHeritageTypes(output: DocSection, apiItem: ApiDeclaredItem): void { + #writeHeritageTypes(output: DocSection, apiItem: ApiDeclaredItem): void { const configuration: TSDocConfiguration = this.#tsdocConfiguration; if (apiItem instanceof ApiClass) { @@ -344,7 +344,7 @@ export class MarkdownDocumenter { new DocPlainText({ configuration, text: 'Extends: ' }) ]) ]); - this._appendExcerptWithHyperlinks(extendsParagraph, apiItem.extendsType.excerpt); + this.#appendExcerptWithHyperlinks(extendsParagraph, apiItem.extendsType.excerpt); output.appendNode(extendsParagraph); } if (apiItem.implementsTypes.length > 0) { @@ -358,7 +358,7 @@ export class MarkdownDocumenter { if (needsComma) { implementsParagraph.appendNode(new DocPlainText({ configuration, text: ', ' })); } - this._appendExcerptWithHyperlinks(implementsParagraph, implementsType.excerpt); + this.#appendExcerptWithHyperlinks(implementsParagraph, implementsType.excerpt); needsComma = true; } output.appendNode(implementsParagraph); @@ -377,7 +377,7 @@ export class MarkdownDocumenter { if (needsComma) { extendsParagraph.appendNode(new DocPlainText({ configuration, text: ', ' })); } - this._appendExcerptWithHyperlinks(extendsParagraph, extendsType.excerpt); + this.#appendExcerptWithHyperlinks(extendsParagraph, extendsType.excerpt); needsComma = true; } output.appendNode(extendsParagraph); @@ -409,7 +409,7 @@ export class MarkdownDocumenter { referencesParagraph.appendNode(new DocPlainText({ configuration, text: ', ' })); } - this._appendExcerptTokenWithHyperlinks(referencesParagraph, ref); + this.#appendExcerptTokenWithHyperlinks(referencesParagraph, ref); needsComma = true; } output.appendNode(referencesParagraph); @@ -417,7 +417,7 @@ export class MarkdownDocumenter { } } - private _writeRemarksSection(output: DocSection, apiItem: ApiItem): void { + #writeRemarksSection(output: DocSection, apiItem: ApiItem): void { const configuration: TSDocConfiguration = this.#tsdocConfiguration; if (apiItem instanceof ApiDocumentedItem) { @@ -427,7 +427,7 @@ export class MarkdownDocumenter { // Write the @remarks block if (tsdocComment.remarksBlock) { output.appendNode(new DocHeading({ configuration, title: 'Remarks' })); - this._appendSection(output, tsdocComment.remarksBlock.content); + this.#appendSection(output, tsdocComment.remarksBlock.content); } // Write the @example blocks @@ -441,7 +441,7 @@ export class MarkdownDocumenter { output.appendNode(new DocHeading({ configuration, title: heading })); - this._appendSection(output, exampleBlock.content); + this.#appendSection(output, exampleBlock.content); ++exampleNumber; } @@ -449,7 +449,7 @@ export class MarkdownDocumenter { } } - private _writeThrowsSection(output: DocSection, apiItem: ApiItem): void { + #writeThrowsSection(output: DocSection, apiItem: ApiItem): void { const configuration: TSDocConfiguration = this.#tsdocConfiguration; if (apiItem instanceof ApiDocumentedItem) { @@ -466,14 +466,14 @@ export class MarkdownDocumenter { output.appendNode(new DocHeading({ configuration, title: heading })); for (const throwsBlock of throwsBlocks) { - this._appendSection(output, throwsBlock.content); + this.#appendSection(output, throwsBlock.content); } } } } } - private _writeDefaultValueSection(output: DocSection, apiItem: ApiItem): void { + #writeDefaultValueSection(output: DocSection, apiItem: ApiItem): void { const configuration: TSDocConfiguration = this.#tsdocConfiguration; if (apiItem instanceof ApiDocumentedItem) { @@ -490,7 +490,7 @@ export class MarkdownDocumenter { output.appendNode(new DocHeading({ configuration, title: heading })); for (const defaultValueBlock of defaultValueBlocks) { - this._appendSection(output, defaultValueBlock.content); + this.#appendSection(output, defaultValueBlock.content); } } } @@ -500,7 +500,7 @@ export class MarkdownDocumenter { /** * GENERATE PAGE: MODEL */ - private _writeModelTable(output: DocSection, apiModel: ApiModel): void { + #writeModelTable(output: DocSection, apiModel: ApiModel): void { const configuration: TSDocConfiguration = this.#tsdocConfiguration; const packagesTable: DocTable = new DocTable({ @@ -510,14 +510,14 @@ export class MarkdownDocumenter { for (const apiMember of apiModel.members) { const row: DocTableRow = new DocTableRow({ configuration }, [ - this._createTitleCell(apiMember), - this._createDescriptionCell(apiMember) + this.#createTitleCell(apiMember), + this.#createDescriptionCell(apiMember) ]); switch (apiMember.kind) { case ApiItemKind.Package: packagesTable.addRow(row); - this._writeApiItemPage(apiMember); + this.#writeApiItemPage(apiMember); break; } } @@ -531,7 +531,7 @@ export class MarkdownDocumenter { /** * GENERATE PAGE: PACKAGE or NAMESPACE */ - private _writePackageOrNamespaceTables(output: DocSection, apiContainer: ApiPackage | ApiNamespace): void { + #writePackageOrNamespaceTables(output: DocSection, apiContainer: ApiPackage | ApiNamespace): void { const configuration: TSDocConfiguration = this.#tsdocConfiguration; const abstractClassesTable: DocTable = new DocTable({ @@ -581,8 +581,8 @@ export class MarkdownDocumenter { for (const apiMember of apiMembers) { const row: DocTableRow = new DocTableRow({ configuration }, [ - this._createTitleCell(apiMember), - this._createDescriptionCell(apiMember) + this.#createTitleCell(apiMember), + this.#createDescriptionCell(apiMember) ]); switch (apiMember.kind) { @@ -592,37 +592,37 @@ export class MarkdownDocumenter { } else { classesTable.addRow(row); } - this._writeApiItemPage(apiMember); + this.#writeApiItemPage(apiMember); break; case ApiItemKind.Enum: enumerationsTable.addRow(row); - this._writeApiItemPage(apiMember); + this.#writeApiItemPage(apiMember); break; case ApiItemKind.Interface: interfacesTable.addRow(row); - this._writeApiItemPage(apiMember); + this.#writeApiItemPage(apiMember); break; case ApiItemKind.Namespace: namespacesTable.addRow(row); - this._writeApiItemPage(apiMember); + this.#writeApiItemPage(apiMember); break; case ApiItemKind.Function: functionsTable.addRow(row); - this._writeApiItemPage(apiMember); + this.#writeApiItemPage(apiMember); break; case ApiItemKind.TypeAlias: typeAliasesTable.addRow(row); - this._writeApiItemPage(apiMember); + this.#writeApiItemPage(apiMember); break; case ApiItemKind.Variable: variablesTable.addRow(row); - this._writeApiItemPage(apiMember); + this.#writeApiItemPage(apiMember); break; } } @@ -670,7 +670,7 @@ export class MarkdownDocumenter { /** * GENERATE PAGE: CLASS */ - private _writeClassTables(output: DocSection, apiClass: ApiClass): void { + #writeClassTables(output: DocSection, apiClass: ApiClass): void { const configuration: TSDocConfiguration = this.#tsdocConfiguration; const eventsTable: DocTable = new DocTable({ @@ -693,56 +693,56 @@ export class MarkdownDocumenter { headerTitles: ['Method', 'Modifiers', 'Description'] }); - const apiMembers: readonly ApiItem[] = this._getMembersAndWriteIncompleteWarning(apiClass, output); + const apiMembers: readonly ApiItem[] = this.#getMembersAndWriteIncompleteWarning(apiClass, output); for (const apiMember of apiMembers) { const isInherited: boolean = apiMember.parent !== apiClass; switch (apiMember.kind) { case ApiItemKind.Constructor: { constructorsTable.addRow( new DocTableRow({ configuration }, [ - this._createTitleCell(apiMember), - this._createModifiersCell(apiMember), - this._createDescriptionCell(apiMember, isInherited) + this.#createTitleCell(apiMember), + this.#createModifiersCell(apiMember), + this.#createDescriptionCell(apiMember, isInherited) ]) ); - this._writeApiItemPage(apiMember); + this.#writeApiItemPage(apiMember); break; } case ApiItemKind.Method: { methodsTable.addRow( new DocTableRow({ configuration }, [ - this._createTitleCell(apiMember), - this._createModifiersCell(apiMember), - this._createDescriptionCell(apiMember, isInherited) + this.#createTitleCell(apiMember), + this.#createModifiersCell(apiMember), + this.#createDescriptionCell(apiMember, isInherited) ]) ); - this._writeApiItemPage(apiMember); + this.#writeApiItemPage(apiMember); break; } case ApiItemKind.Property: { if ((apiMember as ApiPropertyItem).isEventProperty) { eventsTable.addRow( new DocTableRow({ configuration }, [ - this._createTitleCell(apiMember), - this._createModifiersCell(apiMember), - this._createPropertyTypeCell(apiMember), - this._createDescriptionCell(apiMember, isInherited) + this.#createTitleCell(apiMember), + this.#createModifiersCell(apiMember), + this.#createPropertyTypeCell(apiMember), + this.#createDescriptionCell(apiMember, isInherited) ]) ); } else { propertiesTable.addRow( new DocTableRow({ configuration }, [ - this._createTitleCell(apiMember), - this._createModifiersCell(apiMember), - this._createPropertyTypeCell(apiMember), - this._createDescriptionCell(apiMember, isInherited) + this.#createTitleCell(apiMember), + this.#createModifiersCell(apiMember), + this.#createPropertyTypeCell(apiMember), + this.#createDescriptionCell(apiMember, isInherited) ]) ); } - this._writeApiItemPage(apiMember); + this.#writeApiItemPage(apiMember); break; } } @@ -772,7 +772,7 @@ export class MarkdownDocumenter { /** * GENERATE PAGE: ENUM */ - private _writeEnumTables(output: DocSection, apiEnum: ApiEnum): void { + #writeEnumTables(output: DocSection, apiEnum: ApiEnum): void { const configuration: TSDocConfiguration = this.#tsdocConfiguration; const enumMembersTable: DocTable = new DocTable({ @@ -788,8 +788,8 @@ export class MarkdownDocumenter { new DocPlainText({ configuration, text: Utilities.getConciseSignature(apiEnumMember) }) ]) ]), - this._createInitializerCell(apiEnumMember), - this._createDescriptionCell(apiEnumMember) + this.#createInitializerCell(apiEnumMember), + this.#createDescriptionCell(apiEnumMember) ]) ); } @@ -803,7 +803,7 @@ export class MarkdownDocumenter { /** * GENERATE PAGE: INTERFACE */ - private _writeInterfaceTables(output: DocSection, apiInterface: ApiInterface): void { + #writeInterfaceTables(output: DocSection, apiInterface: ApiInterface): void { const configuration: TSDocConfiguration = this.#tsdocConfiguration; const eventsTable: DocTable = new DocTable({ @@ -821,7 +821,7 @@ export class MarkdownDocumenter { headerTitles: ['Method', 'Description'] }); - const apiMembers: readonly ApiItem[] = this._getMembersAndWriteIncompleteWarning(apiInterface, output); + const apiMembers: readonly ApiItem[] = this.#getMembersAndWriteIncompleteWarning(apiInterface, output); for (const apiMember of apiMembers) { const isInherited: boolean = apiMember.parent !== apiInterface; switch (apiMember.kind) { @@ -829,36 +829,36 @@ export class MarkdownDocumenter { case ApiItemKind.MethodSignature: { methodsTable.addRow( new DocTableRow({ configuration }, [ - this._createTitleCell(apiMember), - this._createDescriptionCell(apiMember, isInherited) + this.#createTitleCell(apiMember), + this.#createDescriptionCell(apiMember, isInherited) ]) ); - this._writeApiItemPage(apiMember); + this.#writeApiItemPage(apiMember); break; } case ApiItemKind.PropertySignature: { if ((apiMember as ApiPropertyItem).isEventProperty) { eventsTable.addRow( new DocTableRow({ configuration }, [ - this._createTitleCell(apiMember), - this._createModifiersCell(apiMember), - this._createPropertyTypeCell(apiMember), - this._createDescriptionCell(apiMember, isInherited) + this.#createTitleCell(apiMember), + this.#createModifiersCell(apiMember), + this.#createPropertyTypeCell(apiMember), + this.#createDescriptionCell(apiMember, isInherited) ]) ); } else { propertiesTable.addRow( new DocTableRow({ configuration }, [ - this._createTitleCell(apiMember), - this._createModifiersCell(apiMember), - this._createPropertyTypeCell(apiMember), - this._createDescriptionCell(apiMember, isInherited) + this.#createTitleCell(apiMember), + this.#createModifiersCell(apiMember), + this.#createPropertyTypeCell(apiMember), + this.#createDescriptionCell(apiMember, isInherited) ]) ); } - this._writeApiItemPage(apiMember); + this.#writeApiItemPage(apiMember); break; } } @@ -883,7 +883,7 @@ export class MarkdownDocumenter { /** * GENERATE PAGE: FUNCTION-LIKE */ - private _writeParameterTables(output: DocSection, apiParameterListMixin: ApiParameterListMixin): void { + #writeParameterTables(output: DocSection, apiParameterListMixin: ApiParameterListMixin): void { const configuration: TSDocConfiguration = this.#tsdocConfiguration; const parametersTable: DocTable = new DocTable({ @@ -903,7 +903,7 @@ export class MarkdownDocumenter { } if (apiParameter.tsdocParamBlock) { - this._appendAndMergeSection(parameterDescription, apiParameter.tsdocParamBlock.content); + this.#appendAndMergeSection(parameterDescription, apiParameter.tsdocParamBlock.content); } parametersTable.addRow( @@ -914,7 +914,7 @@ export class MarkdownDocumenter { ]) ]), new DocTableCell({ configuration }, [ - this._createParagraphForTypeExcerpt(apiParameter.parameterTypeExcerpt) + this.#createParagraphForTypeExcerpt(apiParameter.parameterTypeExcerpt) ]), new DocTableCell({ configuration }, parameterDescription.nodes) ]) @@ -936,17 +936,17 @@ export class MarkdownDocumenter { ]) ); - output.appendNode(this._createParagraphForTypeExcerpt(returnTypeExcerpt)); + output.appendNode(this.#createParagraphForTypeExcerpt(returnTypeExcerpt)); if (apiParameterListMixin instanceof ApiDocumentedItem) { if (apiParameterListMixin.tsdocComment && apiParameterListMixin.tsdocComment.returnsBlock) { - this._appendSection(output, apiParameterListMixin.tsdocComment.returnsBlock.content); + this.#appendSection(output, apiParameterListMixin.tsdocComment.returnsBlock.content); } } } } - private _createParagraphForTypeExcerpt(excerpt: Excerpt): DocParagraph { + #createParagraphForTypeExcerpt(excerpt: Excerpt): DocParagraph { const configuration: TSDocConfiguration = this.#tsdocConfiguration; const paragraph: DocParagraph = new DocParagraph({ configuration }); @@ -954,19 +954,19 @@ export class MarkdownDocumenter { if (!excerpt.text.trim()) { paragraph.appendNode(new DocPlainText({ configuration, text: '(not declared)' })); } else { - this._appendExcerptWithHyperlinks(paragraph, excerpt); + this.#appendExcerptWithHyperlinks(paragraph, excerpt); } return paragraph; } - private _appendExcerptWithHyperlinks(docNodeContainer: DocNodeContainer, excerpt: Excerpt): void { + #appendExcerptWithHyperlinks(docNodeContainer: DocNodeContainer, excerpt: Excerpt): void { for (const token of excerpt.spannedTokens) { - this._appendExcerptTokenWithHyperlinks(docNodeContainer, token); + this.#appendExcerptTokenWithHyperlinks(docNodeContainer, token); } } - private _appendExcerptTokenWithHyperlinks(docNodeContainer: DocNodeContainer, token: ExcerptToken): void { + #appendExcerptTokenWithHyperlinks(docNodeContainer: DocNodeContainer, token: ExcerptToken): void { const configuration: TSDocConfiguration = this.#tsdocConfiguration; // Markdown doesn't provide a standardized syntax for hyperlinks inside code spans, so we will render @@ -987,7 +987,7 @@ export class MarkdownDocumenter { configuration, tagName: '@link', linkText: unwrappedTokenText, - urlDestination: this._getLinkFilenameForApiItem(apiItemResult.resolvedApiItem) + urlDestination: this.#getLinkFilenameForApiItem(apiItemResult.resolvedApiItem) }) ); return; @@ -998,7 +998,7 @@ export class MarkdownDocumenter { docNodeContainer.appendNode(new DocPlainText({ configuration, text: unwrappedTokenText })); } - private _createTitleCell(apiItem: ApiItem): DocTableCell { + #createTitleCell(apiItem: ApiItem): DocTableCell { const configuration: TSDocConfiguration = this.#tsdocConfiguration; let linkText: string = Utilities.getConciseSignature(apiItem); @@ -1012,7 +1012,7 @@ export class MarkdownDocumenter { configuration, tagName: '@link', linkText: linkText, - urlDestination: this._getLinkFilenameForApiItem(apiItem) + urlDestination: this.#getLinkFilenameForApiItem(apiItem) }) ]) ]); @@ -1025,7 +1025,7 @@ export class MarkdownDocumenter { * We mostly assume that the input is an ApiDocumentedItem, but it's easier to perform this as a runtime * check than to have each caller perform a type cast. */ - private _createDescriptionCell(apiItem: ApiItem, isInherited: boolean = false): DocTableCell { + #createDescriptionCell(apiItem: ApiItem, isInherited: boolean = false): DocTableCell { const configuration: TSDocConfiguration = this.#tsdocConfiguration; const section: DocSection = new DocSection({ configuration }); @@ -1055,7 +1055,7 @@ export class MarkdownDocumenter { if (apiItem instanceof ApiDocumentedItem) { if (apiItem.tsdocComment !== undefined) { - this._appendAndMergeSection(section, apiItem.tsdocComment.summarySection); + this.#appendAndMergeSection(section, apiItem.tsdocComment.summarySection); } } @@ -1067,7 +1067,7 @@ export class MarkdownDocumenter { configuration, tagName: '@link', linkText: apiItem.parent.displayName, - urlDestination: this._getLinkFilenameForApiItem(apiItem.parent) + urlDestination: this.#getLinkFilenameForApiItem(apiItem.parent) }), new DocPlainText({ configuration, text: ')' }) ]) @@ -1077,7 +1077,7 @@ export class MarkdownDocumenter { return new DocTableCell({ configuration }, section.nodes); } - private _createModifiersCell(apiItem: ApiItem): DocTableCell { + #createModifiersCell(apiItem: ApiItem): DocTableCell { const configuration: TSDocConfiguration = this.#tsdocConfiguration; const section: DocSection = new DocSection({ configuration }); @@ -1121,19 +1121,19 @@ export class MarkdownDocumenter { return new DocTableCell({ configuration }, section.nodes); } - private _createPropertyTypeCell(apiItem: ApiItem): DocTableCell { + #createPropertyTypeCell(apiItem: ApiItem): DocTableCell { const configuration: TSDocConfiguration = this.#tsdocConfiguration; const section: DocSection = new DocSection({ configuration }); if (apiItem instanceof ApiPropertyItem) { - section.appendNode(this._createParagraphForTypeExcerpt(apiItem.propertyTypeExcerpt)); + section.appendNode(this.#createParagraphForTypeExcerpt(apiItem.propertyTypeExcerpt)); } return new DocTableCell({ configuration }, section.nodes); } - private _createInitializerCell(apiItem: ApiItem): DocTableCell { + #createInitializerCell(apiItem: ApiItem): DocTableCell { const configuration: TSDocConfiguration = this.#tsdocConfiguration; const section: DocSection = new DocSection({ configuration }); @@ -1149,7 +1149,7 @@ export class MarkdownDocumenter { return new DocTableCell({ configuration }, section.nodes); } - private _writeBreadcrumb(output: DocSection, apiItem: ApiItem): void { + #writeBreadcrumb(output: DocSection, apiItem: ApiItem): void { const configuration: TSDocConfiguration = this.#tsdocConfiguration; output.appendNodeInParagraph( @@ -1157,7 +1157,7 @@ export class MarkdownDocumenter { configuration, tagName: '@link', linkText: 'Home', - urlDestination: this._getLinkFilenameForApiItem(this.#apiModel) + urlDestination: this.#getLinkFilenameForApiItem(this.#apiModel) }) ); @@ -1179,14 +1179,14 @@ export class MarkdownDocumenter { configuration, tagName: '@link', linkText: hierarchyItem.displayName, - urlDestination: this._getLinkFilenameForApiItem(hierarchyItem) + urlDestination: this.#getLinkFilenameForApiItem(hierarchyItem) }) ]); } } } - private _writeAlphaWarning(output: DocSection): void { + #writeAlphaWarning(output: DocSection): void { const configuration: TSDocConfiguration = this.#tsdocConfiguration; const betaWarning: string = 'This API is provided as an alpha preview for developers and may change' + @@ -1198,7 +1198,7 @@ export class MarkdownDocumenter { ); } - private _writeBetaWarning(output: DocSection): void { + #writeBetaWarning(output: DocSection): void { const configuration: TSDocConfiguration = this.#tsdocConfiguration; const betaWarning: string = 'This API is provided as a beta preview for developers and may change' + @@ -1210,13 +1210,13 @@ export class MarkdownDocumenter { ); } - private _appendSection(output: DocSection, docSection: DocSection): void { + #appendSection(output: DocSection, docSection: DocSection): void { for (const node of docSection.nodes) { output.appendNode(node); } } - private _appendAndMergeSection(output: DocSection, docSection: DocSection): void { + #appendAndMergeSection(output: DocSection, docSection: DocSection): void { let firstNode: boolean = true; for (const node of docSection.nodes) { if (firstNode) { @@ -1232,7 +1232,7 @@ export class MarkdownDocumenter { } } - private _getMembersAndWriteIncompleteWarning( + #getMembersAndWriteIncompleteWarning( apiClassOrInterface: ApiClass | ApiInterface, output: DocSection ): readonly ApiItem[] { @@ -1266,7 +1266,7 @@ export class MarkdownDocumenter { return result.items; } - private _getFilenameForApiItem(apiItem: ApiItem): string { + #getFilenameForApiItem(apiItem: ApiItem): string { if (apiItem.kind === ApiItemKind.Model) { return 'index.md'; } @@ -1298,11 +1298,11 @@ export class MarkdownDocumenter { return baseName + '.md'; } - private _getLinkFilenameForApiItem(apiItem: ApiItem): string { - return './' + this._getFilenameForApiItem(apiItem); + #getLinkFilenameForApiItem(apiItem: ApiItem): string { + return './' + this.#getFilenameForApiItem(apiItem); } - private _deleteOldOutputFiles(): void { + #deleteOldOutputFiles(): void { console.log('Deleting old output from ' + this.#outputFolder); FileSystem.ensureEmptyFolder(this.#outputFolder); } diff --git a/apps/api-documenter/src/documenters/OfficeYamlDocumenter.ts b/apps/api-documenter/src/documenters/OfficeYamlDocumenter.ts index 9119f328931..cf6316791ac 100644 --- a/apps/api-documenter/src/documenters/OfficeYamlDocumenter.ts +++ b/apps/api-documenter/src/documenters/OfficeYamlDocumenter.ts @@ -74,16 +74,16 @@ export class OfficeYamlDocumenter extends YamlDocumenter { protected override onCustomizeYamlItem(yamlItem: IYamlItem): void { const nameWithoutPackage: string = yamlItem.uid.replace(/^[^.]+\!/, ''); if (yamlItem.summary) { - yamlItem.summary = this._fixupApiSet(yamlItem.summary, yamlItem.uid); + yamlItem.summary = this.#fixupApiSet(yamlItem.summary, yamlItem.uid); } if (yamlItem.remarks) { - yamlItem.remarks = this._fixupApiSet(yamlItem.remarks, yamlItem.uid); + yamlItem.remarks = this.#fixupApiSet(yamlItem.remarks, yamlItem.uid); } const snippets: string[] | undefined = this.#snippetsAll[nameWithoutPackage]; if (snippets) { delete this.#snippets[nameWithoutPackage]; - const snippetText: string = this._generateExampleSnippetText(snippets); + const snippetText: string = this.#generateExampleSnippetText(snippets); if (yamlItem.remarks) { yamlItem.remarks += snippetText; } else if (yamlItem.syntax && yamlItem.syntax.return) { @@ -97,18 +97,18 @@ export class OfficeYamlDocumenter extends YamlDocumenter { } } - private _fixupApiSet(markup: string, uid: string): string { + #fixupApiSet(markup: string, uid: string): string { // Search for a pattern such as this: // \[Api set: ExcelApi 1.1\] // // Hyperlink it like this: // \[ [API set: ExcelApi 1.1](http://bing.com?type=excel) \] markup = markup.replace(/Api/, 'API'); - return markup.replace(/\\\[(API set:[^\]]+)\\\]/, '\\[ [$1](' + this._getApiSetUrl(uid) + ') \\]'); + return markup.replace(/\\\[(API set:[^\]]+)\\\]/, '\\[ [$1](' + this.#getApiSetUrl(uid) + ') \\]'); } // Gets the link to the API set based on product context. Seeks a case-insensitive match in the hash set. - private _getApiSetUrl(uid: string): string { + #getApiSetUrl(uid: string): string { for (const key of Object.keys(this.#apiSetUrls)) { const regexp: RegExp = new RegExp(key, 'i'); if (regexp.test(uid)) { @@ -118,7 +118,7 @@ export class OfficeYamlDocumenter extends YamlDocumenter { return this.#apiSetUrlDefault; // match not found. } - private _generateExampleSnippetText(snippets: string[]): string { + #generateExampleSnippetText(snippets: string[]): string { const text: string[] = ['\n\n#### Examples\n']; for (const snippet of snippets) { text.push(`\`\`\`TypeScript\n${snippet}\n\`\`\``); diff --git a/apps/api-documenter/src/documenters/YamlDocumenter.ts b/apps/api-documenter/src/documenters/YamlDocumenter.ts index eeaf805633c..f460cf1de78 100644 --- a/apps/api-documenter/src/documenters/YamlDocumenter.ts +++ b/apps/api-documenter/src/documenters/YamlDocumenter.ts @@ -116,24 +116,24 @@ export class YamlDocumenter { this.#markdownEmitter = new CustomMarkdownEmitter(this.#apiModel); this.#apiItemsByCanonicalReference = new Map(); - this._initApiItems(); + this.#initApiItems(); } /** @virtual */ public generateFiles(outputFolder: string): void { console.log(); - this._deleteOldOutputFiles(outputFolder); + this.#deleteOldOutputFiles(outputFolder); for (const apiPackage of this.#apiModel.packages) { console.log(`Writing ${apiPackage.name} package`); - this._visitApiItems(outputFolder, apiPackage, undefined); + this.#visitApiItems(outputFolder, apiPackage, undefined); } if (this.#yamlFormat === 'sdp') { convertUDPYamlToSDP(outputFolder); } - this._writeTocFile(outputFolder, this.#apiModel.packages); + this.#writeTocFile(outputFolder, this.#apiModel.packages); } /** @virtual */ @@ -151,7 +151,7 @@ export class YamlDocumenter { // (overridden by child class) } - private _visitApiItems( + #visitApiItems( outputFolder: string, apiItem: ApiDocumentedItem, parentYamlFile: IYamlApiFile | undefined @@ -162,7 +162,7 @@ export class YamlDocumenter { this.#yamlReferences = undefined; } - const yamlItem: IYamlItem | undefined = this._generateYamlItem(apiItem); + const yamlItem: IYamlItem | undefined = this.#generateYamlItem(apiItem); if (!yamlItem) { return false; } @@ -183,7 +183,7 @@ export class YamlDocumenter { const children: ApiItem[] = this._getLogicalChildren(apiItem); for (const child of children) { if (child instanceof ApiDocumentedItem) { - if (this._visitApiItems(outputFolder, child, newYamlFile)) { + if (this.#visitApiItems(outputFolder, child, newYamlFile)) { if (!yamlItem.children) { yamlItem.children = []; } @@ -198,25 +198,25 @@ export class YamlDocumenter { this.#yamlReferences = savedYamlReferences; - const yamlFilePath: string = this._getYamlFilePath(outputFolder, apiItem); + const yamlFilePath: string = this.#getYamlFilePath(outputFolder, apiItem); if (apiItem.kind === ApiItemKind.Package) { console.log('Writing ' + yamlFilePath); } - this._writeYamlFile(newYamlFile, yamlFilePath, 'UniversalReference', yamlApiSchema); + this.#writeYamlFile(newYamlFile, yamlFilePath, 'UniversalReference', yamlApiSchema); if (parentYamlFile) { // References should be recorded in the parent YAML file with the local name of the embedded item. // This avoids unnecessary repetition when listing items inside of a namespace. - this._recordYamlReference( - this._ensureYamlReferences(), + this.#recordYamlReference( + this.#ensureYamlReferences(), this._getUid(apiItem), - this._getYamlItemName(apiItem, { + this.#getYamlItemName(apiItem, { includeNamespace: !this.newDocfxNamespaces, includeSignature: true }), - this._getYamlItemName(apiItem, { includeNamespace: true, includeSignature: true }) + this.#getYamlItemName(apiItem, { includeNamespace: true, includeSignature: true }) ); } } @@ -228,13 +228,13 @@ export class YamlDocumenter { const children: ApiItem[] = []; if (apiItem.kind === ApiItemKind.Package) { // Skip over the entry point, since it's not part of the documentation hierarchy - this._flattenNamespaces( + this.#flattenNamespaces( apiItem.members[0].members, children, this.newDocfxNamespaces ? FlattenMode.NestedNamespacesAndChildren : FlattenMode.NestedChildren ); } else { - this._flattenNamespaces( + this.#flattenNamespaces( apiItem.members, children, this.newDocfxNamespaces ? FlattenMode.ImmediateChildren : FlattenMode.NestedChildren @@ -249,7 +249,7 @@ export class YamlDocumenter { // - X // - X.Y // - X.Y.Z - private _flattenNamespaces( + #flattenNamespaces( items: ReadonlyArray, childrenOut: ApiItem[], mode: FlattenMode @@ -260,7 +260,7 @@ export class YamlDocumenter { switch (mode) { case FlattenMode.NestedChildren: // Include children of namespaces, but not the namespaces themselves. This matches existing legacy behavior. - this._flattenNamespaces(item.members, childrenOut, FlattenMode.NestedChildren); + this.#flattenNamespaces(item.members, childrenOut, FlattenMode.NestedChildren); break; case FlattenMode.NestedNamespacesOnly: case FlattenMode.NestedNamespacesAndChildren: @@ -271,7 +271,7 @@ export class YamlDocumenter { const index: number = childrenOut.length; childrenOut.push(item); - if (!this._flattenNamespaces(item.members, childrenOut, FlattenMode.NestedNamespacesOnly)) { + if (!this.#flattenNamespaces(item.members, childrenOut, FlattenMode.NestedNamespacesOnly)) { // This namespace had no non-namespace children, remove it. childrenOut.splice(index, 1); } @@ -295,12 +295,12 @@ export class YamlDocumenter { /** * Write the table of contents */ - private _writeTocFile(outputFolder: string, apiItems: ReadonlyArray): void { + #writeTocFile(outputFolder: string, apiItems: ReadonlyArray): void { const tocFile: IYamlTocFile = this.buildYamlTocFile(apiItems); const tocFilePath: string = path.join(outputFolder, 'toc.yml'); console.log('Writing ' + tocFilePath); - this._writeYamlFile(tocFile, tocFilePath, '', undefined); + this.#writeYamlFile(tocFile, tocFilePath, '', undefined); } /** @virtual */ @@ -312,11 +312,11 @@ export class YamlDocumenter { const rootItem: IYamlTocItem = this.onGetTocRoot(); tocFile.items.push(rootItem); - rootItem.items!.push(...this._buildTocItems(apiItems)); + rootItem.items!.push(...this.#buildTocItems(apiItems)); return tocFile; } - private _buildTocItems(apiItems: ReadonlyArray): IYamlTocItem[] { + #buildTocItems(apiItems: ReadonlyArray): IYamlTocItem[] { const tocItems: IYamlTocItem[] = []; for (const apiItem of apiItems) { let tocItem: IYamlTocItem; @@ -339,7 +339,7 @@ export class YamlDocumenter { tocItems.push(tocItem); const children: ApiItem[] = this._getLogicalChildren(apiItem); - const childItems: IYamlTocItem[] = this._buildTocItems(children); + const childItems: IYamlTocItem[] = this.#buildTocItems(children); if (childItems.length > 0) { tocItem.items = childItems; } @@ -353,7 +353,7 @@ export class YamlDocumenter { if (apiItem.kind === ApiItemKind.Package) { name = PackageName.getUnscopedName(apiItem.displayName); } else { - name = this._getYamlItemName(apiItem); + name = this.#getYamlItemName(apiItem); } if (name === apiItem.displayName && apiItem.getMergedSiblings().length > 1) { @@ -388,7 +388,7 @@ export class YamlDocumenter { return true; } - private _generateYamlItem(apiItem: ApiDocumentedItem): IYamlItem | undefined { + #generateYamlItem(apiItem: ApiDocumentedItem): IYamlItem | undefined { // Filter out known items that are not yet supported if (!this._shouldInclude(apiItem.kind)) { return undefined; @@ -402,14 +402,14 @@ export class YamlDocumenter { if (apiItem.tsdocComment) { const tsdocComment: DocComment = apiItem.tsdocComment; if (tsdocComment.summarySection) { - const summary: string = this._renderMarkdown(tsdocComment.summarySection, apiItem); + const summary: string = this.#renderMarkdown(tsdocComment.summarySection, apiItem); if (summary) { yamlItem.summary = summary; } } if (tsdocComment.remarksBlock) { - const remarks: string = this._renderMarkdown(tsdocComment.remarksBlock.content, apiItem); + const remarks: string = this.#renderMarkdown(tsdocComment.remarksBlock.content, apiItem); if (remarks) { yamlItem.remarks = remarks; } @@ -422,7 +422,7 @@ export class YamlDocumenter { ); for (const exampleBlock of exampleBlocks) { - const example: string = this._renderMarkdown(exampleBlock.content, apiItem); + const example: string = this.#renderMarkdown(exampleBlock.content, apiItem); if (example) { yamlItem.example = [...(yamlItem.example || []), example]; } @@ -434,7 +434,7 @@ export class YamlDocumenter { ); for (const defaultValueBlock of defaultValueBlocks) { - const defaultValueContent: string = this._renderMarkdown(defaultValueBlock.content, apiItem); + const defaultValueContent: string = this.#renderMarkdown(defaultValueBlock.content, apiItem); if (defaultValueContent) { yamlItem.defaultValue = defaultValueContent.trim(); } @@ -442,7 +442,7 @@ export class YamlDocumenter { } if (tsdocComment.deprecatedBlock) { - const deprecatedMessage: string = this._renderMarkdown(tsdocComment.deprecatedBlock.content, apiItem); + const deprecatedMessage: string = this.#renderMarkdown(tsdocComment.deprecatedBlock.content, apiItem); if (deprecatedMessage.length > 0) { yamlItem.deprecated = { content: deprecatedMessage }; } @@ -455,11 +455,11 @@ export class YamlDocumenter { } } - yamlItem.name = this._getYamlItemName(apiItem, { + yamlItem.name = this.#getYamlItemName(apiItem, { includeSignature: true, includeNamespace: !this.newDocfxNamespaces }); - yamlItem.fullName = this._getYamlItemName(apiItem, { includeSignature: true, includeNamespace: true }); + yamlItem.fullName = this.#getYamlItemName(apiItem, { includeSignature: true, includeNamespace: true }); yamlItem.langs = ['typeScript']; // Add the namespace of the item if it is contained in one. @@ -488,21 +488,21 @@ export class YamlDocumenter { break; case ApiItemKind.Class: yamlItem.type = 'class'; - this._populateYamlClassOrInterface(uid, yamlItem, apiItem as ApiClass); + this.#populateYamlClassOrInterface(uid, yamlItem, apiItem as ApiClass); break; case ApiItemKind.Interface: yamlItem.type = 'interface'; - this._populateYamlClassOrInterface(uid, yamlItem, apiItem as ApiInterface); + this.#populateYamlClassOrInterface(uid, yamlItem, apiItem as ApiInterface); break; case ApiItemKind.Method: case ApiItemKind.MethodSignature: yamlItem.type = 'method'; - this._populateYamlFunctionLike(uid, yamlItem, apiItem as ApiMethod | ApiMethodSignature); + this.#populateYamlFunctionLike(uid, yamlItem, apiItem as ApiMethod | ApiMethodSignature); break; case ApiItemKind.Constructor: yamlItem.type = 'constructor'; - this._populateYamlFunctionLike(uid, yamlItem, apiItem as ApiConstructor); + this.#populateYamlFunctionLike(uid, yamlItem, apiItem as ApiConstructor); break; case ApiItemKind.Package: @@ -519,22 +519,22 @@ export class YamlDocumenter { } else { yamlItem.type = 'property'; } - this._populateYamlProperty(uid, yamlItem, apiProperty); + this.#populateYamlProperty(uid, yamlItem, apiProperty); break; case ApiItemKind.Function: yamlItem.type = 'function'; - this._populateYamlFunctionLike(uid, yamlItem, apiItem as ApiFunction); + this.#populateYamlFunctionLike(uid, yamlItem, apiItem as ApiFunction); break; case ApiItemKind.Variable: yamlItem.type = 'variable'; - this._populateYamlVariable(uid, yamlItem, apiItem as ApiVariable); + this.#populateYamlVariable(uid, yamlItem, apiItem as ApiVariable); break; case ApiItemKind.TypeAlias: yamlItem.type = 'typealias'; - this._populateYamlTypeAlias(uid, yamlItem, apiItem as ApiTypeAlias); + this.#populateYamlTypeAlias(uid, yamlItem, apiItem as ApiTypeAlias); break; default: @@ -552,7 +552,7 @@ export class YamlDocumenter { return yamlItem as IYamlItem; } - private _populateYamlTypeParameters( + #populateYamlTypeParameters( contextUid: DeclarationReference, apiItem: ApiTypeParameterListMixin ): IYamlParameter[] { @@ -563,14 +563,14 @@ export class YamlDocumenter { }; if (apiTypeParameter.tsdocTypeParamBlock) { - typeParameter.description = this._renderMarkdown( + typeParameter.description = this.#renderMarkdown( apiTypeParameter.tsdocTypeParamBlock.content, apiItem ); } if (!apiTypeParameter.constraintExcerpt.isEmpty) { - typeParameter.type = [this._renderType(contextUid, apiTypeParameter.constraintExcerpt)]; + typeParameter.type = [this.#renderType(contextUid, apiTypeParameter.constraintExcerpt)]; } typeParameters.push(typeParameter); @@ -578,32 +578,32 @@ export class YamlDocumenter { return typeParameters; } - private _populateYamlClassOrInterface( + #populateYamlClassOrInterface( uid: DeclarationReference, yamlItem: Partial, apiItem: ApiClass | ApiInterface ): void { if (apiItem instanceof ApiClass) { if (apiItem.extendsType) { - yamlItem.extends = [this._renderType(uid, apiItem.extendsType.excerpt)]; - yamlItem.inheritance = this._renderInheritance(uid, [apiItem.extendsType]); + yamlItem.extends = [this.#renderType(uid, apiItem.extendsType.excerpt)]; + yamlItem.inheritance = this.#renderInheritance(uid, [apiItem.extendsType]); } if (apiItem.implementsTypes.length > 0) { yamlItem.implements = []; for (const implementsType of apiItem.implementsTypes) { - yamlItem.implements.push(this._renderType(uid, implementsType.excerpt)); + yamlItem.implements.push(this.#renderType(uid, implementsType.excerpt)); } } } else if (apiItem instanceof ApiInterface) { if (apiItem.extendsTypes.length > 0) { yamlItem.extends = []; for (const extendsType of apiItem.extendsTypes) { - yamlItem.extends.push(this._renderType(uid, extendsType.excerpt)); + yamlItem.extends.push(this.#renderType(uid, extendsType.excerpt)); } - yamlItem.inheritance = this._renderInheritance(uid, apiItem.extendsTypes); + yamlItem.inheritance = this.#renderInheritance(uid, apiItem.extendsTypes); } - const typeParameters: IYamlParameter[] = this._populateYamlTypeParameters(uid, apiItem); + const typeParameters: IYamlParameter[] = this.#populateYamlTypeParameters(uid, apiItem); if (typeParameters.length) { yamlItem.syntax = { typeParameters }; } @@ -626,7 +626,7 @@ export class YamlDocumenter { } } - private _populateYamlFunctionLike( + #populateYamlFunctionLike( uid: DeclarationReference, yamlItem: Partial, apiItem: ApiMethod | ApiMethodSignature | ApiConstructor | ApiFunction @@ -637,12 +637,12 @@ export class YamlDocumenter { yamlItem.syntax = syntax; if (ApiReturnTypeMixin.isBaseClassOf(apiItem)) { - const returnType: string = this._renderType(uid, apiItem.returnTypeExcerpt); + const returnType: string = this.#renderType(uid, apiItem.returnTypeExcerpt); let returnDescription: string = ''; if (apiItem.tsdocComment && apiItem.tsdocComment.returnsBlock) { - returnDescription = this._renderMarkdown(apiItem.tsdocComment.returnsBlock.content, apiItem); + returnDescription = this.#renderMarkdown(apiItem.tsdocComment.returnsBlock.content, apiItem); // temporary workaround for people who mistakenly add a hyphen, e.g. "@returns - blah" returnDescription = returnDescription.replace(/^\s*-\s+/, ''); } @@ -659,13 +659,13 @@ export class YamlDocumenter { for (const apiParameter of apiItem.parameters) { let parameterDescription: string = ''; if (apiParameter.tsdocParamBlock) { - parameterDescription = this._renderMarkdown(apiParameter.tsdocParamBlock.content, apiItem); + parameterDescription = this.#renderMarkdown(apiParameter.tsdocParamBlock.content, apiItem); } parameters.push({ id: apiParameter.name, description: parameterDescription, - type: [this._renderType(uid, apiParameter.parameterTypeExcerpt)], + type: [this.#renderType(uid, apiParameter.parameterTypeExcerpt)], optional: apiParameter.isOptional } as IYamlParameter); } @@ -675,14 +675,14 @@ export class YamlDocumenter { } if (ApiTypeParameterListMixin.isBaseClassOf(apiItem)) { - const typeParameters: IYamlParameter[] = this._populateYamlTypeParameters(uid, apiItem); + const typeParameters: IYamlParameter[] = this.#populateYamlTypeParameters(uid, apiItem); if (typeParameters.length) { syntax.typeParameters = typeParameters; } } } - private _populateYamlProperty( + #populateYamlProperty( uid: DeclarationReference, yamlItem: Partial, apiItem: ApiPropertyItem @@ -694,12 +694,12 @@ export class YamlDocumenter { if (apiItem.propertyTypeExcerpt.text) { syntax.return = { - type: [this._renderType(uid, apiItem.propertyTypeExcerpt)] + type: [this.#renderType(uid, apiItem.propertyTypeExcerpt)] }; } } - private _populateYamlVariable( + #populateYamlVariable( uid: DeclarationReference, yamlItem: Partial, apiItem: ApiVariable @@ -711,12 +711,12 @@ export class YamlDocumenter { if (apiItem.variableTypeExcerpt.text) { syntax.return = { - type: [this._renderType(uid, apiItem.variableTypeExcerpt)] + type: [this.#renderType(uid, apiItem.variableTypeExcerpt)] }; } } - private _populateYamlTypeAlias( + #populateYamlTypeAlias( uid: DeclarationReference, yamlItem: Partial, apiItem: ApiTypeAlias @@ -726,19 +726,19 @@ export class YamlDocumenter { }; yamlItem.syntax = syntax; - const typeParameters: IYamlParameter[] = this._populateYamlTypeParameters(uid, apiItem); + const typeParameters: IYamlParameter[] = this.#populateYamlTypeParameters(uid, apiItem); if (typeParameters.length) { syntax.typeParameters = typeParameters; } if (apiItem.typeExcerpt.text) { syntax.return = { - type: [this._renderType(uid, apiItem.typeExcerpt)] + type: [this.#renderType(uid, apiItem.typeExcerpt)] }; } } - private _renderMarkdown(docSection: DocSection, contextApiItem: ApiItem): string { + #renderMarkdown(docSection: DocSection, contextApiItem: ApiItem): string { const stringBuilder: StringBuilder = new StringBuilder(); this.#markdownEmitter.emit(stringBuilder, docSection, { @@ -762,7 +762,7 @@ export class YamlDocumenter { return stringBuilder.toString().trim(); } - private _writeYamlFile( + #writeYamlFile( dataObject: {}, filePath: string, yamlMimeType: string, @@ -803,14 +803,14 @@ export class YamlDocumenter { /** * Initialize the _apiItemsByCanonicalReference data structure. */ - private _initApiItems(): void { - this._initApiItemsRecursive(this.#apiModel); + #initApiItems(): void { + this.#initApiItemsRecursive(this.#apiModel); } /** * Helper for _initApiItems() */ - private _initApiItemsRecursive(apiItem: ApiItem): void { + #initApiItemsRecursive(apiItem: ApiItem): void { if (apiItem.canonicalReference && !apiItem.canonicalReference.isEmpty) { this.#apiItemsByCanonicalReference.set(apiItem.canonicalReference.toString(), apiItem); } @@ -818,12 +818,12 @@ export class YamlDocumenter { // Recurse container members if (ApiItemContainerMixin.isBaseClassOf(apiItem)) { for (const apiMember of apiItem.members) { - this._initApiItemsRecursive(apiMember); + this.#initApiItemsRecursive(apiMember); } } } - private _ensureYamlReferences(): IYamlReferences { + #ensureYamlReferences(): IYamlReferences { if (!this.#yamlReferences) { this.#yamlReferences = { references: [], @@ -834,25 +834,25 @@ export class YamlDocumenter { return this.#yamlReferences; } - private _renderInheritance( + #renderInheritance( contextUid: DeclarationReference, heritageTypes: ReadonlyArray ): IYamlInheritanceTree[] { const result: IYamlInheritanceTree[] = []; for (const heritageType of heritageTypes) { - const type: string = this._renderType(contextUid, heritageType.excerpt); + const type: string = this.#renderType(contextUid, heritageType.excerpt); const yamlInheritance: IYamlInheritanceTree = { type }; const apiItem: ApiItem | undefined = this.#apiItemsByCanonicalReference.get(type); if (apiItem) { if (apiItem instanceof ApiClass) { if (apiItem.extendsType) { - yamlInheritance.inheritance = this._renderInheritance(this._getUidObject(apiItem), [ + yamlInheritance.inheritance = this.#renderInheritance(this._getUidObject(apiItem), [ apiItem.extendsType ]); } } else if (apiItem instanceof ApiInterface) { if (apiItem.extendsTypes.length > 0) { - yamlInheritance.inheritance = this._renderInheritance( + yamlInheritance.inheritance = this.#renderInheritance( this._getUidObject(apiItem), apiItem.extendsTypes ); @@ -864,7 +864,7 @@ export class YamlDocumenter { return result; } - private _renderType(contextUid: DeclarationReference, typeExcerpt: Excerpt): string { + #renderType(contextUid: DeclarationReference, typeExcerpt: Excerpt): string { const excerptTokens: ExcerptToken[] = [...typeExcerpt.spannedTokens]; // copy the read-only array if (excerptTokens.length === 0) { @@ -887,7 +887,7 @@ export class YamlDocumenter { return typeName; } - const yamlReferences: IYamlReferences = this._ensureYamlReferences(); + const yamlReferences: IYamlReferences = this.#ensureYamlReferences(); const existingUid: string | undefined = yamlReferences.typeNameToUid.get(typeName); // If this type has already been referenced for the current file, return its uid. @@ -903,11 +903,11 @@ export class YamlDocumenter { ) { const excerptRef: string = excerptTokens[0].canonicalReference.toString(); const apiItem: ApiItem | undefined = this.#apiItemsByCanonicalReference.get(excerptRef); - return this._recordYamlReference( + return this.#recordYamlReference( yamlReferences, excerptTokens[0].canonicalReference.toString(), - apiItem ? this._getYamlItemName(apiItem) : typeName, - apiItem ? this._getYamlItemName(apiItem, { includeNamespace: true }) : typeName + apiItem ? this.#getYamlItemName(apiItem) : typeName, + apiItem ? this.#getYamlItemName(apiItem, { includeNamespace: true }) : typeName ); } @@ -926,10 +926,10 @@ export class YamlDocumenter { .withOverloadIndex(undefined) .toString(); - return this._recordYamlReference(yamlReferences, uid, typeName, typeName, excerptTokens); + return this.#recordYamlReference(yamlReferences, uid, typeName, typeName, excerptTokens); } - private _recordYamlReference( + #recordYamlReference( yamlReferences: IYamlReferences, uid: string, name: string, @@ -997,7 +997,7 @@ export class YamlDocumenter { return uid; } - private _getYamlItemName(apiItem: ApiItem, options: INameOptions = {}): string { + #getYamlItemName(apiItem: ApiItem, options: INameOptions = {}): string { const { includeSignature, includeNamespace } = options; const baseName: string = includeSignature ? Utilities.getConciseSignature(apiItem) : apiItem.displayName; if ( @@ -1047,7 +1047,7 @@ export class YamlDocumenter { } } - private _getYamlFilePath(outputFolder: string, apiItem: ApiItem): string { + #getYamlFilePath(outputFolder: string, apiItem: ApiItem): string { let result: string = ''; for (const current of apiItem.getHierarchy()) { @@ -1077,7 +1077,7 @@ export class YamlDocumenter { return path.join(outputFolder, result + disambiguator + '.yml'); } - private _deleteOldOutputFiles(outputFolder: string): void { + #deleteOldOutputFiles(outputFolder: string): void { console.log('Deleting old output from ' + outputFolder); FileSystem.ensureEmptyFolder(outputFolder); } diff --git a/apps/api-documenter/src/utils/IndentedWriter.ts b/apps/api-documenter/src/utils/IndentedWriter.ts index 3b583118b19..706ba4ee831 100644 --- a/apps/api-documenter/src/utils/IndentedWriter.ts +++ b/apps/api-documenter/src/utils/IndentedWriter.ts @@ -83,7 +83,7 @@ export class IndentedWriter { */ public increaseIndent(indentPrefix?: string): void { this.#indentStack.push(indentPrefix !== undefined ? indentPrefix : this.defaultIndentPrefix); - this._updateIndentText(); + this.#updateIndentText(); } /** @@ -92,7 +92,7 @@ export class IndentedWriter { */ public decreaseIndent(): void { this.#indentStack.pop(); - this._updateIndentText(); + this.#updateIndentText(); } /** @@ -111,7 +111,7 @@ export class IndentedWriter { public ensureNewLine(): void { const lastCharacter: string = this.peekLastCharacter(); if (lastCharacter !== '\n' && lastCharacter !== '') { - this._writeNewLine(); + this.#writeNewLine(); } } @@ -120,12 +120,12 @@ export class IndentedWriter { */ public ensureSkippedLine(): void { if (this.peekLastCharacter() !== '\n') { - this._writeNewLine(); + this.#writeNewLine(); } const secondLastCharacter: string = this.peekSecondLastCharacter(); if (secondLastCharacter !== '\n' && secondLastCharacter !== '') { - this._writeNewLine(); + this.#writeNewLine(); } } @@ -190,12 +190,12 @@ export class IndentedWriter { } if (!this.#isWritingBeforeStack) { - this._writeBeforeStack(); + this.#writeBeforeStack(); } // If there are no newline characters, then append the string verbatim if (!/[\r\n]/.test(message)) { - this._writeLinePart(message); + this.#writeLinePart(message); return; } @@ -203,12 +203,12 @@ export class IndentedWriter { let first: boolean = true; for (const linePart of message.split('\n')) { if (!first) { - this._writeNewLine(); + this.#writeNewLine(); } else { first = false; } if (linePart) { - this._writeLinePart(linePart.replace(/[\r]/g, '')); + this.#writeLinePart(linePart.replace(/[\r]/g, '')); } } } @@ -221,35 +221,35 @@ export class IndentedWriter { if (message.length > 0) { this.write(message); } else if (!this.#isWritingBeforeStack) { - this._writeBeforeStack(); + this.#writeBeforeStack(); } - this._writeNewLine(); + this.#writeNewLine(); } /** * Writes a string that does not contain any newline characters. */ - private _writeLinePart(message: string): void { + #writeLinePart(message: string): void { if (message.length > 0) { if (this.#atStartOfLine && this.#indentText.length > 0) { - this._write(this.#indentText); + this.#write(this.#indentText); } - this._write(message); + this.#write(message); this.#atStartOfLine = false; } } - private _writeNewLine(): void { + #writeNewLine(): void { if (this.#atStartOfLine && this.#indentText.length > 0) { - this._write(this.#indentText); + this.#write(this.#indentText); } - this._write('\n'); + this.#write('\n'); this.#atStartOfLine = true; } - private _write(s: string): void { + #write(s: string): void { this.#previousChunk = this.#latestChunk; this.#latestChunk = s; this.#builder.append(s); @@ -259,7 +259,7 @@ export class IndentedWriter { * Writes all messages in our before stack, processing them in FIFO order. This stack is * populated by the `writeTentative` method. */ - private _writeBeforeStack(): void { + #writeBeforeStack(): void { this.#isWritingBeforeStack = true; for (const message of this.#beforeStack) { @@ -270,7 +270,7 @@ export class IndentedWriter { this.#beforeStack = []; } - private _updateIndentText(): void { + #updateIndentText(): void { this.#indentText = this.#indentStack.join(''); } } diff --git a/apps/api-extractor/src/analyzer/AstReferenceResolver.ts b/apps/api-extractor/src/analyzer/AstReferenceResolver.ts index 91aa924f69b..d381e5263cd 100644 --- a/apps/api-extractor/src/analyzer/AstReferenceResolver.ts +++ b/apps/api-extractor/src/analyzer/AstReferenceResolver.ts @@ -76,7 +76,7 @@ export class AstReferenceResolver { const rootMemberReference: tsdoc.DocMemberReference = declarationReference.memberReferences[0]; - const exportName: string | ResolverFailure = this._getMemberReferenceIdentifier(rootMemberReference); + const exportName: string | ResolverFailure = this.#getMemberReferenceIdentifier(rootMemberReference); if (exportName instanceof ResolverFailure) { return exportName; } @@ -96,7 +96,7 @@ export class AstReferenceResolver { return new ResolverFailure('This type of declaration is not supported yet by the resolver'); } - let currentDeclaration: AstDeclaration | ResolverFailure = this._selectDeclaration( + let currentDeclaration: AstDeclaration | ResolverFailure = this.#selectDeclaration( rootAstEntity.astDeclarations, rootMemberReference, rootAstEntity.localName @@ -109,7 +109,7 @@ export class AstReferenceResolver { for (let index: number = 1; index < declarationReference.memberReferences.length; ++index) { const memberReference: tsdoc.DocMemberReference = declarationReference.memberReferences[index]; - const memberName: string | ResolverFailure = this._getMemberReferenceIdentifier(memberReference); + const memberName: string | ResolverFailure = this.#getMemberReferenceIdentifier(memberReference); if (memberName instanceof ResolverFailure) { return memberName; } @@ -120,7 +120,7 @@ export class AstReferenceResolver { return new ResolverFailure(`No member was found with name "${memberName}"`); } - const selectedDeclaration: AstDeclaration | ResolverFailure = this._selectDeclaration( + const selectedDeclaration: AstDeclaration | ResolverFailure = this.#selectDeclaration( matchingChildren, memberReference, memberName @@ -136,7 +136,7 @@ export class AstReferenceResolver { return currentDeclaration; } - private _getMemberReferenceIdentifier(memberReference: tsdoc.DocMemberReference): string | ResolverFailure { + #getMemberReferenceIdentifier(memberReference: tsdoc.DocMemberReference): string | ResolverFailure { if (memberReference.memberSymbol !== undefined) { return new ResolverFailure('ECMAScript symbol selectors are not supported'); } @@ -146,7 +146,7 @@ export class AstReferenceResolver { return memberReference.memberIdentifier.identifier; } - private _selectDeclaration( + #selectDeclaration( astDeclarations: ReadonlyArray, memberReference: tsdoc.DocMemberReference, astSymbolName: string @@ -160,7 +160,7 @@ export class AstReferenceResolver { // If we found multiple matches, but the extra ones are all ancillary declarations, // then return the main declaration. const nonAncillaryMatch: AstDeclaration | undefined = - this._tryDisambiguateAncillaryMatches(astDeclarations); + this.#tryDisambiguateAncillaryMatches(astDeclarations); if (nonAncillaryMatch) { return nonAncillaryMatch; } @@ -174,15 +174,15 @@ export class AstReferenceResolver { switch (memberSelector.selectorKind) { case tsdoc.SelectorKind.System: - return this._selectUsingSystemSelector(astDeclarations, memberSelector, astSymbolName); + return this.#selectUsingSystemSelector(astDeclarations, memberSelector, astSymbolName); case tsdoc.SelectorKind.Index: - return this._selectUsingIndexSelector(astDeclarations, memberSelector, astSymbolName); + return this.#selectUsingIndexSelector(astDeclarations, memberSelector, astSymbolName); } return new ResolverFailure(`The selector "${memberSelector.selector}" is not a supported selector type`); } - private _selectUsingSystemSelector( + #selectUsingSystemSelector( astDeclarations: ReadonlyArray, memberSelector: tsdoc.DocMemberSelector, astSymbolName: string @@ -229,7 +229,7 @@ export class AstReferenceResolver { if (matches.length > 1) { // If we found multiple matches, but the extra ones are all ancillary declarations, // then return the main declaration. - const nonAncillaryMatch: AstDeclaration | undefined = this._tryDisambiguateAncillaryMatches(matches); + const nonAncillaryMatch: AstDeclaration | undefined = this.#tryDisambiguateAncillaryMatches(matches); if (nonAncillaryMatch) { return nonAncillaryMatch; } @@ -241,7 +241,7 @@ export class AstReferenceResolver { return matches[0]; } - private _selectUsingIndexSelector( + #selectUsingIndexSelector( astDeclarations: ReadonlyArray, memberSelector: tsdoc.DocMemberSelector, astSymbolName: string @@ -265,7 +265,7 @@ export class AstReferenceResolver { if (matches.length > 1) { // If we found multiple matches, but the extra ones are all ancillary declarations, // then return the main declaration. - const nonAncillaryMatch: AstDeclaration | undefined = this._tryDisambiguateAncillaryMatches(matches); + const nonAncillaryMatch: AstDeclaration | undefined = this.#tryDisambiguateAncillaryMatches(matches); if (nonAncillaryMatch) { return nonAncillaryMatch; } @@ -282,7 +282,7 @@ export class AstReferenceResolver { * This resolves an ambiguous match in the case where the extra matches are all ancillary declarations, * except for one match that is the main declaration. */ - private _tryDisambiguateAncillaryMatches( + #tryDisambiguateAncillaryMatches( matches: ReadonlyArray ): AstDeclaration | undefined { let result: AstDeclaration | undefined = undefined; diff --git a/apps/api-extractor/src/analyzer/AstSymbolTable.ts b/apps/api-extractor/src/analyzer/AstSymbolTable.ts index 6f48e5bb2aa..b135f5b0a5a 100644 --- a/apps/api-extractor/src/analyzer/AstSymbolTable.ts +++ b/apps/api-extractor/src/analyzer/AstSymbolTable.ts @@ -109,7 +109,7 @@ export class AstSymbolTable { this.#exportAnalyzer = new ExportAnalyzer(this.#program, this.#typeChecker, bundledPackageNames, { analyze: this.analyze.bind(this), - fetchAstSymbol: this._fetchAstSymbol.bind(this) + fetchAstSymbol: this.#fetchAstSymbol.bind(this) }); this.#alreadyWarnedGlobalNames = new Set(); @@ -152,11 +152,11 @@ export class AstSymbolTable { */ public analyze(astEntity: AstEntity): void { if (astEntity instanceof AstSymbol) { - return this._analyzeAstSymbol(astEntity); + return this.#analyzeAstSymbol(astEntity); } if (astEntity instanceof AstNamespaceImport) { - return this._analyzeAstNamespaceImport(astEntity); + return this.#analyzeAstNamespaceImport(astEntity); } } @@ -277,7 +277,7 @@ export class AstSymbolTable { return unquotedName; } - private _analyzeAstNamespaceImport(astNamespaceImport: AstNamespaceImport): void { + #analyzeAstNamespaceImport(astNamespaceImport: AstNamespaceImport): void { if (astNamespaceImport.analyzed) { return; } @@ -294,7 +294,7 @@ export class AstSymbolTable { } } - private _analyzeAstSymbol(astSymbol: AstSymbol): void { + #analyzeAstSymbol(astSymbol: AstSymbol): void { if (astSymbol.analyzed) { return; } @@ -310,7 +310,7 @@ export class AstSymbolTable { // Calculate the full child tree for each definition for (const astDeclaration of rootAstSymbol.astDeclarations) { - this._analyzeChildTree(astDeclaration.declaration, astDeclaration); + this.#analyzeChildTree(astDeclaration.declaration, astDeclaration); } rootAstSymbol._notifyAnalyzed(); @@ -324,13 +324,13 @@ export class AstSymbolTable { // Walk up to the root of the tree, looking for any imports along the way if (referencedAstEntity instanceof AstSymbol) { if (!referencedAstEntity.isExternal) { - this._analyzeAstSymbol(referencedAstEntity); + this.#analyzeAstSymbol(referencedAstEntity); } } if (referencedAstEntity instanceof AstNamespaceImport) { if (!referencedAstEntity.astModule.isExternal) { - this._analyzeAstNamespaceImport(referencedAstEntity); + this.#analyzeAstNamespaceImport(referencedAstEntity); } } } @@ -341,7 +341,7 @@ export class AstSymbolTable { /** * Used by analyze to recursively analyze the entire child tree. */ - private _analyzeChildTree(node: ts.Node, governingAstDeclaration: AstDeclaration): void { + #analyzeChildTree(node: ts.Node, governingAstDeclaration: AstDeclaration): void { switch (node.kind) { case ts.SyntaxKind.JSDocComment: // Skip JSDoc comments - TS considers @param tags TypeReference nodes return; @@ -433,7 +433,7 @@ export class AstSymbolTable { let referencedAstEntity: AstEntity | undefined = undefined; if (symbol === governingAstDeclaration.astSymbol.followedSymbol) { - referencedAstEntity = this._fetchEntityForNode(identifierNode, governingAstDeclaration); + referencedAstEntity = this.#fetchEntityForNode(identifierNode, governingAstDeclaration); } this.#entitiesByNode.set(identifierNode, referencedAstEntity); @@ -447,7 +447,7 @@ export class AstSymbolTable { let referencedAstEntity: AstEntity | undefined = this.#entitiesByNode.get(importTypeNode); if (!this.#entitiesByNode.has(importTypeNode)) { - referencedAstEntity = this._fetchEntityForNode(importTypeNode, governingAstDeclaration); + referencedAstEntity = this.#fetchEntityForNode(importTypeNode, governingAstDeclaration); if (!referencedAstEntity) { // This should never happen @@ -465,17 +465,17 @@ export class AstSymbolTable { } // Is this node declaring a new AstSymbol? - const newGoverningAstDeclaration: AstDeclaration | undefined = this._fetchAstDeclaration( + const newGoverningAstDeclaration: AstDeclaration | undefined = this.#fetchAstDeclaration( node, governingAstDeclaration.astSymbol.isExternal ); for (const childNode of node.getChildren()) { - this._analyzeChildTree(childNode, newGoverningAstDeclaration || governingAstDeclaration); + this.#analyzeChildTree(childNode, newGoverningAstDeclaration || governingAstDeclaration); } } - private _fetchEntityForNode( + #fetchEntityForNode( node: ts.Identifier | ts.ImportTypeNode, governingAstDeclaration: AstDeclaration ): AstEntity | undefined { @@ -503,7 +503,7 @@ export class AstSymbolTable { return referencedAstEntity; } - private _fetchAstDeclaration(node: ts.Node, isExternal: boolean): AstDeclaration | undefined { + #fetchAstDeclaration(node: ts.Node, isExternal: boolean): AstDeclaration | undefined { if (!AstDeclaration.isSupportedSyntaxKind(node.kind)) { return undefined; } @@ -516,7 +516,7 @@ export class AstSymbolTable { throw new InternalError('Unable to find symbol for node'); } - const astSymbol: AstSymbol | undefined = this._fetchAstSymbol({ + const astSymbol: AstSymbol | undefined = this.#fetchAstSymbol({ followedSymbol: symbol, isExternal: isExternal, includeNominalAnalysis: true, @@ -536,7 +536,7 @@ export class AstSymbolTable { return astDeclaration; } - private _fetchAstSymbol(options: IFetchAstSymbolOptions): AstSymbol | undefined { + #fetchAstSymbol(options: IFetchAstSymbolOptions): AstSymbol | undefined { const followedSymbol: ts.Symbol = options.followedSymbol; // Filter out symbols representing constructs that we don't care about @@ -618,7 +618,7 @@ export class AstSymbolTable { // Is there a parent AstSymbol? First we check to see if there is a parent declaration: if (arbitraryDeclaration) { const arbitraryParentDeclaration: ts.Node | undefined = - this._tryFindFirstAstDeclarationParent(arbitraryDeclaration); + this.#tryFindFirstAstDeclarationParent(arbitraryDeclaration); if (arbitraryParentDeclaration) { const parentSymbol: ts.Symbol = TypeScriptHelpers.getSymbolForDeclaration( @@ -626,7 +626,7 @@ export class AstSymbolTable { this.#typeChecker ); - parentAstSymbol = this._fetchAstSymbol({ + parentAstSymbol = this.#fetchAstSymbol({ followedSymbol: parentSymbol, isExternal: options.isExternal, includeNominalAnalysis: false, @@ -658,7 +658,7 @@ export class AstSymbolTable { for (const declaration of followedSymbol.declarations || []) { let parentAstDeclaration: AstDeclaration | undefined = undefined; if (parentAstSymbol) { - const parentDeclaration: ts.Node | undefined = this._tryFindFirstAstDeclarationParent(declaration); + const parentDeclaration: ts.Node | undefined = this.#tryFindFirstAstDeclarationParent(declaration); if (!parentDeclaration) { throw new InternalError('Missing parent declaration'); @@ -694,7 +694,7 @@ export class AstSymbolTable { /** * Returns the first parent satisfying isAstDeclaration(), or undefined if none is found. */ - private _tryFindFirstAstDeclarationParent(node: ts.Node): ts.Node | undefined { + #tryFindFirstAstDeclarationParent(node: ts.Node): ts.Node | undefined { let currentNode: ts.Node | undefined = node.parent; while (currentNode) { if (AstDeclaration.isSupportedSyntaxKind(currentNode.kind)) { diff --git a/apps/api-extractor/src/analyzer/ExportAnalyzer.ts b/apps/api-extractor/src/analyzer/ExportAnalyzer.ts index 2d92e1c32c6..ee5866578af 100644 --- a/apps/api-extractor/src/analyzer/ExportAnalyzer.ts +++ b/apps/api-extractor/src/analyzer/ExportAnalyzer.ts @@ -95,7 +95,7 @@ export class ExportAnalyzer { moduleReference: IAstModuleReference | undefined, isExternal: boolean ): AstModule { - const moduleSymbol: ts.Symbol = this._getModuleSymbolFromSourceFile(sourceFile, moduleReference); + const moduleSymbol: ts.Symbol = this.#getModuleSymbolFromSourceFile(sourceFile, moduleReference); // Don't traverse into a module that we already processed before: // The compiler allows m1 to have "export * from 'm2'" and "export * from 'm3'", @@ -157,7 +157,7 @@ export class ExportAnalyzer { if (exportStarSymbol) { for (const exportStarDeclaration of exportStarSymbol.getDeclarations() || []) { if (ts.isExportDeclaration(exportStarDeclaration)) { - const starExportedModule: AstModule | undefined = this._fetchSpecifierAstModule( + const starExportedModule: AstModule | undefined = this.#fetchSpecifierAstModule( exportStarDeclaration, exportStarSymbol ); @@ -186,7 +186,7 @@ export class ExportAnalyzer { * (This is a deprecated construct and mainly used for typings such as `@types/node`.) In this situation, * `moduleReference` helps us to fish out the correct module symbol. */ - private _getModuleSymbolFromSourceFile( + #getModuleSymbolFromSourceFile( sourceFile: ts.SourceFile, moduleReference: IAstModuleReference | undefined ): ts.Symbol { @@ -250,7 +250,7 @@ export class ExportAnalyzer { starExportedExternalModules: new Set() }; - this._collectAllExportsRecursive(astModuleExportInfo, entryPointAstModule); + this.#collectAllExportsRecursive(astModuleExportInfo, entryPointAstModule); entryPointAstModule.astModuleExportInfo = astModuleExportInfo; } @@ -261,7 +261,7 @@ export class ExportAnalyzer { * Returns true if the module specifier refers to an external package. Ignores packages listed in the * "bundledPackages" setting from the api-extractor.json config file. */ - private _isExternalModulePath( + #isExternalModulePath( importOrExportDeclaration: ts.ImportDeclaration | ts.ExportDeclaration | ts.ImportTypeNode, moduleSpecifier: string ): boolean { @@ -322,7 +322,7 @@ export class ExportAnalyzer { return this.#importableAmbientSourceFiles.has(sourceFile); } - private _collectAllExportsRecursive(astModuleExportInfo: IAstModuleExportInfo, astModule: AstModule): void { + #collectAllExportsRecursive(astModuleExportInfo: IAstModuleExportInfo, astModule: AstModule): void { const { visitedAstModules, starExportedExternalModules, exportedLocalEntities } = astModuleExportInfo; if (visitedAstModules.has(astModule)) { return; @@ -343,7 +343,7 @@ export class ExportAnalyzer { // Don't collect the "export default" symbol unless this is the entry point module if (exportName !== ts.InternalSymbolName.Default || visitedAstModules.size === 1) { if (!exportedLocalEntities.has(exportSymbol.name)) { - const astEntity: AstEntity = this._getExportOfAstModule(exportSymbol.name, astModule); + const astEntity: AstEntity = this.#getExportOfAstModule(exportSymbol.name, astModule); if (astEntity instanceof AstSymbol && !astEntity.isExternal) { this.#astSymbolTable.analyze(astEntity); @@ -362,7 +362,7 @@ export class ExportAnalyzer { } for (const starExportedModule of astModule.starExportedModules) { - this._collectAllExportsRecursive(astModuleExportInfo, starExportedModule); + this.#collectAllExportsRecursive(astModuleExportInfo, starExportedModule); } } } @@ -396,11 +396,11 @@ export class ExportAnalyzer { // Is this symbol an import/export that we need to follow to find the real declaration? for (const declaration of current.declarations || []) { let matchedAstEntity: AstEntity | undefined; - matchedAstEntity = this._tryMatchExportDeclaration(declaration, current); + matchedAstEntity = this.#tryMatchExportDeclaration(declaration, current); if (matchedAstEntity !== undefined) { return matchedAstEntity; } - matchedAstEntity = this._tryMatchImportDeclaration(declaration, current); + matchedAstEntity = this.#tryMatchImportDeclaration(declaration, current); if (matchedAstEntity !== undefined) { return matchedAstEntity; } @@ -439,7 +439,7 @@ export class ExportAnalyzer { node: ts.ImportTypeNode, referringModuleIsExternal: boolean ): AstEntity | undefined { - const externalModulePath: string | undefined = this._tryGetExternalModulePath(node); + const externalModulePath: string | undefined = this.#tryGetExternalModulePath(node); if (externalModulePath) { let exportName: string; @@ -460,7 +460,7 @@ export class ExportAnalyzer { exportName = SyntaxHelpers.makeCamelCaseIdentifier(externalModulePath); } - return this._fetchAstImport(undefined, { + return this.#fetchAstImport(undefined, { importKind: AstImportKind.ImportType, exportName: exportName, modulePath: externalModulePath, @@ -528,7 +528,7 @@ export class ExportAnalyzer { return astSymbol; } - private _tryMatchExportDeclaration( + #tryMatchExportDeclaration( declaration: ts.Declaration, declarationSymbol: ts.Symbol ): AstEntity | undefined { @@ -573,8 +573,8 @@ export class ExportAnalyzer { // Issue tracking this feature: https://github.com/microsoft/rushstack/issues/2780 - const astModule: AstModule = this._fetchSpecifierAstModule(exportDeclaration, declarationSymbol); - return this._getAstNamespaceExport(astModule, declarationSymbol, declaration); + const astModule: AstModule = this.#fetchSpecifierAstModule(exportDeclaration, declarationSymbol); + return this.#getAstNamespaceExport(astModule, declarationSymbol, declaration); } else { throw new InternalError( `Unimplemented export declaration kind: ${declaration.getText()}\n` + @@ -584,10 +584,10 @@ export class ExportAnalyzer { // Ignore "export { A }" without a module specifier if (exportDeclaration.moduleSpecifier) { - const externalModulePath: string | undefined = this._tryGetExternalModulePath(exportDeclaration); + const externalModulePath: string | undefined = this.#tryGetExternalModulePath(exportDeclaration); if (externalModulePath !== undefined) { - return this._fetchAstImport(declarationSymbol, { + return this.#fetchAstImport(declarationSymbol, { importKind: AstImportKind.NamedImport, modulePath: externalModulePath, exportName: exportName, @@ -595,19 +595,19 @@ export class ExportAnalyzer { }); } - return this._getExportOfSpecifierAstModule(exportName, exportDeclaration, declarationSymbol); + return this.#getExportOfSpecifierAstModule(exportName, exportDeclaration, declarationSymbol); } } return undefined; } - private _getAstNamespaceExport( + #getAstNamespaceExport( astModule: AstModule, declarationSymbol: ts.Symbol, declaration: ts.Declaration ): AstNamespaceExport { - const imoprtNamespace: AstNamespaceImport = this._getAstNamespaceImport( + const imoprtNamespace: AstNamespaceImport = this.#getAstNamespaceImport( astModule, declarationSymbol, declaration @@ -621,7 +621,7 @@ export class ExportAnalyzer { }); } - private _tryMatchImportDeclaration( + #tryMatchImportDeclaration( declaration: ts.Declaration, declarationSymbol: ts.Symbol ): AstEntity | undefined { @@ -629,7 +629,7 @@ export class ExportAnalyzer { TypeScriptHelpers.findFirstParent(declaration, ts.SyntaxKind.ImportDeclaration); if (importDeclaration) { - const externalModulePath: string | undefined = this._tryGetExternalModulePath(importDeclaration); + const externalModulePath: string | undefined = this.#tryGetExternalModulePath(importDeclaration); if (declaration.kind === ts.SyntaxKind.NamespaceImport) { // EXAMPLE: @@ -647,13 +647,13 @@ export class ExportAnalyzer { // SemicolonToken: pre=[;] if (externalModulePath === undefined) { - const astModule: AstModule = this._fetchSpecifierAstModule(importDeclaration, declarationSymbol); - return this._getAstNamespaceImport(astModule, declarationSymbol, declaration); + const astModule: AstModule = this.#fetchSpecifierAstModule(importDeclaration, declarationSymbol); + return this.#getAstNamespaceImport(astModule, declarationSymbol, declaration); } // Here importSymbol=undefined because {@inheritDoc} and such are not going to work correctly for // a package or source file. - return this._fetchAstImport(undefined, { + return this.#fetchAstImport(undefined, { importKind: AstImportKind.StarImport, exportName: declarationSymbol.name, modulePath: externalModulePath, @@ -686,7 +686,7 @@ export class ExportAnalyzer { const exportName: string = (importSpecifier.propertyName || importSpecifier.name).getText().trim(); if (externalModulePath !== undefined) { - return this._fetchAstImport(declarationSymbol, { + return this.#fetchAstImport(declarationSymbol, { importKind: AstImportKind.NamedImport, modulePath: externalModulePath, exportName: exportName, @@ -694,7 +694,7 @@ export class ExportAnalyzer { }); } - return this._getExportOfSpecifierAstModule(exportName, importDeclaration, declarationSymbol); + return this.#getExportOfSpecifierAstModule(exportName, importDeclaration, declarationSymbol); } else if (declaration.kind === ts.SyntaxKind.ImportClause) { // EXAMPLE: // "import A, { B } from './A';" @@ -720,7 +720,7 @@ export class ExportAnalyzer { : ts.InternalSymbolName.Default; if (externalModulePath !== undefined) { - return this._fetchAstImport(declarationSymbol, { + return this.#fetchAstImport(declarationSymbol, { importKind: AstImportKind.DefaultImport, modulePath: externalModulePath, exportName, @@ -728,7 +728,7 @@ export class ExportAnalyzer { }); } - return this._getExportOfSpecifierAstModule( + return this.#getExportOfSpecifierAstModule( ts.InternalSymbolName.Default, importDeclaration, declarationSymbol @@ -762,7 +762,7 @@ export class ExportAnalyzer { declaration.moduleReference.expression ); - return this._fetchAstImport(declarationSymbol, { + return this.#fetchAstImport(declarationSymbol, { importKind: AstImportKind.EqualsImport, modulePath: externalModuleName, exportName: variableName, @@ -775,7 +775,7 @@ export class ExportAnalyzer { return undefined; } - private _getAstNamespaceImport( + #getAstNamespaceImport( astModule: AstModule, declarationSymbol: ts.Symbol, declaration: ts.Declaration @@ -794,22 +794,22 @@ export class ExportAnalyzer { return namespaceImport; } - private _getExportOfSpecifierAstModule( + #getExportOfSpecifierAstModule( exportName: string, importOrExportDeclaration: ts.ImportDeclaration | ts.ExportDeclaration, exportSymbol: ts.Symbol ): AstEntity { - const specifierAstModule: AstModule = this._fetchSpecifierAstModule( + const specifierAstModule: AstModule = this.#fetchSpecifierAstModule( importOrExportDeclaration, exportSymbol ); - const astEntity: AstEntity = this._getExportOfAstModule(exportName, specifierAstModule); + const astEntity: AstEntity = this.#getExportOfAstModule(exportName, specifierAstModule); return astEntity; } - private _getExportOfAstModule(exportName: string, astModule: AstModule): AstEntity { + #getExportOfAstModule(exportName: string, astModule: AstModule): AstEntity { const visitedAstModules: Set = new Set(); - const astEntity: AstEntity | undefined = this._tryGetExportOfAstModule( + const astEntity: AstEntity | undefined = this.#tryGetExportOfAstModule( exportName, astModule, visitedAstModules @@ -827,10 +827,10 @@ export class ExportAnalyzer { */ public tryGetExportOfAstModule(exportName: string, astModule: AstModule): AstEntity | undefined { const visitedAstModules: Set = new Set(); - return this._tryGetExportOfAstModule(exportName, astModule, visitedAstModules); + return this.#tryGetExportOfAstModule(exportName, astModule, visitedAstModules); } - private _tryGetExportOfAstModule( + #tryGetExportOfAstModule( exportName: string, astModule: AstModule, visitedAstModules: Set @@ -861,13 +861,13 @@ export class ExportAnalyzer { // Try each of the star imports for (const starExportedModule of astModule.starExportedModules) { - astEntity = this._tryGetExportOfAstModule(exportName, starExportedModule, visitedAstModules); + astEntity = this.#tryGetExportOfAstModule(exportName, starExportedModule, visitedAstModules); if (astEntity !== undefined) { if (starExportedModule.externalModulePath !== undefined) { // This entity was obtained from an external module, so return an AstImport instead const astSymbol: AstSymbol = astEntity as AstSymbol; - return this._fetchAstImport(astSymbol.followedSymbol, { + return this.#fetchAstImport(astSymbol.followedSymbol, { importKind: AstImportKind.NamedImport, modulePath: starExportedModule.externalModulePath, exportName: exportName, @@ -882,11 +882,11 @@ export class ExportAnalyzer { return undefined; } - private _tryGetExternalModulePath( + #tryGetExternalModulePath( importOrExportDeclaration: ts.ImportDeclaration | ts.ExportDeclaration | ts.ImportTypeNode ): string | undefined { - const moduleSpecifier: string = this._getModuleSpecifier(importOrExportDeclaration); - if (this._isExternalModulePath(importOrExportDeclaration, moduleSpecifier)) { + const moduleSpecifier: string = this.#getModuleSpecifier(importOrExportDeclaration); + if (this.#isExternalModulePath(importOrExportDeclaration, moduleSpecifier)) { return moduleSpecifier; } @@ -897,11 +897,11 @@ export class ExportAnalyzer { * Given an ImportDeclaration of the form `export { X } from "___";`, this interprets the module specifier (`"___"`) * and fetches the corresponding AstModule object. */ - private _fetchSpecifierAstModule( + #fetchSpecifierAstModule( importOrExportDeclaration: ts.ImportDeclaration | ts.ExportDeclaration, exportSymbol: ts.Symbol ): AstModule { - const moduleSpecifier: string = this._getModuleSpecifier(importOrExportDeclaration); + const moduleSpecifier: string = this.#getModuleSpecifier(importOrExportDeclaration); const mode: ts.ModuleKind.CommonJS | ts.ModuleKind.ESNext | undefined = importOrExportDeclaration.moduleSpecifier && ts.isStringLiteralLike(importOrExportDeclaration.moduleSpecifier) @@ -944,7 +944,7 @@ export class ExportAnalyzer { ); } - const isExternal: boolean = this._isExternalModulePath(importOrExportDeclaration, moduleSpecifier); + const isExternal: boolean = this.#isExternalModulePath(importOrExportDeclaration, moduleSpecifier); const moduleReference: IAstModuleReference = { moduleSpecifier: moduleSpecifier, moduleSpecifierSymbol: exportSymbol @@ -958,7 +958,7 @@ export class ExportAnalyzer { return specifierAstModule; } - private _fetchAstImport(importSymbol: ts.Symbol | undefined, options: IAstImportOptions): AstImport { + #fetchAstImport(importSymbol: ts.Symbol | undefined, options: IAstImportOptions): AstImport { const key: string = AstImport.getKey(options); let astImport: AstImport | undefined = this.#astImportsByKey.get(key); @@ -988,7 +988,7 @@ export class ExportAnalyzer { return astImport; } - private _getModuleSpecifier( + #getModuleSpecifier( importOrExportDeclaration: ts.ImportDeclaration | ts.ExportDeclaration | ts.ImportTypeNode ): string { // The name of the module, which could be like "./SomeLocalFile' or like 'external-package/entry/point' diff --git a/apps/api-extractor/src/analyzer/Span.ts b/apps/api-extractor/src/analyzer/Span.ts index d033c62829c..315daf04667 100644 --- a/apps/api-extractor/src/analyzer/Span.ts +++ b/apps/api-extractor/src/analyzer/Span.ts @@ -293,9 +293,9 @@ export class Span { public get prefix(): string { if (this.children.length) { // Everything up to the first child - return this._getSubstring(this.startIndex, this.children[0].startIndex); + return this.#getSubstring(this.startIndex, this.children[0].startIndex); } else { - return this._getSubstring(this.startIndex, this.endIndex); + return this.#getSubstring(this.startIndex, this.endIndex); } } @@ -306,7 +306,7 @@ export class Span { public get suffix(): string { if (this.children.length) { // Everything after the last child - return this._getSubstring(this.children[this.children.length - 1].endIndex, this.endIndex); + return this.#getSubstring(this.children[this.children.length - 1].endIndex, this.endIndex); } else { return ''; } @@ -317,7 +317,7 @@ export class Span { * Here we mean "next" according to an inorder traversal, not necessarily a sibling. */ public get separator(): string { - return this._getSubstring(this.#separatorStartIndex, this.#separatorEndIndex); + return this.#getSubstring(this.#separatorStartIndex, this.#separatorEndIndex); } /** @@ -385,7 +385,7 @@ export class Span { const writer: IndentedWriter = new IndentedWriter(); writer.trimLeadingSpaces = true; - this._writeModifiedText({ + this.#writeModifiedText({ writer: writer, separatorOverride: undefined, indentDocCommentState: IndentDocCommentState.Inactive @@ -395,7 +395,7 @@ export class Span { } public writeModifiedText(output: IndentedWriter): void { - this._writeModifiedText({ + this.#writeModifiedText({ writer: output, separatorOverride: undefined, indentDocCommentState: IndentDocCommentState.Inactive @@ -410,13 +410,13 @@ export class Span { let result: string = indent + ts.SyntaxKind[this.node.kind] + ': '; if (this.prefix) { - result += ' pre=[' + this._getTrimmed(this.prefix) + ']'; + result += ' pre=[' + this.#getTrimmed(this.prefix) + ']'; } if (this.suffix) { - result += ' suf=[' + this._getTrimmed(this.suffix) + ']'; + result += ' suf=[' + this.#getTrimmed(this.suffix) + ']'; } if (this.separator) { - result += ' sep=[' + this._getTrimmed(this.separator) + ']'; + result += ' sep=[' + this.#getTrimmed(this.separator) + ']'; } result += '\n'; @@ -434,13 +434,13 @@ export class Span { let result: string = indent + ts.SyntaxKind[this.node.kind] + ': '; if (this.prefix) { - result += ' pre=[' + this._getTrimmed(this.modification.prefix) + ']'; + result += ' pre=[' + this.#getTrimmed(this.modification.prefix) + ']'; } if (this.suffix) { - result += ' suf=[' + this._getTrimmed(this.modification.suffix) + ']'; + result += ' suf=[' + this.#getTrimmed(this.modification.suffix) + ']'; } if (this.separator) { - result += ' sep=[' + this._getTrimmed(this.separator) + ']'; + result += ' sep=[' + this.#getTrimmed(this.separator) + ']'; } if (this.modification.indentDocComment !== IndentDocCommentScope.None) { result += ' indentDocComment=' + IndentDocCommentScope[this.modification.indentDocComment]; @@ -473,7 +473,7 @@ export class Span { /** * Recursive implementation of `getModifiedText()` and `writeModifiedText()`. */ - private _writeModifiedText(options: IWriteModifiedTextOptions): void { + #writeModifiedText(options: IWriteModifiedTextOptions): void { // Apply indentation based on "{" and "}" if (this.prefix === '{') { options.writer.increaseIndent(); @@ -482,13 +482,13 @@ export class Span { } if (this.modification.indentDocComment !== IndentDocCommentScope.None) { - this._beginIndentDocComment(options); + this.#beginIndentDocComment(options); } - this._write(this.modification.prefix, options); + this.#write(this.modification.prefix, options); if (this.modification.indentDocComment === IndentDocCommentScope.PrefixOnly) { - this._endIndentDocComment(options); + this.#endIndentDocComment(options); } let sortedSubset: Span[] | undefined; @@ -538,7 +538,7 @@ export class Span { } } - current._writeModifiedText(childOptions); + current.#writeModifiedText(childOptions); } } else { // This is the normal case that does not need to sort children @@ -559,45 +559,45 @@ export class Span { ) { const childOptions: IWriteModifiedTextOptions = { ...options }; childOptions.separatorOverride = undefined; - child._writeModifiedText(childOptions); + child.#writeModifiedText(childOptions); } else { - child._writeModifiedText(options); + child.#writeModifiedText(options); } } } else { // The normal simple case for (const child of this.children) { - child._writeModifiedText(options); + child.#writeModifiedText(options); } } } - this._write(this.modification.suffix, options); + this.#write(this.modification.suffix, options); if (options.separatorOverride !== undefined) { if (this.separator || childrenLength === 0) { - this._write(options.separatorOverride, options); + this.#write(options.separatorOverride, options); } } else { if (!this.modification.omitSeparatorAfter) { - this._write(this.separator, options); + this.#write(this.separator, options); } } } if (this.modification.indentDocComment === IndentDocCommentScope.SpanAndChildren) { - this._endIndentDocComment(options); + this.#endIndentDocComment(options); } } - private _beginIndentDocComment(options: IWriteModifiedTextOptions): void { + #beginIndentDocComment(options: IWriteModifiedTextOptions): void { if (options.indentDocCommentState !== IndentDocCommentState.Inactive) { throw new InternalError('indentDocComment cannot be nested'); } options.indentDocCommentState = IndentDocCommentState.AwaitingOpenDelimiter; } - private _endIndentDocComment(options: IWriteModifiedTextOptions): void { + #endIndentDocComment(options: IWriteModifiedTextOptions): void { if (options.indentDocCommentState === IndentDocCommentState.AwaitingCloseDelimiter) { throw new InternalError('missing "*/" delimiter for comment block'); } @@ -607,7 +607,7 @@ export class Span { /** * Writes one chunk of `text` to the `options.writer`, applying the `indentDocComment` rewriting. */ - private _write(text: string, options: IWriteModifiedTextOptions): void { + #write(text: string, options: IWriteModifiedTextOptions): void { let parsedText: string = text; if (options.indentDocCommentState === IndentDocCommentState.AwaitingOpenDelimiter) { @@ -637,11 +637,11 @@ export class Span { options.writer.write(parsedText); } - private _getTrimmed(text: string): string { + #getTrimmed(text: string): string { return Text.truncateWithEllipsis(Text.convertToLf(text), 100); } - private _getSubstring(startIndex: number, endIndex: number): string { + #getSubstring(startIndex: number, endIndex: number): string { if (startIndex === endIndex) { return ''; } diff --git a/apps/api-extractor/src/api/ExtractorConfig.ts b/apps/api-extractor/src/api/ExtractorConfig.ts index 50ccb9b48a1..62da2e4b248 100644 --- a/apps/api-extractor/src/api/ExtractorConfig.ts +++ b/apps/api-extractor/src/api/ExtractorConfig.ts @@ -314,7 +314,7 @@ export class ExtractorConfig { * @deprecated Use {@link ExtractorConfig.reportConfigs} to access all report configurations. */ public get reportFilePath(): string { - const completeConfig: IExtractorConfigApiReport | undefined = this._getCompleteReportConfig(); + const completeConfig: IExtractorConfigApiReport | undefined = this.#getCompleteReportConfig(); return completeConfig === undefined ? '' : path.join(this.reportFolder, completeConfig.fileName); } @@ -324,7 +324,7 @@ export class ExtractorConfig { * @deprecated Use {@link ExtractorConfig.reportConfigs} to access all report configurations. */ public get reportTempFilePath(): string { - const completeConfig: IExtractorConfigApiReport | undefined = this._getCompleteReportConfig(); + const completeConfig: IExtractorConfigApiReport | undefined = this.#getCompleteReportConfig(); return completeConfig === undefined ? '' : path.join(this.reportTempFolder, completeConfig.fileName); } @@ -1166,7 +1166,7 @@ export class ExtractorConfig { /** * Gets the report configuration for the "complete" (default) report configuration, if one was specified. */ - private _getCompleteReportConfig(): IExtractorConfigApiReport | undefined { + #getCompleteReportConfig(): IExtractorConfigApiReport | undefined { return this.reportConfigs.find((x) => x.variant === 'complete'); } diff --git a/apps/api-extractor/src/cli/ApiExtractorCommandLine.ts b/apps/api-extractor/src/cli/ApiExtractorCommandLine.ts index 8142d5166b1..781e1476c13 100644 --- a/apps/api-extractor/src/cli/ApiExtractorCommandLine.ts +++ b/apps/api-extractor/src/cli/ApiExtractorCommandLine.ts @@ -23,7 +23,7 @@ export class ApiExtractorCommandLine extends CommandLineParser { ' published with your NPM package, and a doc model file (.api.json) to be used with a documentation' + ' tool such as api-documenter. For details, please visit the web site.' }); - this._populateActions(); + this.#populateActions(); this.#debugParameter = this.defineFlagParameter({ parameterLongName: '--debug', @@ -52,7 +52,7 @@ export class ApiExtractorCommandLine extends CommandLineParser { } } - private _populateActions(): void { + #populateActions(): void { this.addAction(new InitAction(this)); this.addAction(new RunAction(this)); } diff --git a/apps/api-extractor/src/collector/Collector.ts b/apps/api-extractor/src/collector/Collector.ts index 25e9dbe4d82..d15205e83ac 100644 --- a/apps/api-extractor/src/collector/Collector.ts +++ b/apps/api-extractor/src/collector/Collector.ts @@ -271,7 +271,7 @@ export class Collector { // Create a CollectorEntity for each top-level export. const processedAstEntities: AstEntity[] = []; for (const [exportName, astEntity] of exportedLocalEntities) { - this._createCollectorEntity(astEntity, exportName); + this.#createCollectorEntity(astEntity, exportName); processedAstEntities.push(astEntity); } @@ -279,7 +279,7 @@ export class Collector { // have been processed. const alreadySeenAstEntities: Set = new Set(); for (const astEntity of processedAstEntities) { - this._recursivelyCreateEntities(astEntity, alreadySeenAstEntities); + this.#recursivelyCreateEntities(astEntity, alreadySeenAstEntities); if (astEntity instanceof AstSymbol) { this.fetchSymbolMetadata(astEntity); } @@ -307,9 +307,9 @@ export class Collector { // It is intuitive for developers to include references that they explicitly want part of // their public API in a file like the entrypoint, which is likely to only contain reexports, // and this picks those up. - this._collectReferenceDirectivesFromSourceFiles(nonExternalSourceFiles, true); + this.#collectReferenceDirectivesFromSourceFiles(nonExternalSourceFiles, true); - this._makeUniqueNames(); + this.#makeUniqueNames(); for (const starExportedExternalModule of starExportedExternalModules) { if (starExportedExternalModule.externalModulePath !== undefined) { @@ -354,7 +354,7 @@ export class Collector { public fetchSymbolMetadata(astSymbol: AstSymbol): SymbolMetadata { if (astSymbol.symbolMetadata === undefined) { - this._fetchSymbolMetadata(astSymbol); + this.#fetchSymbolMetadata(astSymbol); } return astSymbol.symbolMetadata as SymbolMetadata; } @@ -362,7 +362,7 @@ export class Collector { public fetchDeclarationMetadata(astDeclaration: AstDeclaration): DeclarationMetadata { if (astDeclaration.declarationMetadata === undefined) { // Fetching the SymbolMetadata always constructs the DeclarationMetadata - this._fetchSymbolMetadata(astDeclaration.astSymbol); + this.#fetchSymbolMetadata(astDeclaration.astSymbol); } return astDeclaration.declarationMetadata as DeclarationMetadata; } @@ -370,7 +370,7 @@ export class Collector { public fetchApiItemMetadata(astDeclaration: AstDeclaration): ApiItemMetadata { if (astDeclaration.apiItemMetadata === undefined) { // Fetching the SymbolMetadata always constructs the ApiItemMetadata - this._fetchSymbolMetadata(astDeclaration.astSymbol); + this.#fetchSymbolMetadata(astDeclaration.astSymbol); } return astDeclaration.apiItemMetadata as ApiItemMetadata; } @@ -460,7 +460,7 @@ export class Collector { return overloadIndex; } - private _createCollectorEntity( + #createCollectorEntity( astEntity: AstEntity, exportName?: string, parent?: CollectorEntity @@ -477,7 +477,7 @@ export class Collector { this.#entitiesBySymbol.set(astEntity.symbol, entity); } this.#entities.push(entity); - this._collectReferenceDirectives(astEntity); + this.#collectReferenceDirectives(astEntity); } if (exportName) { @@ -491,7 +491,7 @@ export class Collector { return entity; } - private _recursivelyCreateEntities(astEntity: AstEntity, alreadySeenAstEntities: Set): void { + #recursivelyCreateEntities(astEntity: AstEntity, alreadySeenAstEntities: Set): void { if (alreadySeenAstEntities.has(astEntity)) return; alreadySeenAstEntities.add(astEntity); @@ -503,13 +503,13 @@ export class Collector { // nested inside a namespace, only the namespace gets a collector entity. Note that this // is not true for AstNamespaceImports below. if (referencedAstEntity.parentAstSymbol === undefined) { - this._createCollectorEntity(referencedAstEntity); + this.#createCollectorEntity(referencedAstEntity); } } else { - this._createCollectorEntity(referencedAstEntity); + this.#createCollectorEntity(referencedAstEntity); } - this._recursivelyCreateEntities(referencedAstEntity, alreadySeenAstEntities); + this.#recursivelyCreateEntities(referencedAstEntity, alreadySeenAstEntities); } }); } @@ -526,8 +526,8 @@ export class Collector { for (const [localExportName, localAstEntity] of astModuleExportInfo.exportedLocalEntities) { // Create a CollectorEntity for each local export within an AstNamespaceImport entity. - this._createCollectorEntity(localAstEntity, localExportName, parentEntity); - this._recursivelyCreateEntities(localAstEntity, alreadySeenAstEntities); + this.#createCollectorEntity(localAstEntity, localExportName, parentEntity); + this.#recursivelyCreateEntities(localAstEntity, alreadySeenAstEntities); } } } @@ -535,7 +535,7 @@ export class Collector { /** * Ensures a unique name for each item in the package typings file. */ - private _makeUniqueNames(): void { + #makeUniqueNames(): void { // The following examples illustrate the nameForEmit heuristics: // // Example 1: @@ -618,7 +618,7 @@ export class Collector { } } - private _fetchSymbolMetadata(astSymbol: AstSymbol): void { + #fetchSymbolMetadata(astSymbol: AstSymbol): void { if (astSymbol.symbolMetadata) { return; } @@ -626,15 +626,15 @@ export class Collector { // When we solve an astSymbol, then we always also solve all of its parents and all of its declarations. // The parent is solved first. if (astSymbol.parentAstSymbol && astSymbol.parentAstSymbol.symbolMetadata === undefined) { - this._fetchSymbolMetadata(astSymbol.parentAstSymbol); + this.#fetchSymbolMetadata(astSymbol.parentAstSymbol); } // Construct the DeclarationMetadata objects, and detect any ancillary declarations - this._calculateDeclarationMetadataForDeclarations(astSymbol); + this.#calculateDeclarationMetadataForDeclarations(astSymbol); // Calculate the ApiItemMetadata objects for (const astDeclaration of astSymbol.astDeclarations) { - this._calculateApiItemMetadata(astDeclaration); + this.#calculateApiItemMetadata(astDeclaration); } // The most public effectiveReleaseTag for all declarations @@ -657,7 +657,7 @@ export class Collector { }); } - private _calculateDeclarationMetadataForDeclarations(astSymbol: AstSymbol): void { + #calculateDeclarationMetadataForDeclarations(astSymbol: AstSymbol): void { // Initialize DeclarationMetadata for each declaration for (const astDeclaration of astSymbol.astDeclarations) { if (astDeclaration.declarationMetadata) { @@ -667,7 +667,7 @@ export class Collector { } const metadata: InternalDeclarationMetadata = new InternalDeclarationMetadata(); - metadata.tsdocParserContext = this._parseTsdocForAstDeclaration(astDeclaration); + metadata.tsdocParserContext = this.#parseTsdocForAstDeclaration(astDeclaration); astDeclaration.declarationMetadata = metadata; } @@ -680,7 +680,7 @@ export class Collector { for (const getterAstDeclaration of astDeclaration.astSymbol.astDeclarations) { if (getterAstDeclaration.declaration.kind === ts.SyntaxKind.GetAccessor) { // Associate it with the getter - this._addAncillaryDeclaration(getterAstDeclaration, astDeclaration); + this.#addAncillaryDeclaration(getterAstDeclaration, astDeclaration); foundGetter = true; } @@ -697,7 +697,7 @@ export class Collector { } } - private _addAncillaryDeclaration( + #addAncillaryDeclaration( mainAstDeclaration: AstDeclaration, ancillaryAstDeclaration: AstDeclaration ): void { @@ -741,7 +741,7 @@ export class Collector { mainMetadata.ancillaryDeclarations.push(ancillaryAstDeclaration); } - private _calculateApiItemMetadata(astDeclaration: AstDeclaration): void { + #calculateApiItemMetadata(astDeclaration: AstDeclaration): void { const declarationMetadata: InternalDeclarationMetadata = astDeclaration.declarationMetadata as InternalDeclarationMetadata; if (declarationMetadata.isAncillary) { @@ -910,7 +910,7 @@ export class Collector { } } - private _parseTsdocForAstDeclaration(astDeclaration: AstDeclaration): tsdoc.ParserContext | undefined { + #parseTsdocForAstDeclaration(astDeclaration: AstDeclaration): tsdoc.ParserContext | undefined { const declaration: ts.Declaration = astDeclaration.declaration; let nodeForComment: ts.Node = declaration; @@ -967,7 +967,7 @@ export class Collector { return parserContext; } - private _collectReferenceDirectives(astEntity: AstEntity): void { + #collectReferenceDirectives(astEntity: AstEntity): void { // Here, we're collecting reference directives from source files that contain extracted // definitions (i.e. - files that contain `export class ...`, `export interface ...`, ...). // These references may or may not include the `preserve="true" attribute. In TS < 5.5, @@ -984,16 +984,16 @@ export class Collector { const sourceFiles: ts.SourceFile[] = astEntity.astDeclarations.map((astDeclaration) => astDeclaration.declaration.getSourceFile() ); - return this._collectReferenceDirectivesFromSourceFiles(sourceFiles, false); + return this.#collectReferenceDirectivesFromSourceFiles(sourceFiles, false); } if (astEntity instanceof AstNamespaceImport) { const sourceFiles: ts.SourceFile[] = [astEntity.astModule.sourceFile]; - return this._collectReferenceDirectivesFromSourceFiles(sourceFiles, false); + return this.#collectReferenceDirectivesFromSourceFiles(sourceFiles, false); } } - private _collectReferenceDirectivesFromSourceFiles( + #collectReferenceDirectivesFromSourceFiles( sourceFiles: Iterable, onlyIncludeExplicitlyPreserved: boolean ): void { @@ -1011,7 +1011,7 @@ export class Collector { seenFilenames.add(fileName); for (const typeReferenceDirective of typeReferenceDirectives) { - const name: string | undefined = this._getReferenceDirectiveFromSourceFile( + const name: string | undefined = this.#getReferenceDirectiveFromSourceFile( sourceFileText, typeReferenceDirective, onlyIncludeExplicitlyPreserved @@ -1022,7 +1022,7 @@ export class Collector { } for (const libReferenceDirective of libReferenceDirectives) { - const reference: string | undefined = this._getReferenceDirectiveFromSourceFile( + const reference: string | undefined = this.#getReferenceDirectiveFromSourceFile( sourceFileText, libReferenceDirective, onlyIncludeExplicitlyPreserved @@ -1036,7 +1036,7 @@ export class Collector { } } - private _getReferenceDirectiveFromSourceFile( + #getReferenceDirectiveFromSourceFile( sourceFileText: string, { pos, end, preserve }: ts.FileReference, onlyIncludeExplicitlyPreserved: boolean diff --git a/apps/api-extractor/src/collector/MessageRouter.ts b/apps/api-extractor/src/collector/MessageRouter.ts index 9c0139905cd..f1652ffbc32 100644 --- a/apps/api-extractor/src/collector/MessageRouter.ts +++ b/apps/api-extractor/src/collector/MessageRouter.ts @@ -107,13 +107,13 @@ export class MessageRouter { this.showVerboseMessages = showVerboseMessages || showDiagnostics; this.showDiagnostics = showDiagnostics; - this._applyMessagesConfig(messagesConfig); + this.#applyMessagesConfig(messagesConfig); } /** * Read the api-extractor.json configuration and build up the tables of routing rules. */ - private _applyMessagesConfig(messagesConfig: IExtractorMessagesConfig): void { + #applyMessagesConfig(messagesConfig: IExtractorMessagesConfig): void { if (messagesConfig.compilerMessageReporting) { for (const messageId of Object.getOwnPropertyNames(messagesConfig.compilerMessageReporting)) { const reportingRule: IReportingRule = _getNormalizedRule( @@ -244,7 +244,7 @@ export class MessageRouter { properties ); - this._associateMessageWithAstDeclaration(extractorMessage, astDeclaration); + this.#associateMessageWithAstDeclaration(extractorMessage, astDeclaration); } /** @@ -274,7 +274,7 @@ export class MessageRouter { const extractorMessage: ExtractorMessage = new ExtractorMessage(options); if (astDeclaration) { - this._associateMessageWithAstDeclaration(extractorMessage, astDeclaration); + this.#associateMessageWithAstDeclaration(extractorMessage, astDeclaration); } this.#messages.push(extractorMessage); @@ -302,7 +302,7 @@ export class MessageRouter { /** * Record this message in _associatedMessagesForAstDeclaration */ - private _associateMessageWithAstDeclaration( + #associateMessageWithAstDeclaration( extractorMessage: ExtractorMessage, astDeclaration: AstDeclaration ): void { @@ -361,7 +361,7 @@ export class MessageRouter { // Make sure we didn't already report this message for some reason if (!associatedMessage.handled) { // Is this message type configured to go in the API report file? - const reportingRule: IReportingRule = this._getRuleForMessage(associatedMessage); + const reportingRule: IReportingRule = this.#getRuleForMessage(associatedMessage); if (reportingRule.addToApiReportFile) { // Include it in the result, and record that it went to the API report file messagesForApiReportFile.push(associatedMessage); @@ -370,7 +370,7 @@ export class MessageRouter { } } - this._sortMessagesForOutput(messagesForApiReportFile); + this.#sortMessagesForOutput(messagesForApiReportFile); return messagesForApiReportFile; } @@ -385,7 +385,7 @@ export class MessageRouter { // Make sure we didn't already report this message for some reason if (!unassociatedMessage.handled) { // Is this message type configured to go in the API report file? - const reportingRule: IReportingRule = this._getRuleForMessage(unassociatedMessage); + const reportingRule: IReportingRule = this.#getRuleForMessage(unassociatedMessage); if (reportingRule.addToApiReportFile) { // Include it in the result, and record that it went to the API report file messagesForApiReportFile.push(unassociatedMessage); @@ -394,7 +394,7 @@ export class MessageRouter { } } - this._sortMessagesForOutput(messagesForApiReportFile); + this.#sortMessagesForOutput(messagesForApiReportFile); return messagesForApiReportFile; } @@ -413,10 +413,10 @@ export class MessageRouter { } } - this._sortMessagesForOutput(messagesForLogger); + this.#sortMessagesForOutput(messagesForLogger); for (const message of messagesForLogger) { - this._handleMessage(message); + this.#handleMessage(message); } } @@ -425,7 +425,7 @@ export class MessageRouter { message: string, properties?: IExtractorMessageProperties ): void { - this._handleMessage( + this.#handleMessage( new ExtractorMessage({ category: ExtractorMessageCategory.Console, messageId, @@ -441,7 +441,7 @@ export class MessageRouter { message: string, properties?: IExtractorMessageProperties ): void { - this._handleMessage( + this.#handleMessage( new ExtractorMessage({ category: ExtractorMessageCategory.Console, messageId, @@ -457,7 +457,7 @@ export class MessageRouter { message: string, properties?: IExtractorMessageProperties ): void { - this._handleMessage( + this.#handleMessage( new ExtractorMessage({ category: ExtractorMessageCategory.Console, messageId, @@ -473,7 +473,7 @@ export class MessageRouter { message: string, properties?: IExtractorMessageProperties ): void { - this._handleMessage( + this.#handleMessage( new ExtractorMessage({ category: ExtractorMessageCategory.Console, messageId, @@ -503,7 +503,7 @@ export class MessageRouter { /** * Give the calling application a chance to handle the `ExtractorMessage`, and if not, display it on the console. */ - private _handleMessage(message: ExtractorMessage): void { + #handleMessage(message: ExtractorMessage): void { // Don't tally messages that were already "handled" by writing them into the API report if (message.handled) { return; @@ -513,7 +513,7 @@ export class MessageRouter { if (message.category === ExtractorMessageCategory.Console) { // Console messages have their category log level assigned via logInfo(), logVerbose(), etc. } else { - const reportingRule: IReportingRule = this._getRuleForMessage(message); + const reportingRule: IReportingRule = this.#getRuleForMessage(message); message.logLevel = reportingRule.logLevel; } @@ -573,7 +573,7 @@ export class MessageRouter { /** * For a given message, determine the IReportingRule based on the rule tables. */ - private _getRuleForMessage(message: ExtractorMessage): IReportingRule { + #getRuleForMessage(message: ExtractorMessage): IReportingRule { const reportingRule: IReportingRule | undefined = this.#reportingRuleByMessageId.get(message.messageId); if (reportingRule) { return reportingRule; @@ -593,7 +593,7 @@ export class MessageRouter { /** * Sorts an array of messages according to a reasonable ordering */ - private _sortMessagesForOutput(messages: ExtractorMessage[]): void { + #sortMessagesForOutput(messages: ExtractorMessage[]): void { messages.sort((a, b) => { let diff: number; // First sort by file name diff --git a/apps/api-extractor/src/collector/SourceMapper.ts b/apps/api-extractor/src/collector/SourceMapper.ts index a54f95ae90a..2ce7d847c21 100644 --- a/apps/api-extractor/src/collector/SourceMapper.ts +++ b/apps/api-extractor/src/collector/SourceMapper.ts @@ -91,11 +91,11 @@ export class SourceMapper { return sourceLocation; } - const mappedSourceLocation: ISourceLocation | undefined = this._getMappedSourceLocation(sourceLocation); + const mappedSourceLocation: ISourceLocation | undefined = this.#getMappedSourceLocation(sourceLocation); return mappedSourceLocation || sourceLocation; } - private _getMappedSourceLocation(sourceLocation: ISourceLocation): ISourceLocation | undefined { + #getMappedSourceLocation(sourceLocation: ISourceLocation): ISourceLocation | undefined { const { sourceFilePath, sourceFileLine, sourceFileColumn } = sourceLocation; if (!FileSystem.exists(sourceFilePath)) { @@ -103,7 +103,7 @@ export class SourceMapper { throw new InternalError('The referenced path was not found: ' + sourceFilePath); } - const sourceMap: ISourceMap | null = this._getSourceMap(sourceFilePath); + const sourceMap: ISourceMap | null = this.#getSourceMap(sourceFilePath); if (!sourceMap) return; const nearestMappingItem: MappingItem | undefined = _findNearestMappingItem(sourceMap.mappingItems, { @@ -168,7 +168,8 @@ export class SourceMapper { } } - private _getSourceMap(sourceFilePath: string): ISourceMap | null { + // eslint-disable-next-line @rushstack/no-new-null -- The decoupled ESLint plugin does not recognize native private fields yet. + #getSourceMap(sourceFilePath: string): ISourceMap | null { let sourceMap: ISourceMap | null | undefined = this.#sourceMapByFilePath.get(sourceFilePath); if (sourceMap === undefined) { diff --git a/apps/api-extractor/src/enhancers/DocCommentEnhancer.ts b/apps/api-extractor/src/enhancers/DocCommentEnhancer.ts index 3c235b96008..9f2113ba191 100644 --- a/apps/api-extractor/src/enhancers/DocCommentEnhancer.ts +++ b/apps/api-extractor/src/enhancers/DocCommentEnhancer.ts @@ -35,14 +35,14 @@ export class DocCommentEnhancer { this.#collector.extractorConfig.docModelIncludeForgottenExports ) { entity.astEntity.forEachDeclarationRecursive((astDeclaration: AstDeclaration) => { - this._analyzeApiItem(astDeclaration); + this.#analyzeApiItem(astDeclaration); }); } } } } - private _analyzeApiItem(astDeclaration: AstDeclaration): void { + #analyzeApiItem(astDeclaration: AstDeclaration): void { const metadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); if (metadata.docCommentEnhancerVisitorState === VisitorState.Visited) { return; @@ -59,17 +59,17 @@ export class DocCommentEnhancer { metadata.docCommentEnhancerVisitorState = VisitorState.Visiting; if (metadata.tsdocComment && metadata.tsdocComment.inheritDocTag) { - this._applyInheritDoc(astDeclaration, metadata.tsdocComment, metadata.tsdocComment.inheritDocTag); + this.#applyInheritDoc(astDeclaration, metadata.tsdocComment, metadata.tsdocComment.inheritDocTag); } - this._analyzeNeedsDocumentation(astDeclaration, metadata); + this.#analyzeNeedsDocumentation(astDeclaration, metadata); - this._checkForBrokenLinks(astDeclaration, metadata); + this.#checkForBrokenLinks(astDeclaration, metadata); metadata.docCommentEnhancerVisitorState = VisitorState.Visited; } - private _analyzeNeedsDocumentation(astDeclaration: AstDeclaration, metadata: ApiItemMetadata): void { + #analyzeNeedsDocumentation(astDeclaration: AstDeclaration, metadata: ApiItemMetadata): void { if (astDeclaration.declaration.kind === ts.SyntaxKind.Constructor) { // Constructors always do pretty much the same thing, so it's annoying to require people to write // descriptions for them. Instead, if the constructor lacks a TSDoc summary, then API Extractor @@ -145,7 +145,7 @@ export class DocCommentEnhancer { metadata.undocumented = false; } else if (metadata.tsdocComment.inheritDocTag) { if ( - this._refersToDeclarationInWorkingPackage( + this.#refersToDeclarationInWorkingPackage( metadata.tsdocComment.inheritDocTag.declarationReference ) ) { @@ -172,20 +172,20 @@ export class DocCommentEnhancer { } } - private _checkForBrokenLinks(astDeclaration: AstDeclaration, metadata: ApiItemMetadata): void { + #checkForBrokenLinks(astDeclaration: AstDeclaration, metadata: ApiItemMetadata): void { if (!metadata.tsdocComment) { return; } - this._checkForBrokenLinksRecursive(astDeclaration, metadata.tsdocComment); + this.#checkForBrokenLinksRecursive(astDeclaration, metadata.tsdocComment); } - private _checkForBrokenLinksRecursive(astDeclaration: AstDeclaration, node: tsdoc.DocNode): void { + #checkForBrokenLinksRecursive(astDeclaration: AstDeclaration, node: tsdoc.DocNode): void { if (node instanceof tsdoc.DocLinkTag) { if (node.codeDestination) { // Is it referring to the working package? If not, we don't do any link validation, because // AstReferenceResolver doesn't support it yet (but ModelReferenceResolver does of course). // Tracked by: https://github.com/microsoft/rushstack/issues/1195 - if (this._refersToDeclarationInWorkingPackage(node.codeDestination)) { + if (this.#refersToDeclarationInWorkingPackage(node.codeDestination)) { const referencedAstDeclaration: AstDeclaration | ResolverFailure = this.#collector.astReferenceResolver.resolve(node.codeDestination); @@ -200,14 +200,14 @@ export class DocCommentEnhancer { } } for (const childNode of node.getChildNodes()) { - this._checkForBrokenLinksRecursive(astDeclaration, childNode); + this.#checkForBrokenLinksRecursive(astDeclaration, childNode); } } /** * Follow an `{@inheritDoc ___}` reference and copy the content that we find in the referenced comment. */ - private _applyInheritDoc( + #applyInheritDoc( astDeclaration: AstDeclaration, docComment: tsdoc.DocComment, inheritDocTag: tsdoc.DocInheritDocTag @@ -221,7 +221,7 @@ export class DocCommentEnhancer { return; } - if (!this._refersToDeclarationInWorkingPackage(inheritDocTag.declarationReference)) { + if (!this.#refersToDeclarationInWorkingPackage(inheritDocTag.declarationReference)) { // The `@inheritDoc` tag is referencing an external package. Skip it, since AstReferenceResolver doesn't // support it yet. As a workaround, this tag will get handled later by api-documenter. // Tracked by: https://github.com/microsoft/rushstack/issues/1195 @@ -240,20 +240,20 @@ export class DocCommentEnhancer { return; } - this._analyzeApiItem(referencedAstDeclaration); + this.#analyzeApiItem(referencedAstDeclaration); const referencedMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(referencedAstDeclaration); if (referencedMetadata.tsdocComment) { - this._copyInheritedDocs(docComment, referencedMetadata.tsdocComment); + this.#copyInheritedDocs(docComment, referencedMetadata.tsdocComment); } } /** * Copy the content from `sourceDocComment` to `targetDocComment`. */ - private _copyInheritedDocs(targetDocComment: tsdoc.DocComment, sourceDocComment: tsdoc.DocComment): void { + #copyInheritedDocs(targetDocComment: tsdoc.DocComment, sourceDocComment: tsdoc.DocComment): void { targetDocComment.summarySection = sourceDocComment.summarySection; targetDocComment.remarksBlock = sourceDocComment.remarksBlock; @@ -272,7 +272,7 @@ export class DocCommentEnhancer { /** * Determines whether or not the provided declaration reference points to an item in the working package. */ - private _refersToDeclarationInWorkingPackage( + #refersToDeclarationInWorkingPackage( declarationReference: tsdoc.DocDeclarationReference | undefined ): boolean { return ( diff --git a/apps/api-extractor/src/generators/ApiModelGenerator.ts b/apps/api-extractor/src/generators/ApiModelGenerator.ts index 85766192889..abce36098da 100644 --- a/apps/api-extractor/src/generators/ApiModelGenerator.ts +++ b/apps/api-extractor/src/generators/ApiModelGenerator.ts @@ -115,7 +115,7 @@ export class ApiModelGenerator { // `AstNamespaceImport` entities will be processed by `_processAstNamespaceImport`. However, if // we are including forgotten exports, then process everything. if (entity.exportedFromEntryPoint || this.#collector.extractorConfig.docModelIncludeForgottenExports) { - this._processAstEntity(entity.astEntity, { + this.#processAstEntity(entity.astEntity, { name: entity.nameForEmit!, isExported: entity.exportedFromEntryPoint, parentApiItem: apiEntryPoint @@ -126,11 +126,11 @@ export class ApiModelGenerator { return apiPackage; } - private _processAstEntity(astEntity: AstEntity, context: IProcessAstEntityContext): void { + #processAstEntity(astEntity: AstEntity, context: IProcessAstEntityContext): void { if (astEntity instanceof AstSymbol) { // Skip ancillary declarations; we will process them with the main declaration for (const astDeclaration of this.#collector.getNonAncillaryDeclarations(astEntity)) { - this._processDeclaration(astDeclaration, context); + this.#processDeclaration(astDeclaration, context); } return; } @@ -150,7 +150,7 @@ export class ApiModelGenerator { // // This could be improved in the future, but it requires a stable mechanism for choosing an associated parent. // For thoughts about this: https://github.com/microsoft/rushstack/issues/1308 - this._processAstNamespaceImport(astEntity, context); + this.#processAstNamespaceImport(astEntity, context); return; } @@ -159,14 +159,14 @@ export class ApiModelGenerator { // form "export { X } from 'external-package'". We can also use this to solve GitHub issue #950. } - private _processAstNamespaceImport( + #processAstNamespaceImport( astNamespaceImport: AstNamespaceImport, context: IProcessAstEntityContext ): void { const astModule: AstModule = astNamespaceImport.astModule; const { name, isExported, parentApiItem } = context; const containerKey: string = ApiNamespace.getContainerKey(name); - const fileUrlPath: string = this._getFileUrlPath(astNamespaceImport.declaration); + const fileUrlPath: string = this.#getFileUrlPath(astNamespaceImport.declaration); let apiNamespace: ApiNamespace | undefined = parentApiItem.tryGetMemberByKey( containerKey @@ -186,7 +186,7 @@ export class ApiModelGenerator { astModule.astModuleExportInfo!.exportedLocalEntities.forEach( (exportedEntity: AstEntity, exportedName: string) => { - this._processAstEntity(exportedEntity, { + this.#processAstEntity(exportedEntity, { name: exportedName, isExported: true, parentApiItem: apiNamespace! @@ -195,7 +195,7 @@ export class ApiModelGenerator { ); } - private _processDeclaration(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { + #processDeclaration(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { if ((astDeclaration.modifierFlags & ts.ModifierFlags.Private) !== 0) { return; // trim out private declarations } @@ -208,81 +208,81 @@ export class ApiModelGenerator { switch (astDeclaration.declaration.kind) { case ts.SyntaxKind.CallSignature: - this._processApiCallSignature(astDeclaration, context); + this.#processApiCallSignature(astDeclaration, context); break; case ts.SyntaxKind.Constructor: - this._processApiConstructor(astDeclaration, context); + this.#processApiConstructor(astDeclaration, context); break; case ts.SyntaxKind.ConstructSignature: - this._processApiConstructSignature(astDeclaration, context); + this.#processApiConstructSignature(astDeclaration, context); break; case ts.SyntaxKind.ClassDeclaration: - this._processApiClass(astDeclaration, context); + this.#processApiClass(astDeclaration, context); break; case ts.SyntaxKind.EnumDeclaration: - this._processApiEnum(astDeclaration, context); + this.#processApiEnum(astDeclaration, context); break; case ts.SyntaxKind.EnumMember: - this._processApiEnumMember(astDeclaration, context); + this.#processApiEnumMember(astDeclaration, context); break; case ts.SyntaxKind.FunctionDeclaration: - this._processApiFunction(astDeclaration, context); + this.#processApiFunction(astDeclaration, context); break; case ts.SyntaxKind.GetAccessor: - this._processApiProperty(astDeclaration, context); + this.#processApiProperty(astDeclaration, context); break; case ts.SyntaxKind.SetAccessor: - this._processApiProperty(astDeclaration, context); + this.#processApiProperty(astDeclaration, context); break; case ts.SyntaxKind.IndexSignature: - this._processApiIndexSignature(astDeclaration, context); + this.#processApiIndexSignature(astDeclaration, context); break; case ts.SyntaxKind.InterfaceDeclaration: - this._processApiInterface(astDeclaration, context); + this.#processApiInterface(astDeclaration, context); break; case ts.SyntaxKind.MethodDeclaration: - this._processApiMethod(astDeclaration, context); + this.#processApiMethod(astDeclaration, context); break; case ts.SyntaxKind.MethodSignature: - this._processApiMethodSignature(astDeclaration, context); + this.#processApiMethodSignature(astDeclaration, context); break; case ts.SyntaxKind.ModuleDeclaration: - this._processApiNamespace(astDeclaration, context); + this.#processApiNamespace(astDeclaration, context); break; case ts.SyntaxKind.PropertyDeclaration: - this._processApiProperty(astDeclaration, context); + this.#processApiProperty(astDeclaration, context); break; case ts.SyntaxKind.PropertySignature: - this._processApiPropertySignature(astDeclaration, context); + this.#processApiPropertySignature(astDeclaration, context); break; case ts.SyntaxKind.TypeAliasDeclaration: - this._processApiTypeAlias(astDeclaration, context); + this.#processApiTypeAlias(astDeclaration, context); break; case ts.SyntaxKind.VariableDeclaration: // check for arrow functions in variable declaration const functionDeclaration: ts.FunctionDeclaration | undefined = - this._tryFindFunctionDeclaration(astDeclaration); + this.#tryFindFunctionDeclaration(astDeclaration); if (functionDeclaration) { - this._processApiFunction(astDeclaration, context, functionDeclaration); + this.#processApiFunction(astDeclaration, context, functionDeclaration); } else { - this._processApiVariable(astDeclaration, context); + this.#processApiVariable(astDeclaration, context); } break; @@ -291,23 +291,23 @@ export class ApiModelGenerator { } } - private _tryFindFunctionDeclaration(astDeclaration: AstDeclaration): ts.FunctionDeclaration | undefined { + #tryFindFunctionDeclaration(astDeclaration: AstDeclaration): ts.FunctionDeclaration | undefined { const children: readonly ts.Node[] = astDeclaration.declaration.getChildren( astDeclaration.declaration.getSourceFile() ); return children.find(ts.isFunctionTypeNode) as ts.FunctionDeclaration | undefined; } - private _processChildDeclarations(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { + #processChildDeclarations(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { for (const childDeclaration of astDeclaration.children) { - this._processDeclaration(childDeclaration, { + this.#processDeclaration(childDeclaration, { ...context, name: childDeclaration.astSymbol.localName }); } } - private _processApiCallSignature(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { + #processApiCallSignature(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { parentApiItem } = context; const overloadIndex: number = this.#collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiCallSignature.getContainerKey(overloadIndex); @@ -327,21 +327,21 @@ export class ApiModelGenerator { nodeTransforms.push({ node: callSignature.type, captureTokenRange: returnTypeTokenRange }); } - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + const typeParameters: IApiTypeParameterOptions[] = this.#captureTypeParameters( nodeTransforms, callSignature.typeParameters ); - const parameters: IApiParameterOptions[] = this._captureParameters( + const parameters: IApiParameterOptions[] = this.#captureParameters( nodeTransforms, callSignature.parameters ); - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, nodeTransforms); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; - const fileUrlPath: string = this._getFileUrlPath(callSignature); + const fileUrlPath: string = this.#getFileUrlPath(callSignature); apiCallSignature = new ApiCallSignature({ docComment, @@ -358,7 +358,7 @@ export class ApiModelGenerator { } } - private _processApiConstructor(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { + #processApiConstructor(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { parentApiItem } = context; const overloadIndex: number = this.#collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiConstructor.getContainerKey(overloadIndex); @@ -373,17 +373,17 @@ export class ApiModelGenerator { const nodeTransforms: IExcerptBuilderNodeTransform[] = []; - const parameters: IApiParameterOptions[] = this._captureParameters( + const parameters: IApiParameterOptions[] = this.#captureParameters( nodeTransforms, constructorDeclaration.parameters ); - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, nodeTransforms); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const isProtected: boolean = (astDeclaration.modifierFlags & ts.ModifierFlags.Protected) !== 0; - const fileUrlPath: string = this._getFileUrlPath(constructorDeclaration); + const fileUrlPath: string = this.#getFileUrlPath(constructorDeclaration); apiConstructor = new ApiConstructor({ docComment, @@ -399,7 +399,7 @@ export class ApiModelGenerator { } } - private _processApiClass(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { + #processApiClass(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { name, isExported, parentApiItem } = context; const containerKey: string = ApiClass.getContainerKey(name); @@ -410,7 +410,7 @@ export class ApiModelGenerator { const nodeTransforms: IExcerptBuilderNodeTransform[] = []; - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + const typeParameters: IApiTypeParameterOptions[] = this.#captureTypeParameters( nodeTransforms, classDeclaration.typeParameters ); @@ -433,13 +433,13 @@ export class ApiModelGenerator { } } - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, nodeTransforms); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const isAbstract: boolean = (ts.getCombinedModifierFlags(classDeclaration) & ts.ModifierFlags.Abstract) !== 0; - const fileUrlPath: string = this._getFileUrlPath(classDeclaration); + const fileUrlPath: string = this.#getFileUrlPath(classDeclaration); apiClass = new ApiClass({ name, @@ -457,13 +457,13 @@ export class ApiModelGenerator { parentApiItem.addMember(apiClass); } - this._processChildDeclarations(astDeclaration, { + this.#processChildDeclarations(astDeclaration, { ...context, parentApiItem: apiClass }); } - private _processApiConstructSignature( + #processApiConstructSignature( astDeclaration: AstDeclaration, context: IProcessAstEntityContext ): void { @@ -486,21 +486,21 @@ export class ApiModelGenerator { nodeTransforms.push({ node: constructSignature.type, captureTokenRange: returnTypeTokenRange }); } - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + const typeParameters: IApiTypeParameterOptions[] = this.#captureTypeParameters( nodeTransforms, constructSignature.typeParameters ); - const parameters: IApiParameterOptions[] = this._captureParameters( + const parameters: IApiParameterOptions[] = this.#captureParameters( nodeTransforms, constructSignature.parameters ); - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, nodeTransforms); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; - const fileUrlPath: string = this._getFileUrlPath(constructSignature); + const fileUrlPath: string = this.#getFileUrlPath(constructSignature); apiConstructSignature = new ApiConstructSignature({ docComment, @@ -517,20 +517,20 @@ export class ApiModelGenerator { } } - private _processApiEnum(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { + #processApiEnum(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { name, isExported, parentApiItem } = context; const containerKey: string = ApiEnum.getContainerKey(name); let apiEnum: ApiEnum | undefined = parentApiItem.tryGetMemberByKey(containerKey) as ApiEnum; if (apiEnum === undefined) { - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, []); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, []); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const preserveMemberOrder: boolean = this.#collector.extractorConfig.enumMemberOrder === EnumMemberOrder.Preserve; - const fileUrlPath: string = this._getFileUrlPath(astDeclaration.declaration); + const fileUrlPath: string = this.#getFileUrlPath(astDeclaration.declaration); apiEnum = new ApiEnum({ name, @@ -544,13 +544,13 @@ export class ApiModelGenerator { parentApiItem.addMember(apiEnum); } - this._processChildDeclarations(astDeclaration, { + this.#processChildDeclarations(astDeclaration, { ...context, parentApiItem: apiEnum }); } - private _processApiEnumMember(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { + #processApiEnumMember(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { name, parentApiItem } = context; const containerKey: string = ApiEnumMember.getContainerKey(name); @@ -569,11 +569,11 @@ export class ApiModelGenerator { nodeTransforms.push({ node: enumMember.initializer, captureTokenRange: initializerTokenRange }); } - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, nodeTransforms); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; - const fileUrlPath: string = this._getFileUrlPath(enumMember); + const fileUrlPath: string = this.#getFileUrlPath(enumMember); apiEnumMember = new ApiEnumMember({ name, @@ -588,7 +588,7 @@ export class ApiModelGenerator { } } - private _processApiFunction( + #processApiFunction( astDeclaration: AstDeclaration, context: IProcessAstEntityContext, altFunctionDeclaration?: ts.FunctionDeclaration @@ -611,21 +611,21 @@ export class ApiModelGenerator { nodeTransforms.push({ node: functionDeclaration.type, captureTokenRange: returnTypeTokenRange }); } - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + const typeParameters: IApiTypeParameterOptions[] = this.#captureTypeParameters( nodeTransforms, functionDeclaration.typeParameters ); - const parameters: IApiParameterOptions[] = this._captureParameters( + const parameters: IApiParameterOptions[] = this.#captureParameters( nodeTransforms, functionDeclaration.parameters ); - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, nodeTransforms); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; - const fileUrlPath: string = this._getFileUrlPath(functionDeclaration); + const fileUrlPath: string = this.#getFileUrlPath(functionDeclaration); apiFunction = new ApiFunction({ name, @@ -644,7 +644,7 @@ export class ApiModelGenerator { } } - private _processApiIndexSignature(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { + #processApiIndexSignature(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { parentApiItem } = context; const overloadIndex: number = this.#collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiIndexSignature.getContainerKey(overloadIndex); @@ -662,17 +662,17 @@ export class ApiModelGenerator { const returnTypeTokenRange: IExcerptTokenRange = ExcerptBuilder.createEmptyTokenRange(); nodeTransforms.push({ node: indexSignature.type, captureTokenRange: returnTypeTokenRange }); - const parameters: IApiParameterOptions[] = this._captureParameters( + const parameters: IApiParameterOptions[] = this.#captureParameters( nodeTransforms, indexSignature.parameters ); - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, nodeTransforms); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; - const isReadonly: boolean = this._isReadonly(astDeclaration); - const fileUrlPath: string = this._getFileUrlPath(indexSignature); + const isReadonly: boolean = this.#isReadonly(astDeclaration); + const fileUrlPath: string = this.#getFileUrlPath(indexSignature); apiIndexSignature = new ApiIndexSignature({ docComment, @@ -689,7 +689,7 @@ export class ApiModelGenerator { } } - private _processApiInterface(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { + #processApiInterface(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { name, isExported, parentApiItem } = context; const containerKey: string = ApiInterface.getContainerKey(name); @@ -703,7 +703,7 @@ export class ApiModelGenerator { const nodeTransforms: IExcerptBuilderNodeTransform[] = []; - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + const typeParameters: IApiTypeParameterOptions[] = this.#captureTypeParameters( nodeTransforms, interfaceDeclaration.typeParameters ); @@ -720,11 +720,11 @@ export class ApiModelGenerator { } } - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, nodeTransforms); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; - const fileUrlPath: string = this._getFileUrlPath(interfaceDeclaration); + const fileUrlPath: string = this.#getFileUrlPath(interfaceDeclaration); apiInterface = new ApiInterface({ name, @@ -740,13 +740,13 @@ export class ApiModelGenerator { parentApiItem.addMember(apiInterface); } - this._processChildDeclarations(astDeclaration, { + this.#processChildDeclarations(astDeclaration, { ...context, parentApiItem: apiInterface }); } - private _processApiMethod(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { + #processApiMethod(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { name, parentApiItem } = context; const isStatic: boolean = (astDeclaration.modifierFlags & ts.ModifierFlags.Static) !== 0; const overloadIndex: number = this.#collector.getOverloadIndex(astDeclaration); @@ -764,17 +764,17 @@ export class ApiModelGenerator { nodeTransforms.push({ node: methodDeclaration.type, captureTokenRange: returnTypeTokenRange }); } - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + const typeParameters: IApiTypeParameterOptions[] = this.#captureTypeParameters( nodeTransforms, methodDeclaration.typeParameters ); - const parameters: IApiParameterOptions[] = this._captureParameters( + const parameters: IApiParameterOptions[] = this.#captureParameters( nodeTransforms, methodDeclaration.parameters ); - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, nodeTransforms); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; @@ -785,7 +785,7 @@ export class ApiModelGenerator { (astDeclaration.astSymbol.followedSymbol.flags & ts.SymbolFlags.Optional) !== 0; const isProtected: boolean = (astDeclaration.modifierFlags & ts.ModifierFlags.Protected) !== 0; const isAbstract: boolean = (astDeclaration.modifierFlags & ts.ModifierFlags.Abstract) !== 0; - const fileUrlPath: string = this._getFileUrlPath(methodDeclaration); + const fileUrlPath: string = this.#getFileUrlPath(methodDeclaration); apiMethod = new ApiMethod({ name, @@ -807,7 +807,7 @@ export class ApiModelGenerator { } } - private _processApiMethodSignature( + #processApiMethodSignature( astDeclaration: AstDeclaration, context: IProcessAstEntityContext ): void { @@ -829,23 +829,23 @@ export class ApiModelGenerator { nodeTransforms.push({ node: methodSignature.type, captureTokenRange: returnTypeTokenRange }); } - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + const typeParameters: IApiTypeParameterOptions[] = this.#captureTypeParameters( nodeTransforms, methodSignature.typeParameters ); - const parameters: IApiParameterOptions[] = this._captureParameters( + const parameters: IApiParameterOptions[] = this.#captureParameters( nodeTransforms, methodSignature.parameters ); - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, nodeTransforms); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const isOptional: boolean = (astDeclaration.astSymbol.followedSymbol.flags & ts.SymbolFlags.Optional) !== 0; - const fileUrlPath: string = this._getFileUrlPath(methodSignature); + const fileUrlPath: string = this.#getFileUrlPath(methodSignature); apiMethodSignature = new ApiMethodSignature({ name, @@ -864,7 +864,7 @@ export class ApiModelGenerator { } } - private _processApiNamespace(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { + #processApiNamespace(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { name, isExported, parentApiItem } = context; const containerKey: string = ApiNamespace.getContainerKey(name); @@ -873,11 +873,11 @@ export class ApiModelGenerator { ) as ApiNamespace; if (apiNamespace === undefined) { - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, []); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, []); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; - const fileUrlPath: string = this._getFileUrlPath(astDeclaration.declaration); + const fileUrlPath: string = this.#getFileUrlPath(astDeclaration.declaration); apiNamespace = new ApiNamespace({ name, @@ -890,13 +890,13 @@ export class ApiModelGenerator { parentApiItem.addMember(apiNamespace); } - this._processChildDeclarations(astDeclaration, { + this.#processChildDeclarations(astDeclaration, { ...context, parentApiItem: apiNamespace }); } - private _processApiProperty(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { + #processApiProperty(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { name, parentApiItem } = context; const isStatic: boolean = (astDeclaration.modifierFlags & ts.ModifierFlags.Static) !== 0; const containerKey: string = ApiProperty.getContainerKey(name, isStatic); @@ -929,7 +929,7 @@ export class ApiModelGenerator { nodeTransforms.push({ node: declaration.initializer, captureTokenRange: initializerTokenRange }); } - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, nodeTransforms); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; @@ -937,8 +937,8 @@ export class ApiModelGenerator { (astDeclaration.astSymbol.followedSymbol.flags & ts.SymbolFlags.Optional) !== 0; const isProtected: boolean = (astDeclaration.modifierFlags & ts.ModifierFlags.Protected) !== 0; const isAbstract: boolean = (astDeclaration.modifierFlags & ts.ModifierFlags.Abstract) !== 0; - const isReadonly: boolean = this._isReadonly(astDeclaration); - const fileUrlPath: string = this._getFileUrlPath(declaration); + const isReadonly: boolean = this.#isReadonly(astDeclaration); + const fileUrlPath: string = this.#getFileUrlPath(declaration); apiProperty = new ApiProperty({ name, @@ -961,7 +961,7 @@ export class ApiModelGenerator { } } - private _processApiPropertySignature( + #processApiPropertySignature( astDeclaration: AstDeclaration, context: IProcessAstEntityContext ): void { @@ -982,14 +982,14 @@ export class ApiModelGenerator { nodeTransforms.push({ node: propertySignature.type, captureTokenRange: propertyTypeTokenRange }); } - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, nodeTransforms); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; const isOptional: boolean = (astDeclaration.astSymbol.followedSymbol.flags & ts.SymbolFlags.Optional) !== 0; - const isReadonly: boolean = this._isReadonly(astDeclaration); - const fileUrlPath: string = this._getFileUrlPath(propertySignature); + const isReadonly: boolean = this.#isReadonly(astDeclaration); + const fileUrlPath: string = this.#getFileUrlPath(propertySignature); apiPropertySignature = new ApiPropertySignature({ name, @@ -1009,7 +1009,7 @@ export class ApiModelGenerator { } } - private _processApiTypeAlias(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { + #processApiTypeAlias(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { name, isExported, parentApiItem } = context; const containerKey: string = ApiTypeAlias.getContainerKey(name); @@ -1024,7 +1024,7 @@ export class ApiModelGenerator { const nodeTransforms: IExcerptBuilderNodeTransform[] = []; - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + const typeParameters: IApiTypeParameterOptions[] = this.#captureTypeParameters( nodeTransforms, typeAliasDeclaration.typeParameters ); @@ -1032,11 +1032,11 @@ export class ApiModelGenerator { const typeTokenRange: IExcerptTokenRange = ExcerptBuilder.createEmptyTokenRange(); nodeTransforms.push({ node: typeAliasDeclaration.type, captureTokenRange: typeTokenRange }); - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, nodeTransforms); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; - const fileUrlPath: string = this._getFileUrlPath(typeAliasDeclaration); + const fileUrlPath: string = this.#getFileUrlPath(typeAliasDeclaration); apiTypeAlias = new ApiTypeAlias({ name, @@ -1053,7 +1053,7 @@ export class ApiModelGenerator { } } - private _processApiVariable(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { + #processApiVariable(astDeclaration: AstDeclaration, context: IProcessAstEntityContext): void { const { name, isExported, parentApiItem } = context; const containerKey: string = ApiVariable.getContainerKey(name); @@ -1080,12 +1080,12 @@ export class ApiModelGenerator { }); } - const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodeTransforms); + const excerptTokens: IExcerptToken[] = this.#buildExcerptTokens(astDeclaration, nodeTransforms); const apiItemMetadata: ApiItemMetadata = this.#collector.fetchApiItemMetadata(astDeclaration); const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; - const isReadonly: boolean = this._isReadonly(astDeclaration); - const fileUrlPath: string = this._getFileUrlPath(variableDeclaration); + const isReadonly: boolean = this.#isReadonly(astDeclaration); + const fileUrlPath: string = this.#getFileUrlPath(variableDeclaration); apiVariable = new ApiVariable({ name, @@ -1106,7 +1106,7 @@ export class ApiModelGenerator { /** * @param nodeTransforms - A list of child nodes whose token ranges we want to capture */ - private _buildExcerptTokens( + #buildExcerptTokens( astDeclaration: AstDeclaration, nodeTransforms: IExcerptBuilderNodeTransform[] ): IExcerptToken[] { @@ -1131,7 +1131,7 @@ export class ApiModelGenerator { return excerptTokens; } - private _captureTypeParameters( + #captureTypeParameters( nodeTransforms: IExcerptBuilderNodeTransform[], typeParameterNodes: ts.NodeArray | undefined ): IApiTypeParameterOptions[] { @@ -1158,7 +1158,7 @@ export class ApiModelGenerator { return typeParameters; } - private _captureParameters( + #captureParameters( nodeTransforms: IExcerptBuilderNodeTransform[], parameterNodes: ts.NodeArray ): IApiParameterOptions[] { @@ -1187,7 +1187,7 @@ export class ApiModelGenerator { return parameters; } - private _isReadonly(astDeclaration: AstDeclaration): boolean { + #isReadonly(astDeclaration: AstDeclaration): boolean { switch (astDeclaration.declaration.kind) { case ts.SyntaxKind.GetAccessor: case ts.SyntaxKind.IndexSignature: @@ -1218,7 +1218,7 @@ export class ApiModelGenerator { } } - private _getFileUrlPath(declaration: ts.Declaration): string { + #getFileUrlPath(declaration: ts.Declaration): string { const sourceFile: ts.SourceFile = declaration.getSourceFile(); const sourceLocation: ISourceLocation = this.#collector.sourceMapper.getSourceLocation({ sourceFile, diff --git a/apps/api-extractor/src/generators/DeclarationReferenceGenerator.ts b/apps/api-extractor/src/generators/DeclarationReferenceGenerator.ts index 047cd77a92e..1eb8cbe4f5e 100644 --- a/apps/api-extractor/src/generators/DeclarationReferenceGenerator.ts +++ b/apps/api-extractor/src/generators/DeclarationReferenceGenerator.ts @@ -56,10 +56,10 @@ export class DeclarationReferenceGenerator { symbol: ts.Symbol, meaning: ts.SymbolFlags ): DeclarationReference | undefined { - return this._symbolToDeclarationReference(symbol, meaning, /*includeModuleSymbols*/ false); + return this.#symbolToDeclarationReference(symbol, meaning, /*includeModuleSymbols*/ false); } - private _getNavigationToSymbol(symbol: ts.Symbol): Navigation { + #getNavigationToSymbol(symbol: ts.Symbol): Navigation { const declaration: ts.Declaration | undefined = TypeScriptHelpers.tryGetADeclaration(symbol); const sourceFile: ts.SourceFile | undefined = declaration?.getSourceFile(); const parent: ts.Symbol | undefined = TypeScriptInternals.getSymbolParent(symbol); @@ -104,7 +104,7 @@ export class DeclarationReferenceGenerator { return Navigation.Locals; } - private _symbolToDeclarationReference( + #symbolToDeclarationReference( symbol: ts.Symbol, meaning: ts.SymbolFlags, includeModuleSymbols: boolean @@ -130,7 +130,7 @@ export class DeclarationReferenceGenerator { if (!includeModuleSymbols) { return undefined; } - return new DeclarationReference(this._sourceFileToModuleSource(sourceFile)); + return new DeclarationReference(this.#sourceFileToModuleSource(sourceFile)); } // Do not generate a declaration reference for a type parameter. @@ -138,7 +138,7 @@ export class DeclarationReferenceGenerator { return undefined; } - let parentRef: DeclarationReference | undefined = this._getParentReference(followedSymbol); + let parentRef: DeclarationReference | undefined = this.#getParentReference(followedSymbol); if (!parentRef) { return undefined; } @@ -173,7 +173,7 @@ export class DeclarationReferenceGenerator { } } - const navigation: Navigation = this._getNavigationToSymbol(followedSymbol); + const navigation: Navigation = this.#getNavigationToSymbol(followedSymbol); // If the symbol is a global, ensure the source is global. if (sourceFile && !ts.isExternalModule(sourceFile) && parentRef.source !== GlobalSource.instance) { @@ -185,7 +185,7 @@ export class DeclarationReferenceGenerator { .withMeaning(_getMeaningOfSymbol(followedSymbol, meaning)); } - private _getParentReference(symbol: ts.Symbol): DeclarationReference | undefined { + #getParentReference(symbol: ts.Symbol): DeclarationReference | undefined { const declaration: ts.Node | undefined = TypeScriptHelpers.tryGetADeclaration(symbol); const sourceFile: ts.SourceFile | undefined = declaration?.getSourceFile(); @@ -195,7 +195,7 @@ export class DeclarationReferenceGenerator { const entity: CollectorEntity | undefined = this.#collector.tryGetEntityForSymbol(symbol); if (entity) { if (entity.exportedFromEntryPoint) { - return new DeclarationReference(this._sourceFileToModuleSource(sourceFile)); + return new DeclarationReference(this.#sourceFileToModuleSource(sourceFile)); } const firstExportingConsumableParent: CollectorEntity | undefined = @@ -209,7 +209,7 @@ export class DeclarationReferenceGenerator { this.#collector.typeChecker ); if (parentSymbol) { - return this._symbolToDeclarationReference( + return this.#symbolToDeclarationReference( parentSymbol, parentSymbol.flags, /*includeModuleSymbols*/ true @@ -221,7 +221,7 @@ export class DeclarationReferenceGenerator { // Next, try to find a parent symbol via the symbol tree. const parentSymbol: ts.Symbol | undefined = TypeScriptInternals.getSymbolParent(symbol); if (parentSymbol) { - return this._symbolToDeclarationReference( + return this.#symbolToDeclarationReference( parentSymbol, parentSymbol.flags, /*includeModuleSymbols*/ true @@ -247,7 +247,7 @@ export class DeclarationReferenceGenerator { this.#collector.typeChecker ); if (grandParentSymbol) { - return this._symbolToDeclarationReference( + return this.#symbolToDeclarationReference( grandParentSymbol, grandParentSymbol.flags, /*includeModuleSymbols*/ true @@ -257,13 +257,13 @@ export class DeclarationReferenceGenerator { // At this point, we have a local symbol in a module. if (sourceFile && ts.isExternalModule(sourceFile)) { - return new DeclarationReference(this._sourceFileToModuleSource(sourceFile)); + return new DeclarationReference(this.#sourceFileToModuleSource(sourceFile)); } else { return new DeclarationReference(GlobalSource.instance); } } - private _getPackageName(sourceFile: ts.SourceFile): string { + #getPackageName(sourceFile: ts.SourceFile): string { if (this.#collector.program.isSourceFileFromExternalLibrary(sourceFile)) { const packageJson: INodePackageJson | undefined = this.#collector.packageJsonLookup.tryLoadNodePackageJsonFor(sourceFile.fileName); @@ -276,9 +276,9 @@ export class DeclarationReferenceGenerator { return this.#collector.workingPackage.name; } - private _sourceFileToModuleSource(sourceFile: ts.SourceFile | undefined): GlobalSource | ModuleSource { + #sourceFileToModuleSource(sourceFile: ts.SourceFile | undefined): GlobalSource | ModuleSource { if (sourceFile && ts.isExternalModule(sourceFile)) { - const packageName: string = this._getPackageName(sourceFile); + const packageName: string = this.#getPackageName(sourceFile); if (this.#collector.bundledPackageNames.has(packageName)) { // The api-extractor.json config file has a "bundledPackages" setting, which causes imports from diff --git a/apps/api-extractor/src/generators/IndentedWriter.ts b/apps/api-extractor/src/generators/IndentedWriter.ts index 32661a47e02..2a59eb81ff5 100644 --- a/apps/api-extractor/src/generators/IndentedWriter.ts +++ b/apps/api-extractor/src/generators/IndentedWriter.ts @@ -114,7 +114,7 @@ export class IndentedWriter { */ public increaseIndent(indentPrefix?: string): void { this.#indentStack.push(indentPrefix !== undefined ? indentPrefix : this.defaultIndentPrefix); - this._updateIndentText(); + this.#updateIndentText(); } /** @@ -123,7 +123,7 @@ export class IndentedWriter { */ public decreaseIndent(): void { this.#indentStack.pop(); - this._updateIndentText(); + this.#updateIndentText(); } /** @@ -142,7 +142,7 @@ export class IndentedWriter { public ensureNewLine(): void { const lastCharacter: string = this.peekLastCharacter(); if (lastCharacter !== '\n' && lastCharacter !== '') { - this._writeNewLine(); + this.#writeNewLine(); } } @@ -154,7 +154,7 @@ export class IndentedWriter { public ensureSkippedLine(): void { this.ensureNewLine(); if (!this.#previousLineIsBlank) { - this._writeNewLine(); + this.#writeNewLine(); } } @@ -196,7 +196,7 @@ export class IndentedWriter { // If there are no newline characters, then append the string verbatim if (!/[\r\n]/.test(message)) { - this._writeLinePart(message); + this.#writeLinePart(message); return; } @@ -204,12 +204,12 @@ export class IndentedWriter { let first: boolean = true; for (const linePart of message.split('\n')) { if (!first) { - this._writeNewLine(); + this.#writeNewLine(); } else { first = false; } if (linePart) { - this._writeLinePart(linePart.replace(/[\r]/g, '')); + this.#writeLinePart(linePart.replace(/[\r]/g, '')); } } } @@ -222,13 +222,13 @@ export class IndentedWriter { if (message.length > 0) { this.write(message); } - this._writeNewLine(); + this.#writeNewLine(); } /** * Writes a string that does not contain any newline characters. */ - private _writeLinePart(message: string): void { + #writeLinePart(message: string): void { let trimmedMessage: string = message; if (this.trimLeadingSpaces && this.#atStartOfLine) { @@ -237,9 +237,9 @@ export class IndentedWriter { if (trimmedMessage.length > 0) { if (this.#atStartOfLine && this.#indentText.length > 0) { - this._write(this.#indentText); + this.#write(this.#indentText); } - this._write(trimmedMessage); + this.#write(trimmedMessage); if (this.#currentLineIsBlank) { if (/\S/.test(trimmedMessage)) { this.#currentLineIsBlank = false; @@ -249,26 +249,26 @@ export class IndentedWriter { } } - private _writeNewLine(): void { + #writeNewLine(): void { if (this.indentBlankLines) { if (this.#atStartOfLine && this.#indentText.length > 0) { - this._write(this.#indentText); + this.#write(this.#indentText); } } this.#previousLineIsBlank = this.#currentLineIsBlank; - this._write('\n'); + this.#write('\n'); this.#currentLineIsBlank = true; this.#atStartOfLine = true; } - private _write(s: string): void { + #write(s: string): void { this.#previousChunk = this.#latestChunk; this.#latestChunk = s; this.#builder.append(s); } - private _updateIndentText(): void { + #updateIndentText(): void { this.#indentText = this.#indentStack.join(''); } } diff --git a/libraries/api-extractor-model/src/items/ApiDeclaredItem.ts b/libraries/api-extractor-model/src/items/ApiDeclaredItem.ts index caabb784e1d..3a5f032b172 100644 --- a/libraries/api-extractor-model/src/items/ApiDeclaredItem.ts +++ b/libraries/api-extractor-model/src/items/ApiDeclaredItem.ts @@ -99,7 +99,7 @@ export class ApiDeclaredItem extends ApiDocumentedItem { */ public get sourceLocation(): SourceLocation { if (!this.#sourceLocation) { - this.#sourceLocation = this._buildSourceLocation(); + this.#sourceLocation = this.#buildSourceLocation(); } return this.#sourceLocation; } @@ -163,7 +163,7 @@ export class ApiDeclaredItem extends ApiDocumentedItem { /** * Builds the cached object used by the `sourceLocation` property. */ - private _buildSourceLocation(): SourceLocation { + #buildSourceLocation(): SourceLocation { const projectFolderUrl: string | undefined = this.getAssociatedPackage()?.projectFolderUrl; let fileUrlPath: string | undefined; diff --git a/libraries/api-extractor-model/src/model/ApiModel.ts b/libraries/api-extractor-model/src/model/ApiModel.ts index 337b982c3ba..467d7a0e8a8 100644 --- a/libraries/api-extractor-model/src/model/ApiModel.ts +++ b/libraries/api-extractor-model/src/model/ApiModel.ts @@ -149,7 +149,7 @@ export class ApiModel extends ApiItemContainerMixin(ApiItem) { this.#apiItemsByCanonicalReference = new Map(); for (const apiPackage of this.packages) { - this._initApiItemsRecursive(apiPackage, this.#apiItemsByCanonicalReference); + this.#initApiItemsRecursive(apiPackage, this.#apiItemsByCanonicalReference); } } @@ -178,7 +178,7 @@ export class ApiModel extends ApiItemContainerMixin(ApiItem) { } } - private _initApiItemsRecursive(apiItem: ApiItem, apiItemsByCanonicalReference: Map): void { + #initApiItemsRecursive(apiItem: ApiItem, apiItemsByCanonicalReference: Map): void { if (apiItem.canonicalReference && !apiItem.canonicalReference.isEmpty) { apiItemsByCanonicalReference.set(apiItem.canonicalReference.toString(), apiItem); } @@ -186,7 +186,7 @@ export class ApiModel extends ApiItemContainerMixin(ApiItem) { // Recurse container members if (ApiItemContainerMixin.isBaseClassOf(apiItem)) { for (const apiMember of apiItem.members) { - this._initApiItemsRecursive(apiMember, apiItemsByCanonicalReference); + this.#initApiItemsRecursive(apiMember, apiItemsByCanonicalReference); } } } diff --git a/libraries/api-extractor-model/src/model/ModelReferenceResolver.ts b/libraries/api-extractor-model/src/model/ModelReferenceResolver.ts index 4c0334a1ba8..68f01c1de36 100644 --- a/libraries/api-extractor-model/src/model/ModelReferenceResolver.ts +++ b/libraries/api-extractor-model/src/model/ModelReferenceResolver.ts @@ -124,10 +124,10 @@ export class ModelReferenceResolver { let memberSelectorResult: IResolveDeclarationReferenceResult; switch (memberSelector.selectorKind) { case SelectorKind.System: - memberSelectorResult = this._selectUsingSystemSelector(foundMembers, memberSelector, identifier); + memberSelectorResult = this.#selectUsingSystemSelector(foundMembers, memberSelector, identifier); break; case SelectorKind.Index: - memberSelectorResult = this._selectUsingIndexSelector(foundMembers, memberSelector, identifier); + memberSelectorResult = this.#selectUsingIndexSelector(foundMembers, memberSelector, identifier); break; default: result.errorMessage = `The selector "${memberSelector.selector}" is not a supported selector type`; @@ -143,7 +143,7 @@ export class ModelReferenceResolver { return result; } - private _selectUsingSystemSelector( + #selectUsingSystemSelector( foundMembers: ReadonlyArray, memberSelector: DocMemberSelector, identifier: string @@ -197,7 +197,7 @@ export class ModelReferenceResolver { return result; } - private _selectUsingIndexSelector( + #selectUsingIndexSelector( foundMembers: ReadonlyArray, memberSelector: DocMemberSelector, identifier: string diff --git a/libraries/credential-cache/src/CredentialCache.ts b/libraries/credential-cache/src/CredentialCache.ts index d71d3594beb..c7535b81872 100644 --- a/libraries/credential-cache/src/CredentialCache.ts +++ b/libraries/credential-cache/src/CredentialCache.ts @@ -117,7 +117,7 @@ export class CredentialCache implements Disposable { } public setCacheEntry(cacheId: string, entry: ICredentialCacheEntry): void { - this._validate(true); + this.#validate(true); const { expires, credential, credentialMetadata } = entry; const expiresMilliseconds: number = expires?.getTime() || 0; @@ -137,7 +137,7 @@ export class CredentialCache implements Disposable { } public tryGetCacheEntry(cacheId: string): ICredentialCacheEntry | undefined { - this._validate(false); + this.#validate(false); const cacheEntry: ICacheEntryJson | undefined = this.#cacheEntries.get(cacheId); if (cacheEntry) { @@ -154,7 +154,7 @@ export class CredentialCache implements Disposable { } public deleteCacheEntry(cacheId: string): void { - this._validate(true); + this.#validate(true); if (this.#cacheEntries.has(cacheId)) { this.#modified = true; @@ -163,7 +163,7 @@ export class CredentialCache implements Disposable { } public trimExpiredEntries(): void { - this._validate(true); + this.#validate(true); const now: number = Date.now(); for (const [cacheId, cacheEntry] of this.#cacheEntries.entries()) { @@ -175,7 +175,7 @@ export class CredentialCache implements Disposable { } public async saveIfModifiedAsync(): Promise { - this._validate(true); + this.#validate(true); if (this.#modified) { const cacheEntriesJson: { [cacheId: string]: ICacheEntryJson } = {}; @@ -206,7 +206,7 @@ export class CredentialCache implements Disposable { this.#disposed = true; } - private _validate(requiresEditing: boolean): void { + #validate(requiresEditing: boolean): void { if (!this.#supportsEditing && requiresEditing) { throw new Error(`This instance of ${CredentialCache.name} does not support editing.`); } diff --git a/libraries/debug-certificate-manager/src/CertificateManager.ts b/libraries/debug-certificate-manager/src/CertificateManager.ts index 98456579fb9..a2e589c4b7d 100644 --- a/libraries/debug-certificate-manager/src/CertificateManager.ts +++ b/libraries/debug-certificate-manager/src/CertificateManager.ts @@ -210,7 +210,7 @@ export class CertificateManager { if (!options?.skipCertificateTrust) { await this.untrustCertificateAsync(terminal); } - return await this._ensureCertificateInternalAsync(optionsWithDefaults, terminal); + return await this.#ensureCertificateInternalAsync(optionsWithDefaults, terminal); } else { validationResult.validationMessages.push( 'Untrust the certificate and generate a new one, or set the ' + @@ -220,7 +220,7 @@ export class CertificateManager { throw new Error(validationResult.validationMessages.join(' ')); } } else if (canGenerateNewCertificate) { - return await this._ensureCertificateInternalAsync(optionsWithDefaults, terminal); + return await this.#ensureCertificateInternalAsync(optionsWithDefaults, terminal); } else { throw new Error( 'No development certificate found. Generate a new certificate manually, or set the ' + @@ -275,7 +275,7 @@ export class CertificateManager { return false; } - const shaHash: string | undefined = this._parseMacOsMatchingCertificateHash( + const shaHash: string | undefined = this.#parseMacOsMatchingCertificateHash( macFindCertificateResult.stdout.join(EOL) ); @@ -313,7 +313,7 @@ export class CertificateManager { } } - private async _createCACertificateAsync( + async #createCACertificateAsync( validityInDays: number, forge: typeof import('node-forge') ): Promise { @@ -388,7 +388,7 @@ export class CertificateManager { }; } - private async _createDevelopmentCertificateAsync( + async #createDevelopmentCertificateAsync( options: Required ): Promise { const forge: typeof import('node-forge') = await import('node-forge'); @@ -400,7 +400,7 @@ export class CertificateManager { const { subjectAltNames: subjectNames, subjectIPAddresses: subjectIpAddresses, validityInDays } = options; - const { certificate: caCertificate, privateKey: caPrivateKey } = await this._createCACertificateAsync( + const { certificate: caCertificate, privateKey: caPrivateKey } = await this.#createCACertificateAsync( validityInDays, forge ); @@ -490,7 +490,7 @@ export class CertificateManager { }; } - private async _tryTrustCertificateAsync(certificatePath: string, terminal: ITerminal): Promise { + async #tryTrustCertificateAsync(certificatePath: string, terminal: ITerminal): Promise { switch (process.platform) { case 'win32': terminal.writeLine( @@ -580,7 +580,7 @@ export class CertificateManager { } } - private async _detectIfCertificateIsTrustedAsync(terminal: ITerminal): Promise { + async #detectIfCertificateIsTrustedAsync(terminal: ITerminal): Promise { switch (process.platform) { case 'win32': const winVerifyStoreResult: IRunResult = await runAsync(CERTUTIL_EXE_NAME, [ @@ -624,7 +624,7 @@ export class CertificateManager { return false; } - const shaHash: string | undefined = this._parseMacOsMatchingCertificateHash( + const shaHash: string | undefined = this.#parseMacOsMatchingCertificateHash( macFindCertificateResult.stdout.join(EOL) ); @@ -652,7 +652,7 @@ export class CertificateManager { } } - private async _trySetFriendlyNameAsync(certificatePath: string, terminal: ITerminal): Promise { + async #trySetFriendlyNameAsync(certificatePath: string, terminal: ITerminal): Promise { if (process.platform === 'win32') { const basePath: string = path.dirname(certificatePath); const fileName: string = path.basename(certificatePath, path.extname(certificatePath)); @@ -690,12 +690,12 @@ export class CertificateManager { } } - private async _ensureCertificateInternalAsync( + async #ensureCertificateInternalAsync( options: Required, terminal: ITerminal ): Promise { const certificateStore: CertificateStore = this.certificateStore; - const generatedCertificate: ICertificate = await this._createDevelopmentCertificateAsync(options); + const generatedCertificate: ICertificate = await this.#createDevelopmentCertificateAsync(options); const certificateName: string = Date.now().toString(); const tempDirName: string = randomTmpPath('rushstack', 'temp'); @@ -711,7 +711,7 @@ export class CertificateManager { const trustCertificateResult: boolean = options.skipCertificateTrust ? true - : await this._tryTrustCertificateAsync(tempCertificatePath, terminal); + : await this.#tryTrustCertificateAsync(tempCertificatePath, terminal); let subjectAltNames: readonly string[] | undefined; if (trustCertificateResult) { @@ -721,7 +721,7 @@ export class CertificateManager { subjectAltNames = generatedCertificate.subjectAltNames; // Try to set the friendly name, and warn if we can't - if (!(await this._trySetFriendlyNameAsync(tempCertificatePath, terminal))) { + if (!(await this.#trySetFriendlyNameAsync(tempCertificatePath, terminal))) { terminal.writeWarningLine("Unable to set the certificate's friendly name."); } } else { @@ -827,7 +827,7 @@ export class CertificateManager { ); } - const isTrusted: boolean = await this._detectIfCertificateIsTrustedAsync(terminal); + const isTrusted: boolean = await this.#detectIfCertificateIsTrustedAsync(terminal); if (!isTrusted) { messages.push('The existing development certificate is not currently trusted by your system.'); } @@ -851,7 +851,7 @@ export class CertificateManager { }; } - private _parseMacOsMatchingCertificateHash(findCertificateOuput: string): string | undefined { + #parseMacOsMatchingCertificateHash(findCertificateOuput: string): string | undefined { let shaHash: string | undefined = undefined; for (const line of findCertificateOuput.split(EOL)) { // Sets `shaHash` to the current certificate SHA-1 as we progress through the lines of certificate text. diff --git a/libraries/heft-config-file/src/ConfigurationFileBase.ts b/libraries/heft-config-file/src/ConfigurationFileBase.ts index b3e2b41ee49..0382fe2099d 100644 --- a/libraries/heft-config-file/src/ConfigurationFileBase.ts +++ b/libraries/heft-config-file/src/ConfigurationFileBase.ts @@ -432,7 +432,7 @@ export abstract class ConfigurationFileBase | undefined; #_schema: JsonSchema | undefined; - private get _schema(): JsonSchema { + get #schema(): JsonSchema { if (!this.#_schema) { this.#_schema = this.#getSchema(); } @@ -512,14 +512,14 @@ export abstract class ConfigurationFileBase = new Set(); const cacheEntry: IConfigurationFileCacheEntry = - this._loadConfigurationFileEntryWithCache( + this.#loadConfigurationFileEntryWithCache( terminal, resolvedConfigurationFilePath, visitedConfigurationFilePaths, onConfigurationFileNotFound ); - const result: TConfigurationFile = this._finalizeConfigurationFile( + const result: TConfigurationFile = this.#finalizeConfigurationFile( cacheEntry, projectFolderPath, terminal @@ -536,14 +536,14 @@ export abstract class ConfigurationFileBase { const visitedConfigurationFilePaths: Set = new Set(); const cacheEntry: IConfigurationFileCacheEntry = - await this._loadConfigurationFileEntryWithCacheAsync( + await this.#loadConfigurationFileEntryWithCacheAsync( terminal, resolvedConfigurationFilePath, visitedConfigurationFilePaths, onFileNotFound ); - const result: TConfigurationFile = this._finalizeConfigurationFile( + const result: TConfigurationFile = this.#finalizeConfigurationFile( cacheEntry, projectFolderPath, terminal @@ -552,7 +552,7 @@ export abstract class ConfigurationFileBase, @@ -573,7 +573,7 @@ export abstract class ConfigurationFileBase, @@ -605,7 +605,7 @@ export abstract class ConfigurationFileBase> | undefined = this.#configPromiseCache.get(resolvedConfigurationFilePath); if (!cacheEntryPromise) { - cacheEntryPromise = this._loadConfigurationFileEntryAsync( + cacheEntryPromise = this.#loadConfigurationFileEntryAsync( terminal, resolvedConfigurationFilePath, visitedConfigurationFilePaths, @@ -626,7 +626,7 @@ export abstract class ConfigurationFileBase, projectFolderPath: string | undefined ): IConfigurationJson & TConfigurationFile { @@ -657,14 +657,14 @@ export abstract class ConfigurationFileBase { - const resolvedPath: string = this._resolvePathProperty( + const resolvedPath: string = this.#resolvePathProperty( { propertyName: fullPayload.path, propertyValue: fullPayload.value, @@ -691,21 +691,21 @@ export abstract class ConfigurationFileBase, projectFolderPath: string | undefined ): Partial { const { parent, resolvedConfigurationFilePath } = entry; const parentConfig: TConfigurationFile | {} = parent - ? this._contextualizeAndFlattenConfigurationFile(parent, projectFolderPath) + ? this.#contextualizeAndFlattenConfigurationFile(parent, projectFolderPath) : {}; - const currentConfig: IConfigurationJson & TConfigurationFile = this._contextualizeConfigurationFile( + const currentConfig: IConfigurationJson & TConfigurationFile = this.#contextualizeConfigurationFile( entry, projectFolderPath ); - const result: Partial = this._mergeConfigurationFiles( + const result: Partial = this.#mergeConfigurationFiles( parentConfig, currentConfig, resolvedConfigurationFilePath @@ -721,20 +721,20 @@ export abstract class ConfigurationFileBase, projectFolderPath: string | undefined, terminal: ITerminal ): TConfigurationFile { const { resolvedConfigurationFilePathForLogging } = entry; - const result: Partial = this._contextualizeAndFlattenConfigurationFile( + const result: Partial = this.#contextualizeAndFlattenConfigurationFile( entry, projectFolderPath ); try { - this._schema.validateObject(result, resolvedConfigurationFilePathForLogging); + this.#schema.validateObject(result, resolvedConfigurationFilePathForLogging); } catch (e) { throw new Error(`Resolved configuration object does not match schema: ${e}`); } @@ -761,7 +761,7 @@ export abstract class ConfigurationFileBase, @@ -781,7 +781,7 @@ export abstract class ConfigurationFileBase, @@ -861,7 +861,7 @@ export abstract class ConfigurationFileBase(resolvedConfigurationFilePath: string, root: TObject): void { + #annotateProperties(resolvedConfigurationFilePath: string, root: TObject): void { if (!root) { return; } @@ -938,7 +938,7 @@ export abstract class ConfigurationFileBase, metadata: IJsonPathMetadata ): string { @@ -993,7 +993,7 @@ export abstract class ConfigurationFileBase, configurationJson: Partial, resolvedConfigurationFilePath: string @@ -1002,7 +1002,7 @@ export abstract class ConfigurationFileBase = this._mergeObjects( + const result: Partial = this.#mergeObjects( parentConfiguration as { [key: string]: unknown }, configurationJson as { [key: string]: unknown }, resolvedConfigurationFilePath, @@ -1019,7 +1019,7 @@ export abstract class ConfigurationFileBase( + #mergeObjects( parentObject: Partial, currentObject: Partial, resolvedConfigurationFilePath: string, @@ -1221,7 +1221,7 @@ export abstract class ConfigurationFileBase extends ConfigurationF projectPath: string, rigConfig?: IRigConfig ): TConfigurationFile { - const projectConfigurationFilePath: string = this._getConfigurationFilePathForProject(projectPath); + const projectConfigurationFilePath: string = this.#getConfigurationFilePathForProject(projectPath); return this._loadConfigurationFileInnerWithCache( terminal, projectConfigurationFilePath, PackageJsonLookup.instance.tryGetPackageFolderFor(projectPath), - this._getRigConfigFallback(terminal, rigConfig) + this.#getRigConfigFallback(terminal, rigConfig) ); } @@ -76,12 +76,12 @@ export class ProjectConfigurationFile extends ConfigurationF projectPath: string, rigConfig?: IRigConfig ): Promise { - const projectConfigurationFilePath: string = this._getConfigurationFilePathForProject(projectPath); + const projectConfigurationFilePath: string = this.#getConfigurationFilePathForProject(projectPath); return await this._loadConfigurationFileInnerWithCacheAsync( terminal, projectConfigurationFilePath, PackageJsonLookup.instance.tryGetPackageFolderFor(projectPath), - this._getRigConfigFallback(terminal, rigConfig) + this.#getRigConfigFallback(terminal, rigConfig) ); } @@ -123,11 +123,11 @@ export class ProjectConfigurationFile extends ConfigurationF } } - private _getConfigurationFilePathForProject(projectPath: string): string { + #getConfigurationFilePathForProject(projectPath: string): string { return nodeJsPath.resolve(projectPath, this.projectRelativeFilePath); } - private _getRigConfigFallback( + #getRigConfigFallback( terminal: ITerminal, rigConfig: IRigConfig | undefined ): IOnConfigurationFileNotFoundCallback | undefined { diff --git a/libraries/lookup-by-path/src/LookupByPath.ts b/libraries/lookup-by-path/src/LookupByPath.ts index 6673296d85e..485300b702a 100644 --- a/libraries/lookup-by-path/src/LookupByPath.ts +++ b/libraries/lookup-by-path/src/LookupByPath.ts @@ -373,7 +373,7 @@ export class LookupByPath implements IReadonlyLookupByPath | undefined = this._findNodeAtPrefix(query, delimeter); + const node: IPathTrieNode | undefined = this.#findNodeAtPrefix(query, delimeter); if (node?.value !== undefined) { node.value = undefined; this.#size--; @@ -390,7 +390,7 @@ export class LookupByPath implements IReadonlyLookupByPath | undefined = this._findNodeAtPrefix(query, delimeter); + const queryNode: IPathTrieNode | undefined = this.#findNodeAtPrefix(query, delimeter); if (!queryNode) { return false; } @@ -461,7 +461,7 @@ export class LookupByPath implements IReadonlyLookupByPath | undefined { - return this._findLongestPrefixMatch(_iteratePrefixes(query, delimiter)); + return this.#findLongestPrefixMatch(_iteratePrefixes(query, delimiter)); } /** @@ -535,7 +535,7 @@ export class LookupByPath implements IReadonlyLookupByPath { let root: IPathTrieNode | undefined; if (query) { - root = this._findNodeAtPrefix(query, delimiter); + root = this.#findNodeAtPrefix(query, delimiter); if (!root) { return; } @@ -574,7 +574,7 @@ export class LookupByPath implements IReadonlyLookupByPath | undefined { - return this._findNodeAtPrefix(query, delimiter); + return this.#findNodeAtPrefix(query, delimiter); } /** @@ -677,7 +677,7 @@ export class LookupByPath implements IReadonlyLookupByPath): IPrefixMatch | undefined { + #findLongestPrefixMatch(prefixes: Iterable): IPrefixMatch | undefined { let node: IPathTrieNode = this.#root; let best: IPrefixMatch | undefined = node.value ? { @@ -716,7 +716,7 @@ export class LookupByPath implements IReadonlyLookupByPath | undefined { diff --git a/libraries/npm-check-fork/src/NpmRegistryClient.ts b/libraries/npm-check-fork/src/NpmRegistryClient.ts index 62068f1b16d..13703a98a5a 100644 --- a/libraries/npm-check-fork/src/NpmRegistryClient.ts +++ b/libraries/npm-check-fork/src/NpmRegistryClient.ts @@ -84,7 +84,7 @@ export class NpmRegistryClient { * @param packageName - The name of the package * @returns The full URL for fetching the package metadata */ - private _buildPackageUrl(packageName: string): string { + #buildPackageUrl(packageName: string): string { // Scoped packages need the slash encoded // @scope/name -> @scope%2Fname const encodedName: string = packageName.replace(/\//g, '%2F'); @@ -109,7 +109,7 @@ export class NpmRegistryClient { * ``` */ public async fetchPackageMetadataAsync(packageName: string): Promise { - const url: string = this._buildPackageUrl(packageName); + const url: string = this.#buildPackageUrl(packageName); return new Promise((resolve) => { const parsedUrl: URL = new URL(url); diff --git a/libraries/operation-graph/src/Operation.ts b/libraries/operation-graph/src/Operation.ts index 0b3434ab5e4..302981a4636 100644 --- a/libraries/operation-graph/src/Operation.ts +++ b/libraries/operation-graph/src/Operation.ts @@ -245,13 +245,13 @@ export class Operation { diff --git a/libraries/operation-graph/src/WatchLoop.ts b/libraries/operation-graph/src/WatchLoop.ts index 8a50f720634..dec3f0698c0 100644 --- a/libraries/operation-graph/src/WatchLoop.ts +++ b/libraries/operation-graph/src/WatchLoop.ts @@ -97,7 +97,7 @@ export class WatchLoop implements IWatchLoopState { return OperationStatus.Aborted; } - result = await this._runIterationAsync(); + result = await this.#runIterationAsync(); } while (this.#runRequested); // Even if the run has finished, if the abort signal was aborted, we should return `Aborted` just in case. @@ -262,7 +262,7 @@ export class WatchLoop implements IWatchLoopState { /** * Resets the abort signal and run request state. */ - private _reset(): void { + #reset(): void { if (this.#abortController.signal.aborted) { this.#abortController = new AbortController(); } @@ -279,8 +279,8 @@ export class WatchLoop implements IWatchLoopState { * Runs a single iteration of the loop. * @returns The status of the iteration. */ - private async _runIterationAsync(): Promise { - this._reset(); + async #runIterationAsync(): Promise { + this.#reset(); this.#options.onBeforeExecute(); try { diff --git a/libraries/operation-graph/src/WorkQueue.ts b/libraries/operation-graph/src/WorkQueue.ts index d9b6dd89a40..5af83c5f35d 100644 --- a/libraries/operation-graph/src/WorkQueue.ts +++ b/libraries/operation-graph/src/WorkQueue.ts @@ -55,11 +55,11 @@ export class WorkQueue { // eslint-disable-next-line @typescript-eslint/no-floating-promises this.#abortPromise.finally(() => resolve(OperationStatus.Aborted)); - this._resolvePushDebounced(); + this.#resolvePushDebounced(); }); } - private _resolvePushDebounced(): void { + #resolvePushDebounced(): void { if (!this.#resolvePushTimeout) { this.#resolvePushTimeout = setTimeout(() => { this.#resolvePushTimeout = undefined; diff --git a/libraries/package-extractor/src/AssetHandler.ts b/libraries/package-extractor/src/AssetHandler.ts index ef8e0db02c4..cf064774d3d 100644 --- a/libraries/package-extractor/src/AssetHandler.ts +++ b/libraries/package-extractor/src/AssetHandler.ts @@ -165,7 +165,7 @@ export class AssetHandler { this.#terminal.writeLine('Creating symlinks'); const linksToCopy: ILinkInfo[] = this.#symlinkAnalyzer.reportSymlinks(); await Async.forEachAsync(linksToCopy, async (linkToCopy: ILinkInfo) => { - await this._extractSymlinkAsync(linkToCopy); + await this.#extractSymlinkAsync(linkToCopy); }); } @@ -182,7 +182,7 @@ export class AssetHandler { /** * Create a symlink as described by the ILinkInfo object. */ - private async _extractSymlinkAsync(linkInfo: ILinkInfo): Promise { + async #extractSymlinkAsync(linkInfo: ILinkInfo): Promise { const { kind, linkPath, targetPath } = { ...linkInfo, linkPath: remapSourcePathForTargetFolder({ diff --git a/libraries/package-extractor/src/PackageExtractor.ts b/libraries/package-extractor/src/PackageExtractor.ts index c9e381e818f..e60df7b46ae 100644 --- a/libraries/package-extractor/src/PackageExtractor.ts +++ b/libraries/package-extractor/src/PackageExtractor.ts @@ -413,25 +413,25 @@ export class PackageExtractor { existingDependencyConfigurations.push(dependencyConfiguration); } - await this._performExtractionAsync(options, state); + await this.#performExtractionAsync(options, state); await state.assetHandler.finalizeAsync({ onAfterExtractSymlinksAsync: async () => { // We need the symlinks to be created before attempting to create the bin links, since it requires // the node_modules folder to be realized. While we're here, we may as well perform some specific // link creation tasks and write the extractor-metadata.json file before the asset handler finalizes. if (linkCreation === 'default') { - await this._makeBinLinksAsync(options, state); + await this.#makeBinLinksAsync(options, state); } else if (linkCreation === 'script') { - await this._writeCreateLinksScriptAsync(options, state); + await this.#writeCreateLinksScriptAsync(options, state); } terminal.writeLine('Creating extractor-metadata.json'); - await this._writeExtractorMetadataAsync(options, state); + await this.#writeExtractorMetadataAsync(options, state); } }); } - private async _performExtractionAsync(options: IExtractorOptions, state: IExtractorState): Promise { + async #performExtractionAsync(options: IExtractorOptions, state: IExtractorState): Promise { const { terminal, mainProjectName, @@ -470,7 +470,7 @@ export class PackageExtractor { terminal.writeLine(Colorize.cyan(`Analyzing project: ${projectName}`)); startingFolders.push(projectFolder); } - await this._collectFoldersAsync(startingFolders, options, state); + await this.#collectFoldersAsync(startingFolders, options, state); if (!createArchiveOnly) { terminal.writeLine(`Copying folders to target folder "${targetRootFolder}"`); @@ -478,7 +478,7 @@ export class PackageExtractor { await Async.forEachAsync( foldersToCopy, async (folderToCopy: string) => { - await this._extractFolderAsync(folderToCopy, options, state); + await this.#extractFolderAsync(folderToCopy, options, state); }, { concurrency: MAX_CONCURRENCY @@ -494,14 +494,14 @@ export class PackageExtractor { sourceRootFolder: additionalFolderPath, targetRootFolder }; - await this._extractFolderAsync(additionalFolderPath, additionalFolderExtractorOptions, state); + await this.#extractFolderAsync(additionalFolderPath, additionalFolderExtractorOptions, state); } } /** * Recursively crawl the node_modules dependencies and collect the result in IExtractorState.foldersToCopy. */ - private async _collectFoldersAsync( + async #collectFoldersAsync( packageJsonFolders: string[], options: IExtractorOptions, state: IExtractorState @@ -566,7 +566,7 @@ export class PackageExtractor { } } - this._applyDependencyFilters( + this.#applyDependencyFilters( terminal, dependencyNamesToProcess, projectConfiguration.additionalDependenciesToInclude, @@ -653,7 +653,7 @@ export class PackageExtractor { ); } - private _applyDependencyFilters( + #applyDependencyFilters( terminal: ITerminal, allDependencyNames: Set, additionalDependenciesToInclude: string[] = [], @@ -696,7 +696,7 @@ export class PackageExtractor { /** * Copy one package folder to the extractor target folder. */ - private async _extractFolderAsync( + async #extractFolderAsync( sourceFolderPath: string, options: IExtractorOptions, state: IExtractorState @@ -884,7 +884,7 @@ export class PackageExtractor { /** * Write the common/deploy/deploy-metadata.json file. */ - private async _writeExtractorMetadataAsync( + async #writeExtractorMetadataAsync( options: IExtractorOptions, state: IExtractorState ): Promise { @@ -936,7 +936,7 @@ export class PackageExtractor { }); } - private async _makeBinLinksAsync(options: IExtractorOptions, state: IExtractorState): Promise { + async #makeBinLinksAsync(options: IExtractorOptions, state: IExtractorState): Promise { const { terminal } = options; const extractedProjectFolderPaths: string[] = []; @@ -958,7 +958,7 @@ export class PackageExtractor { ); } - private async _writeCreateLinksScriptAsync( + async #writeCreateLinksScriptAsync( options: IExtractorOptions, state: IExtractorState ): Promise { diff --git a/libraries/stream-collator/src/StreamCollator.ts b/libraries/stream-collator/src/StreamCollator.ts index 9931ce01c55..0e3f059bb91 100644 --- a/libraries/stream-collator/src/StreamCollator.ts +++ b/libraries/stream-collator/src/StreamCollator.ts @@ -108,7 +108,7 @@ export class StreamCollator { if (this.#activeWriter === undefined) { // If there is no active writer, then the first one to be registered becomes active. - this._assignActiveWriter(writer); + this.#assignActiveWriter(writer); } return writer; @@ -120,11 +120,11 @@ export class StreamCollator { chunk: ITerminalChunk, bufferedChunks: ITerminalChunk[] ): void { - this._checkForReentrantCall(); + this.#checkForReentrantCall(); if (this.#activeWriter === undefined) { // If no writer is currently active, then the first one to write something becomes active - this._assignActiveWriter(writer); + this.#assignActiveWriter(writer); } if (writer.isActive) { @@ -136,7 +136,7 @@ export class StreamCollator { /** @internal */ public _writerClose(writer: CollatedWriter, bufferedChunks: ITerminalChunk[]): void { - this._checkForReentrantCall(); + this.#checkForReentrantCall(); if (writer.isActive) { writer._flushBufferedChunks(); @@ -147,7 +147,7 @@ export class StreamCollator { // We copy the set, since _assignActiveWriter() will be deleting from it. for (const closedInactiveWriter of [...this.#closedInactiveWriters]) { try { - this._assignActiveWriter(closedInactiveWriter); + this.#assignActiveWriter(closedInactiveWriter); } finally { this.#activeWriter = undefined; } @@ -171,7 +171,7 @@ export class StreamCollator { } if (writerToActivate) { - this._assignActiveWriter(writerToActivate); + this.#assignActiveWriter(writerToActivate); } } else { this.#openInactiveWriters.delete(writer); @@ -179,7 +179,7 @@ export class StreamCollator { } } - private _assignActiveWriter(writer: CollatedWriter): void { + #assignActiveWriter(writer: CollatedWriter): void { this.#activeWriter = writer; this.#closedInactiveWriters.delete(writer); @@ -197,7 +197,7 @@ export class StreamCollator { writer._flushBufferedChunks(); } - private _checkForReentrantCall(): void { + #checkForReentrantCall(): void { if (this.#preventReentrantCall) { throw new InternalError('Reentrant call to StreamCollator'); } diff --git a/libraries/terminal/src/StdioLineTransform.ts b/libraries/terminal/src/StdioLineTransform.ts index 7574b92cd9e..6b60a401939 100644 --- a/libraries/terminal/src/StdioLineTransform.ts +++ b/libraries/terminal/src/StdioLineTransform.ts @@ -106,7 +106,7 @@ export class StderrLineTransform extends TerminalTransform { // append everything up to \n this.#accumulatedLine += text.substring(startIndex, endIndex); - this._processAccumulatedLine(); + this.#processAccumulatedLine(); // skip the \n startIndex = endIndex + 1; @@ -115,12 +115,12 @@ export class StderrLineTransform extends TerminalTransform { protected onClose(): void { if (this.#accumulatedLine.length > 0) { - this._processAccumulatedLine(); + this.#processAccumulatedLine(); } this.autocloseDestination(); } - private _processAccumulatedLine(): void { + #processAccumulatedLine(): void { this.#accumulatedLine += this.newline; if (this.#accumulatedStderr) { diff --git a/libraries/terminal/src/Terminal.ts b/libraries/terminal/src/Terminal.ts index 39421234a36..f718fbdc598 100644 --- a/libraries/terminal/src/Terminal.ts +++ b/libraries/terminal/src/Terminal.ts @@ -36,16 +36,16 @@ export class Terminal implements ITerminal { * {@inheritdoc ITerminal.write} */ public write(...messageParts: TerminalWriteParameters): void { - const { parts } = this._normalizeWriteParameters(messageParts); - this._writeSegmentsToProviders(parts, TerminalProviderSeverity.log, false); + const { parts } = this.#normalizeWriteParameters(messageParts); + this.#writeSegmentsToProviders(parts, TerminalProviderSeverity.log, false); } /** * {@inheritdoc ITerminal.writeLine} */ public writeLine(...messageParts: TerminalWriteParameters): void { - const { parts } = this._normalizeWriteParameters(messageParts); - this._writeSegmentsToProviders(parts, TerminalProviderSeverity.log, true); + const { parts } = this.#normalizeWriteParameters(messageParts); + this.#writeSegmentsToProviders(parts, TerminalProviderSeverity.log, true); } /** @@ -55,8 +55,8 @@ export class Terminal implements ITerminal { const { parts, options: { doNotOverrideSgrCodes } - } = this._normalizeWriteParameters(messageParts); - this._writeSegmentsToProviders( + } = this.#normalizeWriteParameters(messageParts); + this.#writeSegmentsToProviders( doNotOverrideSgrCodes ? parts : parts.map((part): string => Colorize.yellow(AnsiEscape.removeCodes(part))), @@ -72,8 +72,8 @@ export class Terminal implements ITerminal { const { parts, options: { doNotOverrideSgrCodes } - } = this._normalizeWriteParameters(messageParts); - this._writeSegmentsToProviders( + } = this.#normalizeWriteParameters(messageParts); + this.#writeSegmentsToProviders( doNotOverrideSgrCodes ? parts : parts.map((part): string => Colorize.yellow(AnsiEscape.removeCodes(part))), @@ -89,8 +89,8 @@ export class Terminal implements ITerminal { const { parts, options: { doNotOverrideSgrCodes } - } = this._normalizeWriteParameters(messageParts); - this._writeSegmentsToProviders( + } = this.#normalizeWriteParameters(messageParts); + this.#writeSegmentsToProviders( doNotOverrideSgrCodes ? parts : parts.map((part): string => Colorize.red(AnsiEscape.removeCodes(part))), TerminalProviderSeverity.error, false @@ -104,8 +104,8 @@ export class Terminal implements ITerminal { const { parts, options: { doNotOverrideSgrCodes } - } = this._normalizeWriteParameters(messageParts); - this._writeSegmentsToProviders( + } = this.#normalizeWriteParameters(messageParts); + this.#writeSegmentsToProviders( doNotOverrideSgrCodes ? parts : parts.map((part): string => Colorize.red(AnsiEscape.removeCodes(part))), TerminalProviderSeverity.error, true @@ -116,35 +116,35 @@ export class Terminal implements ITerminal { * {@inheritdoc ITerminal.writeVerbose} */ public writeVerbose(...messageParts: TerminalWriteParameters): void { - const { parts } = this._normalizeWriteParameters(messageParts); - this._writeSegmentsToProviders(parts, TerminalProviderSeverity.verbose, false); + const { parts } = this.#normalizeWriteParameters(messageParts); + this.#writeSegmentsToProviders(parts, TerminalProviderSeverity.verbose, false); } /** * {@inheritdoc ITerminal.writeVerboseLine} */ public writeVerboseLine(...messageParts: TerminalWriteParameters): void { - const { parts } = this._normalizeWriteParameters(messageParts); - this._writeSegmentsToProviders(parts, TerminalProviderSeverity.verbose, true); + const { parts } = this.#normalizeWriteParameters(messageParts); + this.#writeSegmentsToProviders(parts, TerminalProviderSeverity.verbose, true); } /** * {@inheritdoc ITerminal.writeDebug} */ public writeDebug(...messageParts: TerminalWriteParameters): void { - const { parts } = this._normalizeWriteParameters(messageParts); - this._writeSegmentsToProviders(parts, TerminalProviderSeverity.debug, false); + const { parts } = this.#normalizeWriteParameters(messageParts); + this.#writeSegmentsToProviders(parts, TerminalProviderSeverity.debug, false); } /** * {@inheritdoc ITerminal.writeDebugLine} */ public writeDebugLine(...messageParts: TerminalWriteParameters): void { - const { parts } = this._normalizeWriteParameters(messageParts); - this._writeSegmentsToProviders(parts, TerminalProviderSeverity.debug, true); + const { parts } = this.#normalizeWriteParameters(messageParts); + this.#writeSegmentsToProviders(parts, TerminalProviderSeverity.debug, true); } - private _writeSegmentsToProviders( + #writeSegmentsToProviders( segments: string[], severity: TerminalProviderSeverity, followedByEol: boolean @@ -186,7 +186,7 @@ export class Terminal implements ITerminal { } } - private _normalizeWriteParameters(parameters: TerminalWriteParameters): { + #normalizeWriteParameters(parameters: TerminalWriteParameters): { parts: string[]; options: ITerminalWriteOptions; } { diff --git a/libraries/terminal/src/TextRewriterTransform.ts b/libraries/terminal/src/TextRewriterTransform.ts index 727fda0a548..2d464c4f327 100644 --- a/libraries/terminal/src/TextRewriterTransform.ts +++ b/libraries/terminal/src/TextRewriterTransform.ts @@ -101,15 +101,15 @@ export class TextRewriterTransform extends TerminalTransform { protected onWriteChunk(chunk: ITerminalChunk): void { if (chunk.kind === TerminalChunkKind.Stderr) { - this._processText(chunk, this.#stderrStates); + this.#processText(chunk, this.#stderrStates); } else if (chunk.kind === TerminalChunkKind.Stdout) { - this._processText(chunk, this.#stdoutStates); + this.#processText(chunk, this.#stdoutStates); } else { this.destination.writeChunk(chunk); } } - private _processText(chunk: ITerminalChunk, states: TextRewriterState[]): void { + #processText(chunk: ITerminalChunk, states: TextRewriterState[]): void { let text: string = chunk.text; for (let i: number = 0; i < states.length; ++i) { if (text.length > 0) { @@ -129,7 +129,7 @@ export class TextRewriterTransform extends TerminalTransform { } } - private _closeRewriters(states: TextRewriterState[], chunkKind: TerminalChunkKind): void { + #closeRewriters(states: TextRewriterState[], chunkKind: TerminalChunkKind): void { let text: string = ''; for (let i: number = 0; i < states.length; ++i) { if (text.length > 0) { @@ -146,8 +146,8 @@ export class TextRewriterTransform extends TerminalTransform { } protected onClose(): void { - this._closeRewriters(this.#stderrStates, TerminalChunkKind.Stderr); - this._closeRewriters(this.#stdoutStates, TerminalChunkKind.Stdout); + this.#closeRewriters(this.#stderrStates, TerminalChunkKind.Stderr); + this.#closeRewriters(this.#stdoutStates, TerminalChunkKind.Stdout); this.autocloseDestination(); } diff --git a/libraries/ts-command-line/src/providers/CommandLineParameterProvider.ts b/libraries/ts-command-line/src/providers/CommandLineParameterProvider.ts index d85aafac399..2fe89023a36 100644 --- a/libraries/ts-command-line/src/providers/CommandLineParameterProvider.ts +++ b/libraries/ts-command-line/src/providers/CommandLineParameterProvider.ts @@ -208,7 +208,7 @@ export abstract class CommandLineParameterProvider { * This method throws an exception if the parameter is not defined. */ public getChoiceParameter(parameterLongName: string, parameterScope?: string): CommandLineChoiceParameter { - return this._getParameter(parameterLongName, CommandLineParameterKind.Choice, parameterScope); + return this.#getParameter(parameterLongName, CommandLineParameterKind.Choice, parameterScope); } /** @@ -239,7 +239,7 @@ export abstract class CommandLineParameterProvider { parameterLongName: string, parameterScope?: string ): CommandLineChoiceListParameter { - return this._getParameter(parameterLongName, CommandLineParameterKind.ChoiceList, parameterScope); + return this.#getParameter(parameterLongName, CommandLineParameterKind.ChoiceList, parameterScope); } /** @@ -264,7 +264,7 @@ export abstract class CommandLineParameterProvider { * This method throws an exception if the parameter is not defined. */ public getFlagParameter(parameterLongName: string, parameterScope?: string): CommandLineFlagParameter { - return this._getParameter(parameterLongName, CommandLineParameterKind.Flag, parameterScope); + return this.#getParameter(parameterLongName, CommandLineParameterKind.Flag, parameterScope); } /** @@ -310,7 +310,7 @@ export abstract class CommandLineParameterProvider { parameterLongName: string, parameterScope?: string ): CommandLineIntegerParameter { - return this._getParameter(parameterLongName, CommandLineParameterKind.Integer, parameterScope); + return this.#getParameter(parameterLongName, CommandLineParameterKind.Integer, parameterScope); } /** @@ -340,7 +340,7 @@ export abstract class CommandLineParameterProvider { parameterLongName: string, parameterScope?: string ): CommandLineIntegerListParameter { - return this._getParameter(parameterLongName, CommandLineParameterKind.IntegerList, parameterScope); + return this.#getParameter(parameterLongName, CommandLineParameterKind.IntegerList, parameterScope); } /** @@ -383,7 +383,7 @@ export abstract class CommandLineParameterProvider { * This method throws an exception if the parameter is not defined. */ public getStringParameter(parameterLongName: string, parameterScope?: string): CommandLineStringParameter { - return this._getParameter(parameterLongName, CommandLineParameterKind.String, parameterScope); + return this.#getParameter(parameterLongName, CommandLineParameterKind.String, parameterScope); } /** @@ -436,7 +436,7 @@ export abstract class CommandLineParameterProvider { parameterLongName: string, parameterScope?: string ): CommandLineStringListParameter { - return this._getParameter(parameterLongName, CommandLineParameterKind.StringList, parameterScope); + return this.#getParameter(parameterLongName, CommandLineParameterKind.StringList, parameterScope); } /** @@ -634,7 +634,7 @@ export abstract class CommandLineParameterProvider { // When the parser key matches the actually registered parameter, we know that this is an ambiguous // parameter sourced from the parent action or tool if (this._registeredParameterParserKeysByName.get(parameterName) === parserKey) { - this._throwParserExitError(parserOptions, data, 1, `Ambiguous option: "${parameterName}".`); + this.#throwParserExitError(parserOptions, data, 1, `Ambiguous option: "${parameterName}".`); } // Determine if the ambiguous parameter is a short name or a long name, since the process of finding @@ -672,7 +672,7 @@ export abstract class CommandLineParameterProvider { // Throw an error including the non-ambiguous long names for the parameters that have the ambiguous // short name, ex. // Error: Ambiguous option "-p" could match "--param1", "--param2" - this._throwParserExitError( + this.#throwParserExitError( parserOptions, data, 1, @@ -699,7 +699,7 @@ export abstract class CommandLineParameterProvider { // Throw an error including the non-ambiguous scoped long names for the parameters that have the // ambiguous long name, ex. // Error: Ambiguous option: "--param" could match --scope1:param, --scope2:param - this._throwParserExitError( + this.#throwParserExitError( parserOptions, data, 1, @@ -708,7 +708,7 @@ export abstract class CommandLineParameterProvider { } // This shouldn't happen, but we also shouldn't allow the user to use the ambiguous parameter - this._throwParserExitError(parserOptions, data, 1, `Ambiguous option: "${parameterName}".`); + this.#throwParserExitError(parserOptions, data, 1, `Ambiguous option: "${parameterName}".`); } } @@ -733,7 +733,7 @@ export abstract class CommandLineParameterProvider { } // Generate and set the parser key at definition time - parameter._parserKey = this._generateKey(); + parameter._parserKey = this.#generateKey(); this.#parameters.push(parameter); @@ -772,7 +772,7 @@ export abstract class CommandLineParameterProvider { this._registeredParameterParserKeysByName.get(name) || this._ambiguousParameterParserKeysByName.get(name); if (!existingParserKey) { - existingParserKey = this._generateKey(); + existingParserKey = this.#generateKey(); } this._ambiguousParameterParserKeysByName.set(name, existingParserKey); @@ -970,11 +970,11 @@ export abstract class CommandLineParameterProvider { }); } - private _generateKey(): string { + #generateKey(): string { return 'key_' + (_keyCounter++).toString(); } - private _getParameter( + #getParameter( parameterLongName: string, expectedKind: CommandLineParameterKind, parameterScope?: string @@ -1015,7 +1015,7 @@ export abstract class CommandLineParameterProvider { return parameter as T; } - private _throwParserExitError( + #throwParserExitError( parserOptions: ICommandLineParserOptions, data: ICommandLineParserData, errorCode: number, diff --git a/libraries/ts-command-line/src/providers/CommandLineParser.ts b/libraries/ts-command-line/src/providers/CommandLineParser.ts index b469d84c34f..13c8fe19f7a 100644 --- a/libraries/ts-command-line/src/providers/CommandLineParser.ts +++ b/libraries/ts-command-line/src/providers/CommandLineParser.ts @@ -209,7 +209,7 @@ export class CommandLineParser extends CommandLineParameterProvider { } this.#executed = true; - this._validateDefinitions(); + this.#validateDefinitions(); // Register the parameters before we print help or parse the CLI const initialState: IRegisterDefinedParametersState = { @@ -316,7 +316,7 @@ export class CommandLineParser extends CommandLineParameterProvider { } } - private _validateDefinitions(): void { + #validateDefinitions(): void { if (this.remainder && this.actions.length > 0) { // This is apparently not supported by argparse throw new Error('defineCommandLineRemainder() cannot be called for a CommandLineParser with actions'); diff --git a/libraries/ts-command-line/src/providers/TabCompletionAction.ts b/libraries/ts-command-line/src/providers/TabCompletionAction.ts index 8461fcf7d45..7403be832e9 100644 --- a/libraries/ts-command-line/src/providers/TabCompletionAction.ts +++ b/libraries/ts-command-line/src/providers/TabCompletionAction.ts @@ -86,17 +86,17 @@ export class TabCompleteAction extends CommandLineAction { const actions: Map> = this.#actions; if (!commandLine || !caretPosition) { - yield* this._getAllActions(); + yield* this.#getAllActions(); return; } const tokens: string[] = Array.from(this.tokenizeCommandLine(commandLine)); // offset arguments by the number of global params in the input - const globalParameterOffset: number = this._getGlobalParameterOffset(tokens); + const globalParameterOffset: number = this.#getGlobalParameterOffset(tokens); if (tokens.length < 2 + globalParameterOffset) { - yield* this._getAllActions(); + yield* this.#getAllActions(); return; } @@ -122,20 +122,20 @@ export class TabCompleteAction extends CommandLineAction { if (completePartialWord) { for (const parameterName of parameterNames) { if (parameterName === secondLastToken) { - const values: ReadonlySet = await this._getParameterValueCompletionsAsync( + const values: ReadonlySet = await this.#getParameterValueCompletionsAsync( parameterNameMap.get(parameterName)! ); if (values.size > 0) { - yield* this._completeParameterValues(values, lastToken); + yield* this.#completeParameterValues(values, lastToken); return; } } } - yield* this._completeParameterValues(parameterNames, lastToken); + yield* this.#completeParameterValues(parameterNames, lastToken); } else { for (const parameterName of parameterNames) { if (parameterName === lastToken) { - const values: ReadonlySet = await this._getParameterValueCompletionsAsync( + const values: ReadonlySet = await this.#getParameterValueCompletionsAsync( parameterNameMap.get(parameterName)! ); if (values.size > 0) { @@ -163,7 +163,7 @@ export class TabCompleteAction extends CommandLineAction { } } - private *_getAllActions(): IterableIterator { + *#getAllActions(): IterableIterator { yield* this.#actions.keys(); yield* this.#globalParameters.keys(); } @@ -172,7 +172,7 @@ export class TabCompleteAction extends CommandLineAction { return stringArgv(commandLine); } - private async _getParameterValueCompletionsAsync( + async #getParameterValueCompletionsAsync( parameter: CommandLineParameter ): Promise> { let choiceParameterValues: ReadonlySet | undefined; @@ -198,7 +198,7 @@ export class TabCompleteAction extends CommandLineAction { return choiceParameterValues ?? new Set(); } - private _getGlobalParameterOffset(tokens: string[]): number { + #getGlobalParameterOffset(tokens: string[]): number { const globalParameters: Map = this.#globalParameters; let count: number = 0; @@ -214,7 +214,7 @@ export class TabCompleteAction extends CommandLineAction { return count; } - private *_completeParameterValues( + *#completeParameterValues( choiceParameterValues: ReadonlyArray | ReadonlySet, lastToken: string ): IterableIterator { diff --git a/libraries/typings-generator/src/TypingsGenerator.ts b/libraries/typings-generator/src/TypingsGenerator.ts index cdc962e4ce2..9069012e87a 100644 --- a/libraries/typings-generator/src/TypingsGenerator.ts +++ b/libraries/typings-generator/src/TypingsGenerator.ts @@ -184,7 +184,7 @@ export class TypingsGenerator { this.terminal = terminal; - this._options.fileExtensions = this._normalizeFileExtensions(fileExtensions); + this._options.fileExtensions = this.#normalizeFileExtensions(fileExtensions); this.#dependenciesOfFile = new Map(); this.#consumersOfFile = new Map(); @@ -210,7 +210,7 @@ export class TypingsGenerator { }); } - await this._reprocessFilesAsync(relativeFilePaths!, checkFilePaths); + await this.#reprocessFilesAsync(relativeFilePaths!, checkFilePaths); } public async runWatcherAsync(): Promise { @@ -232,7 +232,7 @@ export class TypingsGenerator { const toProcess: string[] = Array.from(queue); queue.clear(); - this._reprocessFilesAsync(toProcess, false) + this.#reprocessFilesAsync(toProcess, false) .then(() => { processing = false; // If the timeout was invoked again, immediately re-execute with the changed files. @@ -269,7 +269,7 @@ export class TypingsGenerator { watcher.on('change', onChange); watcher.on('unlink', async (relativePath) => { await Promise.all( - this._getOutputFilePathsWithoutCheck(relativePath).map(async (outputFile: string) => { + this.#getOutputFilePathsWithoutCheck(relativePath).map(async (outputFile: string) => { await FileSystem.deleteFileAsync(outputFile); }) ); @@ -308,16 +308,16 @@ export class TypingsGenerator { throw new Error(`"${relativePath}" must be relative`); } - return this._getOutputFilePathsWithoutCheck(relativePath); + return this.#getOutputFilePathsWithoutCheck(relativePath); } - private _getOutputFilePathsWithoutCheck(relativePath: string): string[] { - const typingsFilePaths: Iterable = this._getTypingsFilePaths(relativePath); + #getOutputFilePathsWithoutCheck(relativePath: string): string[] { + const typingsFilePaths: Iterable = this.#getTypingsFilePaths(relativePath); const additionalPaths: string[] | undefined = this._options.getAdditionalOutputFiles?.(relativePath); return additionalPaths ? [...typingsFilePaths, ...additionalPaths] : Array.from(typingsFilePaths); } - private async _reprocessFilesAsync( + async #reprocessFilesAsync( relativePaths: Iterable, checkFilePaths: boolean ): Promise { @@ -352,15 +352,15 @@ export class TypingsGenerator { if (!relativePath) { throw new Error(`Missing relative path for file ${resolvedPath}`); } - await this._parseFileAndGenerateTypingsAsync(relativePath, resolvedPath); + await this.#parseFileAndGenerateTypingsAsync(relativePath, resolvedPath); }, { concurrency: 20 } ); } - private async _parseFileAndGenerateTypingsAsync(relativePath: string, resolvedPath: string): Promise { + async #parseFileAndGenerateTypingsAsync(relativePath: string, resolvedPath: string): Promise { // Clear registered dependencies prior to reprocessing. - this._clearDependencies(resolvedPath); + this.#clearDependencies(resolvedPath); try { const fileContents: TFileContents = await this._options.readFile(resolvedPath, relativePath); @@ -389,7 +389,7 @@ export class TypingsGenerator { declarationMappings.length > 0 ); - const generatedTsFilePaths: Iterable = this._getTypingsFilePaths(relativePath); + const generatedTsFilePaths: Iterable = this.#getTypingsFilePaths(relativePath); for (const generatedTsFilePath of generatedTsFilePaths) { const outputLines: string[] = [...headerLines, typingsData]; if (emitDeclarationMap) { @@ -426,7 +426,7 @@ export class TypingsGenerator { /** * Removes the consumer from all extant dependencies */ - private _clearDependencies(consumer: string): void { + #clearDependencies(consumer: string): void { const dependencies: Set | undefined = this.#dependenciesOfFile.get(consumer); if (dependencies) { for (const dependency of dependencies) { @@ -436,7 +436,7 @@ export class TypingsGenerator { } } - private *_getTypingsFilePaths(relativePath: string): Iterable { + *#getTypingsFilePaths(relativePath: string): Iterable { const { generatedTsFolder, secondaryGeneratedTsFolders } = this._options; const dtsFilename: string = `${relativePath}.d.ts`; yield `${generatedTsFolder}/${dtsFilename}`; @@ -447,7 +447,7 @@ export class TypingsGenerator { } } - private _normalizeFileExtensions(fileExtensions: string[]): string[] { + #normalizeFileExtensions(fileExtensions: string[]): string[] { const result: Set = new Set(); for (const fileExtension of fileExtensions) { if (!fileExtension.startsWith('.')) { diff --git a/libraries/worker-pool/src/WorkerPool.ts b/libraries/worker-pool/src/WorkerPool.ts index 09f04ec3a6c..b406ae3a0f3 100644 --- a/libraries/worker-pool/src/WorkerPool.ts +++ b/libraries/worker-pool/src/WorkerPool.ts @@ -184,7 +184,7 @@ export class WorkerPool { let worker: Worker | undefined = this.#idle.shift(); if (!worker && allowCreate) { - worker = this._createWorker(); + worker = this.#createWorker(); } if (worker) { @@ -199,7 +199,7 @@ export class WorkerPool { /** * Creates a new worker if allowed by maxSize. */ - private _createWorker(): Worker | undefined { + #createWorker(): Worker | undefined { if (this.#alive.length >= this.maxWorkers) { return; } @@ -218,15 +218,15 @@ export class WorkerPool { this.#alive.push(worker); worker.on('error', (err) => { - this._onError(err); - this._destroyWorker(worker); + this.#onError(err); + this.#destroyWorker(worker); }); worker.once('exit', (exitCode) => { if (exitCode !== 0) { - this._onError(new Error(`Worker ${id} exited with code ${exitCode}`)); + this.#onError(new Error(`Worker ${id} exited with code ${exitCode}`)); } - this._destroyWorker(worker); + this.#destroyWorker(worker); }); if (this.#prepare) { @@ -239,7 +239,7 @@ export class WorkerPool { /** * Cleans up a worker */ - private _destroyWorker(worker: Worker): void { + #destroyWorker(worker: Worker): void { const aliveIndex: number = this.#alive.indexOf(worker); if (aliveIndex >= 0) { this.#alive.splice(aliveIndex, 1); @@ -266,7 +266,7 @@ export class WorkerPool { /** * Notifies all pending callbacks that an error has occurred and switches this pool into error state. */ - private _onError(error: Error): void { + #onError(error: Error): void { this.#error = error; for (const [, reject] of this.#pending.splice(0)) { diff --git a/repo-scripts/doc-plugin-rush-stack/src/RushStackFeature.ts b/repo-scripts/doc-plugin-rush-stack/src/RushStackFeature.ts index 1e781f6232a..a4f49bf1f6f 100644 --- a/repo-scripts/doc-plugin-rush-stack/src/RushStackFeature.ts +++ b/repo-scripts/doc-plugin-rush-stack/src/RushStackFeature.ts @@ -54,7 +54,7 @@ export class RushStackFeature extends MarkdownDocumenterFeature { } ] }; - this._buildNavigation(navigationFile.api_nav, this.context.apiModel); + this.#buildNavigation(navigationFile.api_nav, this.context.apiModel); const navFilePath: string = path.join(this.context.outputFolder, '..', 'api_nav.yaml'); const navFileContent: string = yaml.dump(navigationFile, { lineWidth: 120 }); @@ -62,7 +62,7 @@ export class RushStackFeature extends MarkdownDocumenterFeature { FileSystem.writeFile(navFilePath, navFileContent, { ensureFolderExists: true }); } - private _buildNavigation(parentNodes: INavigationNode[], parentApiItem: ApiItem): void { + #buildNavigation(parentNodes: INavigationNode[], parentApiItem: ApiItem): void { for (const apiItem of parentApiItem.members) { if (this.#apiItemsWithPages.has(apiItem)) { const newNode: INavigationNode = { @@ -74,12 +74,12 @@ export class RushStackFeature extends MarkdownDocumenterFeature { parentNodes.push(newNode); const newNodeSubitems: INavigationNode[] = []; - this._buildNavigation(newNodeSubitems, apiItem); + this.#buildNavigation(newNodeSubitems, apiItem); if (newNodeSubitems.length > 0) { newNode.subitems = newNodeSubitems; } } else { - this._buildNavigation(parentNodes, apiItem); + this.#buildNavigation(parentNodes, apiItem); } } } From 6740253e50f6e04d5c87a9ddb236bbd66d3bdb0d Mon Sep 17 00:00:00 2001 From: Bharat Middha <5100938+bmiddha@users.noreply.github.com> Date: Wed, 19 Aug 2026 23:02:31 -0700 Subject: [PATCH 4/4] fix(eslint-plugin): recognize native privacy Treat PrivateIdentifier class keys like TypeScript private members so no-new-null does not report private API types. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8ebd5bf2-c44b-42d5-be25-e7936d4b0a14 --- .../native-private-null_2026-08-19-22-58-08.json | 9 +++++++++ eslint/eslint-plugin/src/no-new-null.ts | 9 +++++++-- eslint/eslint-plugin/src/test/no-new-null.test.ts | 11 +++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 common/changes/@rushstack/eslint-plugin/native-private-null_2026-08-19-22-58-08.json diff --git a/common/changes/@rushstack/eslint-plugin/native-private-null_2026-08-19-22-58-08.json b/common/changes/@rushstack/eslint-plugin/native-private-null_2026-08-19-22-58-08.json new file mode 100644 index 00000000000..f16f9e815e4 --- /dev/null +++ b/common/changes/@rushstack/eslint-plugin/native-private-null_2026-08-19-22-58-08.json @@ -0,0 +1,9 @@ +{ + "changes": [ + { + "packageName": "@rushstack/eslint-plugin", + "comment": "Fix no-new-null false positives for ECMAScript private class members.", + "type": "patch" + } + ] +} diff --git a/eslint/eslint-plugin/src/no-new-null.ts b/eslint/eslint-plugin/src/no-new-null.ts index 36d3e82db74..9c2774f6df1 100644 --- a/eslint/eslint-plugin/src/no-new-null.ts +++ b/eslint/eslint-plugin/src/no-new-null.ts @@ -9,6 +9,7 @@ type Options = []; interface IAccessible { accessibility?: TSESTree.Accessibility; + key?: TSESTree.Node; } const noNewNullRule: TSESLint.RuleModule = { @@ -37,11 +38,15 @@ const noNewNullRule: TSESLint.RuleModule = { create: (context: TSESLint.RuleContext) => { /** - * Returns true if the accessibility is not explicitly set to private or protected, e.g. class properties, methods. + * Returns true unless a class member uses protected, TypeScript-private, or ECMAScript-private syntax. */ function isPubliclyAccessible(node?: IAccessible): boolean { const accessibility: TSESTree.Accessibility | undefined = node?.accessibility; - return !(accessibility === 'private' || accessibility === 'protected'); + return ( + accessibility !== 'private' && + accessibility !== 'protected' && + node?.key?.type !== AST_NODE_TYPES.PrivateIdentifier + ); } /** diff --git a/eslint/eslint-plugin/src/test/no-new-null.test.ts b/eslint/eslint-plugin/src/test/no-new-null.test.ts index 7ae2fdf8045..87542636f2c 100644 --- a/eslint/eslint-plugin/src/test/no-new-null.test.ts +++ b/eslint/eslint-plugin/src/test/no-new-null.test.ts @@ -104,6 +104,17 @@ ruleTester.run('no-new-null', noNewNullRule, { ' }', '}' ].join('\n') + }, + { + code: [ + 'class NativePrivateNulls {', + ' #field: string | null;', + ' #propertyFunc: (value: string | null) => void;', + ' #method(value: string | null): string | null { return value; }', + ' get #value(): string | null { return this.#field; }', + ' set #value(value: string | null) { this.#field = value; }', + '}' + ].join('\n') } ] });