From e7e9429769d943f8769e17dd34f7ce4f37f3a29f Mon Sep 17 00:00:00 2001 From: Pete Gonzalez <4673363+octogonz@users.noreply.github.com> Date: Tue, 9 Jun 2020 00:12:25 -0700 Subject: [PATCH] prettier . --write --- apps/api-documenter/.eslintrc.js | 4 +- apps/api-documenter/config/api-extractor.json | 2 +- apps/api-documenter/config/jest.json | 2 +- .../src/cli/ApiDocumenterCommandLine.ts | 8 +- apps/api-documenter/src/cli/BaseAction.ts | 46 +- apps/api-documenter/src/cli/GenerateAction.ts | 17 +- apps/api-documenter/src/cli/MarkdownAction.ts | 8 +- apps/api-documenter/src/cli/YamlAction.ts | 32 +- .../src/documenters/DocumenterConfig.ts | 3 +- .../documenters/ExperimentalYamlDocumenter.ts | 16 +- .../src/documenters/MarkdownDocumenter.ts | 226 ++- .../src/documenters/OfficeYamlDocumenter.ts | 28 +- .../src/documenters/YamlDocumenter.ts | 287 ++-- apps/api-documenter/src/index.ts | 13 +- .../src/markdown/CustomMarkdownEmitter.ts | 59 +- .../src/markdown/MarkdownEmitter.ts | 19 +- .../test/CustomMarkdownEmitter.test.ts | 229 ++- .../src/nodes/CustomDocNodeKind.ts | 20 +- .../src/nodes/DocEmphasisSpan.ts | 6 +- apps/api-documenter/src/nodes/DocHeading.ts | 5 +- apps/api-documenter/src/nodes/DocNoteBox.ts | 9 +- apps/api-documenter/src/nodes/DocTable.ts | 11 +- apps/api-documenter/src/nodes/DocTableCell.ts | 9 +- apps/api-documenter/src/nodes/DocTableRow.ts | 19 +- .../plugin/IApiDocumenterPluginManifest.ts | 2 +- .../src/plugin/MarkdownDocumenterAccessor.ts | 2 +- .../src/plugin/MarkdownDocumenterFeature.ts | 3 +- .../src/plugin/PluginFeature.ts | 3 +- .../api-documenter/src/plugin/PluginLoader.ts | 40 +- .../src/schemas/api-documenter-template.json | 6 +- .../src/schemas/api-documenter.schema.json | 5 +- apps/api-documenter/src/start.ts | 6 +- .../src/utils/IndentedWriter.ts | 52 +- apps/api-documenter/src/utils/Utilities.ts | 9 +- .../src/utils/test/IndentedWriter.test.ts | 10 +- apps/api-documenter/src/yaml/IYamlApiFile.ts | 7 +- .../src/yaml/typescript.schema.json | 1268 +++++++++-------- apps/api-documenter/tsconfig.json | 4 +- apps/api-extractor-model/.eslintrc.js | 8 +- .../config/api-extractor.json | 2 +- apps/api-extractor-model/config/jest.json | 2 +- .../src/aedoc/AedocDefinitions.ts | 28 +- .../src/aedoc/ReleaseTag.ts | 44 +- apps/api-extractor-model/src/index.ts | 177 +-- .../src/items/ApiDeclaredItem.ts | 21 +- .../src/items/ApiDocumentedItem.ts | 10 +- apps/api-extractor-model/src/items/ApiItem.ts | 42 +- .../src/items/ApiPropertyItem.ts | 17 +- .../src/mixins/ApiItemContainerMixin.ts | 28 +- .../src/mixins/ApiNameMixin.ts | 14 +- .../src/mixins/ApiParameterListMixin.ts | 19 +- .../src/mixins/ApiReleaseTagMixin.ts | 14 +- .../src/mixins/ApiReturnTypeMixin.ts | 14 +- .../src/mixins/ApiStaticMixin.ts | 14 +- .../src/mixins/ApiTypeParameterListMixin.ts | 33 +- .../api-extractor-model/src/mixins/Excerpt.ts | 11 +- .../src/model/ApiCallSignature.ts | 32 +- .../api-extractor-model/src/model/ApiClass.ts | 47 +- .../src/model/ApiConstructSignature.ts | 32 +- .../src/model/ApiConstructor.ts | 18 +- .../src/model/ApiEntryPoint.ts | 4 +- apps/api-extractor-model/src/model/ApiEnum.ts | 19 +- .../src/model/ApiEnumMember.ts | 24 +- .../src/model/ApiFunction.ts | 33 +- .../src/model/ApiIndexSignature.ts | 23 +- .../src/model/ApiInterface.ts | 69 +- .../src/model/ApiMethod.ts | 37 +- .../src/model/ApiMethodSignature.ts | 33 +- .../api-extractor-model/src/model/ApiModel.ts | 14 +- .../src/model/ApiNamespace.ts | 19 +- .../src/model/ApiPackage.ts | 55 +- .../src/model/ApiProperty.ts | 12 +- .../src/model/ApiPropertySignature.ts | 11 +- .../src/model/ApiTypeAlias.ts | 40 +- .../src/model/ApiVariable.ts | 24 +- .../src/model/Deserializer.ts | 2 +- .../src/model/DeserializerContext.ts | 2 +- .../src/model/ModelReferenceResolver.ts | 31 +- .../src/model/Parameter.ts | 1 - .../src/model/TypeParameter.ts | 1 - apps/api-extractor-model/tsconfig.json | 5 +- apps/api-extractor/.eslintrc.js | 4 +- apps/api-extractor/config/api-extractor.json | 2 +- apps/api-extractor/config/jest.json | 2 +- .../src/aedoc/PackageDocComment.ts | 15 +- .../src/analyzer/AstDeclaration.ts | 13 +- apps/api-extractor/src/analyzer/AstImport.ts | 2 +- .../src/analyzer/AstReferenceResolver.ts | 100 +- .../src/analyzer/AstSymbolTable.ts | 145 +- .../src/analyzer/ExportAnalyzer.ts | 263 ++-- .../src/analyzer/PackageMetadataManager.ts | 58 +- .../analyzer/SourceFileLocationFormatter.ts | 6 +- apps/api-extractor/src/analyzer/Span.ts | 16 +- .../src/analyzer/StringChecks.ts | 20 +- .../src/analyzer/TypeScriptHelpers.ts | 66 +- .../src/analyzer/TypeScriptInternals.ts | 26 +- .../test/PackageMetadataManager.test.ts | 85 +- apps/api-extractor/src/api/CompilerState.ts | 37 +- .../api-extractor/src/api/ConsoleMessageId.ts | 2 +- apps/api-extractor/src/api/Extractor.ts | 138 +- apps/api-extractor/src/api/ExtractorConfig.ts | 245 ++-- .../src/api/ExtractorLogLevel.ts | 2 +- .../api-extractor/src/api/ExtractorMessage.ts | 11 +- .../src/api/ExtractorMessageId.ts | 2 +- apps/api-extractor/src/api/IConfigFile.ts | 2 +- .../src/cli/ApiExtractorCommandLine.ts | 20 +- apps/api-extractor/src/cli/InitAction.ts | 22 +- apps/api-extractor/src/cli/RunAction.ts | 69 +- apps/api-extractor/src/collector/Collector.ts | 177 ++- .../src/collector/CollectorEntity.ts | 2 +- .../src/collector/MessageRouter.ts | 231 +-- .../src/collector/SourceMapper.ts | 47 +- .../src/collector/SymbolMetadata.ts | 2 +- .../src/collector/VisitorState.ts | 2 +- .../src/collector/WorkingPackage.ts | 4 +- .../src/enhancers/DocCommentEnhancer.ts | 83 +- .../src/enhancers/ValidationEnhancer.ts | 41 +- .../src/generators/ApiModelGenerator.ts | 366 +++-- .../src/generators/ApiReportGenerator.ts | 124 +- .../DeclarationReferenceGenerator.ts | 125 +- .../src/generators/DtsEmitHelpers.ts | 14 +- .../src/generators/DtsRollupGenerator.ts | 70 +- .../src/generators/ExcerptBuilder.ts | 56 +- apps/api-extractor/src/index.ts | 15 +- .../src/schemas/api-extractor-defaults.json | 2 +- .../src/schemas/api-extractor-template.json | 23 +- .../src/schemas/api-extractor.schema.json | 15 +- apps/api-extractor/src/start.ts | 6 +- apps/api-extractor/tsconfig.json | 5 +- apps/rush-buildxl/.eslintrc.js | 4 +- apps/rush-buildxl/config/jest.json | 2 +- .../src/cli/RushBuildXLCommandLineParser.ts | 9 +- .../src/cli/actions/CleanAction.ts | 7 +- .../src/cli/actions/GenerateAction.ts | 10 +- apps/rush-buildxl/src/logic/BxlConfig.ts | 10 +- apps/rush-buildxl/src/logic/BxlModule.ts | 3 +- .../rush-buildxl/src/logic/BxlModuleConfig.ts | 5 +- .../src/logic/BxlModulesGenerator.ts | 17 +- apps/rush-buildxl/src/start.ts | 5 +- apps/rush-buildxl/tsconfig.json | 5 +- apps/rush-lib/.eslintrc.js | 4 +- apps/rush-lib/__mocks__/child_process.js | 8 +- .../rush-deploy-init/scenario-template.json | 6 +- .../common/config/rush/command-line.json | 8 +- .../common/config/rush/common-versions.json | 9 +- .../common/config/rush/experiments.json | 24 +- .../rush-init/common/config/rush/pnpmfile.js | 14 +- .../common/config/rush/version-policies.json | 10 +- apps/rush-lib/assets/rush-init/rush.json | 44 +- apps/rush-lib/config/jest.json | 2 +- .../src/api/ApprovedPackagesConfiguration.ts | 41 +- .../src/api/ApprovedPackagesPolicy.ts | 9 +- apps/rush-lib/src/api/ChangeFile.ts | 32 +- apps/rush-lib/src/api/ChangeManagement.ts | 4 +- apps/rush-lib/src/api/ChangeManager.ts | 25 +- .../src/api/CommandLineConfiguration.ts | 66 +- .../src/api/CommonVersionsConfiguration.ts | 76 +- .../src/api/EnvironmentConfiguration.ts | 25 +- apps/rush-lib/src/api/EventHooks.ts | 4 +- .../src/api/ExperimentsConfiguration.ts | 6 +- apps/rush-lib/src/api/LastInstallFlag.ts | 28 +- apps/rush-lib/src/api/PackageJsonEditor.ts | 70 +- apps/rush-lib/src/api/PackageNameParsers.ts | 8 +- apps/rush-lib/src/api/Rush.ts | 24 +- apps/rush-lib/src/api/RushConfiguration.ts | 242 ++-- .../src/api/RushConfigurationProject.ts | 44 +- apps/rush-lib/src/api/Variants.ts | 7 +- apps/rush-lib/src/api/VersionPolicy.ts | 40 +- .../src/api/VersionPolicyConfiguration.ts | 28 +- apps/rush-lib/src/api/test/ChangeFile.test.ts | 19 +- .../api/test/EnvironmentConfiguration.test.ts | 6 +- apps/rush-lib/src/api/test/EventHooks.test.ts | 10 +- .../src/api/test/LastInstallFlag.test.ts | 20 +- .../src/api/test/RushConfiguration.test.ts | 165 ++- .../api/test/VersionMismatchFinder.test.ts | 522 ++++--- .../src/api/test/VersionPolicy.test.ts | 43 +- .../api/test/jsonFiles/common-versions.json | 2 +- .../test/jsonFiles/rushWithLockVersion.json | 2 +- .../rush/browser-approved-packages.json | 2 +- .../rush/nonbrowser-approved-packages.json | 2 +- apps/rush-lib/src/api/test/repo/rush-npm.json | 13 +- .../src/api/test/repo/rush-pnpm-2.json | 13 +- .../src/api/test/repo/rush-pnpm-3.json | 13 +- .../src/api/test/repo/rush-pnpm-global.json | 13 +- .../test/repo/rush-pnpm-invalid-store.json | 13 +- .../src/api/test/repo/rush-pnpm-local.json | 13 +- .../rush-lib/src/api/test/repo/rush-pnpm.json | 13 +- .../src/cli/CommandLineMigrationAdvisor.ts | 36 +- .../rush-lib/src/cli/RushCommandLineParser.ts | 162 ++- apps/rush-lib/src/cli/RushXCommandLine.ts | 79 +- apps/rush-lib/src/cli/actions/AddAction.ts | 73 +- .../src/cli/actions/BaseInstallAction.ts | 65 +- .../src/cli/actions/BaseRushAction.ts | 11 +- apps/rush-lib/src/cli/actions/ChangeAction.ts | 269 ++-- apps/rush-lib/src/cli/actions/CheckAction.ts | 27 +- apps/rush-lib/src/cli/actions/DeployAction.ts | 19 +- apps/rush-lib/src/cli/actions/InitAction.ts | 83 +- .../src/cli/actions/InitDeployAction.ts | 40 +- .../rush-lib/src/cli/actions/InstallAction.ts | 25 +- apps/rush-lib/src/cli/actions/LinkAction.ts | 16 +- apps/rush-lib/src/cli/actions/ListAction.ts | 29 +- .../rush-lib/src/cli/actions/PublishAction.ts | 136 +- apps/rush-lib/src/cli/actions/PurgeAction.ts | 25 +- apps/rush-lib/src/cli/actions/ScanAction.ts | 21 +- apps/rush-lib/src/cli/actions/UnlinkAction.ts | 9 +- apps/rush-lib/src/cli/actions/UpdateAction.ts | 54 +- .../rush-lib/src/cli/actions/VersionAction.ts | 80 +- .../src/cli/actions/test/AddAction.test.ts | 15 +- .../src/cli/scriptActions/BaseScriptAction.ts | 20 +- .../src/cli/scriptActions/BulkScriptAction.ts | 153 +- .../cli/scriptActions/GlobalScriptAction.ts | 25 +- apps/rush-lib/src/cli/test/Cli.test.ts | 2 +- .../src/cli/test/CommandLineHelp.test.ts | 4 +- .../cli/test/RushCommandLineParser.test.ts | 92 +- .../common/config/rush/command-line.json | 7 +- .../common/config/rush/command-line.json | 7 +- .../common/config/rush/command-line.json | 2 +- .../common/config/rush/command-line.json | 2 +- .../common/config/rush/command-line.json | 4 +- .../common/config/rush/command-line.json | 4 +- .../common/config/rush/command-line.json | 2 +- .../common/config/rush/command-line.json | 2 +- .../repo/common/config/rush/command-line.json | 6 +- .../cli/test/repo/common/scripts/deploy.js | 2 +- apps/rush-lib/src/cli/test/repo/rush.json | 3 +- apps/rush-lib/src/index.ts | 67 +- .../src/logic/ApprovedPackagesChecker.ts | 25 +- apps/rush-lib/src/logic/ChangeFiles.ts | 34 +- apps/rush-lib/src/logic/ChangeManager.ts | 25 +- apps/rush-lib/src/logic/ChangelogGenerator.ts | 88 +- apps/rush-lib/src/logic/EventHooksManager.ts | 28 +- apps/rush-lib/src/logic/Git.ts | 33 +- apps/rush-lib/src/logic/InstallManager.ts | 525 ++++--- apps/rush-lib/src/logic/JsonSchemaUrls.ts | 8 +- apps/rush-lib/src/logic/LinkManagerFactory.ts | 5 +- .../rush-lib/src/logic/NodeJsCompatibility.ts | 68 +- .../src/logic/PackageChangeAnalyzer.ts | 48 +- apps/rush-lib/src/logic/PackageJsonUpdater.ts | 133 +- apps/rush-lib/src/logic/ProjectCommandSet.ts | 7 +- apps/rush-lib/src/logic/PublishGit.ts | 37 +- apps/rush-lib/src/logic/PublishUtilities.ts | 177 +-- apps/rush-lib/src/logic/PurgeManager.ts | 28 +- apps/rush-lib/src/logic/SetupChecks.ts | 52 +- .../src/logic/ShrinkwrapFileFactory.ts | 2 +- .../src/logic/StandardScriptUpdater.ts | 27 +- apps/rush-lib/src/logic/TaskSelector.ts | 42 +- apps/rush-lib/src/logic/Telemetry.ts | 41 +- apps/rush-lib/src/logic/UnlinkManager.ts | 2 +- apps/rush-lib/src/logic/VersionManager.ts | 152 +- .../src/logic/base/BaseLinkManager.ts | 24 +- apps/rush-lib/src/logic/base/BasePackage.ts | 34 +- .../src/logic/base/BaseShrinkwrapFile.ts | 52 +- .../src/logic/deploy/DeployManager.ts | 191 ++- .../src/logic/deploy/SymlinkAnalyzer.ts | 21 +- apps/rush-lib/src/logic/npm/NpmLinkManager.ts | 129 +- apps/rush-lib/src/logic/npm/NpmPackage.ts | 46 +- .../src/logic/npm/NpmShrinkwrapFile.ts | 51 +- .../src/logic/pnpm/PnpmLinkManager.ts | 131 +- .../pnpm/PnpmProjectDependencyManifest.ts | 56 +- .../src/logic/pnpm/PnpmShrinkwrapFile.ts | 117 +- .../src/logic/policy/GitEmailPolicy.ts | 67 +- .../src/logic/policy/PolicyValidator.ts | 9 +- .../src/logic/taskRunner/ProjectTask.ts | 62 +- .../src/logic/taskRunner/TaskCollection.ts | 22 +- .../src/logic/taskRunner/TaskRunner.ts | 114 +- .../src/logic/taskRunner/TaskStatus.ts | 2 +- .../logic/taskRunner/test/ProjectTask.test.ts | 5 +- .../taskRunner/test/TaskCollection.test.ts | 12 +- .../logic/taskRunner/test/TaskRunner.test.ts | 62 +- .../src/logic/test/ChangeFiles.test.ts | 10 +- .../src/logic/test/ChangeManager.test.ts | 103 +- .../src/logic/test/ChangelogGenerator.test.ts | 148 +- .../logic/test/PackageChangeAnalyzer.test.ts | 20 +- .../src/logic/test/PublishUtilities.test.ts | 118 +- .../src/logic/test/ShrinkwrapFile.test.ts | 153 +- .../rush-lib/src/logic/test/Telemetry.test.ts | 17 +- .../src/logic/test/VersionManager.test.ts | 10 +- .../categorizedChanges/@ms/a/changeA.json | 14 +- .../categorizedChanges/@ms/b/changeB.json | 14 +- .../test/categorizedChanges/changeC.json | 14 +- .../src/logic/test/cyclicDeps/change.json | 12 +- .../logic/test/cyclicDepsExplicit/change.json | 12 +- .../test/explicitVersionChange/change1.json | 12 +- .../test/hotfixWithPatchChanges/change1.json | 12 +- .../test/hotfixWithPatchChanges/change2.json | 12 +- .../test/hotfixWithPatchChanges/change3.json | 12 +- .../src/logic/test/leafChange/change1.json | 12 +- .../common/config/rush/version-policies.json | 2 +- .../src/logic/test/multipleChangeFiles/a.json | 14 +- .../src/logic/test/multipleChangeFiles/b.json | 14 +- .../src/logic/test/multipleChangeFiles/c.json | 14 +- .../logic/test/multipleChanges/change1.json | 12 +- .../logic/test/multipleChanges/change2.json | 12 +- .../logic/test/multipleChanges/change3.json | 12 +- .../test/multipleHotfixChanges/change1.json | 12 +- .../test/multipleHotfixChanges/change2.json | 12 +- .../test/multipleHotfixChanges/change3.json | 12 +- .../logic/test/orderedChanges/change1.json | 14 +- .../logic/test/orderedChanges/change2.json | 14 +- .../src/logic/test/packages/rush.json | 8 +- .../src/logic/test/repo/changes/a.json | 14 +- .../src/logic/test/repo/changes/b.json | 14 +- .../src/logic/test/repo/changes/c.json | 14 +- .../src/logic/test/repo/changes/d.json | 14 +- .../common/config/rush/version-policies.json | 2 +- .../src/logic/test/repo/d/package.json | 2 +- .../src/logic/test/repo/e/package.json | 2 +- .../src/logic/test/repo/f/package.json | 2 +- .../src/logic/test/repo/g/package.json | 2 +- .../logic/test/rootHotfixChange/change1.json | 13 +- .../logic/test/rootMajorChange/change1.json | 12 +- .../logic/test/rootPatchChange/change1.json | 12 +- .../src/logic/test/verifyChanges/changes.json | 24 +- .../versionMismatch/VersionMismatchFinder.ts | 75 +- .../VersionMismatchFinderCommonVersions.ts | 19 +- .../VersionMismatchFinderEntity.ts | 13 +- .../VersionMismatchFinderProject.ts | 14 +- .../src/logic/yarn/YarnShrinkwrapFile.ts | 57 +- .../src/schemas/approved-packages.schema.json | 4 +- .../src/schemas/command-line.schema.json | 40 +- .../src/schemas/deploy-scenario.schema.json | 8 +- apps/rush-lib/src/schemas/rush.schema.json | 25 +- .../src/schemas/version-policies.schema.json | 14 +- apps/rush-lib/src/scripts/create-links.ts | 5 +- apps/rush-lib/src/scripts/install-run-rush.ts | 14 +- apps/rush-lib/src/scripts/install-run.ts | 79 +- .../src/utilities/AlreadyReportedError.ts | 1 - apps/rush-lib/src/utilities/AsyncRecycler.ts | 32 +- apps/rush-lib/src/utilities/Npm.ts | 10 +- apps/rush-lib/src/utilities/Stopwatch.ts | 15 +- apps/rush-lib/src/utilities/Utilities.ts | 213 +-- apps/rush-lib/src/utilities/VersionControl.ts | 97 +- apps/rush-lib/src/utilities/test/Npm.test.ts | 35 +- .../src/utilities/test/Stopwatch.test.ts | 4 +- apps/rush-lib/tsconfig.json | 5 +- apps/rush/.eslintrc.js | 4 +- apps/rush/config/jest.json | 2 +- apps/rush/src/MinimalRushConfiguration.ts | 15 +- apps/rush/src/RushCommandSelector.ts | 39 +- apps/rush/src/RushVersionSelector.ts | 92 +- apps/rush/src/start.ts | 27 +- .../src/test/MinimalRushConfiguration.test.ts | 6 +- .../src/test/sandbox/legacy-repo/rush.json | 21 +- apps/rush/src/test/sandbox/repo/rush.json | 21 +- apps/rush/tsconfig.json | 5 +- build-tests/api-documenter-test/build.js | 12 +- .../config/api-documenter.json | 4 +- .../config/api-extractor.json | 2 +- .../api-documenter-test/src/DocClass1.ts | 33 +- .../api-documenter-test/src/DocEnums.ts | 2 +- build-tests/api-documenter-test/src/index.ts | 4 +- build-tests/api-documenter-test/tsconfig.json | 21 +- .../config/api-extractor.json | 2 +- .../src/Lib1ForgottenExport.ts | 3 +- .../api-extractor-lib1-test/src/index.ts | 6 +- .../api-extractor-lib1-test/tsconfig.json | 20 +- .../config/api-extractor.json | 2 +- .../api-extractor-lib2-test/src/index.ts | 6 +- .../api-extractor-lib2-test/tsconfig.json | 21 +- .../config/api-extractor.json | 2 +- .../api-extractor-lib3-test/tsconfig.json | 21 +- .../src/ambientNameConflict/localFile.ts | 3 +- .../src/ambientNameConflict2/Date.ts | 2 +- .../src/ancillaryDeclarations/index.ts | 3 +- .../src/apiItemKinds/classes.ts | 7 +- .../src/apiItemKinds/enums.ts | 6 +- .../src/apiItemKinds/typeLiterals.ts | 5 +- .../src/apiItemKinds/variables.ts | 4 +- .../config/api-extractor-overrides.json | 6 +- .../src/bundledPackages/index.ts | 7 +- .../src/circularImport/IFile.ts | 2 +- .../src/circularImport/IFolder.ts | 2 +- .../src/circularImport2/IFile.ts | 6 +- .../src/circularImport2/IFolder.ts | 6 +- .../src/circularImport2/index.ts | 1 - .../src/defaultExportOfEntryPoint/index.ts | 2 +- .../src/defaultExportOfEntryPoint2/index.ts | 2 +- .../src/defaultExportOfEntryPoint3/index.ts | 2 +- .../src/defaultExportOfEntryPoint4/index.ts | 2 +- .../src/docReferences/index.ts | 13 +- .../src/docReferences2/index.ts | 18 +- .../src/docReferences3/index.ts | 12 +- .../src/exportDuplicate/index.ts | 10 +- .../src/exportImportedExternal/index.ts | 4 +- .../src/exportStar/localFile.ts | 4 +- .../src/exportStar/reexportStar.ts | 2 +- .../src/exportStar2/reexportStar.ts | 2 +- .../src/exportStar3/reexportStar.ts | 2 +- .../config/api-extractor-overrides.json | 4 +- .../src/functionOverload/index.ts | 11 +- .../src/inconsistentReleaseTags/index.ts | 1 - .../src/internationalCharacters/index.ts | 8 +- .../src/preapproved/index.ts | 11 +- .../src/runScenarios.ts | 48 +- .../src/typeOf/index.ts | 2 +- .../src/typeOf2/index.ts | 2 +- .../src/typeParameters/index.ts | 18 +- .../api-extractor-scenarios/tsconfig.json | 21 +- .../config/api-extractor.json | 2 +- .../src/AccessModifiers.ts | 19 +- .../src/ClassWithTypeLiterals.ts | 5 +- .../src/DeclarationMerging.ts | 3 +- .../src/DefaultExportEdgeCase.ts | 3 +- .../src/EcmaScriptSymbols.ts | 8 +- .../api-extractor-test-01/src/Enums.ts | 5 +- .../src/ForgottenExportConsumer3.ts | 5 +- .../src/ReexportedClass3/index.ts | 2 +- .../src/ReferenceLibDirective.ts | 3 +- .../api-extractor-test-01/src/index.ts | 21 +- .../src/variableDeclarations.ts | 2 +- .../api-extractor-test-01/tsconfig.json | 21 +- .../config/api-extractor.json | 2 +- .../src/RenamedReexportedClass.ts | 1 - .../src/TypeFromImportedModule.ts | 3 +- .../api-extractor-test-02/tsconfig.json | 20 +- .../api-extractor-test-03/tsconfig.json | 21 +- .../beta-consumer/package.json | 2 +- .../beta-consumer/tsconfig.json | 16 +- .../config/api-extractor.json | 2 +- .../api-extractor-test-04/src/AlphaClass.ts | 6 +- .../api-extractor-test-04/src/BetaClass.ts | 9 +- .../src/EntangledNamespace.ts | 2 - .../api-extractor-test-04/src/EnumExamples.ts | 4 +- .../src/IPublicComplexInterface.ts | 2 +- .../src/InternalClass.ts | 3 +- .../api-extractor-test-04/src/PublicClass.ts | 18 +- .../api-extractor-test-04/tsconfig.json | 19 +- .../src/chunks/chunkWithoutStrings.ts | 2 +- .../localization-plugin-test-01/src/indexA.ts | 11 +- .../localization-plugin-test-01/tsconfig.json | 9 +- .../webpack.config.js | 36 +- .../src/chunks/chunkWithStrings.ts | 2 +- .../src/chunks/chunkWithoutStrings.ts | 2 +- .../src/chunks/strings2.loc.json | 2 +- .../localization-plugin-test-02/src/indexA.ts | 20 +- .../localization-plugin-test-02/src/indexB.ts | 5 +- .../localization-plugin-test-02/src/indexC.ts | 10 +- .../src/strings1.loc.json | 2 +- .../src/strings3.loc.json | 2 +- .../src/strings4.loc.json | 2 +- .../localization-plugin-test-02/tsconfig.json | 9 +- .../webpack.config.js | 54 +- .../es-es/chunks/strings2.loc.json | 2 +- .../es-es/combinedStringsData.json | 2 +- .../src/chunks/chunkWithStrings.ts | 2 +- .../src/chunks/chunkWithoutStrings.ts | 2 +- .../src/chunks/strings2.loc.json | 2 +- .../src/chunks/unnamedChunkWithStrings.ts | 2 +- .../localization-plugin-test-03/src/indexA.ts | 20 +- .../localization-plugin-test-03/src/indexC.ts | 10 +- .../localization-plugin-test-03/src/indexD.ts | 10 +- .../src/strings1.loc.json | 2 +- .../src/strings3.loc.json | 2 +- .../src/strings4.loc.json | 2 +- .../localization-plugin-test-03/tsconfig.json | 9 +- .../webpack.config.js | 77 +- .../.eslintrc.js | 4 +- .../src/index.ts | 3 +- .../tsconfig.json | 4 +- .../src/index.ts | 3 +- .../src/TestClass.ts | 3 +- .../src/TestClass.ts | 3 +- .../src/TestClass.ts | 3 +- .../src/TestClass.ts | 3 +- .../src/TestClass.ts | 3 +- .../src/TestClass.ts | 3 +- .../src/TestClass.ts | 3 +- .../src/TestClass.ts | 3 +- .../src/TestClass.ts | 3 +- .../src/TestClass.ts | 3 +- .../src/TestClass.ts | 3 +- .../src/TestClass.ts | 3 +- .../ts-command-line-test/src/PushAction.ts | 20 +- .../ts-command-line-test/src/RunAction.ts | 13 +- .../src/WidgetCommandLine.ts | 12 +- .../ts-command-line-test/tsconfig.json | 19 +- .../web-library-build-test/config/jest.json | 2 +- .../config/jest/jest.config.json | 6 +- .../config/pre-copy.json | 6 +- .../web-library-build-test/src/preCopyTest.js | 7 +- .../web-library-build-test/tsconfig.json | 4 +- common/config/azure-pipelines/ci.yaml | 30 +- .../azure-pipelines/npm-publish-rush.yaml | 2 +- .../config/azure-pipelines/npm-publish.yaml | 2 +- .../azure-pipelines/templates/build.yaml | 30 +- .../templates/buildAndPublish.yaml | 18 +- common/config/rush/command-line.json | 4 +- common/config/rush/common-versions.json | 4 +- common/config/rush/experiments.json | 14 +- .../rush/nonbrowser-approved-packages.json | 332 ++--- common/config/rush/pnpmfile.js | 15 +- common/config/rush/version-policies.json | 10 +- common/scripts/install-run-rush.js | 98 +- common/scripts/install-run-rushx.js | 8 +- common/scripts/install-run.js | 625 ++++---- core-build/gulp-core-build-mocha/.eslintrc.js | 4 +- .../src/InstrumentTask.ts | 31 +- .../gulp-core-build-mocha/src/MochaTask.ts | 36 +- core-build/gulp-core-build-sass/.eslintrc.js | 4 +- .../gulp-core-build-sass/config/jest.json | 2 +- .../gulp-core-build-sass/src/CSSModules.ts | 14 +- .../gulp-core-build-sass/src/SassTask.ts | 237 ++- .../src/test/CSSModules.test.ts | 47 +- core-build/gulp-core-build-sass/tsconfig.json | 4 +- core-build/gulp-core-build-serve/.eslintrc.js | 4 +- .../gulp-core-build-serve/src/ReloadTask.ts | 3 +- .../gulp-core-build-serve/src/ServeTask.ts | 71 +- .../src/TrustCertTask.ts | 10 +- .../src/UntrustCertTask.ts | 10 +- .../src/serve.schema.json | 4 +- .../gulp-core-build-typescript/.eslintrc.js | 4 +- .../src/ApiExtractorTask.ts | 20 +- .../src/LintCmdTask.ts | 16 +- .../gulp-core-build-typescript/src/RSCTask.ts | 64 +- .../src/TsParseConfigHost.ts | 7 +- .../src/TscCmdTask.ts | 80 +- .../src/TslintCmdTask.ts | 16 +- .../gulp-core-build-typescript/src/index.ts | 17 +- .../src/schemas/api-extractor.schema.json | 2 +- .../src/schemas/lint-cmd.schema.json | 2 +- .../src/schemas/tsc-cmd.schema.json | 12 +- .../src/schemas/tslint-cmd.schema.json | 2 +- .../gulp-core-build-webpack/.eslintrc.js | 4 +- .../src/WebpackTask.ts | 132 +- .../gulp-core-build-webpack/src/index.ts | 6 +- .../src/webpack.config.ts | 32 +- .../src/webpack.schema.json | 2 +- core-build/gulp-core-build/.eslintrc.js | 8 +- core-build/gulp-core-build/config/jest.json | 2 +- core-build/gulp-core-build/gulpfile.js | 2 +- core-build/gulp-core-build/src/State.ts | 12 +- core-build/gulp-core-build/src/config.ts | 3 +- core-build/gulp-core-build/src/index.ts | 81 +- core-build/gulp-core-build/src/logging.ts | 148 +- .../src/tasks/CleanFlagTask.ts | 17 +- .../gulp-core-build/src/tasks/CleanTask.ts | 15 +- .../gulp-core-build/src/tasks/CopyTask.ts | 27 +- .../src/tasks/GenerateShrinkwrapTask.ts | 2 +- .../gulp-core-build/src/tasks/GulpTask.ts | 77 +- .../gulp-core-build/src/tasks/JestReporter.ts | 6 +- .../gulp-core-build/src/tasks/JestTask.ts | 95 +- .../src/tasks/ValidateShrinkwrapTask.ts | 13 +- .../src/tasks/copy.schema.json | 2 +- .../copyStaticAssets/CopyStaticAssetsTask.ts | 29 +- .../copy-static-assets.schema.json | 2 +- .../src/tasks/jest.schema.json | 2 +- .../gulp-core-build/src/test/GulpTask.test.ts | 84 +- .../gulp-core-build/src/test/index.test.ts | 150 +- .../src/test/mockBuildConfig.ts | 2 +- .../src/test/other-schema-task.config.json | 2 +- .../src/test/schema-task.config.json | 2 +- .../src/test/schema-task.schema.json | 2 +- .../src/utilities/FileDeletionUtility.ts | 2 +- .../src/utilities/GCBTerminalProvider.ts | 7 +- .../test/FileDeletionUtility.test.ts | 82 +- core-build/gulp-core-build/tsconfig.json | 4 +- .../typings-custom/glob-escape/index.d.ts | 3 +- core-build/node-library-build/.eslintrc.js | 4 +- core-build/node-library-build/gulpfile.js | 5 +- core-build/node-library-build/src/index.ts | 7 +- core-build/web-library-build/.eslintrc.js | 4 +- .../src/PostProcessSourceMaps.ts | 7 +- core-build/web-library-build/src/index.ts | 17 +- .../debug-certificate-manager/.eslintrc.js | 4 +- .../config/jest.json | 2 +- .../src/CertificateManager.ts | 156 +- .../src/CertificateStore.ts | 2 +- .../debug-certificate-manager/src/index.ts | 7 +- .../debug-certificate-manager/src/sudoSync.ts | 13 +- .../src/test/index.test.ts | 4 +- .../debug-certificate-manager/tsconfig.json | 5 +- libraries/load-themed-styles/.eslintrc.js | 4 +- libraries/load-themed-styles/config/jest.json | 2 +- libraries/load-themed-styles/gulpfile.js | 21 +- libraries/load-themed-styles/src/index.ts | 102 +- .../load-themed-styles/src/test/index.test.ts | 34 +- libraries/load-themed-styles/tsconfig.json | 5 +- libraries/node-core-library/.eslintrc.js | 6 +- libraries/node-core-library/config/jest.json | 2 +- libraries/node-core-library/src/Constants.ts | 4 +- libraries/node-core-library/src/Executable.ts | 67 +- libraries/node-core-library/src/FileSystem.ts | 144 +- libraries/node-core-library/src/FileWriter.ts | 8 +- .../node-core-library/src/IPackageJson.ts | 20 +- .../node-core-library/src/InternalError.ts | 6 +- libraries/node-core-library/src/JsonFile.ts | 34 +- libraries/node-core-library/src/JsonSchema.ts | 83 +- .../node-core-library/src/LegacyAdapters.ts | 7 +- libraries/node-core-library/src/LockFile.ts | 55 +- .../src/PackageJsonLookup.ts | 36 +- .../node-core-library/src/PackageName.ts | 13 +- .../node-core-library/src/PosixModeBits.ts | 2 +- .../src/ProtectableMapView.ts | 9 +- libraries/node-core-library/src/Sort.ts | 38 +- .../node-core-library/src/Terminal/Colors.ts | 49 +- .../src/Terminal/ITerminalProvider.ts | 2 +- .../src/Terminal/Terminal.ts | 43 +- .../src/Terminal/test/Terminal.test.ts | 30 +- .../src/Terminal/test/createColorGrid.ts | 9 +- .../src/Terminal/test/write-colors.ts | 5 +- libraries/node-core-library/src/Text.ts | 6 +- libraries/node-core-library/src/index.ts | 75 +- .../src/test/Executable.test.ts | 83 +- .../src/test/JsonSchema.test.ts | 17 +- .../src/test/LockFile.test.ts | 55 +- .../src/test/PackageJsonLookup.test.ts | 6 +- .../src/test/PackageName.test.ts | 152 +- .../node-core-library/src/test/Path.test.ts | 1 - .../src/test/ProtectableMap.test.ts | 3 +- .../node-core-library/src/test/Sort.test.ts | 24 +- .../node-core-library/src/test/Text.test.ts | 42 +- .../example-package-no-version/package.json | 2 +- .../test-data/example-package/package.json | 2 +- .../executable/success/javascript-file.js | 1 - .../src/test/test-data/test-schema.json | 11 +- .../src/test/test-data/test.json | 6 +- .../src/test/test-data/test2.json | 6 +- libraries/node-core-library/tsconfig.json | 5 +- libraries/package-deps-hash/.eslintrc.js | 4 +- libraries/package-deps-hash/config/jest.json | 2 +- .../package-deps-hash/src/getPackageDeps.ts | 57 +- libraries/package-deps-hash/src/index.ts | 5 +- .../src/test/getPackageDeps.test.ts | 65 +- .../src/test/nestedTestProject/package.json | 2 +- .../src/test/testProject/package.json | 2 +- libraries/package-deps-hash/tsconfig.json | 5 +- libraries/rushell/.eslintrc.js | 4 +- libraries/rushell/config/jest.json | 2 +- libraries/rushell/src/AstNode.ts | 2 +- libraries/rushell/src/ParseError.ts | 1 - libraries/rushell/src/Parser.ts | 8 +- libraries/rushell/src/Rushell.ts | 5 +- libraries/rushell/src/TextRange.ts | 6 +- libraries/rushell/src/Tokenizer.ts | 34 +- libraries/rushell/src/index.ts | 5 +- libraries/rushell/src/test/Parser.test.ts | 9 +- libraries/rushell/src/test/TextRange.test.ts | 26 +- libraries/rushell/src/test/Tokenizer.test.ts | 29 +- libraries/rushell/tsconfig.json | 5 +- libraries/stream-collator/.eslintrc.js | 4 +- libraries/stream-collator/config/jest.json | 2 +- libraries/stream-collator/src/Interleaver.ts | 35 +- libraries/stream-collator/src/index.ts | 5 +- .../src/test/Interleaver.test.ts | 13 +- libraries/stream-collator/tsconfig.json | 5 +- libraries/ts-command-line/.eslintrc.js | 4 +- libraries/ts-command-line/config/jest.json | 2 +- libraries/ts-command-line/src/index.ts | 24 +- .../src/parameters/BaseClasses.ts | 74 +- .../parameters/CommandLineChoiceParameter.ts | 24 +- .../src/parameters/CommandLineDefinition.ts | 4 +- .../parameters/CommandLineFlagParameter.ts | 9 +- .../parameters/CommandLineIntegerParameter.ts | 12 +- .../src/parameters/CommandLineRemainder.ts | 5 +- .../CommandLineStringListParameter.ts | 32 +- .../parameters/CommandLineStringParameter.ts | 7 +- .../src/providers/CommandLineAction.ts | 11 +- .../providers/CommandLineParameterProvider.ts | 29 +- .../src/providers/CommandLineParser.ts | 58 +- .../providers/CommandLineParserExitError.ts | 8 +- .../src/providers/DynamicCommandLineAction.ts | 6 +- .../src/providers/DynamicCommandLineParser.ts | 3 +- .../src/test/ActionlessParser.test.ts | 8 +- .../src/test/CommandLineParameter.test.ts | 112 +- .../src/test/CommandLineParser.test.ts | 8 +- .../src/test/CommandLineRemainder.test.ts | 21 +- .../src/test/DynamicCommandLineParser.test.ts | 15 +- libraries/ts-command-line/tsconfig.json | 5 +- libraries/typings-generator/.eslintrc.js | 4 +- .../src/StringValuesTypingsGenerator.ts | 26 +- .../typings-generator/src/TypingsGenerator.ts | 43 +- libraries/typings-generator/src/index.ts | 7 +- .../doc-plugin-rush-stack/.eslintrc.js | 4 +- .../src/RushStackFeature.ts | 14 +- .../doc-plugin-rush-stack/src/index.ts | 6 +- .../doc-plugin-rush-stack/tsconfig.json | 4 +- .../generate-api-docs/api-documenter.json | 2 +- repo-scripts/repo-toolbox/.eslintrc.js | 4 +- repo-scripts/repo-toolbox/src/ReadmeAction.ts | 27 +- .../repo-toolbox/src/ToolboxCommandLine.ts | 15 +- repo-scripts/repo-toolbox/tsconfig.json | 4 +- repo-scripts/tombstone/postinstall.js | 10 +- rush.json | 141 +- stack/eslint-config/index.js | 324 +++-- stack/eslint-config/patch-eslint6.js | 8 +- stack/eslint-config/react.js | 48 +- stack/eslint-plugin/src/index.ts | 4 +- stack/eslint-plugin/src/no-null.ts | 26 +- .../src/no-untyped-underscore.ts | 50 +- stack/eslint-plugin/tsconfig.json | 4 +- stack/rush-stack-compiler-2.4/.eslintrc.js | 4 +- stack/rush-stack-compiler-2.4/gulpfile.js | 26 +- .../includes/tsconfig-base.json | 10 +- .../includes/tsconfig-node.json | 2 +- .../includes/tsconfig-web.json | 9 +- .../includes/tslint.json | 30 +- stack/rush-stack-compiler-2.4/tsconfig.json | 2 +- stack/rush-stack-compiler-2.7/.eslintrc.js | 4 +- stack/rush-stack-compiler-2.7/gulpfile.js | 26 +- .../includes/tsconfig-base.json | 10 +- .../includes/tsconfig-node.json | 2 +- .../includes/tsconfig-web.json | 9 +- .../includes/tslint.json | 30 +- stack/rush-stack-compiler-2.7/tsconfig.json | 2 +- stack/rush-stack-compiler-2.8/.eslintrc.js | 4 +- stack/rush-stack-compiler-2.8/gulpfile.js | 26 +- .../includes/tsconfig-base.json | 10 +- .../includes/tsconfig-node.json | 2 +- .../includes/tsconfig-web.json | 9 +- .../includes/tslint.json | 30 +- stack/rush-stack-compiler-2.8/tsconfig.json | 2 +- stack/rush-stack-compiler-2.9/.eslintrc.js | 4 +- stack/rush-stack-compiler-2.9/gulpfile.js | 26 +- .../includes/tsconfig-base.json | 10 +- .../includes/tsconfig-node.json | 2 +- .../includes/tsconfig-web.json | 9 +- .../includes/tslint.json | 30 +- stack/rush-stack-compiler-2.9/tsconfig.json | 2 +- stack/rush-stack-compiler-3.0/.eslintrc.js | 4 +- stack/rush-stack-compiler-3.0/gulpfile.js | 26 +- .../includes/tsconfig-base.json | 10 +- .../includes/tsconfig-node.json | 2 +- .../includes/tsconfig-web.json | 9 +- .../includes/tslint.json | 30 +- stack/rush-stack-compiler-3.0/tsconfig.json | 2 +- stack/rush-stack-compiler-3.1/.eslintrc.js | 4 +- stack/rush-stack-compiler-3.1/gulpfile.js | 26 +- .../includes/tsconfig-base.json | 10 +- .../includes/tsconfig-node.json | 2 +- .../includes/tsconfig-web.json | 9 +- .../includes/tslint.json | 30 +- stack/rush-stack-compiler-3.1/tsconfig.json | 2 +- stack/rush-stack-compiler-3.2/.eslintrc.js | 4 +- stack/rush-stack-compiler-3.2/gulpfile.js | 26 +- .../includes/tsconfig-base.json | 10 +- .../includes/tsconfig-node.json | 2 +- .../includes/tsconfig-web.json | 9 +- .../includes/tslint.json | 30 +- stack/rush-stack-compiler-3.2/tsconfig.json | 2 +- stack/rush-stack-compiler-3.3/.eslintrc.js | 4 +- stack/rush-stack-compiler-3.3/gulpfile.js | 26 +- .../includes/tsconfig-base.json | 10 +- .../includes/tsconfig-node.json | 2 +- .../includes/tsconfig-web.json | 9 +- .../includes/tslint.json | 30 +- stack/rush-stack-compiler-3.3/tsconfig.json | 2 +- stack/rush-stack-compiler-3.4/.eslintrc.js | 4 +- stack/rush-stack-compiler-3.4/gulpfile.js | 26 +- .../includes/tsconfig-base.json | 10 +- .../includes/tsconfig-node.json | 2 +- .../includes/tsconfig-web.json | 9 +- .../includes/tslint.json | 30 +- stack/rush-stack-compiler-3.4/tsconfig.json | 2 +- stack/rush-stack-compiler-3.5/.eslintrc.js | 4 +- stack/rush-stack-compiler-3.5/gulpfile.js | 26 +- .../includes/tsconfig-base.json | 10 +- .../includes/tsconfig-node.json | 2 +- .../includes/tsconfig-web.json | 9 +- .../includes/tslint.json | 30 +- stack/rush-stack-compiler-3.5/tsconfig.json | 2 +- stack/rush-stack-compiler-3.6/.eslintrc.js | 4 +- stack/rush-stack-compiler-3.6/gulpfile.js | 26 +- .../includes/tsconfig-base.json | 10 +- .../includes/tsconfig-node.json | 2 +- .../includes/tsconfig-web.json | 9 +- .../includes/tslint.json | 30 +- stack/rush-stack-compiler-3.6/tsconfig.json | 2 +- stack/rush-stack-compiler-3.7/.eslintrc.js | 4 +- stack/rush-stack-compiler-3.7/gulpfile.js | 26 +- .../includes/tsconfig-base.json | 10 +- .../includes/tsconfig-node.json | 2 +- .../includes/tsconfig-web.json | 9 +- .../includes/tslint.json | 30 +- stack/rush-stack-compiler-3.7/tsconfig.json | 2 +- .../src/shared/ApiExtractorRunner.ts | 11 +- .../src/shared/CmdRunner.ts | 45 +- .../src/shared/EslintRunner.ts | 42 +- .../src/shared/LoggingUtilities.ts | 16 +- .../src/shared/ToolPackages.d.ts | 6 +- .../src/shared/TslintRunner.ts | 39 +- .../src/shared/TypescriptCompiler.ts | 29 +- .../src/shared/index.ts | 26 +- .../loader-load-themed-styles/.eslintrc.js | 4 +- .../config/jest.json | 2 +- .../src/LoadThemedStylesLoader.ts | 8 +- .../src/test/LoadThemedStylesLoader.test.ts | 2 +- .../src/test/testData/MockStyle1.ts | 5 +- .../loader-load-themed-styles/tsconfig.json | 5 +- webpack/loader-raw-script/.eslintrc.js | 4 +- webpack/loader-raw-script/config/jest.json | 2 +- .../loader-raw-script/src/RawScriptLoader.ts | 4 +- .../src/test/RawScriptLoader.test.ts | 2 +- webpack/loader-raw-script/tsconfig.json | 5 +- webpack/localization-plugin/.eslintrc.js | 4 +- .../localization-plugin/src/AssetProcessor.ts | 95 +- .../src/LocFileTypingsGenerator.ts | 21 +- .../src/LocalizationPlugin.ts | 219 +-- .../src/Pseudolocalization.ts | 2 +- .../src/WebpackConfigurationUpdater.ts | 103 +- webpack/localization-plugin/src/index.ts | 15 +- webpack/localization-plugin/src/interfaces.ts | 2 +- .../src/loaders/InPlaceLocFileLoader.ts | 44 +- .../src/loaders/LoaderFactory.ts | 6 +- .../src/loaders/LocLoader.ts | 76 +- .../src/schemas/locJson.schema.json | 2 +- .../src/utilities/Constants.ts | 4 +- .../src/utilities/LoaderTerminalProvider.ts | 9 +- .../src/utilities/LocFileParser.ts | 19 +- .../src/utilities/ResxReader.ts | 118 +- .../.eslintrc.js | 4 +- .../src/SetPublicPathPlugin.ts | 41 +- .../src/V3Interfaces.ts | 5 +- .../src/codeGenerator.ts | 148 +- .../src/index.ts | 5 +- 814 files changed, 12359 insertions(+), 11784 deletions(-) diff --git a/apps/api-documenter/.eslintrc.js b/apps/api-documenter/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/apps/api-documenter/.eslintrc.js +++ b/apps/api-documenter/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/apps/api-documenter/config/api-extractor.json b/apps/api-documenter/config/api-extractor.json index 3e8571b570b..aa9d8f810fd 100644 --- a/apps/api-documenter/config/api-extractor.json +++ b/apps/api-documenter/config/api-extractor.json @@ -15,6 +15,6 @@ "dtsRollup": { "enabled": true, - "untrimmedFilePath": "/dist/rollup.d.ts", + "untrimmedFilePath": "/dist/rollup.d.ts" } } diff --git a/apps/api-documenter/config/jest.json b/apps/api-documenter/config/jest.json index b4a7ec97a56..902b00ea176 100644 --- a/apps/api-documenter/config/jest.json +++ b/apps/api-documenter/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": true -} \ No newline at end of file +} diff --git a/apps/api-documenter/src/cli/ApiDocumenterCommandLine.ts b/apps/api-documenter/src/cli/ApiDocumenterCommandLine.ts index 6b466c0e1b2..7e9cc248260 100644 --- a/apps/api-documenter/src/cli/ApiDocumenterCommandLine.ts +++ b/apps/api-documenter/src/cli/ApiDocumenterCommandLine.ts @@ -10,13 +10,15 @@ export class ApiDocumenterCommandLine extends CommandLineParser { public constructor() { super({ toolFilename: 'api-documenter', - toolDescription: 'Reads *.api.json files produced by api-extractor, ' - + ' and generates API documentation in various output formats.' + toolDescription: + 'Reads *.api.json files produced by api-extractor, ' + + ' and generates API documentation in various output formats.', }); this._populateActions(); } - protected onDefineParameters(): void { // override + protected onDefineParameters(): void { + // override // No parameters } diff --git a/apps/api-documenter/src/cli/BaseAction.ts b/apps/api-documenter/src/cli/BaseAction.ts index 02944450990..3262a1e6fd0 100644 --- a/apps/api-documenter/src/cli/BaseAction.ts +++ b/apps/api-documenter/src/cli/BaseAction.ts @@ -5,17 +5,14 @@ import * as path from 'path'; import * as tsdoc from '@microsoft/tsdoc'; import * as colors from 'colors'; -import { - CommandLineAction, - CommandLineStringParameter -} from '@rushstack/ts-command-line'; +import { CommandLineAction, CommandLineStringParameter } from '@rushstack/ts-command-line'; import { FileSystem } from '@rushstack/node-core-library'; import { ApiModel, ApiItem, ApiItemContainerMixin, ApiDocumentedItem, - IResolveDeclarationReferenceResult + IResolveDeclarationReferenceResult, } from '@microsoft/api-extractor-model'; export abstract class BaseAction extends CommandLineAction { @@ -25,22 +22,25 @@ export abstract class BaseAction extends CommandLineAction { private _inputFolderParameter: CommandLineStringParameter; private _outputFolderParameter: CommandLineStringParameter; - protected onDefineParameters(): void { // override + protected onDefineParameters(): void { + // override this._inputFolderParameter = this.defineStringParameter({ parameterLongName: '--input-folder', parameterShortName: '-i', argumentName: 'FOLDER1', - description: `Specifies the input folder containing the *.api.json files to be processed.` - + ` If omitted, the default is "./input"` + description: + `Specifies the input folder containing the *.api.json files to be processed.` + + ` If omitted, the default is "./input"`, }); this._outputFolderParameter = this.defineStringParameter({ parameterLongName: '--output-folder', parameterShortName: '-o', argumentName: 'FOLDER2', - description: `Specifies the output folder where the documentation will be written.` - + ` ANY EXISTING CONTENTS WILL BE DELETED!` - + ` If omitted, the default is "./${this.actionName}"` + description: + `Specifies the output folder where the documentation will be written.` + + ` ANY EXISTING CONTENTS WILL BE DELETED!` + + ` If omitted, the default is "./${this.actionName}"`, }); } @@ -72,28 +72,33 @@ export abstract class BaseAction extends CommandLineAction { // 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 { - if (apiItem instanceof ApiDocumentedItem) { if (apiItem.tsdocComment) { const inheritDocTag: tsdoc.DocInheritDocTag | undefined = apiItem.tsdocComment.inheritDocTag; if (inheritDocTag && inheritDocTag.declarationReference) { // Attempt to resolve the declaration reference - const result: IResolveDeclarationReferenceResult - = apiModel.resolveDeclarationReference(inheritDocTag.declarationReference, apiItem); + const result: IResolveDeclarationReferenceResult = apiModel.resolveDeclarationReference( + inheritDocTag.declarationReference, + apiItem + ); if (result.errorMessage) { - console.log(colors.yellow(`Warning: Unresolved @inheritDoc tag for ${apiItem.displayName}: ` - + result.errorMessage)); + console.log( + colors.yellow( + `Warning: Unresolved @inheritDoc tag for ${apiItem.displayName}: ` + result.errorMessage + ) + ); } else { - if (result.resolvedApiItem instanceof ApiDocumentedItem - && result.resolvedApiItem.tsdocComment - && result.resolvedApiItem !== apiItem) { + if ( + result.resolvedApiItem instanceof ApiDocumentedItem && + result.resolvedApiItem.tsdocComment && + result.resolvedApiItem !== apiItem + ) { this._copyInheritedDocs(apiItem.tsdocComment, result.resolvedApiItem.tsdocComment); } } } - } } @@ -124,5 +129,4 @@ export abstract class BaseAction extends CommandLineAction { targetDocComment.inheritDocTag = undefined; } - } diff --git a/apps/api-documenter/src/cli/GenerateAction.ts b/apps/api-documenter/src/cli/GenerateAction.ts index 330a4bbde06..1d3e2fcfd31 100644 --- a/apps/api-documenter/src/cli/GenerateAction.ts +++ b/apps/api-documenter/src/cli/GenerateAction.ts @@ -17,12 +17,14 @@ export class GenerateAction extends BaseAction { super({ actionName: 'generate', summary: 'EXPERIMENTAL', - documentation: 'EXPERIMENTAL - This action is a prototype of a new config file driven mode of operation for' - + ' API Documenter. It is not ready for general usage yet. Its design may change in the future.' + documentation: + 'EXPERIMENTAL - This action is a prototype of a new config file driven mode of operation for' + + ' API Documenter. It is not ready for general usage yet. Its design may change in the future.', }); } - protected onExecute(): Promise { // override + protected onExecute(): Promise { + // override // Look for the config file under the current folder let configFilePath: string = path.join(process.cwd(), DocumenterConfig.FILENAME); @@ -32,7 +34,9 @@ export class GenerateAction extends BaseAction { // Otherwise try the standard "config" subfolder configFilePath = path.join(process.cwd(), 'config', DocumenterConfig.FILENAME); if (!FileSystem.exists(configFilePath)) { - throw new Error(`Unable to find ${DocumenterConfig.FILENAME} in the current folder or in a "config" subfolder`); + throw new Error( + `Unable to find ${DocumenterConfig.FILENAME} in the current folder or in a "config" subfolder` + ); } } @@ -44,7 +48,10 @@ export class GenerateAction extends BaseAction { const markdownDocumenter: MarkdownDocumenter = new MarkdownDocumenter(apiModel, documenterConfig); markdownDocumenter.generateFiles(this.outputFolder); } else { - const yamlDocumenter: ExperimentalYamlDocumenter = new ExperimentalYamlDocumenter(apiModel, documenterConfig); + const yamlDocumenter: ExperimentalYamlDocumenter = new ExperimentalYamlDocumenter( + apiModel, + documenterConfig + ); yamlDocumenter.generateFiles(this.outputFolder); } diff --git a/apps/api-documenter/src/cli/MarkdownAction.ts b/apps/api-documenter/src/cli/MarkdownAction.ts index 4df97df2c41..923df6861f7 100644 --- a/apps/api-documenter/src/cli/MarkdownAction.ts +++ b/apps/api-documenter/src/cli/MarkdownAction.ts @@ -11,12 +11,14 @@ export class MarkdownAction extends BaseAction { super({ actionName: 'markdown', summary: 'Generate documentation as Markdown files (*.md)', - documentation: 'Generates API documentation as a collection of files in' - + ' Markdown format, suitable for example for publishing on a GitHub site.' + documentation: + 'Generates API documentation as a collection of files in' + + ' Markdown format, suitable for example for publishing on a GitHub site.', }); } - protected onExecute(): Promise { // override + protected onExecute(): Promise { + // override const apiModel: ApiModel = this.buildApiModel(); const markdownDocumenter: MarkdownDocumenter = new MarkdownDocumenter(apiModel, undefined); diff --git a/apps/api-documenter/src/cli/YamlAction.ts b/apps/api-documenter/src/cli/YamlAction.ts index 74cb85d98a0..dc9969b693a 100644 --- a/apps/api-documenter/src/cli/YamlAction.ts +++ b/apps/api-documenter/src/cli/YamlAction.ts @@ -1,9 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - CommandLineFlagParameter -} from '@rushstack/ts-command-line'; +import { CommandLineFlagParameter } from '@rushstack/ts-command-line'; import { ApiDocumenterCommandLine } from './ApiDocumenterCommandLine'; import { BaseAction } from './BaseAction'; @@ -20,34 +18,38 @@ export class YamlAction extends BaseAction { super({ actionName: 'yaml', summary: 'Generate documentation as universal reference YAML files (*.yml)', - documentation: 'Generates API documentation as a collection of files conforming' - + ' to the universal reference YAML format, which is used by the docs.microsoft.com' - + ' pipeline.' + documentation: + 'Generates API documentation as a collection of files conforming' + + ' to the universal reference YAML format, which is used by the docs.microsoft.com' + + ' pipeline.', }); } - protected onDefineParameters(): void { // override + protected onDefineParameters(): void { + // override super.onDefineParameters(); this._officeParameter = this.defineFlagParameter({ parameterLongName: '--office', - description: `Enables some additional features specific to Office Add-ins` + description: `Enables some additional features specific to Office Add-ins`, }); this._newDocfxNamespacesParameter = this.defineFlagParameter({ parameterLongName: '--new-docfx-namespaces', - description: `This enables an experimental feature that will be officially released with the next major version` - + ` of API Documenter. It requires DocFX 2.46 or newer. It enables documentation for namespaces and` - + ` 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.` + description: + `This enables an experimental feature that will be officially released with the next major version` + + ` of API Documenter. It requires DocFX 2.46 or newer. It enables documentation for namespaces and` + + ` 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.`, }); } - protected onExecute(): Promise { // override + protected onExecute(): Promise { + // override const apiModel: ApiModel = this.buildApiModel(); const yamlDocumenter: YamlDocumenter = this._officeParameter.value - ? new OfficeYamlDocumenter(apiModel, this.inputFolder, this._newDocfxNamespacesParameter.value) - : new YamlDocumenter(apiModel, this._newDocfxNamespacesParameter.value); + ? new OfficeYamlDocumenter(apiModel, this.inputFolder, this._newDocfxNamespacesParameter.value) + : new YamlDocumenter(apiModel, this._newDocfxNamespacesParameter.value); yamlDocumenter.generateFiles(this.outputFolder); return Promise.resolve(); diff --git a/apps/api-documenter/src/documenters/DocumenterConfig.ts b/apps/api-documenter/src/documenters/DocumenterConfig.ts index 6adff8aaf6b..e3fbb3cc4f4 100644 --- a/apps/api-documenter/src/documenters/DocumenterConfig.ts +++ b/apps/api-documenter/src/documenters/DocumenterConfig.ts @@ -24,7 +24,8 @@ export class DocumenterConfig { * The JSON Schema for API Extractor config file (api-extractor.schema.json). */ public static readonly jsonSchema: JsonSchema = JsonSchema.fromFile( - path.join(__dirname, '..', 'schemas', 'api-documenter.schema.json')); + path.join(__dirname, '..', 'schemas', 'api-documenter.schema.json') + ); /** * The config file name "api-extractor.json". diff --git a/apps/api-documenter/src/documenters/ExperimentalYamlDocumenter.ts b/apps/api-documenter/src/documenters/ExperimentalYamlDocumenter.ts index 0fea06fa1b6..a278d7092a0 100644 --- a/apps/api-documenter/src/documenters/ExperimentalYamlDocumenter.ts +++ b/apps/api-documenter/src/documenters/ExperimentalYamlDocumenter.ts @@ -39,7 +39,7 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { let tocItem: IYamlTocItem; if (apiItem.kind === ApiItemKind.Namespace && !this.newDocfxNamespaces) { tocItem = { - name: this._getTocItemName(apiItem) + name: this._getTocItemName(apiItem), }; } else { if (this._shouldEmbed(apiItem.kind)) { @@ -49,7 +49,7 @@ export class ExperimentalYamlDocumenter extends YamlDocumenter { tocItem = { name: this._getTocItemName(apiItem), - uid: this._getUid(apiItem) + uid: this._getUid(apiItem), }; if (apiItem.kind !== ApiItemKind.Package) { @@ -98,10 +98,9 @@ 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) - : undefined; + const docInlineTag: DocInlineTag | undefined = categoryInlineTag + ? this._findInlineTagByName(categoryInlineTag, apiItem.tsdocComment) + : undefined; const tagContent: string | undefined = docInlineTag && docInlineTag.tagContent && docInlineTag.tagContent.trim(); @@ -134,7 +133,10 @@ 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(tagName: string, docComment: DocComment | undefined): DocInlineTag | undefined { + private _findInlineTagByName( + tagName: string, + docComment: DocComment | undefined + ): DocInlineTag | undefined { const tagNameToCheck: string = `@${tagName}`; if (docComment instanceof DocInlineTag) { diff --git a/apps/api-documenter/src/documenters/MarkdownDocumenter.ts b/apps/api-documenter/src/documenters/MarkdownDocumenter.ts index 7f6118ea8c0..2be3b80b867 100644 --- a/apps/api-documenter/src/documenters/MarkdownDocumenter.ts +++ b/apps/api-documenter/src/documenters/MarkdownDocumenter.ts @@ -4,11 +4,7 @@ /* eslint max-lines: "off" */ import * as path from 'path'; -import { - PackageName, - FileSystem, - NewlineKind -} from '@rushstack/node-core-library'; +import { PackageName, FileSystem, NewlineKind } from '@rushstack/node-core-library'; import { DocSection, DocPlainText, @@ -21,7 +17,7 @@ import { DocFencedCode, StandardTags, DocBlock, - DocComment + DocComment, } from '@microsoft/tsdoc'; import { ApiModel, @@ -42,7 +38,7 @@ import { ApiDeclaredItem, ApiNamespace, ExcerptTokenKind, - IResolveDeclarationReferenceResult + IResolveDeclarationReferenceResult, } from '@microsoft/api-extractor-model'; import { CustomDocNodes } from '../nodes/CustomDocNodeKind'; @@ -57,7 +53,7 @@ import { CustomMarkdownEmitter } from '../markdown/CustomMarkdownEmitter'; import { PluginLoader } from '../plugin/PluginLoader'; import { IMarkdownDocumenterFeatureOnBeforeWritePageArgs, - MarkdownDocumenterFeatureContext + MarkdownDocumenterFeatureContext, } from '../plugin/MarkdownDocumenterFeature'; import { DocumenterConfig } from './DocumenterConfig'; import { MarkdownDocumenterAccessor } from '../plugin/MarkdownDocumenterAccessor'; @@ -94,8 +90,8 @@ export class MarkdownDocumenter { documenter: new MarkdownDocumenterAccessor({ getLinkForApiItem: (apiItem: ApiItem) => { return this._getLinkFilenameForApiItem(apiItem); - } - }) + }, + }), }); }); } @@ -174,20 +170,17 @@ export class MarkdownDocumenter { const tsdocComment: DocComment | undefined = apiItem.tsdocComment; if (tsdocComment) { - if (tsdocComment.deprecatedBlock) { output.appendNode( - new DocNoteBox({ configuration: this._tsdocConfiguration }, - [ - new DocParagraph({ configuration: this._tsdocConfiguration }, [ - new DocPlainText({ - configuration: this._tsdocConfiguration, - text: 'Warning: This API is now obsolete. ' - }) - ]), - ...tsdocComment.deprecatedBlock.content.nodes - ] - ) + new DocNoteBox({ configuration: this._tsdocConfiguration }, [ + new DocParagraph({ configuration: this._tsdocConfiguration }, [ + new DocPlainText({ + configuration: this._tsdocConfiguration, + text: 'Warning: This API is now obsolete. ', + }), + ]), + ...tsdocComment.deprecatedBlock.content.nodes, + ]) ); } @@ -200,12 +193,16 @@ export class MarkdownDocumenter { output.appendNode( new DocParagraph({ configuration }, [ new DocEmphasisSpan({ configuration, bold: true }, [ - new DocPlainText({ configuration, text: 'Signature:' }) - ]) + new DocPlainText({ configuration, text: 'Signature:' }), + ]), ]) ); output.appendNode( - new DocFencedCode({ configuration, code: apiItem.getExcerptWithModifiers(), language: 'typescript' }) + new DocFencedCode({ + configuration, + code: apiItem.getExcerptWithModifiers(), + language: 'typescript', + }) ); } } @@ -266,13 +263,15 @@ export class MarkdownDocumenter { const filename: string = path.join(this._outputFolder, this._getFilenameForApiItem(apiItem)); const stringBuilder: StringBuilder = new StringBuilder(); - stringBuilder.append('\n\n'); + stringBuilder.append( + '\n\n' + ); this._markdownEmitter.emit(stringBuilder, output, { contextApiItem: apiItem, onGetFilenameForApiItem: (apiItemForFilename: ApiItem) => { return this._getLinkFilenameForApiItem(apiItemForFilename); - } + }, }); let pageContent: string = stringBuilder.toString(); @@ -282,14 +281,14 @@ export class MarkdownDocumenter { const eventArgs: IMarkdownDocumenterFeatureOnBeforeWritePageArgs = { apiItem: apiItem, outputFilename: filename, - pageContent: pageContent + pageContent: pageContent, }; 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, }); } @@ -305,8 +304,9 @@ export class MarkdownDocumenter { } // Write the @example blocks - const exampleBlocks: DocBlock[] = tsdocComment.customBlocks.filter(x => x.blockTag.tagNameWithUpperCase - === StandardTags.example.tagNameWithUpperCase); + const exampleBlocks: DocBlock[] = tsdocComment.customBlocks.filter( + (x) => x.blockTag.tagNameWithUpperCase === StandardTags.example.tagNameWithUpperCase + ); let exampleNumber: number = 1; for (const exampleBlock of exampleBlocks) { @@ -328,8 +328,9 @@ export class MarkdownDocumenter { if (tsdocComment) { // Write the @throws blocks - const throwsBlocks: DocBlock[] = tsdocComment.customBlocks.filter(x => x.blockTag.tagNameWithUpperCase - === StandardTags.throws.tagNameWithUpperCase); + const throwsBlocks: DocBlock[] = tsdocComment.customBlocks.filter( + (x) => x.blockTag.tagNameWithUpperCase === StandardTags.throws.tagNameWithUpperCase + ); if (throwsBlocks.length > 0) { const heading: string = 'Exceptions'; @@ -351,14 +352,13 @@ export class MarkdownDocumenter { const packagesTable: DocTable = new DocTable({ configuration, - headerTitles: ['Package', 'Description'] + headerTitles: ['Package', 'Description'], }); for (const apiMember of apiModel.members) { - const row: DocTableRow = new DocTableRow({ configuration }, [ this._createTitleCell(apiMember), - this._createDescriptionCell(apiMember) + this._createDescriptionCell(apiMember), ]); switch (apiMember.kind) { @@ -383,48 +383,48 @@ export class MarkdownDocumenter { const classesTable: DocTable = new DocTable({ configuration, - headerTitles: ['Class', 'Description'] + headerTitles: ['Class', 'Description'], }); const enumerationsTable: DocTable = new DocTable({ configuration, - headerTitles: ['Enumeration', 'Description'] + headerTitles: ['Enumeration', 'Description'], }); const functionsTable: DocTable = new DocTable({ configuration, - headerTitles: ['Function', 'Description'] + headerTitles: ['Function', 'Description'], }); const interfacesTable: DocTable = new DocTable({ configuration, - headerTitles: ['Interface', 'Description'] + headerTitles: ['Interface', 'Description'], }); const namespacesTable: DocTable = new DocTable({ configuration, - headerTitles: ['Namespace', 'Description'] + headerTitles: ['Namespace', 'Description'], }); const variablesTable: DocTable = new DocTable({ configuration, - headerTitles: ['Variable', 'Description'] + headerTitles: ['Variable', 'Description'], }); const typeAliasesTable: DocTable = new DocTable({ configuration, - headerTitles: ['Type Alias', 'Description'] + headerTitles: ['Type Alias', 'Description'], }); - const apiMembers: ReadonlyArray = apiContainer.kind === ApiItemKind.Package ? - (apiContainer as ApiPackage).entryPoints[0].members - : (apiContainer as ApiNamespace).members; + const apiMembers: ReadonlyArray = + apiContainer.kind === ApiItemKind.Package + ? (apiContainer as ApiPackage).entryPoints[0].members + : (apiContainer as ApiNamespace).members; for (const apiMember of apiMembers) { - const row: DocTableRow = new DocTableRow({ configuration }, [ this._createTitleCell(apiMember), - this._createDescriptionCell(apiMember) + this._createDescriptionCell(apiMember), ]); switch (apiMember.kind) { @@ -508,33 +508,32 @@ export class MarkdownDocumenter { const eventsTable: DocTable = new DocTable({ configuration, - headerTitles: ['Property', 'Modifiers', 'Type', 'Description'] + headerTitles: ['Property', 'Modifiers', 'Type', 'Description'], }); const constructorsTable: DocTable = new DocTable({ configuration, - headerTitles: ['Constructor', 'Modifiers', 'Description'] + headerTitles: ['Constructor', 'Modifiers', 'Description'], }); const propertiesTable: DocTable = new DocTable({ configuration, - headerTitles: ['Property', 'Modifiers', 'Type', 'Description'] + headerTitles: ['Property', 'Modifiers', 'Type', 'Description'], }); const methodsTable: DocTable = new DocTable({ configuration, - headerTitles: ['Method', 'Modifiers', 'Description'] + headerTitles: ['Method', 'Modifiers', 'Description'], }); for (const apiMember of apiClass.members) { - switch (apiMember.kind) { case ApiItemKind.Constructor: { constructorsTable.addRow( new DocTableRow({ configuration }, [ this._createTitleCell(apiMember), this._createModifiersCell(apiMember), - this._createDescriptionCell(apiMember) + this._createDescriptionCell(apiMember), ]) ); @@ -546,7 +545,7 @@ export class MarkdownDocumenter { new DocTableRow({ configuration }, [ this._createTitleCell(apiMember), this._createModifiersCell(apiMember), - this._createDescriptionCell(apiMember) + this._createDescriptionCell(apiMember), ]) ); @@ -554,14 +553,13 @@ export class MarkdownDocumenter { 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) + this._createDescriptionCell(apiMember), ]) ); } else { @@ -570,7 +568,7 @@ export class MarkdownDocumenter { this._createTitleCell(apiMember), this._createModifiersCell(apiMember), this._createPropertyTypeCell(apiMember), - this._createDescriptionCell(apiMember) + this._createDescriptionCell(apiMember), ]) ); } @@ -578,7 +576,6 @@ export class MarkdownDocumenter { this._writeApiItemPage(apiMember); break; } - } } @@ -611,32 +608,33 @@ export class MarkdownDocumenter { const enumMembersTable: DocTable = new DocTable({ configuration, - headerTitles: ['Member', 'Value', 'Description'] + headerTitles: ['Member', 'Value', 'Description'], }); for (const apiEnumMember of apiEnum.members) { enumMembersTable.addRow( new DocTableRow({ configuration }, [ - new DocTableCell({ configuration }, [ new DocParagraph({ configuration }, [ - new DocPlainText({ configuration, text: Utilities.getConciseSignature(apiEnumMember) }) - ]) + new DocPlainText({ configuration, text: Utilities.getConciseSignature(apiEnumMember) }), + ]), ]), new DocTableCell({ configuration }, [ new DocParagraph({ configuration }, [ - new DocCodeSpan({ configuration, code: apiEnumMember.initializerExcerpt.text }) - ]) + new DocCodeSpan({ configuration, code: apiEnumMember.initializerExcerpt.text }), + ]), ]), - this._createDescriptionCell(apiEnumMember) + this._createDescriptionCell(apiEnumMember), ]) ); } if (enumMembersTable.rows.length > 0) { - output.appendNode(new DocHeading({ configuration: this._tsdocConfiguration, title: 'Enumeration Members' })); + output.appendNode( + new DocHeading({ configuration: this._tsdocConfiguration, title: 'Enumeration Members' }) + ); output.appendNode(enumMembersTable); } } @@ -649,28 +647,27 @@ export class MarkdownDocumenter { const eventsTable: DocTable = new DocTable({ configuration, - headerTitles: ['Property', 'Type', 'Description'] + headerTitles: ['Property', 'Type', 'Description'], }); const propertiesTable: DocTable = new DocTable({ configuration, - headerTitles: ['Property', 'Type', 'Description'] + headerTitles: ['Property', 'Type', 'Description'], }); const methodsTable: DocTable = new DocTable({ configuration, - headerTitles: ['Method', 'Description'] + headerTitles: ['Method', 'Description'], }); for (const apiMember of apiClass.members) { - switch (apiMember.kind) { case ApiItemKind.ConstructSignature: case ApiItemKind.MethodSignature: { methodsTable.addRow( new DocTableRow({ configuration }, [ this._createTitleCell(apiMember), - this._createDescriptionCell(apiMember) + this._createDescriptionCell(apiMember), ]) ); @@ -678,13 +675,12 @@ export class MarkdownDocumenter { break; } case ApiItemKind.PropertySignature: { - if ((apiMember as ApiPropertyItem).isEventProperty) { eventsTable.addRow( new DocTableRow({ configuration }, [ this._createTitleCell(apiMember), this._createPropertyTypeCell(apiMember), - this._createDescriptionCell(apiMember) + this._createDescriptionCell(apiMember), ]) ); } else { @@ -692,7 +688,7 @@ export class MarkdownDocumenter { new DocTableRow({ configuration }, [ this._createTitleCell(apiMember), this._createPropertyTypeCell(apiMember), - this._createDescriptionCell(apiMember) + this._createDescriptionCell(apiMember), ]) ); } @@ -700,7 +696,6 @@ export class MarkdownDocumenter { this._writeApiItemPage(apiMember); break; } - } } @@ -728,7 +723,7 @@ export class MarkdownDocumenter { const parametersTable: DocTable = new DocTable({ configuration, - headerTitles: ['Parameter', 'Type', 'Description'] + headerTitles: ['Parameter', 'Type', 'Description'], }); for (const apiParameter of apiParameterListMixin.parameters) { const parameterDescription: DocSection = new DocSection({ configuration }); @@ -740,13 +735,13 @@ export class MarkdownDocumenter { new DocTableRow({ configuration }, [ new DocTableCell({ configuration }, [ new DocParagraph({ configuration }, [ - new DocPlainText({ configuration, text: apiParameter.name }) - ]) + new DocPlainText({ configuration, text: apiParameter.name }), + ]), ]), new DocTableCell({ configuration }, [ - this._createParagraphForTypeExcerpt(apiParameter.parameterTypeExcerpt) + this._createParagraphForTypeExcerpt(apiParameter.parameterTypeExcerpt), ]), - new DocTableCell({ configuration }, parameterDescription.nodes) + new DocTableCell({ configuration }, parameterDescription.nodes), ]) ); } @@ -761,14 +756,12 @@ export class MarkdownDocumenter { output.appendNode( new DocParagraph({ configuration }, [ new DocEmphasisSpan({ configuration, bold: true }, [ - new DocPlainText({ configuration, text: 'Returns:' }) - ]) + new DocPlainText({ configuration, text: 'Returns:' }), + ]), ]) ); - output.appendNode( - this._createParagraphForTypeExcerpt(returnTypeExcerpt) - ); + output.appendNode(this._createParagraphForTypeExcerpt(returnTypeExcerpt)); if (apiParameterListMixin instanceof ApiDocumentedItem) { if (apiParameterListMixin.tsdocComment && apiParameterListMixin.tsdocComment.returnsBlock) { @@ -795,15 +788,19 @@ export class MarkdownDocumenter { // If it's hyperlinkable, then append a DocLinkTag if (token.kind === ExcerptTokenKind.Reference && token.canonicalReference) { const apiItemResult: IResolveDeclarationReferenceResult = this._apiModel.resolveDeclarationReference( - token.canonicalReference, undefined); + token.canonicalReference, + undefined + ); if (apiItemResult.resolvedApiItem) { - paragraph.appendNode(new DocLinkTag({ - configuration, - tagName: '@link', - linkText: unwrappedTokenText, - urlDestination: this._getLinkFilenameForApiItem(apiItemResult.resolvedApiItem) - })); + paragraph.appendNode( + new DocLinkTag({ + configuration, + tagName: '@link', + linkText: unwrappedTokenText, + urlDestination: this._getLinkFilenameForApiItem(apiItemResult.resolvedApiItem), + }) + ); continue; } } @@ -825,9 +822,9 @@ export class MarkdownDocumenter { configuration, tagName: '@link', linkText: Utilities.getConciseSignature(apiItem), - urlDestination: this._getLinkFilenameForApiItem(apiItem) - }) - ]) + urlDestination: this._getLinkFilenameForApiItem(apiItem), + }), + ]), ]); } @@ -847,9 +844,9 @@ export class MarkdownDocumenter { if (apiItem.releaseTag === ReleaseTag.Beta) { section.appendNodesInParagraph([ new DocEmphasisSpan({ configuration, bold: true, italic: true }, [ - new DocPlainText({ configuration, text: '(BETA)' }) + new DocPlainText({ configuration, text: '(BETA)' }), ]), - new DocPlainText({ configuration, text: ' ' }) + new DocPlainText({ configuration, text: ' ' }), ]); } } @@ -883,21 +880,21 @@ export class MarkdownDocumenter { 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 _writeBreadcrumb(output: DocSection, apiItem: ApiItem): void { - output.appendNodeInParagraph(new DocLinkTag({ - configuration: this._tsdocConfiguration, - tagName: '@link', - linkText: 'Home', - urlDestination: this._getLinkFilenameForApiItem(this._apiModel) - })); + output.appendNodeInParagraph( + new DocLinkTag({ + configuration: this._tsdocConfiguration, + tagName: '@link', + linkText: 'Home', + urlDestination: this._getLinkFilenameForApiItem(this._apiModel), + }) + ); for (const hierarchyItem of apiItem.getHierarchy()) { switch (hierarchyItem.kind) { @@ -911,14 +908,14 @@ export class MarkdownDocumenter { output.appendNodesInParagraph([ new DocPlainText({ configuration: this._tsdocConfiguration, - text: ' > ' + text: ' > ', }), new DocLinkTag({ configuration: this._tsdocConfiguration, tagName: '@link', linkText: hierarchyItem.displayName, - urlDestination: this._getLinkFilenameForApiItem(hierarchyItem) - }) + urlDestination: this._getLinkFilenameForApiItem(hierarchyItem), + }), ]); } } @@ -926,13 +923,12 @@ export class MarkdownDocumenter { private _writeBetaWarning(output: DocSection): void { const configuration: TSDocConfiguration = this._tsdocConfiguration; - const betaWarning: string = 'This API is provided as a preview for developers and may change' - + ' based on feedback that we receive. Do not use this API in a production environment.'; + const betaWarning: string = + 'This API is provided as a preview for developers and may change' + + ' based on feedback that we receive. Do not use this API in a production environment.'; output.appendNode( new DocNoteBox({ configuration }, [ - new DocParagraph({ configuration }, [ - new DocPlainText({ configuration, text: betaWarning }) - ]) + new DocParagraph({ configuration }, [new DocPlainText({ configuration, text: betaWarning })]), ]) ); } diff --git a/apps/api-documenter/src/documenters/OfficeYamlDocumenter.ts b/apps/api-documenter/src/documenters/OfficeYamlDocumenter.ts index b494e3d8ba5..8f2ffc500ab 100644 --- a/apps/api-documenter/src/documenters/OfficeYamlDocumenter.ts +++ b/apps/api-documenter/src/documenters/OfficeYamlDocumenter.ts @@ -32,11 +32,11 @@ export class OfficeYamlDocumenter extends YamlDocumenter { // Hash set of API Set URLs based on product. private _apiSetUrls: Record = { - 'Excel': '/office/dev/add-ins/reference/requirement-sets/excel-api-requirement-sets', - 'OneNote': '/office/dev/add-ins/reference/requirement-sets/onenote-api-requirement-sets', - 'Visio': '/office/dev/add-ins/reference/overview/visio-javascript-reference-overview', - 'Outlook': '/office/dev/add-ins/reference/requirement-sets/outlook-api-requirement-sets', - 'Word': '/office/dev/add-ins/reference/requirement-sets/word-api-requirement-sets' + Excel: '/office/dev/add-ins/reference/requirement-sets/excel-api-requirement-sets', + OneNote: '/office/dev/add-ins/reference/requirement-sets/onenote-api-requirement-sets', + Visio: '/office/dev/add-ins/reference/overview/visio-javascript-reference-overview', + Outlook: '/office/dev/add-ins/reference/requirement-sets/outlook-api-requirement-sets', + Word: '/office/dev/add-ins/reference/requirement-sets/word-api-requirement-sets', }; public constructor(apiModel: ApiModel, inputFolder: string, newDocfxNamespaces?: boolean) { @@ -63,11 +63,12 @@ export class OfficeYamlDocumenter extends YamlDocumenter { } /** @override */ - protected onGetTocRoot(): IYamlTocItem { // override + protected onGetTocRoot(): IYamlTocItem { + // override return { name: 'API reference', href: '~/docs-ref-autogen/overview/office.md', - items: [ ] + items: [], }; } @@ -83,10 +84,10 @@ export class OfficeYamlDocumenter extends YamlDocumenter { yamlItem.remarks = this._fixBoldAndItalics(yamlItem.remarks); } if (yamlItem.syntax && yamlItem.syntax.parameters) { - yamlItem.syntax.parameters.forEach(part => { - if (part.description) { - part.description = this._fixBoldAndItalics(part.description); - } + yamlItem.syntax.parameters.forEach((part) => { + if (part.description) { + part.description = this._fixBoldAndItalics(part.description); + } }); } @@ -122,7 +123,7 @@ export class OfficeYamlDocumenter extends YamlDocumenter { 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. @@ -137,7 +138,6 @@ export class OfficeYamlDocumenter extends YamlDocumenter { for (const snippet of snippets) { if (snippet.search(/await/) === -1) { text.push('```javascript'); - } else { text.push('```typescript'); } @@ -147,4 +147,4 @@ export class OfficeYamlDocumenter extends YamlDocumenter { } return text.join('\n'); } -} \ No newline at end of file +} diff --git a/apps/api-documenter/src/documenters/YamlDocumenter.ts b/apps/api-documenter/src/documenters/YamlDocumenter.ts index d0463e5a57e..2f081660750 100644 --- a/apps/api-documenter/src/documenters/YamlDocumenter.ts +++ b/apps/api-documenter/src/documenters/YamlDocumenter.ts @@ -10,7 +10,7 @@ import { PackageName, FileSystem, NewlineKind, - InternalError + InternalError, } from '@rushstack/node-core-library'; import { StringBuilder, DocSection, DocComment } from '@microsoft/tsdoc'; import { @@ -37,13 +37,9 @@ import { ExcerptTokenKind, HeritageType, ApiVariable, - ApiTypeAlias + ApiTypeAlias, } from '@microsoft/api-extractor-model'; -import { - DeclarationReference, - Navigation, - Meaning -} from '@microsoft/tsdoc/lib/beta/DeclarationReference'; +import { DeclarationReference, Navigation, Meaning } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; import { IYamlApiFile, IYamlItem, @@ -51,16 +47,15 @@ import { IYamlParameter, IYamlReference, IYamlReferenceSpec, - IYamlInheritanceTree + IYamlInheritanceTree, } from '../yaml/IYamlApiFile'; -import { - IYamlTocFile, - IYamlTocItem -} from '../yaml/IYamlTocFile'; +import { IYamlTocFile, IYamlTocItem } from '../yaml/IYamlTocFile'; import { Utilities } from '../utils/Utilities'; -import { CustomMarkdownEmitter} from '../markdown/CustomMarkdownEmitter'; +import { CustomMarkdownEmitter } from '../markdown/CustomMarkdownEmitter'; -const yamlApiSchema: JsonSchema = JsonSchema.fromFile(path.join(__dirname, '..', 'yaml', 'typescript.schema.json')); +const yamlApiSchema: JsonSchema = JsonSchema.fromFile( + path.join(__dirname, '..', 'yaml', 'typescript.schema.json') +); interface IYamlReferences { references: IYamlReference[]; @@ -76,7 +71,7 @@ const enum FlattenMode { /** Include entries for non-namespace immediate children. */ ImmediateChildren, /** Include entries for nested non-namespace children. */ - NestedChildren + NestedChildren, } interface INameOptions { @@ -125,12 +120,13 @@ export class YamlDocumenter { return { name: 'SharePoint Framework reference', href: '~/overview/sharepoint.md', - items: [ ] + items: [], }; } /** @virtual */ - protected onCustomizeYamlItem(yamlItem: IYamlItem): void { // virtual + protected onCustomizeYamlItem(yamlItem: IYamlItem): void { + // virtual // (overridden by child class) } @@ -155,7 +151,7 @@ export class YamlDocumenter { parentYamlFile.items.push(yamlItem); } else { const newYamlFile: IYamlApiFile = { - items: [] + items: [], }; newYamlFile.items.push(yamlItem); @@ -191,8 +187,12 @@ export class YamlDocumenter { this._recordYamlReference( this._ensureYamlReferences(), this._getUid(apiItem), - this._getYamlItemName(apiItem, { includeNamespace: !this.newDocfxNamespaces, includeSignature: true }), - this._getYamlItemName(apiItem, { includeNamespace: true, includeSignature: true })); + this._getYamlItemName(apiItem, { + includeNamespace: !this.newDocfxNamespaces, + includeSignature: true, + }), + this._getYamlItemName(apiItem, { includeNamespace: true, includeSignature: true }) + ); } } @@ -203,11 +203,17 @@ 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(apiItem.members[0].members, children, - this.newDocfxNamespaces ? FlattenMode.NestedNamespacesAndChildren : FlattenMode.NestedChildren); + this._flattenNamespaces( + apiItem.members[0].members, + children, + this.newDocfxNamespaces ? FlattenMode.NestedNamespacesAndChildren : FlattenMode.NestedChildren + ); } else { - this._flattenNamespaces(apiItem.members, children, - this.newDocfxNamespaces ? FlattenMode.ImmediateChildren : FlattenMode.NestedChildren); + this._flattenNamespaces( + apiItem.members, + children, + this.newDocfxNamespaces ? FlattenMode.ImmediateChildren : FlattenMode.NestedChildren + ); } return children; } @@ -218,7 +224,11 @@ export class YamlDocumenter { // - X // - X.Y // - X.Y.Z - private _flattenNamespaces(items: ReadonlyArray, childrenOut: ApiItem[], mode: FlattenMode): boolean { + private _flattenNamespaces( + items: ReadonlyArray, + childrenOut: ApiItem[], + mode: FlattenMode + ): boolean { let hasNonNamespaceChildren: boolean = false; for (const item of items) { if (item.kind === ApiItemKind.Namespace) { @@ -271,7 +281,7 @@ export class YamlDocumenter { /** @virtual */ protected buildYamlTocFile(apiItems: ReadonlyArray): IYamlTocFile { const tocFile: IYamlTocFile = { - items: [ ] + items: [], }; const rootItem: IYamlTocItem = this.onGetTocRoot(); @@ -287,7 +297,7 @@ export class YamlDocumenter { let tocItem: IYamlTocItem; if (apiItem.kind === ApiItemKind.Namespace && !this.newDocfxNamespaces) { tocItem = { - name: this._getTocItemName(apiItem) + name: this._getTocItemName(apiItem), }; } else { if (this._shouldEmbed(apiItem.kind)) { @@ -297,7 +307,7 @@ export class YamlDocumenter { tocItem = { name: this._getTocItemName(apiItem), - uid: this._getUid(apiItem) + uid: this._getUid(apiItem), }; } @@ -360,7 +370,7 @@ export class YamlDocumenter { const uid: DeclarationReference = this._getUidObject(apiItem); const yamlItem: Partial = { - uid: uid.toString() + uid: uid.toString(), }; if (apiItem.tsdocComment) { @@ -393,15 +403,21 @@ export class YamlDocumenter { } } - yamlItem.name = this._getYamlItemName(apiItem, { includeSignature: true, - includeNamespace: !this.newDocfxNamespaces }); + yamlItem.name = this._getYamlItemName(apiItem, { + includeSignature: true, + includeNamespace: !this.newDocfxNamespaces, + }); yamlItem.fullName = this._getYamlItemName(apiItem, { includeSignature: true, includeNamespace: true }); - yamlItem.langs = [ 'typeScript' ]; + yamlItem.langs = ['typeScript']; // Add the namespace of the item if it is contained in one. // Do not add the namespace parent of a namespace as they are flattened in the documentation. - if (apiItem.kind !== ApiItemKind.Namespace && apiItem.parent && apiItem.parent.kind === ApiItemKind.Namespace && - this.newDocfxNamespaces) { + if ( + apiItem.kind !== ApiItemKind.Namespace && + apiItem.parent && + apiItem.parent.kind === ApiItemKind.Namespace && + this.newDocfxNamespaces + ) { yamlItem.namespace = apiItem.parent.canonicalReference.toString(); } @@ -484,21 +500,25 @@ export class YamlDocumenter { return yamlItem as IYamlItem; } - private _populateYamlTypeParameters(contextUid: DeclarationReference, apiItem: ApiTypeParameterListMixin): - IYamlParameter[] { - + private _populateYamlTypeParameters( + contextUid: DeclarationReference, + apiItem: ApiTypeParameterListMixin + ): IYamlParameter[] { const typeParameters: IYamlParameter[] = []; for (const apiTypeParameter of apiItem.typeParameters) { const typeParameter: IYamlParameter = { - id: apiTypeParameter.name + id: apiTypeParameter.name, }; if (apiTypeParameter.tsdocTypeParamBlock) { - typeParameter.description = this._renderMarkdown(apiTypeParameter.tsdocTypeParamBlock.content, apiItem); + 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); @@ -506,12 +526,14 @@ export class YamlDocumenter { return typeParameters; } - private _populateYamlClassOrInterface(uid: DeclarationReference, yamlItem: Partial, apiItem: ApiClass | - ApiInterface): void { - + private _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.extends = [this._renderType(uid, apiItem.extendsType.excerpt)]; yamlItem.inheritance = this._renderInheritance(uid, [apiItem.extendsType]); } if (apiItem.implementsTypes.length > 0) { @@ -552,11 +574,13 @@ export class YamlDocumenter { } } - private _populateYamlFunctionLike(uid: DeclarationReference, yamlItem: Partial, apiItem: ApiMethod | - ApiMethodSignature | ApiConstructor | ApiFunction): void { - + private _populateYamlFunctionLike( + uid: DeclarationReference, + yamlItem: Partial, + apiItem: ApiMethod | ApiMethodSignature | ApiConstructor | ApiFunction + ): void { const syntax: IYamlSyntax = { - content: apiItem.getExcerptWithModifiers() + content: apiItem.getExcerptWithModifiers(), }; yamlItem.syntax = syntax; @@ -573,8 +597,8 @@ export class YamlDocumenter { if (returnType || returnDescription) { syntax.return = { - type: [ returnType ], - description: returnDescription + type: [returnType], + description: returnDescription, }; } } @@ -586,13 +610,11 @@ export class YamlDocumenter { parameterDescription = this._renderMarkdown(apiParameter.tsdocParamBlock.content, apiItem); } - parameters.push( - { - id: apiParameter.name, - description: parameterDescription, - type: [ this._renderType(uid, apiParameter.parameterTypeExcerpt) ] - } as IYamlParameter - ); + parameters.push({ + id: apiParameter.name, + description: parameterDescription, + type: [this._renderType(uid, apiParameter.parameterTypeExcerpt)], + } as IYamlParameter); } if (parameters.length) { @@ -605,44 +627,49 @@ export class YamlDocumenter { syntax.typeParameters = typeParameters; } } - } - private _populateYamlProperty(uid: DeclarationReference, yamlItem: Partial, apiItem: ApiPropertyItem): - void { - + private _populateYamlProperty( + uid: DeclarationReference, + yamlItem: Partial, + apiItem: ApiPropertyItem + ): void { const syntax: IYamlSyntax = { - content: apiItem.getExcerptWithModifiers() + content: apiItem.getExcerptWithModifiers(), }; yamlItem.syntax = syntax; if (apiItem.propertyTypeExcerpt.text) { syntax.return = { - type: [ this._renderType(uid, apiItem.propertyTypeExcerpt) ] + type: [this._renderType(uid, apiItem.propertyTypeExcerpt)], }; } } - private _populateYamlVariable(uid: DeclarationReference, yamlItem: Partial, apiItem: ApiVariable): - void { - + private _populateYamlVariable( + uid: DeclarationReference, + yamlItem: Partial, + apiItem: ApiVariable + ): void { const syntax: IYamlSyntax = { - content: apiItem.getExcerptWithModifiers() + content: apiItem.getExcerptWithModifiers(), }; yamlItem.syntax = syntax; if (apiItem.variableTypeExcerpt.text) { syntax.return = { - type: [ this._renderType(uid, apiItem.variableTypeExcerpt) ] + type: [this._renderType(uid, apiItem.variableTypeExcerpt)], }; } } - private _populateYamlTypeAlias(uid: DeclarationReference, yamlItem: Partial, apiItem: ApiTypeAlias): - void { - + private _populateYamlTypeAlias( + uid: DeclarationReference, + yamlItem: Partial, + apiItem: ApiTypeAlias + ): void { const syntax: IYamlSyntax = { - content: apiItem.getExcerptWithModifiers() + content: apiItem.getExcerptWithModifiers(), }; yamlItem.syntax = syntax; @@ -653,7 +680,7 @@ export class YamlDocumenter { if (apiItem.typeExcerpt.text) { syntax.return = { - type: [ this._renderType(uid, apiItem.typeExcerpt) ] + type: [this._renderType(uid, apiItem.typeExcerpt)], }; } } @@ -674,21 +701,24 @@ export class YamlDocumenter { // markdown spec insists that they are only valid when balanced. To reduce // the overhead we only support balanced parenthesis with a depth of 1. return encodeURI(`xref:${this._getUid(apiItem)}`) - .replace(/[#?]/g, s => encodeURIComponent(s)) - .replace(/(\([^(]*\))|[()]/g, (s, balanced) => balanced || ('\\' + s)); - } + .replace(/[#?]/g, (s) => encodeURIComponent(s)) + .replace(/(\([^(]*\))|[()]/g, (s, balanced) => balanced || '\\' + s); + }, }); return stringBuilder.toString().trim(); } - private _writeYamlFile(dataObject: {}, filePath: string, yamlMimeType: string, - schema: JsonSchema|undefined): void { - + private _writeYamlFile( + dataObject: {}, + filePath: string, + yamlMimeType: string, + schema: JsonSchema | undefined + ): void { JsonFile.validateNoUndefinedMembers(dataObject); let stringified: string = yaml.safeDump(dataObject, { - lineWidth: 120 + lineWidth: 120, }); if (yamlMimeType) { @@ -697,7 +727,7 @@ export class YamlDocumenter { FileSystem.writeFile(filePath, stringified, { convertLineEndings: NewlineKind.CrLf, - ensureFolderExists: true + ensureFolderExists: true, }); if (schema) { @@ -745,15 +775,16 @@ export class YamlDocumenter { this._yamlReferences = { references: [], typeNameToUid: new Map(), - uidTypeReferenceCounters: new Map() + uidTypeReferenceCounters: new Map(), }; } return this._yamlReferences; } - private _renderInheritance(contextUid: DeclarationReference, heritageTypes: ReadonlyArray): - IYamlInheritanceTree[] { - + private _renderInheritance( + contextUid: DeclarationReference, + heritageTypes: ReadonlyArray + ): IYamlInheritanceTree[] { const result: IYamlInheritanceTree[] = []; for (const heritageType of heritageTypes) { const type: string = this._renderType(contextUid, heritageType.excerpt); @@ -762,11 +793,16 @@ export class YamlDocumenter { if (apiItem) { if (apiItem instanceof ApiClass) { if (apiItem.extendsType) { - yamlInheritance.inheritance = this._renderInheritance(this._getUidObject(apiItem), [apiItem.extendsType]); + yamlInheritance.inheritance = this._renderInheritance(this._getUidObject(apiItem), [ + apiItem.extendsType, + ]); } } else if (apiItem instanceof ApiInterface) { if (apiItem.extendsTypes.length > 0) { - yamlInheritance.inheritance = this._renderInheritance(this._getUidObject(apiItem), apiItem.extendsTypes); + yamlInheritance.inheritance = this._renderInheritance( + this._getUidObject(apiItem), + apiItem.extendsTypes + ); } } } @@ -794,7 +830,7 @@ export class YamlDocumenter { const typeName: string = typeExcerpt.text.trim(); // If there are no references to be used for a complex type, return the type name. - if (!excerptTokens.some(tok => tok.kind === ExcerptTokenKind.Reference && !!tok.canonicalReference)) { + if (!excerptTokens.some((tok) => tok.kind === ExcerptTokenKind.Reference && !!tok.canonicalReference)) { return typeName; } @@ -807,9 +843,11 @@ export class YamlDocumenter { } // If the excerpt consists of a single reference token, record the reference. - if (excerptTokens.length === 1 && + if ( + excerptTokens.length === 1 && excerptTokens[0].kind === ExcerptTokenKind.Reference && - excerptTokens[0].canonicalReference) { + excerptTokens[0].canonicalReference + ) { const excerptRef: string = excerptTokens[0].canonicalReference.toString(); const apiItem: ApiItem | undefined = this._apiItemsByCanonicalReference.get(excerptRef); return this._recordYamlReference( @@ -822,10 +860,7 @@ export class YamlDocumenter { // Otherwise, the type is complex and consists of one or more reference tokens. Record a reference // and return its uid. - const baseUid: string = contextUid - .withMeaning(undefined) - .withOverloadIndex(undefined) - .toString(); + const baseUid: string = contextUid.withMeaning(undefined).withOverloadIndex(undefined).toString(); // Keep track of the count for the base uid (without meaning or overload index) to ensure // that each complex type reference is unique. @@ -841,10 +876,14 @@ export class YamlDocumenter { return this._recordYamlReference(yamlReferences, uid, typeName, typeName, excerptTokens); } - private _recordYamlReference(yamlReferences: IYamlReferences, uid: string, name: string, fullName: string, - excerptTokens?: ExcerptToken[]): string { - - if (yamlReferences.references.some(ref => ref.uid === uid)) { + private _recordYamlReference( + yamlReferences: IYamlReferences, + uid: string, + name: string, + fullName: string, + excerptTokens?: ExcerptToken[] + ): string { + if (yamlReferences.references.some((ref) => ref.uid === uid)) { return uid; } @@ -853,37 +892,44 @@ export class YamlDocumenter { if (excerptTokens) { for (const token of excerptTokens) { if (token.kind === ExcerptTokenKind.Reference) { - const spec: IYamlReferenceSpec = { }; + const spec: IYamlReferenceSpec = {}; const specUid: string | undefined = token.canonicalReference && token.canonicalReference.toString(); - const apiItem: ApiItem | undefined = specUid ? this._apiItemsByCanonicalReference.get(specUid) : undefined; + const apiItem: ApiItem | undefined = specUid + ? this._apiItemsByCanonicalReference.get(specUid) + : undefined; if (specUid) { spec.uid = specUid; } spec.name = token.text; - spec.fullName = - apiItem ? apiItem.getScopedNameWithinPackage() : - token.canonicalReference ? token.canonicalReference - .withSource(undefined) - .withMeaning(undefined) - .withOverloadIndex(undefined) - .toString() : - token.text; + spec.fullName = apiItem + ? apiItem.getScopedNameWithinPackage() + : token.canonicalReference + ? token.canonicalReference + .withSource(undefined) + .withMeaning(undefined) + .withOverloadIndex(undefined) + .toString() + : token.text; specs.push(spec); } else { - specs.push( - { - name: token.text, - fullName: token.text - } - ); + specs.push({ + name: token.text, + fullName: token.text, + }); } } } const yamlReference: IYamlReference = { uid }; if (specs.length > 0) { - yamlReference.name = specs.map(s => s.name).join('').trim(); - yamlReference.fullName = specs.map(s => s.fullName || s.name).join('').trim(); + yamlReference.name = specs + .map((s) => s.name) + .join('') + .trim(); + yamlReference.fullName = specs + .map((s) => s.fullName || s.name) + .join('') + .trim(); yamlReference['spec.typeScript'] = specs; } else { if (name !== uid) { @@ -901,8 +947,11 @@ export class YamlDocumenter { private _getYamlItemName(apiItem: ApiItem, options: INameOptions = {}): string { const { includeSignature, includeNamespace } = options; const baseName: string = includeSignature ? Utilities.getConciseSignature(apiItem) : apiItem.displayName; - if ((includeNamespace || apiItem.kind === ApiItemKind.Namespace) && apiItem.parent && - apiItem.parent.kind === ApiItemKind.Namespace) { + if ( + (includeNamespace || apiItem.kind === ApiItemKind.Namespace) && + apiItem.parent && + apiItem.parent.kind === ApiItemKind.Namespace + ) { // If the immediate parent is a namespace, then add the namespaces to the name. For example: // // // Name: "N1" @@ -929,7 +978,7 @@ export class YamlDocumenter { // embeds this entry in the web page for "N1.N2.C", so the container is obvious. Whereas "N1.N2.f(x,y)" // needs to be qualified because the DocFX template doesn't make pages for namespaces. Instead, they get // flattened into the package's page. - const nameParts: string[] = [ baseName ]; + const nameParts: string[] = [baseName]; for (let current: ApiItem | undefined = apiItem.parent; current; current = current.parent) { if (current.kind !== ApiItemKind.Namespace) { diff --git a/apps/api-documenter/src/index.ts b/apps/api-documenter/src/index.ts index 514ff7a7994..c401c4ee6b9 100644 --- a/apps/api-documenter/src/index.ts +++ b/apps/api-documenter/src/index.ts @@ -9,19 +9,12 @@ * @packageDocumentation */ -export { - IFeatureDefinition, - IApiDocumenterPluginManifest -} from './plugin/IApiDocumenterPluginManifest'; +export { IFeatureDefinition, IApiDocumenterPluginManifest } from './plugin/IApiDocumenterPluginManifest'; export { MarkdownDocumenterAccessor } from './plugin/MarkdownDocumenterAccessor'; export { MarkdownDocumenterFeatureContext, IMarkdownDocumenterFeatureOnBeforeWritePageArgs, IMarkdownDocumenterFeatureOnFinishedArgs, - MarkdownDocumenterFeature + MarkdownDocumenterFeature, } from './plugin/MarkdownDocumenterFeature'; -export { - PluginFeature, - PluginFeatureContext, - PluginFeatureInitialization -} from './plugin/PluginFeature'; +export { PluginFeature, PluginFeatureContext, PluginFeatureInitialization } from './plugin/PluginFeature'; diff --git a/apps/api-documenter/src/markdown/CustomMarkdownEmitter.ts b/apps/api-documenter/src/markdown/CustomMarkdownEmitter.ts index 005075b50ea..d843ad1809e 100644 --- a/apps/api-documenter/src/markdown/CustomMarkdownEmitter.ts +++ b/apps/api-documenter/src/markdown/CustomMarkdownEmitter.ts @@ -3,14 +3,8 @@ import * as colors from 'colors'; -import { - DocNode, DocLinkTag, StringBuilder -} from '@microsoft/tsdoc'; -import { - ApiModel, - IResolveDeclarationReferenceResult, - ApiItem -} from '@microsoft/api-extractor-model'; +import { DocNode, DocLinkTag, StringBuilder } from '@microsoft/tsdoc'; +import { ApiModel, IResolveDeclarationReferenceResult, ApiItem } from '@microsoft/api-extractor-model'; import { CustomDocNodeKind } from '../nodes/CustomDocNodeKind'; import { DocHeading } from '../nodes/DocHeading'; @@ -18,11 +12,7 @@ import { DocNoteBox } from '../nodes/DocNoteBox'; import { DocTable } from '../nodes/DocTable'; import { DocTableCell } from '../nodes/DocTableCell'; import { DocEmphasisSpan } from '../nodes/DocEmphasisSpan'; -import { - MarkdownEmitter, - IMarkdownEmitterContext, - IMarkdownEmitterOptions -} from './MarkdownEmitter'; +import { MarkdownEmitter, IMarkdownEmitterContext, IMarkdownEmitterOptions } from './MarkdownEmitter'; import { IndentedWriter } from '../utils/IndentedWriter'; export interface ICustomMarkdownEmitterOptions extends IMarkdownEmitterOptions { @@ -34,13 +24,17 @@ export interface ICustomMarkdownEmitterOptions extends IMarkdownEmitterOptions { export class CustomMarkdownEmitter extends MarkdownEmitter { private _apiModel: ApiModel; - public constructor (apiModel: ApiModel) { + public constructor(apiModel: ApiModel) { super(); this._apiModel = apiModel; } - public emit(stringBuilder: StringBuilder, docNode: DocNode, options: ICustomMarkdownEmitterOptions): string { + public emit( + stringBuilder: StringBuilder, + docNode: DocNode, + options: ICustomMarkdownEmitterOptions + ): string { return super.emit(stringBuilder, docNode, options); } @@ -55,9 +49,15 @@ export class CustomMarkdownEmitter extends MarkdownEmitter { let prefix: string; switch (docHeading.level) { - case 1: prefix = '##'; break; - case 2: prefix = '###'; break; - case 3: prefix = '###'; break; + case 1: + prefix = '##'; + break; + case 2: + prefix = '###'; + break; + case 3: + prefix = '###'; + break; default: prefix = '####'; } @@ -152,13 +152,16 @@ export class CustomMarkdownEmitter extends MarkdownEmitter { } /** @override */ - protected writeLinkTagWithCodeDestination(docLinkTag: DocLinkTag, - context: IMarkdownEmitterContext): void { - + protected writeLinkTagWithCodeDestination( + docLinkTag: DocLinkTag, + context: IMarkdownEmitterContext + ): void { const options: ICustomMarkdownEmitterOptions = context.options; - const result: IResolveDeclarationReferenceResult - = this._apiModel.resolveDeclarationReference(docLinkTag.codeDestination!, options.contextApiItem); + const result: IResolveDeclarationReferenceResult = this._apiModel.resolveDeclarationReference( + docLinkTag.codeDestination!, + options.contextApiItem + ); if (result.resolvedApiItem) { const filename: string | undefined = options.onGetFilenameForApiItem(result.resolvedApiItem); @@ -166,7 +169,6 @@ export class CustomMarkdownEmitter extends MarkdownEmitter { if (filename) { let linkText: string = docLinkTag.linkText || ''; if (linkText.length === 0) { - // Generate a name such as Namespace1.Namespace2.MyClass.myMethod() linkText = result.resolvedApiItem.getScopedNameWithinPackage(); } @@ -181,9 +183,12 @@ export class CustomMarkdownEmitter extends MarkdownEmitter { } } } else if (result.errorMessage) { - console.log(colors.yellow(`WARNING: Unable to resolve reference "${docLinkTag.codeDestination!.emitAsTsdoc()}": ` - + result.errorMessage)); + console.log( + colors.yellow( + `WARNING: Unable to resolve reference "${docLinkTag.codeDestination!.emitAsTsdoc()}": ` + + result.errorMessage + ) + ); } } - } diff --git a/apps/api-documenter/src/markdown/MarkdownEmitter.ts b/apps/api-documenter/src/markdown/MarkdownEmitter.ts index 33cb36cf1c4..5a9f3589daa 100644 --- a/apps/api-documenter/src/markdown/MarkdownEmitter.ts +++ b/apps/api-documenter/src/markdown/MarkdownEmitter.ts @@ -16,14 +16,13 @@ import { DocNodeTransforms, DocEscapedText, DocErrorText, - DocBlockTag + DocBlockTag, } from '@microsoft/tsdoc'; import { InternalError } from '@rushstack/node-core-library'; import { IndentedWriter } from '../utils/IndentedWriter'; -export interface IMarkdownEmitterOptions { -} +export interface IMarkdownEmitterOptions {} export interface IMarkdownEmitterContext { writer: IndentedWriter; @@ -43,7 +42,6 @@ export interface IMarkdownEmitterContext { * For more info: https://en.wikipedia.org/wiki/Markdown */ export class MarkdownEmitter { - public emit(stringBuilder: StringBuilder, docNode: DocNode, options: IMarkdownEmitterOptions): string { const writer: IndentedWriter = new IndentedWriter(stringBuilder); @@ -57,7 +55,7 @@ export class MarkdownEmitter { writingBold: false, writingItalic: false, - options + options, }; this.writeNode(docNode, context, false); @@ -69,7 +67,7 @@ export class MarkdownEmitter { protected getEscapedText(text: string): string { const textWithBackslashes: string = text - .replace(/\\/g, '\\\\') // first replace the escape character + .replace(/\\/g, '\\\\') // first replace the escape character .replace(/[*#[\]_|`~]/g, (x) => '\\' + x) // then escape any special characters .replace(/---/g, '\\-\\-\\-') // hyphens only if it's 3 or more .replace(/&/g, '&') @@ -204,15 +202,14 @@ export class MarkdownEmitter { /** @virtual */ protected writeLinkTagWithCodeDestination(docLinkTag: DocLinkTag, context: IMarkdownEmitterContext): void { - // The subclass needs to implement this to support code destinations throw new InternalError('writeLinkTagWithCodeDestination()'); } /** @virtual */ protected writeLinkTagWithUrlDestination(docLinkTag: DocLinkTag, context: IMarkdownEmitterContext): void { - const linkText: string = docLinkTag.linkText !== undefined ? docLinkTag.linkText - : docLinkTag.urlDestination!; + const linkText: string = + docLinkTag.linkText !== undefined ? docLinkTag.linkText : docLinkTag.urlDestination!; const encodedLinkText: string = this.getEscapedText(linkText.replace(/\s+/g, ' ')); @@ -227,7 +224,7 @@ export class MarkdownEmitter { // split out the [ leading whitespace, content, trailing whitespace ] const parts: string[] = text.match(/^(\s*)(.*?)(\s*)$/) || []; - writer.write(parts[1]); // write leading whitespace + writer.write(parts[1]); // write leading whitespace const middle: string = parts[2]; @@ -265,7 +262,7 @@ export class MarkdownEmitter { } } - writer.write(parts[3]); // write trailing whitespace + writer.write(parts[3]); // write trailing whitespace } protected writeNodes(docNodes: ReadonlyArray, context: IMarkdownEmitterContext): void { diff --git a/apps/api-documenter/src/markdown/test/CustomMarkdownEmitter.test.ts b/apps/api-documenter/src/markdown/test/CustomMarkdownEmitter.test.ts index a0dfe7d5a1c..6a34423fdc3 100644 --- a/apps/api-documenter/src/markdown/test/CustomMarkdownEmitter.test.ts +++ b/apps/api-documenter/src/markdown/test/CustomMarkdownEmitter.test.ts @@ -11,7 +11,7 @@ import { DocLinkTag, DocHtmlStartTag, DocHtmlEndTag, - DocBlockTag + DocBlockTag, } from '@microsoft/tsdoc'; import { CustomDocNodes } from '../../nodes/CustomDocNodeKind'; @@ -30,185 +30,140 @@ test('render Markdown from TSDoc', () => { output.appendNodes([ new DocHeading({ configuration, title: 'Simple bold test' }), - new DocParagraph({ configuration }, - [ - new DocPlainText({ configuration, text: 'This is a ' }), - new DocEmphasisSpan({ configuration, bold: true }, - [ - new DocPlainText({ configuration, text: 'bold' }) - ] - ), - new DocPlainText({ configuration, text: ' word.' }) - ] - ) + new DocParagraph({ configuration }, [ + new DocPlainText({ configuration, text: 'This is a ' }), + new DocEmphasisSpan({ configuration, bold: true }, [new DocPlainText({ configuration, text: 'bold' })]), + new DocPlainText({ configuration, text: ' word.' }), + ]), ]); output.appendNodes([ new DocHeading({ configuration, title: 'All whitespace bold' }), - new DocParagraph({ configuration }, - [ - new DocEmphasisSpan({ configuration, bold: true }, - [ - new DocPlainText({ configuration, text: ' ' }) - ] - ) - ] - ) + new DocParagraph({ configuration }, [ + new DocEmphasisSpan({ configuration, bold: true }, [new DocPlainText({ configuration, text: ' ' })]), + ]), ]); output.appendNodes([ new DocHeading({ configuration, title: 'Newline bold' }), - new DocParagraph({ configuration }, - [ - new DocEmphasisSpan({ configuration, bold: true }, - [ - new DocPlainText({ configuration, text: 'line 1' }), - new DocSoftBreak({ configuration }), - new DocPlainText({ configuration, text: 'line 2' }) - ] - ) - ] - ) + new DocParagraph({ configuration }, [ + new DocEmphasisSpan({ configuration, bold: true }, [ + new DocPlainText({ configuration, text: 'line 1' }), + new DocSoftBreak({ configuration }), + new DocPlainText({ configuration, text: 'line 2' }), + ]), + ]), ]); output.appendNodes([ new DocHeading({ configuration, title: 'Newline bold with spaces' }), - new DocParagraph({ configuration }, - [ - new DocEmphasisSpan({ configuration, bold: true }, - [ - new DocPlainText({ configuration, text: ' line 1 ' }), - new DocSoftBreak({ configuration }), - new DocPlainText({ configuration, text: ' line 2 ' }), - new DocSoftBreak({ configuration }), - new DocPlainText({ configuration, text: ' line 3 ' }) - ] - ) - ] - ) + new DocParagraph({ configuration }, [ + new DocEmphasisSpan({ configuration, bold: true }, [ + new DocPlainText({ configuration, text: ' line 1 ' }), + new DocSoftBreak({ configuration }), + new DocPlainText({ configuration, text: ' line 2 ' }), + new DocSoftBreak({ configuration }), + new DocPlainText({ configuration, text: ' line 3 ' }), + ]), + ]), ]); output.appendNodes([ new DocHeading({ configuration, title: 'Adjacent bold regions' }), - new DocParagraph({ configuration }, - [ - new DocEmphasisSpan({ configuration, bold: true }, - [ new DocPlainText({ configuration, text: 'one' }) ] - ), - new DocEmphasisSpan({ configuration, bold: true }, - [ new DocPlainText({ configuration, text: 'two' }) ] - ), - new DocEmphasisSpan({ configuration, bold: true }, - [ new DocPlainText({ configuration, text: ' three ' }) ] - ), - new DocPlainText({ configuration, text: '' }), - new DocEmphasisSpan({ configuration, bold: true }, - [ new DocPlainText({ configuration, text: 'four' }) ] - ), - new DocPlainText({ configuration, text: 'non-bold' }), - new DocEmphasisSpan({ configuration, bold: true }, - [ new DocPlainText({ configuration, text: 'five' }) ] - ) - ] - ) + new DocParagraph({ configuration }, [ + new DocEmphasisSpan({ configuration, bold: true }, [new DocPlainText({ configuration, text: 'one' })]), + new DocEmphasisSpan({ configuration, bold: true }, [new DocPlainText({ configuration, text: 'two' })]), + new DocEmphasisSpan({ configuration, bold: true }, [ + new DocPlainText({ configuration, text: ' three ' }), + ]), + new DocPlainText({ configuration, text: '' }), + new DocEmphasisSpan({ configuration, bold: true }, [new DocPlainText({ configuration, text: 'four' })]), + new DocPlainText({ configuration, text: 'non-bold' }), + new DocEmphasisSpan({ configuration, bold: true }, [new DocPlainText({ configuration, text: 'five' })]), + ]), ]); output.appendNodes([ new DocHeading({ configuration, title: 'Adjacent to other characters' }), - new DocParagraph({ configuration }, - [ - new DocLinkTag({ - configuration, - tagName: '@link', - linkText: 'a link', - urlDestination: './index.md' - }), - new DocEmphasisSpan({ configuration, bold: true }, - [ new DocPlainText({ configuration, text: 'bold' }) ] - ), - new DocPlainText({ configuration, text: 'non-bold' }), - new DocPlainText({ configuration, text: 'more-non-bold' }) - ] - ) + new DocParagraph({ configuration }, [ + new DocLinkTag({ + configuration, + tagName: '@link', + linkText: 'a link', + urlDestination: './index.md', + }), + new DocEmphasisSpan({ configuration, bold: true }, [new DocPlainText({ configuration, text: 'bold' })]), + new DocPlainText({ configuration, text: 'non-bold' }), + new DocPlainText({ configuration, text: 'more-non-bold' }), + ]), ]); output.appendNodes([ new DocHeading({ configuration, title: 'Unknown block tag' }), - new DocParagraph({ configuration }, - [ - new DocBlockTag({ - configuration, - tagName: '@unknown' - }), - new DocEmphasisSpan({ configuration, bold: true }, - [ new DocPlainText({ configuration, text: 'bold' }) ] - ), - new DocPlainText({ configuration, text: 'non-bold' }), - new DocPlainText({ configuration, text: 'more-non-bold' }) - ] - ) + new DocParagraph({ configuration }, [ + new DocBlockTag({ + configuration, + tagName: '@unknown', + }), + new DocEmphasisSpan({ configuration, bold: true }, [new DocPlainText({ configuration, text: 'bold' })]), + new DocPlainText({ configuration, text: 'non-bold' }), + new DocPlainText({ configuration, text: 'more-non-bold' }), + ]), ]); output.appendNodes([ new DocHeading({ configuration, title: 'Bad characters' }), - new DocParagraph({ configuration }, - [ - new DocEmphasisSpan({ configuration, bold: true }, - [ new DocPlainText({ configuration, text: '*one*two*' }) ] - ), - new DocEmphasisSpan({ configuration, bold: true }, - [ new DocPlainText({ configuration, text: 'three*four' }) ] - ) - ] - ) + new DocParagraph({ configuration }, [ + new DocEmphasisSpan({ configuration, bold: true }, [ + new DocPlainText({ configuration, text: '*one*two*' }), + ]), + new DocEmphasisSpan({ configuration, bold: true }, [ + new DocPlainText({ configuration, text: 'three*four' }), + ]), + ]), ]); output.appendNodes([ new DocHeading({ configuration, title: 'Characters that should be escaped' }), new DocParagraph({ configuration }, [ - new DocPlainText({ configuration, text: 'Double-encoded JSON: "{ \\"A\\": 123}"' }) + new DocPlainText({ configuration, text: 'Double-encoded JSON: "{ \\"A\\": 123}"' }), + ]), + new DocParagraph({ configuration }, [ + new DocPlainText({ configuration, text: 'HTML chars: ' }), + ]), + new DocParagraph({ configuration }, [new DocPlainText({ configuration, text: 'HTML escape: "' })]), + new DocParagraph({ configuration }, [ + new DocPlainText({ configuration, text: '3 or more hyphens: - -- --- ---- ----- ------' }), ]), - new DocParagraph({ configuration }, - [ new DocPlainText({ configuration, text: 'HTML chars: ' }) ] - ), - new DocParagraph({ configuration }, - [ new DocPlainText({ configuration, text: 'HTML escape: "' }) ] - ), - new DocParagraph({ configuration }, - [ new DocPlainText({ configuration, text: '3 or more hyphens: - -- --- ---- ----- ------' }) ] - ) ]); output.appendNodes([ new DocHeading({ configuration, title: 'HTML tag' }), - new DocParagraph({ configuration }, - [ - new DocHtmlStartTag({ configuration, name: 'b' }), - new DocPlainText({ configuration, text: 'bold' }), - new DocHtmlEndTag({ configuration, name: 'b' }) - ] - ) + new DocParagraph({ configuration }, [ + new DocHtmlStartTag({ configuration, name: 'b' }), + new DocPlainText({ configuration, text: 'bold' }), + new DocHtmlEndTag({ configuration, name: 'b' }), + ]), ]); output.appendNodes([ new DocHeading({ configuration, title: 'Table' }), - new DocTable({ + new DocTable( + { configuration, - headerTitles: [ 'Header 1', 'Header 2' ] - }, [ - new DocTableRow({ configuration }, [ - new DocTableCell({ configuration }, [ - new DocParagraph({ configuration }, - [ new DocPlainText({ configuration, text: 'Cell 1' }) ] - ) + headerTitles: ['Header 1', 'Header 2'], + }, + [ + new DocTableRow({ configuration }, [ + new DocTableCell({ configuration }, [ + new DocParagraph({ configuration }, [new DocPlainText({ configuration, text: 'Cell 1' })]), + ]), + new DocTableCell({ configuration }, [ + new DocParagraph({ configuration }, [new DocPlainText({ configuration, text: 'Cell 2' })]), + ]), ]), - new DocTableCell({ configuration }, [ - new DocParagraph({ configuration }, - [ new DocPlainText({ configuration, text: 'Cell 2' }) ] - ) - ]) - ]) - ]) + ] + ), ]); const stringBuilder: StringBuilder = new StringBuilder(); @@ -218,7 +173,7 @@ test('render Markdown from TSDoc', () => { contextApiItem: undefined, onGetFilenameForApiItem: (apiItem: ApiItem) => { return '#'; - } + }, }); expect(stringBuilder).toMatchSnapshot(); diff --git a/apps/api-documenter/src/nodes/CustomDocNodeKind.ts b/apps/api-documenter/src/nodes/CustomDocNodeKind.ts index 94bb644ac6a..5bdcfd47868 100644 --- a/apps/api-documenter/src/nodes/CustomDocNodeKind.ts +++ b/apps/api-documenter/src/nodes/CustomDocNodeKind.ts @@ -13,12 +13,12 @@ import { DocTableRow } from './DocTableRow'; * Identifies custom subclasses of {@link DocNode}. */ export const enum CustomDocNodeKind { - EmphasisSpan = 'EmphasisSpan', - Heading = 'Heading', - NoteBox = 'NoteBox', - Table = 'Table', - TableCell = 'TableCell', - TableRow = 'TableRow' + EmphasisSpan = 'EmphasisSpan', + Heading = 'Heading', + NoteBox = 'NoteBox', + Table = 'Table', + TableCell = 'TableCell', + TableRow = 'TableRow', } export class CustomDocNodes { @@ -34,22 +34,22 @@ export class CustomDocNodes { { docNodeKind: CustomDocNodeKind.NoteBox, constructor: DocNoteBox }, { docNodeKind: CustomDocNodeKind.Table, constructor: DocTable }, { docNodeKind: CustomDocNodeKind.TableCell, constructor: DocTableCell }, - { docNodeKind: CustomDocNodeKind.TableRow, constructor: DocTableRow } + { docNodeKind: CustomDocNodeKind.TableRow, constructor: DocTableRow }, ]); configuration.docNodeManager.registerAllowableChildren(CustomDocNodeKind.EmphasisSpan, [ DocNodeKind.PlainText, - DocNodeKind.SoftBreak + DocNodeKind.SoftBreak, ]); configuration.docNodeManager.registerAllowableChildren(DocNodeKind.Section, [ CustomDocNodeKind.Heading, CustomDocNodeKind.NoteBox, - CustomDocNodeKind.Table + CustomDocNodeKind.Table, ]); configuration.docNodeManager.registerAllowableChildren(DocNodeKind.Paragraph, [ - CustomDocNodeKind.EmphasisSpan + CustomDocNodeKind.EmphasisSpan, ]); CustomDocNodes._configuration = configuration; diff --git a/apps/api-documenter/src/nodes/DocEmphasisSpan.ts b/apps/api-documenter/src/nodes/DocEmphasisSpan.ts index 986d5029a41..0f1f543b877 100644 --- a/apps/api-documenter/src/nodes/DocEmphasisSpan.ts +++ b/apps/api-documenter/src/nodes/DocEmphasisSpan.ts @@ -1,11 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - DocNode, - DocNodeContainer, - IDocNodeContainerParameters -} from '@microsoft/tsdoc'; +import { DocNode, DocNodeContainer, IDocNodeContainerParameters } from '@microsoft/tsdoc'; import { CustomDocNodeKind } from './CustomDocNodeKind'; /** diff --git a/apps/api-documenter/src/nodes/DocHeading.ts b/apps/api-documenter/src/nodes/DocHeading.ts index 7109dbfb409..d5d48227667 100644 --- a/apps/api-documenter/src/nodes/DocHeading.ts +++ b/apps/api-documenter/src/nodes/DocHeading.ts @@ -1,10 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - IDocNodeParameters, - DocNode -} from '@microsoft/tsdoc'; +import { IDocNodeParameters, DocNode } from '@microsoft/tsdoc'; import { CustomDocNodeKind } from './CustomDocNodeKind'; /** diff --git a/apps/api-documenter/src/nodes/DocNoteBox.ts b/apps/api-documenter/src/nodes/DocNoteBox.ts index 302112d45f3..85372fb5a29 100644 --- a/apps/api-documenter/src/nodes/DocNoteBox.ts +++ b/apps/api-documenter/src/nodes/DocNoteBox.ts @@ -1,18 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - IDocNodeParameters, - DocNode, - DocSection -} from '@microsoft/tsdoc'; +import { IDocNodeParameters, DocNode, DocSection } from '@microsoft/tsdoc'; import { CustomDocNodeKind } from './CustomDocNodeKind'; /** * Constructor parameters for {@link DocNoteBox}. */ -export interface IDocNoteBoxParameters extends IDocNodeParameters { -} +export interface IDocNoteBoxParameters extends IDocNodeParameters {} /** * Represents a note box, which is typically displayed as a bordered box containing informational text. diff --git a/apps/api-documenter/src/nodes/DocTable.ts b/apps/api-documenter/src/nodes/DocTable.ts index 0d74003c59d..095e39e3b1f 100644 --- a/apps/api-documenter/src/nodes/DocTable.ts +++ b/apps/api-documenter/src/nodes/DocTable.ts @@ -1,10 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - IDocNodeParameters, - DocNode -} from '@microsoft/tsdoc'; +import { IDocNodeParameters, DocNode } from '@microsoft/tsdoc'; import { CustomDocNodeKind } from './CustomDocNodeKind'; import { DocTableRow } from './DocTableRow'; import { DocTableCell } from './DocTableCell'; @@ -34,8 +31,10 @@ export class DocTable extends DocNode { if (parameters) { if (parameters.headerTitles) { if (parameters.headerCells) { - throw new Error('IDocTableParameters.headerCells and IDocTableParameters.headerTitles' - + ' cannot both be specified'); + throw new Error( + 'IDocTableParameters.headerCells and IDocTableParameters.headerTitles' + + ' cannot both be specified' + ); } for (const cellText of parameters.headerTitles) { this.header.addPlainTextCell(cellText); diff --git a/apps/api-documenter/src/nodes/DocTableCell.ts b/apps/api-documenter/src/nodes/DocTableCell.ts index 23b679d8c5f..8a56c13a836 100644 --- a/apps/api-documenter/src/nodes/DocTableCell.ts +++ b/apps/api-documenter/src/nodes/DocTableCell.ts @@ -1,18 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - IDocNodeParameters, - DocNode, - DocSection -} from '@microsoft/tsdoc'; +import { IDocNodeParameters, DocNode, DocSection } from '@microsoft/tsdoc'; import { CustomDocNodeKind } from './CustomDocNodeKind'; /** * Constructor parameters for {@link DocTableCell}. */ -export interface IDocTableCellParameters extends IDocNodeParameters { -} +export interface IDocTableCellParameters extends IDocNodeParameters {} /** * Represents table cell, similar to an HTML `` element. diff --git a/apps/api-documenter/src/nodes/DocTableRow.ts b/apps/api-documenter/src/nodes/DocTableRow.ts index 2391b01f14d..1f55994ab96 100644 --- a/apps/api-documenter/src/nodes/DocTableRow.ts +++ b/apps/api-documenter/src/nodes/DocTableRow.ts @@ -1,19 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - IDocNodeParameters, - DocNode, - DocPlainText -} from '@microsoft/tsdoc'; +import { IDocNodeParameters, DocNode, DocPlainText } from '@microsoft/tsdoc'; import { CustomDocNodeKind } from './CustomDocNodeKind'; import { DocTableCell } from './DocTableCell'; /** * Constructor parameters for {@link DocTableRow}. */ -export interface IDocTableRowParameters extends IDocNodeParameters { -} +export interface IDocTableRowParameters extends IDocNodeParameters {} /** * Represents table row, similar to an HTML `` element. @@ -53,10 +48,12 @@ export class DocTableRow extends DocNode { public addPlainTextCell(cellContent: string): DocTableCell { const cell: DocTableCell = this.createAndAddCell(); - cell.content.appendNodeInParagraph(new DocPlainText({ - configuration: this.configuration, - text: cellContent - })); + cell.content.appendNodeInParagraph( + new DocPlainText({ + configuration: this.configuration, + text: cellContent, + }) + ); return cell; } diff --git a/apps/api-documenter/src/plugin/IApiDocumenterPluginManifest.ts b/apps/api-documenter/src/plugin/IApiDocumenterPluginManifest.ts index 501f4f65a2f..1e047bff133 100644 --- a/apps/api-documenter/src/plugin/IApiDocumenterPluginManifest.ts +++ b/apps/api-documenter/src/plugin/IApiDocumenterPluginManifest.ts @@ -30,7 +30,7 @@ export interface IFeatureDefinition { /** * Your subclass that extends from the base class. */ - subclass: { new(initialization: PluginFeatureInitialization): MarkdownDocumenterFeature }; + subclass: { new (initialization: PluginFeatureInitialization): MarkdownDocumenterFeature }; } /** diff --git a/apps/api-documenter/src/plugin/MarkdownDocumenterAccessor.ts b/apps/api-documenter/src/plugin/MarkdownDocumenterAccessor.ts index d1f7062b568..41a57a8e6df 100644 --- a/apps/api-documenter/src/plugin/MarkdownDocumenterAccessor.ts +++ b/apps/api-documenter/src/plugin/MarkdownDocumenterAccessor.ts @@ -21,7 +21,7 @@ export class MarkdownDocumenterAccessor { private _implementation: IMarkdownDocumenterAccessorImplementation; /** @internal */ - public constructor (implementation: IMarkdownDocumenterAccessorImplementation) { + public constructor(implementation: IMarkdownDocumenterAccessorImplementation) { this._implementation = implementation; } diff --git a/apps/api-documenter/src/plugin/MarkdownDocumenterFeature.ts b/apps/api-documenter/src/plugin/MarkdownDocumenterFeature.ts index 28149c4e9dd..63ce2c7f570 100644 --- a/apps/api-documenter/src/plugin/MarkdownDocumenterFeature.ts +++ b/apps/api-documenter/src/plugin/MarkdownDocumenterFeature.ts @@ -61,8 +61,7 @@ export interface IMarkdownDocumenterFeatureOnBeforeWritePageArgs { * Event arguments for MarkdownDocumenterFeature.onFinished() * @public */ -export interface IMarkdownDocumenterFeatureOnFinishedArgs { -} +export interface IMarkdownDocumenterFeatureOnFinishedArgs {} /** * Inherit from this base class to implement an API Documenter plugin feature that customizes diff --git a/apps/api-documenter/src/plugin/PluginFeature.ts b/apps/api-documenter/src/plugin/PluginFeature.ts index 9609d34087c..bd754bad372 100644 --- a/apps/api-documenter/src/plugin/PluginFeature.ts +++ b/apps/api-documenter/src/plugin/PluginFeature.ts @@ -25,8 +25,7 @@ export class PluginFeatureInitialization { * * @public */ -export class PluginFeatureContext { -} +export class PluginFeatureContext {} /** * The abstract base class for all API Documenter plugin features. diff --git a/apps/api-documenter/src/plugin/PluginLoader.ts b/apps/api-documenter/src/plugin/PluginLoader.ts index 8fd6cbe1c1d..7820e00069e 100644 --- a/apps/api-documenter/src/plugin/PluginLoader.ts +++ b/apps/api-documenter/src/plugin/PluginLoader.ts @@ -17,13 +17,16 @@ interface ILoadedPlugin { export class PluginLoader { public markdownDocumenterFeature: MarkdownDocumenterFeature | undefined; - public load(documenterConfig: DocumenterConfig, createContext: () => MarkdownDocumenterFeatureContext): void { + public load( + documenterConfig: DocumenterConfig, + createContext: () => MarkdownDocumenterFeatureContext + ): void { const configFileFolder: string = path.dirname(documenterConfig.configFilePath); - for (const configPlugin of (documenterConfig.configFile.plugins || [])) { + for (const configPlugin of documenterConfig.configFile.plugins || []) { try { // Look for the package name in the same place as the config file const resolvedEntryPointPath: string = resolve.sync(configPlugin.packageName, { - basedir: configFileFolder + basedir: configFileFolder, }); // Load the package @@ -34,26 +37,33 @@ export class PluginLoader { throw new Error('Invalid entry point'); } - const manifest: IApiDocumenterPluginManifest + const manifest: IApiDocumenterPluginManifest = // eslint-disable-next-line dot-notation - = entryPoint['apiDocumenterPluginManifest'] as IApiDocumenterPluginManifest; + entryPoint['apiDocumenterPluginManifest'] as IApiDocumenterPluginManifest; if (!manifest) { - throw new Error(`The package is not an API documenter plugin;` - + ` the "apiDocumenterPluginManifest" export was not found`); + throw new Error( + `The package is not an API documenter plugin;` + + ` the "apiDocumenterPluginManifest" export was not found` + ); } if (manifest.manifestVersion !== 1000) { - throw new Error(`The plugin is not compatible with this version of API Documenter;` - + ` unsupported manifestVersion`); + throw new Error( + `The plugin is not compatible with this version of API Documenter;` + + ` unsupported manifestVersion` + ); } const loadedPlugin: ILoadedPlugin = { packageName: configPlugin.packageName, - manifest + manifest, }; - const featureDefinitionsByName: Map = new Map(); + const featureDefinitionsByName: Map = new Map< + string, + IFeatureDefinition + >(); for (const featureDefinition of manifest.features) { featureDefinitionsByName.set(featureDefinition.featureName, featureDefinition); } @@ -61,8 +71,9 @@ export class PluginLoader { for (const featureName of configPlugin.enabledFeatureNames) { const featureDefinition: IFeatureDefinition | undefined = featureDefinitionsByName.get(featureName); if (!featureDefinition) { - throw new Error(`The plugin ${loadedPlugin.packageName} does not have` - + ` a feature with name "${featureName}"`); + throw new Error( + `The plugin ${loadedPlugin.packageName} does not have` + ` a feature with name "${featureName}"` + ); } if (featureDefinition.kind === 'MarkdownDocumenterFeature') { @@ -70,7 +81,7 @@ export class PluginLoader { throw new Error('A MarkdownDocumenterFeature is already loaded'); } - const initialization: PluginFeatureInitialization = new PluginFeatureInitialization(); + const initialization: PluginFeatureInitialization = new PluginFeatureInitialization(); initialization._context = createContext(); let markdownDocumenterFeature: MarkdownDocumenterFeature | undefined = undefined; @@ -99,5 +110,4 @@ export class PluginLoader { } } } - } diff --git a/apps/api-documenter/src/schemas/api-documenter-template.json b/apps/api-documenter/src/schemas/api-documenter-template.json index ec893c904c6..1e57fd7f120 100644 --- a/apps/api-documenter/src/schemas/api-documenter-template.json +++ b/apps/api-documenter/src/schemas/api-documenter-template.json @@ -28,7 +28,7 @@ * This setting currently only affects the 'docfx' output target. It is equivalent to the `--new-docfx-namespaces` * command-line parameter. */ - // "newDocfxNamespaces": false, + // "newDocfxNamespaces": false, /** * Describes plugin packages to be loaded, and which features to enable. @@ -58,7 +58,6 @@ // ] // } // ], - /** * Optional category name that is recommended to include in the `tocConfig`, * along with one of the filters: `filterByApiItemName` or `filterByInlineTag`. @@ -68,7 +67,6 @@ * DEFAULT VALUE: (none) */ // "catchAllCategory": "References", - /** * When loading more than one api.json files that might include the same API items, * toggle either to show duplicates or not. @@ -76,7 +74,6 @@ * DEFAULT VALUE: false */ // "noDuplicateEntries": true, - /** * Toggle either sorting of the API items should be made based on category name presence * in the API item's name. @@ -84,7 +81,6 @@ * DEFAULT VALUE: false */ // "filterByApiItemName": false, - /** * Filter that can be used to sort the API items according to an inline custom tag * that is present on them. diff --git a/apps/api-documenter/src/schemas/api-documenter.schema.json b/apps/api-documenter/src/schemas/api-documenter.schema.json index e8ccd2d477d..7282baf3b00 100644 --- a/apps/api-documenter/src/schemas/api-documenter.schema.json +++ b/apps/api-documenter/src/schemas/api-documenter.schema.json @@ -11,10 +11,7 @@ "outputTarget": { "description": "Specifies what type of documentation will be generated", "type": "string", - "enum": [ - "docfx", - "markdown" - ] + "enum": ["docfx", "markdown"] }, "newlineKind": { diff --git a/apps/api-documenter/src/start.ts b/apps/api-documenter/src/start.ts index 8b2b17ad884..68cae42998b 100644 --- a/apps/api-documenter/src/start.ts +++ b/apps/api-documenter/src/start.ts @@ -10,8 +10,10 @@ import { ApiDocumenterCommandLine } from './cli/ApiDocumenterCommandLine'; const myPackageVersion: string = PackageJsonLookup.loadOwnPackageJson(__dirname).version; -console.log(os.EOL + colors.bold(`api-documenter ${myPackageVersion} ` - + colors.cyan(' - https://api-extractor.com/') + os.EOL)); +console.log( + os.EOL + + colors.bold(`api-documenter ${myPackageVersion} ` + colors.cyan(' - https://api-extractor.com/') + os.EOL) +); const parser: ApiDocumenterCommandLine = new ApiDocumenterCommandLine(); diff --git a/apps/api-documenter/src/utils/IndentedWriter.ts b/apps/api-documenter/src/utils/IndentedWriter.ts index 5c37ea55624..6b57676b530 100644 --- a/apps/api-documenter/src/utils/IndentedWriter.ts +++ b/apps/api-documenter/src/utils/IndentedWriter.ts @@ -4,32 +4,32 @@ import { StringBuilder, IStringBuilder } from '@rushstack/node-core-library'; /** - * A utility for writing indented text. - * - * @remarks - * - * Note that the indentation is inserted at the last possible opportunity. - * For example, this code... - * - * ```ts - * writer.write('begin\n'); - * writer.increaseIndent(); - * writer.write('one\ntwo\n'); - * writer.decreaseIndent(); - * writer.increaseIndent(); - * writer.decreaseIndent(); - * writer.write('end'); - * ``` - * - * ...would produce this output: - * - * ``` - * begin - * one - * two - * end - * ``` - */ + * A utility for writing indented text. + * + * @remarks + * + * Note that the indentation is inserted at the last possible opportunity. + * For example, this code... + * + * ```ts + * writer.write('begin\n'); + * writer.increaseIndent(); + * writer.write('one\ntwo\n'); + * writer.decreaseIndent(); + * writer.increaseIndent(); + * writer.decreaseIndent(); + * writer.write('end'); + * ``` + * + * ...would produce this output: + * + * ``` + * begin + * one + * two + * end + * ``` + */ export class IndentedWriter { /** * The text characters used to create one level of indentation. diff --git a/apps/api-documenter/src/utils/Utilities.ts b/apps/api-documenter/src/utils/Utilities.ts index aff2fe1c24d..0416dc7fa86 100644 --- a/apps/api-documenter/src/utils/Utilities.ts +++ b/apps/api-documenter/src/utils/Utilities.ts @@ -1,19 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - ApiParameterListMixin, - ApiItem -} from '@microsoft/api-extractor-model'; +import { ApiParameterListMixin, ApiItem } from '@microsoft/api-extractor-model'; export class Utilities { - private static readonly _badFilenameCharsRegExp: RegExp = /[^a-z0-9_\-\.]/ig; + private static readonly _badFilenameCharsRegExp: RegExp = /[^a-z0-9_\-\.]/gi; /** * Generates a concise signature for a function. Example: "getArea(width, height)" */ public static getConciseSignature(apiItem: ApiItem): string { if (ApiParameterListMixin.isBaseClassOf(apiItem)) { - return apiItem.displayName + '(' + apiItem.parameters.map(x => x.name).join(', ') + ')'; + return apiItem.displayName + '(' + apiItem.parameters.map((x) => x.name).join(', ') + ')'; } return apiItem.displayName; } diff --git a/apps/api-documenter/src/utils/test/IndentedWriter.test.ts b/apps/api-documenter/src/utils/test/IndentedWriter.test.ts index 8ca09139a4b..f6ac6e7a85a 100644 --- a/apps/api-documenter/src/utils/test/IndentedWriter.test.ts +++ b/apps/api-documenter/src/utils/test/IndentedWriter.test.ts @@ -21,15 +21,15 @@ test('02 Indent something', () => { indentedWriter.write('a'); indentedWriter.write('b'); indentedWriter.increaseIndent(); - indentedWriter.writeLine('c'); - indentedWriter.writeLine('d'); + indentedWriter.writeLine('c'); + indentedWriter.writeLine('d'); indentedWriter.decreaseIndent(); indentedWriter.writeLine('e'); indentedWriter.increaseIndent('>>> '); - indentedWriter.writeLine(); - indentedWriter.writeLine(); - indentedWriter.writeLine('g'); + indentedWriter.writeLine(); + indentedWriter.writeLine(); + indentedWriter.writeLine('g'); indentedWriter.decreaseIndent(); expect(indentedWriter.toString()).toMatchSnapshot(); diff --git a/apps/api-documenter/src/yaml/IYamlApiFile.ts b/apps/api-documenter/src/yaml/IYamlApiFile.ts index 66fcb5d8129..5a728e76c20 100644 --- a/apps/api-documenter/src/yaml/IYamlApiFile.ts +++ b/apps/api-documenter/src/yaml/IYamlApiFile.ts @@ -345,15 +345,12 @@ export type YamlTypeId = | 'event' | 'typealias' | 'variable' - | 'namespace' - ; + | 'namespace'; /** * Development languages supported by the Universal Reference file format, as defined by typescript.schema.json. */ -export type YamlDevLangs = - | 'typeScript' - ; +export type YamlDevLangs = 'typeScript'; /** * Part of the IYamlApiFile structure. Documents the source file where an IYamlItem is defined. diff --git a/apps/api-documenter/src/yaml/typescript.schema.json b/apps/api-documenter/src/yaml/typescript.schema.json index 83e55daf678..7a66b6c77f9 100644 --- a/apps/api-documenter/src/yaml/typescript.schema.json +++ b/apps/api-documenter/src/yaml/typescript.schema.json @@ -1,633 +1,643 @@ { - "title": "Universal Reference YAML Schema for DocFX", - "$schema": "http://json-schema.org/draft-04/schema#", - "type": "object", - "additionalProperties": false, - "required": [ - "items" - ], - "properties": { - "items": { - "description": "This collection represents the main item (the first element) and it's possible children items.", - "type": "array", - "items": { - "$ref": "#/definitions/item" - }, - "minItems": 1, - "uniqueItems": true - }, - "references": { - "description": "References to other items.", - "type": "array", - "items": { - "$ref": "#/definitions/reference" - }, - "minItems": 1, - "uniqueItems": true - }, - "shouldSkipMarkup": { - "type": "boolean" - } - }, - "definitions":{ - "item": { - "description": "Represents basic API elements such as classes, interfaces, members, etc.", - "type": "object", - "additionalProperties": false, - "required": [ - "uid" - ], - "properties": { - "uid": { - "description": "A value that uniquely identifies this item among all other documentation elements. (ex: Microsoft.FSharp.Linq.RuntimeHelpers.AnonymousObject`2)", - "type": "string" - }, - "commentId": { - "description": "A Roslyn comment ID.", - "type": "string" - }, - "id": { - "description": "An ID for the item.", - "type": "string" - }, - "parent": { - "description": "A UID reference to the parent of this item.", - "type": "string" - }, - "children": { - "description": "A list of UID references to the children of this item.", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "href": { - "description": "A link URL for the item.", - "type": "string" - }, - "langs": { - "description": "The development languages supported by this item", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "name": { - "description": "The local name of the item (ex: AnonymousObject). This name should generally not be namespace qualified and should not include parent type information.", - "type": "string" - }, - "nameWithType": { - "description": "The name of the item including its parent type (ex: Colors.Red). This name should generally not be namespace qualified.", - "type": "string" - }, - "fullName": { - "description": "The full-qualified name of the item (ex: Microsoft.FSharp.Linq.RuntimeHelpers.AnonymousObject).", - "type": "string" - }, - "type": { - "description": "The type of source element this item represents", - "enum": [ "class", "constructor", "enum", "field", "function", "interface", "method", "package", "property", "event", "typealias", "variable", "namespace" ] - }, - "source": { - "description": "The source details for the item", - "$ref": "#/definitions/source" - }, - "documentation": { - "description": "Overrides the source details for the item.", - "$ref": "#/definitions/source" - }, - "assemblies": { - "description": "The names of managed assemblies that contain this item.", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "namespace": { - "description": "The UID of the namespace that contains this item.", - "type": "string" - }, - "summary": { - "description": "The summary for the item. Markdown is permitted", - "type": "string" - }, - "remarks": { - "description": "The remarks for the item. Markdown is permitted", - "type": "string" - }, - "examples": { - "description": "The examples for the item. Markdown is permitted", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "syntax": { - "description": "The syntax for this item.", - "$ref": "#/definitions/syntax" - }, - "overridden": { - "description": "The UID of the member this item overrides.", - "type": "string" - }, - "overload": { - "description": "The UID of the member this item overloads.", - "type": "string" - }, - "exceptions": { - "description": "The exceptions thrown by this item.", - "type": "array", - "items": { - "$ref": "#/definitions/exception" - }, - "minItems": 1, - "uniqueItems": true - }, - "seealso": { - "description": "Links to additional content related to this item.", - "type": "array", - "items": { - "$ref": "#/definitions/link" - }, - "minItems": 1, - "uniqueItems": true - }, - "seealsoContent": { - "description": "Additional information about other content related to this item. Markdown is permitted.", - "type": "string" - }, - "see": { - "description": "Links to additional content related to this item.", - "type": "array", - "items": { - "$ref": "#/definitions/link" - }, - "minItems": 1, - "uniqueItems": true - }, - "inheritance": { - "description": "The inheritance tree for this item. Multiple inherited is permitted if the underlying language supports it.", - "type": "array", - "items": { - "$ref": "#/definitions/inheritance" - }, - "minItems": 1, - "uniqueItems": true - }, - "derivedClasses": { - "description": "A list of UIDs for items derived from this item.", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "implements": { - "description": "A list of UIDs for the items this item implements.", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "inheritedMembers": { - "description": "A list of UIDs for the members this item inherits.", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "extensionMethods": { - "description": "A list of UIDs for extension methods for this item.", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "conceptual": { - "description": "The conceptual text for this item.", - "type": "string" - }, - "platform": { - "description": "The platforms supported by this item.", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, + "title": "Universal Reference YAML Schema for DocFX", + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "object", + "additionalProperties": false, + "required": ["items"], + "properties": { + "items": { + "description": "This collection represents the main item (the first element) and it's possible children items.", + "type": "array", + "items": { + "$ref": "#/definitions/item" + }, + "minItems": 1, + "uniqueItems": true + }, + "references": { + "description": "References to other items.", + "type": "array", + "items": { + "$ref": "#/definitions/reference" + }, + "minItems": 1, + "uniqueItems": true + }, + "shouldSkipMarkup": { + "type": "boolean" + } + }, + "definitions": { + "item": { + "description": "Represents basic API elements such as classes, interfaces, members, etc.", + "type": "object", + "additionalProperties": false, + "required": ["uid"], + "properties": { + "uid": { + "description": "A value that uniquely identifies this item among all other documentation elements. (ex: Microsoft.FSharp.Linq.RuntimeHelpers.AnonymousObject`2)", + "type": "string" + }, + "commentId": { + "description": "A Roslyn comment ID.", + "type": "string" + }, + "id": { + "description": "An ID for the item.", + "type": "string" + }, + "parent": { + "description": "A UID reference to the parent of this item.", + "type": "string" + }, + "children": { + "description": "A list of UID references to the children of this item.", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "href": { + "description": "A link URL for the item.", + "type": "string" + }, + "langs": { + "description": "The development languages supported by this item", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "name": { + "description": "The local name of the item (ex: AnonymousObject). This name should generally not be namespace qualified and should not include parent type information.", + "type": "string" + }, + "nameWithType": { + "description": "The name of the item including its parent type (ex: Colors.Red). This name should generally not be namespace qualified.", + "type": "string" + }, + "fullName": { + "description": "The full-qualified name of the item (ex: Microsoft.FSharp.Linq.RuntimeHelpers.AnonymousObject).", + "type": "string" + }, + "type": { + "description": "The type of source element this item represents", + "enum": [ + "class", + "constructor", + "enum", + "field", + "function", + "interface", + "method", + "package", + "property", + "event", + "typealias", + "variable", + "namespace" + ] + }, + "source": { + "description": "The source details for the item", + "$ref": "#/definitions/source" + }, + "documentation": { + "description": "Overrides the source details for the item.", + "$ref": "#/definitions/source" + }, + "assemblies": { + "description": "The names of managed assemblies that contain this item.", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "namespace": { + "description": "The UID of the namespace that contains this item.", + "type": "string" + }, + "summary": { + "description": "The summary for the item. Markdown is permitted", + "type": "string" + }, + "remarks": { + "description": "The remarks for the item. Markdown is permitted", + "type": "string" + }, + "examples": { + "description": "The examples for the item. Markdown is permitted", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "syntax": { + "description": "The syntax for this item.", + "$ref": "#/definitions/syntax" + }, + "overridden": { + "description": "The UID of the member this item overrides.", + "type": "string" + }, + "overload": { + "description": "The UID of the member this item overloads.", + "type": "string" + }, + "exceptions": { + "description": "The exceptions thrown by this item.", + "type": "array", + "items": { + "$ref": "#/definitions/exception" + }, + "minItems": 1, + "uniqueItems": true + }, + "seealso": { + "description": "Links to additional content related to this item.", + "type": "array", + "items": { + "$ref": "#/definitions/link" + }, + "minItems": 1, + "uniqueItems": true + }, + "seealsoContent": { + "description": "Additional information about other content related to this item. Markdown is permitted.", + "type": "string" + }, + "see": { + "description": "Links to additional content related to this item.", + "type": "array", + "items": { + "$ref": "#/definitions/link" + }, + "minItems": 1, + "uniqueItems": true + }, + "inheritance": { + "description": "The inheritance tree for this item. Multiple inherited is permitted if the underlying language supports it.", + "type": "array", + "items": { + "$ref": "#/definitions/inheritance" + }, + "minItems": 1, + "uniqueItems": true + }, + "derivedClasses": { + "description": "A list of UIDs for items derived from this item.", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "implements": { + "description": "A list of UIDs for the items this item implements.", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "inheritedMembers": { + "description": "A list of UIDs for the members this item inherits.", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "extensionMethods": { + "description": "A list of UIDs for extension methods for this item.", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "conceptual": { + "description": "The conceptual text for this item.", + "type": "string" + }, + "platform": { + "description": "The platforms supported by this item.", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, - "deprecated": { - "$ref": "#/definitions/deprecated" - }, - "extends": { - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "isPreview": { - "type": "boolean" - }, - "numericValue": { - "type": "string", - "description": "Used for Enum fields" - }, - "package": { - "type": "string" - } - }, - "patternProperties": { - "^parent\\.": { - "description": "A UID reference to the parent of this item for a specific development language.", - "type": "string" - }, - "^children\\.": { - "description": "A list of UID references to the children of this item for a specific development language.", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "^name\\.": { - "description": "The local name of the item (ex: AnonymousObject) for a specific development language. This name should generally not be namespace qualified and should not include parent type information.", - "type": "string" - }, - "^nameWithType\\.": { - "description": "The name of the item including its parent type (ex: Colors.Red) for a specific development language. This name should generally not be namespace qualified.", - "type": "string" - }, - "^fullName\\.": { - "description": "The full-qualified name of the item (ex: Microsoft.FSharp.Linq.RuntimeHelpers.AnonymousObject) for a specific development language.", - "type": "string" - }, - "^source\\.": { - "description": "The source details for the item for a specific development language.", - "$ref": "#/definitions/source" - }, - "^assemblies\\.": { - "description": "The names of managed assemblies that contain this item for a specific development language.", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "^namespace\\.": { - "description": "The UID of the namespace that contains this item for a specific development language.", - "type": "string" - }, - "^overridden\\.": { - "description": "The UID of the member this item overrides for a specific development language.", - "type": "string" - }, - "^overload\\.": { - "description": "The UID of the member this item overloads for a specific development language.", - "type": "string" - }, - "^exceptions\\.": { - "description": "The exceptions thrown by this item for a specific development language.", - "type": "array", - "items": { - "$ref": "#/definitions/exception" - }, - "minItems": 1, - "uniqueItems": true - }, - "^inheritance\\.": { - "description": "The inheritance tree for this item for a specific development language. Multiple inherited is permitted if the underlying language supports it.", - "type": "array", - "items": { - "$ref": "#/definitions/inheritance" - }, - "minItems": 1, - "uniqueItems": true - }, - "^derivedClasses\\.": { - "description": "A list of UIDs for items derived from this item for a specific development language.", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "^implements\\.": { - "description": "A list of UIDs for the items this item implements for a specific development language.", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "^inheritedMembers\\.": { - "description": "A list of UIDs for the members this item inherits for a specific development language.", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "^extensionMethods\\.": { - "description": "A list of UIDs for extension methods for this item for a specific development language.", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "^platform\\.": { - "description": "The platforms supported by this item for a specific development language.", - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - } - } - }, - "source": { - "type": "object", - "properties": { - "remote": { - "$ref": "#/definitions/remote" - }, - "basePath": { - "type": "string" - }, - "id": { - "type": "string" - }, - "href": { - "type": "string" - }, - "path": { - "type": "string" - }, - "startLine": { - "type": "integer" - }, - "endLine": { - "type": "integer" - }, - "content": { - "type": "string" - }, - "isExternal": { - "type": "boolean" - } - } - }, - "remote": { - "type": "object", - "additionalProperties": false, - "properties": { - "path": { - "type": "string" - }, - "branch": { - "type": "string" - }, - "repo": { - "type": "string" - } - } - }, - "syntax": { - "type": "object", - "additionalProperties": false, - "properties": { - "content": { - "type": "string" - }, - "parameters": { - "type": "array", - "items": { - "$ref": "#/definitions/parameter" - }, - "minItems": 1, - "uniqueItems": true - }, - "typeParameters": { - "type": "array", - "items": { - "$ref": "#/definitions/parameter" - }, - "minItems": 1, - "uniqueItems": true - }, - "return": { - "$ref": "#/definitions/return" - } - }, - "patternProperties": { - "^content\\.": { - "type": "string" - }, - "^return\\.": { - "$ref": "#/definitions/return" - } - } - }, - "parameter": { - "type": "object", - "additionalProperties": false, - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "array", - "items": { - "type": "string" - } - }, - "description": { - "type": "string" - }, - "optional": { - "type": "boolean" - }, - "defaultValue": { - "type": "string" - } - } - }, - "return": { - "type": "object", - "additionalProperties": false, - "properties": { - "type": { - "type": "array", - "items": { - "type": "string" - } - }, - "description": { - "type": "string" - } - } - }, - "exception": { - "type": "object", - "additionalProperties": false, - "properties": { - "type": { - "type": "string" - }, - "description": { - "type": "string" - } - } - }, - "link": { - "type": "object", - "additionalProperties": false, - "required": [ "linkType", "linkId" ], - "properties": { - "linkType": { - "enum": [ "CRef", "HRef" ] - }, - "linkId": { - "type": "string" - }, - "commentId": { - "type": "string" - }, - "altText": { - "type": "string" - } - } - }, - "inheritance": { - "type": "object", - "additionalProperties": false, - "required": [ "type" ], - "properties": { - "type": { - "type": "string" - }, - "inheritance": { - "type": "array", - "items": { - "$ref": "#/definitions/inheritance" - }, - "minItems": 1, - "uniqueItems": true - }, - "level": { - "type": "number" - } - } - }, - "reference": { - "type": "object", - "additionalProperties": false, - "properties": { - "uid": { - "type": "string" - }, - "commentId": { - "type": "string" - }, - "parent": { - "type": "string" - }, - "definition": { - "type": "string" - }, - "isExternal": { - "type": "boolean" - }, - "href": { - "type": "string" - }, - "name": { - "type": "string" - }, - "nameWithType": { - "type": "string" - }, - "fullName": { - "type": "string" - } - }, - "patternProperties": { - "^name\\.": { - "type": "string" - }, - "^nameWithType\\.": { - "type": "string" - }, - "^fullName\\.": { - "type": "string" - }, - "^spec\\.": { - "type": "array", - "items": { - "$ref": "#/definitions/spec" - } - } - } - }, - "spec": { - "type": "object", - "additionalProperties": false, - "properties": { - "uid": { - "type": "string" - }, - "name": { - "type": "string" - }, - "nameWithType": { - "type": "string" - }, - "fullName": { - "type": "string" - }, - "isExternal": { - "type": "boolean" - }, - "href": { - "type": "string" - } - } - }, + "deprecated": { + "$ref": "#/definitions/deprecated" + }, + "extends": { + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "isPreview": { + "type": "boolean" + }, + "numericValue": { + "type": "string", + "description": "Used for Enum fields" + }, + "package": { + "type": "string" + } + }, + "patternProperties": { + "^parent\\.": { + "description": "A UID reference to the parent of this item for a specific development language.", + "type": "string" + }, + "^children\\.": { + "description": "A list of UID references to the children of this item for a specific development language.", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "^name\\.": { + "description": "The local name of the item (ex: AnonymousObject) for a specific development language. This name should generally not be namespace qualified and should not include parent type information.", + "type": "string" + }, + "^nameWithType\\.": { + "description": "The name of the item including its parent type (ex: Colors.Red) for a specific development language. This name should generally not be namespace qualified.", + "type": "string" + }, + "^fullName\\.": { + "description": "The full-qualified name of the item (ex: Microsoft.FSharp.Linq.RuntimeHelpers.AnonymousObject) for a specific development language.", + "type": "string" + }, + "^source\\.": { + "description": "The source details for the item for a specific development language.", + "$ref": "#/definitions/source" + }, + "^assemblies\\.": { + "description": "The names of managed assemblies that contain this item for a specific development language.", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "^namespace\\.": { + "description": "The UID of the namespace that contains this item for a specific development language.", + "type": "string" + }, + "^overridden\\.": { + "description": "The UID of the member this item overrides for a specific development language.", + "type": "string" + }, + "^overload\\.": { + "description": "The UID of the member this item overloads for a specific development language.", + "type": "string" + }, + "^exceptions\\.": { + "description": "The exceptions thrown by this item for a specific development language.", + "type": "array", + "items": { + "$ref": "#/definitions/exception" + }, + "minItems": 1, + "uniqueItems": true + }, + "^inheritance\\.": { + "description": "The inheritance tree for this item for a specific development language. Multiple inherited is permitted if the underlying language supports it.", + "type": "array", + "items": { + "$ref": "#/definitions/inheritance" + }, + "minItems": 1, + "uniqueItems": true + }, + "^derivedClasses\\.": { + "description": "A list of UIDs for items derived from this item for a specific development language.", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "^implements\\.": { + "description": "A list of UIDs for the items this item implements for a specific development language.", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "^inheritedMembers\\.": { + "description": "A list of UIDs for the members this item inherits for a specific development language.", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "^extensionMethods\\.": { + "description": "A list of UIDs for extension methods for this item for a specific development language.", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "^platform\\.": { + "description": "The platforms supported by this item for a specific development language.", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + } + } + }, + "source": { + "type": "object", + "properties": { + "remote": { + "$ref": "#/definitions/remote" + }, + "basePath": { + "type": "string" + }, + "id": { + "type": "string" + }, + "href": { + "type": "string" + }, + "path": { + "type": "string" + }, + "startLine": { + "type": "integer" + }, + "endLine": { + "type": "integer" + }, + "content": { + "type": "string" + }, + "isExternal": { + "type": "boolean" + } + } + }, + "remote": { + "type": "object", + "additionalProperties": false, + "properties": { + "path": { + "type": "string" + }, + "branch": { + "type": "string" + }, + "repo": { + "type": "string" + } + } + }, + "syntax": { + "type": "object", + "additionalProperties": false, + "properties": { + "content": { + "type": "string" + }, + "parameters": { + "type": "array", + "items": { + "$ref": "#/definitions/parameter" + }, + "minItems": 1, + "uniqueItems": true + }, + "typeParameters": { + "type": "array", + "items": { + "$ref": "#/definitions/parameter" + }, + "minItems": 1, + "uniqueItems": true + }, + "return": { + "$ref": "#/definitions/return" + } + }, + "patternProperties": { + "^content\\.": { + "type": "string" + }, + "^return\\.": { + "$ref": "#/definitions/return" + } + } + }, + "parameter": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": { + "type": "string" + }, + "optional": { + "type": "boolean" + }, + "defaultValue": { + "type": "string" + } + } + }, + "return": { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": { + "type": "string" + } + } + }, + "exception": { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string" + }, + "description": { + "type": "string" + } + } + }, + "link": { + "type": "object", + "additionalProperties": false, + "required": ["linkType", "linkId"], + "properties": { + "linkType": { + "enum": ["CRef", "HRef"] + }, + "linkId": { + "type": "string" + }, + "commentId": { + "type": "string" + }, + "altText": { + "type": "string" + } + } + }, + "inheritance": { + "type": "object", + "additionalProperties": false, + "required": ["type"], + "properties": { + "type": { + "type": "string" + }, + "inheritance": { + "type": "array", + "items": { + "$ref": "#/definitions/inheritance" + }, + "minItems": 1, + "uniqueItems": true + }, + "level": { + "type": "number" + } + } + }, + "reference": { + "type": "object", + "additionalProperties": false, + "properties": { + "uid": { + "type": "string" + }, + "commentId": { + "type": "string" + }, + "parent": { + "type": "string" + }, + "definition": { + "type": "string" + }, + "isExternal": { + "type": "boolean" + }, + "href": { + "type": "string" + }, + "name": { + "type": "string" + }, + "nameWithType": { + "type": "string" + }, + "fullName": { + "type": "string" + } + }, + "patternProperties": { + "^name\\.": { + "type": "string" + }, + "^nameWithType\\.": { + "type": "string" + }, + "^fullName\\.": { + "type": "string" + }, + "^spec\\.": { + "type": "array", + "items": { + "$ref": "#/definitions/spec" + } + } + } + }, + "spec": { + "type": "object", + "additionalProperties": false, + "properties": { + "uid": { + "type": "string" + }, + "name": { + "type": "string" + }, + "nameWithType": { + "type": "string" + }, + "fullName": { + "type": "string" + }, + "isExternal": { + "type": "boolean" + }, + "href": { + "type": "string" + } + } + }, - "deprecated": { - "type": "object", - "additionalProperties": false, - "properties": { - "content": { - "description": "The string following the default obsolete message. Supports markdown.", - "type": "string" - } - } - } - } + "deprecated": { + "type": "object", + "additionalProperties": false, + "properties": { + "content": { + "description": "The string following the default obsolete message. Supports markdown.", + "type": "string" + } + } + } + } } diff --git a/apps/api-documenter/tsconfig.json b/apps/api-documenter/tsconfig.json index 47e75f9f181..f81ee11ef26 100644 --- a/apps/api-documenter/tsconfig.json +++ b/apps/api-documenter/tsconfig.json @@ -1,8 +1,6 @@ { "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "jest" - ] + "types": ["jest"] } } diff --git a/apps/api-extractor-model/.eslintrc.js b/apps/api-extractor-model/.eslintrc.js index b00435d3a51..3e2d415e962 100644 --- a/apps/api-extractor-model/.eslintrc.js +++ b/apps/api-extractor-model/.eslintrc.js @@ -1,12 +1,12 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, rules: { // api-extractor-model uses namespaces to represent mixins - "@typescript-eslint/no-namespace": "off" - } + '@typescript-eslint/no-namespace': 'off', + }, }; diff --git a/apps/api-extractor-model/config/api-extractor.json b/apps/api-extractor-model/config/api-extractor.json index 3e8571b570b..aa9d8f810fd 100644 --- a/apps/api-extractor-model/config/api-extractor.json +++ b/apps/api-extractor-model/config/api-extractor.json @@ -15,6 +15,6 @@ "dtsRollup": { "enabled": true, - "untrimmedFilePath": "/dist/rollup.d.ts", + "untrimmedFilePath": "/dist/rollup.d.ts" } } diff --git a/apps/api-extractor-model/config/jest.json b/apps/api-extractor-model/config/jest.json index 0c42a30d2f6..4606bb67eb0 100644 --- a/apps/api-extractor-model/config/jest.json +++ b/apps/api-extractor-model/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": false -} \ No newline at end of file +} diff --git a/apps/api-extractor-model/src/aedoc/AedocDefinitions.ts b/apps/api-extractor-model/src/aedoc/AedocDefinitions.ts index 539d6a95249..f5f92af552f 100644 --- a/apps/api-extractor-model/src/aedoc/AedocDefinitions.ts +++ b/apps/api-extractor-model/src/aedoc/AedocDefinitions.ts @@ -1,12 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - TSDocConfiguration, - TSDocTagDefinition, - TSDocTagSyntaxKind, - StandardTags -} from '@microsoft/tsdoc'; +import { TSDocConfiguration, TSDocTagDefinition, TSDocTagSyntaxKind, StandardTags } from '@microsoft/tsdoc'; /** * @internal @@ -14,27 +9,30 @@ import { export class AedocDefinitions { public static readonly betaDocumentation: TSDocTagDefinition = new TSDocTagDefinition({ tagName: '@betaDocumentation', - syntaxKind: TSDocTagSyntaxKind.ModifierTag + syntaxKind: TSDocTagSyntaxKind.ModifierTag, }); public static readonly internalRemarks: TSDocTagDefinition = new TSDocTagDefinition({ tagName: '@internalRemarks', - syntaxKind: TSDocTagSyntaxKind.BlockTag + syntaxKind: TSDocTagSyntaxKind.BlockTag, }); public static readonly preapprovedTag: TSDocTagDefinition = new TSDocTagDefinition({ tagName: '@preapproved', - syntaxKind: TSDocTagSyntaxKind.ModifierTag + syntaxKind: TSDocTagSyntaxKind.ModifierTag, }); public static get tsdocConfiguration(): TSDocConfiguration { if (!AedocDefinitions._tsdocConfiguration) { const configuration: TSDocConfiguration = new TSDocConfiguration(); - configuration.addTagDefinitions([ - AedocDefinitions.betaDocumentation, - AedocDefinitions.internalRemarks, - AedocDefinitions.preapprovedTag - ], true); + configuration.addTagDefinitions( + [ + AedocDefinitions.betaDocumentation, + AedocDefinitions.internalRemarks, + AedocDefinitions.preapprovedTag, + ], + true + ); configuration.setSupportForTags( [ @@ -57,7 +55,7 @@ export class AedocDefinitions { StandardTags.returns, StandardTags.sealed, StandardTags.throws, - StandardTags.virtual + StandardTags.virtual, ], true ); diff --git a/apps/api-extractor-model/src/aedoc/ReleaseTag.ts b/apps/api-extractor-model/src/aedoc/ReleaseTag.ts index c5cab848b84..e1dc31f9d71 100644 --- a/apps/api-extractor-model/src/aedoc/ReleaseTag.ts +++ b/apps/api-extractor-model/src/aedoc/ReleaseTag.ts @@ -2,19 +2,19 @@ // See LICENSE in the project root for license information. /** - * A "release tag" is a custom TSDoc tag that is applied to an API to communicate the level of support - * provided for third-party developers. - * - * @remarks - * - * The four release tags are: `@internal`, `@alpha`, `@beta`, and `@public`. They are applied to API items such - * as classes, member functions, enums, etc. The release tag applies recursively to members of a container - * (e.g. class or interface). For example, if a class is marked as `@beta`, then all of its members automatically - * have this status; you DON'T need add the `@beta` tag to each member function. However, you could add - * `@internal` to a member function to give it a different release status. - * - * @public - */ + * A "release tag" is a custom TSDoc tag that is applied to an API to communicate the level of support + * provided for third-party developers. + * + * @remarks + * + * The four release tags are: `@internal`, `@alpha`, `@beta`, and `@public`. They are applied to API items such + * as classes, member functions, enums, etc. The release tag applies recursively to members of a container + * (e.g. class or interface). For example, if a class is marked as `@beta`, then all of its members automatically + * have this status; you DON'T need add the `@beta` tag to each member function. However, you could add + * `@internal` to a member function to give it a different release status. + * + * @public + */ export enum ReleaseTag { /** * No release tag was specified in the AEDoc summary. @@ -41,7 +41,7 @@ export enum ReleaseTag { * Indicates that an API item has been officially released. It is part of the supported * contract (e.g. SemVer) for a package. */ - Public = 4 + Public = 4, } /** @@ -57,11 +57,16 @@ export namespace ReleaseTag { */ export function getTagName(releaseTag: ReleaseTag): string { switch (releaseTag) { - case ReleaseTag.None: return '(none)'; - case ReleaseTag.Internal: return '@internal'; - case ReleaseTag.Alpha: return '@alpha'; - case ReleaseTag.Beta: return '@beta'; - case ReleaseTag.Public: return '@public'; + case ReleaseTag.None: + return '(none)'; + case ReleaseTag.Internal: + return '@internal'; + case ReleaseTag.Alpha: + return '@alpha'; + case ReleaseTag.Beta: + return '@beta'; + case ReleaseTag.Public: + return '@public'; } throw new Error('Unsupported release tag'); } @@ -77,5 +82,4 @@ export namespace ReleaseTag { export function compare(a: ReleaseTag, b: ReleaseTag): number { return a - b; } - } diff --git a/apps/api-extractor-model/src/index.ts b/apps/api-extractor-model/src/index.ts index 8107ea4eb3f..acdfb24c9cb 100644 --- a/apps/api-extractor-model/src/index.ts +++ b/apps/api-extractor-model/src/index.ts @@ -14,156 +14,51 @@ export { AedocDefinitions } from './aedoc/AedocDefinitions'; export { ReleaseTag } from './aedoc/ReleaseTag'; // items -export { - IApiDeclaredItemOptions, - ApiDeclaredItem -} from './items/ApiDeclaredItem'; -export { - IApiDocumentedItemOptions, - ApiDocumentedItem -} from './items/ApiDocumentedItem'; -export { - ApiItemKind, - IApiItemOptions, - ApiItem, - IApiItemConstructor -} from './items/ApiItem'; -export { - IApiPropertyItemOptions, - ApiPropertyItem -} from './items/ApiPropertyItem'; +export { IApiDeclaredItemOptions, ApiDeclaredItem } from './items/ApiDeclaredItem'; +export { IApiDocumentedItemOptions, ApiDocumentedItem } from './items/ApiDocumentedItem'; +export { ApiItemKind, IApiItemOptions, ApiItem, IApiItemConstructor } from './items/ApiItem'; +export { IApiPropertyItemOptions, ApiPropertyItem } from './items/ApiPropertyItem'; // mixins export { IApiParameterListMixinOptions, IApiParameterOptions, - ApiParameterListMixin + ApiParameterListMixin, } from './mixins/ApiParameterListMixin'; export { IApiTypeParameterOptions, IApiTypeParameterListMixinOptions, - ApiTypeParameterListMixin + ApiTypeParameterListMixin, } from './mixins/ApiTypeParameterListMixin'; -export { - IApiItemContainerMixinOptions, - ApiItemContainerMixin -} from './mixins/ApiItemContainerMixin'; -export { - IApiReleaseTagMixinOptions, - ApiReleaseTagMixin -} from './mixins/ApiReleaseTagMixin'; -export { - IApiReturnTypeMixinOptions, - ApiReturnTypeMixin -} from './mixins/ApiReturnTypeMixin'; -export { - IApiStaticMixinOptions, - ApiStaticMixin -} from './mixins/ApiStaticMixin'; -export { - IApiNameMixinOptions, - ApiNameMixin -} from './mixins/ApiNameMixin'; -export { - ExcerptTokenKind, - IExcerptTokenRange, - IExcerptToken, - ExcerptToken, - Excerpt -} from './mixins/Excerpt'; -export { - Constructor, - PropertiesOf -} from './mixins/Mixin'; +export { IApiItemContainerMixinOptions, ApiItemContainerMixin } from './mixins/ApiItemContainerMixin'; +export { IApiReleaseTagMixinOptions, ApiReleaseTagMixin } from './mixins/ApiReleaseTagMixin'; +export { IApiReturnTypeMixinOptions, ApiReturnTypeMixin } from './mixins/ApiReturnTypeMixin'; +export { IApiStaticMixinOptions, ApiStaticMixin } from './mixins/ApiStaticMixin'; +export { IApiNameMixinOptions, ApiNameMixin } from './mixins/ApiNameMixin'; +export { ExcerptTokenKind, IExcerptTokenRange, IExcerptToken, ExcerptToken, Excerpt } from './mixins/Excerpt'; +export { Constructor, PropertiesOf } from './mixins/Mixin'; // model -export { - IApiCallSignatureOptions, - ApiCallSignature -} from './model/ApiCallSignature'; -export { - IApiClassOptions, - ApiClass -} from './model/ApiClass'; -export { - IApiConstructorOptions, - ApiConstructor -} from './model/ApiConstructor'; -export { - IApiConstructSignatureOptions, - ApiConstructSignature -} from './model/ApiConstructSignature'; -export { - IApiEntryPointOptions, - ApiEntryPoint -} from './model/ApiEntryPoint'; -export { - IApiEnumOptions, - ApiEnum -} from './model/ApiEnum'; -export { - IApiEnumMemberOptions, - ApiEnumMember -} from './model/ApiEnumMember'; -export { - IApiFunctionOptions, - ApiFunction -} from './model/ApiFunction'; -export { - IApiIndexSignatureOptions, - ApiIndexSignature -} from './model/ApiIndexSignature'; -export { - IApiInterfaceOptions, - ApiInterface -} from './model/ApiInterface'; -export { - IApiMethodOptions, - ApiMethod -} from './model/ApiMethod'; -export { - IApiMethodSignatureOptions, - ApiMethodSignature -} from './model/ApiMethodSignature'; -export { - ApiModel -} from './model/ApiModel'; -export { - IApiNamespaceOptions, - ApiNamespace -} from './model/ApiNamespace'; -export { - IApiPackageOptions, - ApiPackage, - IApiPackageSaveOptions -} from './model/ApiPackage'; -export { - IParameterOptions, - Parameter -} from './model/Parameter'; -export { - IApiPropertyOptions, - ApiProperty -} from './model/ApiProperty'; -export { - IApiPropertySignatureOptions, - ApiPropertySignature -} from './model/ApiPropertySignature'; -export { - IApiTypeAliasOptions, - ApiTypeAlias -} from './model/ApiTypeAlias'; -export { - ITypeParameterOptions, - TypeParameter -} from './model/TypeParameter'; -export { - IApiVariableOptions, - ApiVariable -} from './model/ApiVariable'; -export { - IResolveDeclarationReferenceResult -} from './model/ModelReferenceResolver'; -export { - HeritageType -} from './model/HeritageType'; +export { IApiCallSignatureOptions, ApiCallSignature } from './model/ApiCallSignature'; +export { IApiClassOptions, ApiClass } from './model/ApiClass'; +export { IApiConstructorOptions, ApiConstructor } from './model/ApiConstructor'; +export { IApiConstructSignatureOptions, ApiConstructSignature } from './model/ApiConstructSignature'; +export { IApiEntryPointOptions, ApiEntryPoint } from './model/ApiEntryPoint'; +export { IApiEnumOptions, ApiEnum } from './model/ApiEnum'; +export { IApiEnumMemberOptions, ApiEnumMember } from './model/ApiEnumMember'; +export { IApiFunctionOptions, ApiFunction } from './model/ApiFunction'; +export { IApiIndexSignatureOptions, ApiIndexSignature } from './model/ApiIndexSignature'; +export { IApiInterfaceOptions, ApiInterface } from './model/ApiInterface'; +export { IApiMethodOptions, ApiMethod } from './model/ApiMethod'; +export { IApiMethodSignatureOptions, ApiMethodSignature } from './model/ApiMethodSignature'; +export { ApiModel } from './model/ApiModel'; +export { IApiNamespaceOptions, ApiNamespace } from './model/ApiNamespace'; +export { IApiPackageOptions, ApiPackage, IApiPackageSaveOptions } from './model/ApiPackage'; +export { IParameterOptions, Parameter } from './model/Parameter'; +export { IApiPropertyOptions, ApiProperty } from './model/ApiProperty'; +export { IApiPropertySignatureOptions, ApiPropertySignature } from './model/ApiPropertySignature'; +export { IApiTypeAliasOptions, ApiTypeAlias } from './model/ApiTypeAlias'; +export { ITypeParameterOptions, TypeParameter } from './model/TypeParameter'; +export { IApiVariableOptions, ApiVariable } from './model/ApiVariable'; +export { IResolveDeclarationReferenceResult } from './model/ModelReferenceResolver'; +export { HeritageType } from './model/HeritageType'; diff --git a/apps/api-extractor-model/src/items/ApiDeclaredItem.ts b/apps/api-extractor-model/src/items/ApiDeclaredItem.ts index da75b36e9d7..1a3b9d3a1e5 100644 --- a/apps/api-extractor-model/src/items/ApiDeclaredItem.ts +++ b/apps/api-extractor-model/src/items/ApiDeclaredItem.ts @@ -39,18 +39,22 @@ export class ApiDeclaredItem extends ApiDocumentedItem { public constructor(options: IApiDeclaredItemOptions) { super(options); - this._excerptTokens = options.excerptTokens.map(token => { - const canonicalReference: DeclarationReference | undefined = token.canonicalReference === undefined ? undefined : - DeclarationReference.parse(token.canonicalReference); + 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 }); } /** @override */ - public static onDeserializeInto(options: Partial, context: DeserializerContext, - jsonObject: IApiDeclaredItemJson): void { - + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiDeclaredItemJson + ): void { super.onDeserializeInto(options, context, jsonObject); options.excerptTokens = jsonObject.excerptTokens; @@ -92,8 +96,7 @@ export class ApiDeclaredItem extends ApiDocumentedItem { } } if (modifierTags.length > 0) { - return '/** ' + modifierTags.join(' ') + ' */\n' - + excerpt; + return '/** ' + modifierTags.join(' ') + ' */\n' + excerpt; } } } @@ -104,7 +107,7 @@ export class ApiDeclaredItem extends ApiDocumentedItem { /** @override */ public serializeInto(jsonObject: Partial): void { super.serializeInto(jsonObject); - jsonObject.excerptTokens = this.excerptTokens.map(x => { + jsonObject.excerptTokens = this.excerptTokens.map((x) => { const excerptToken: IExcerptToken = { kind: x.kind, text: x.text }; if (x.canonicalReference !== undefined) { excerptToken.canonicalReference = x.canonicalReference.toString(); diff --git a/apps/api-extractor-model/src/items/ApiDocumentedItem.ts b/apps/api-extractor-model/src/items/ApiDocumentedItem.ts index 9316d479dc5..2e7246fe9a1 100644 --- a/apps/api-extractor-model/src/items/ApiDocumentedItem.ts +++ b/apps/api-extractor-model/src/items/ApiDocumentedItem.ts @@ -37,10 +37,12 @@ export class ApiDocumentedItem extends ApiItem { } /** @override */ - public static onDeserializeInto(options: Partial, context: DeserializerContext, - jsonObject: IApiItemJson): void { - - super.onDeserializeInto(options, context, jsonObject); + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiItemJson + ): void { + super.onDeserializeInto(options, context, jsonObject); const documentedJson: IApiDocumentedItemJson = jsonObject as IApiDocumentedItemJson; diff --git a/apps/api-extractor-model/src/items/ApiItem.ts b/apps/api-extractor-model/src/items/ApiItem.ts index b38a1d2e154..91a1c97b7ea 100644 --- a/apps/api-extractor-model/src/items/ApiItem.ts +++ b/apps/api-extractor-model/src/items/ApiItem.ts @@ -35,15 +35,14 @@ export const enum ApiItemKind { PropertySignature = 'PropertySignature', TypeAlias = 'TypeAlias', Variable = 'Variable', - None = 'None' + None = 'None', } /** * Constructor options for {@link ApiItem}. * @public */ -export interface IApiItemOptions { -} +export interface IApiItemOptions {} export interface IApiItemJson { kind: ApiItemKind; @@ -79,8 +78,11 @@ export class ApiItem { } /** @virtual */ - public static onDeserializeInto(options: Partial, context: DeserializerContext, - jsonObject: IApiItemJson): void { + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiItemJson + ): void { // (implemented by subclasses) } @@ -113,8 +115,7 @@ export class ApiItem { this._canonicalReference = this.buildCanonicalReference(); } catch (e) { const name: string = this.getScopedNameWithinPackage() || this.displayName; - throw new InternalError(`Error building canonical reference for ${name}:\n` - + e.message); + throw new InternalError(`Error building canonical reference for ${name}:\n` + e.message); } } return this._canonicalReference; @@ -145,13 +146,18 @@ export class ApiItem { */ public get displayName(): string { switch (this.kind) { - case ApiItemKind.CallSignature: return '(call)'; - case ApiItemKind.Constructor: return '(constructor)'; - case ApiItemKind.ConstructSignature: return '(new)'; - case ApiItemKind.IndexSignature: return '(indexer)'; - case ApiItemKind.Model: return '(model)'; + case ApiItemKind.CallSignature: + return '(call)'; + case ApiItemKind.Constructor: + return '(constructor)'; + case ApiItemKind.ConstructSignature: + return '(new)'; + case ApiItemKind.IndexSignature: + return '(indexer)'; + case ApiItemKind.Model: + return '(model)'; } - return '(???)'; // All other types should inherit ApiNameMixin which will override this property + return '(???)'; // All other types should inherit ApiNameMixin which will override this property } /** @@ -215,9 +221,11 @@ export class ApiItem { const reversedParts: string[] = []; for (let current: ApiItem | undefined = this; current !== undefined; current = current.parent) { - if (current.kind === ApiItemKind.Model - || current.kind === ApiItemKind.Package - || current.kind === ApiItemKind.EntryPoint) { + if ( + current.kind === ApiItemKind.Model || + current.kind === ApiItemKind.Package || + current.kind === ApiItemKind.EntryPoint + ) { break; } if (reversedParts.length !== 0) { @@ -288,4 +296,4 @@ export class ApiItem { * * @public */ -export interface IApiItemConstructor extends Constructor, PropertiesOf { } +export interface IApiItemConstructor extends Constructor, PropertiesOf {} diff --git a/apps/api-extractor-model/src/items/ApiPropertyItem.ts b/apps/api-extractor-model/src/items/ApiPropertyItem.ts index c0bb2228146..f277e3481ed 100644 --- a/apps/api-extractor-model/src/items/ApiPropertyItem.ts +++ b/apps/api-extractor-model/src/items/ApiPropertyItem.ts @@ -11,11 +11,10 @@ import { DeserializerContext } from '../model/DeserializerContext'; * Constructor options for {@link ApiPropertyItem}. * @public */ -export interface IApiPropertyItemOptions extends - IApiNameMixinOptions, - IApiReleaseTagMixinOptions, - IApiDeclaredItemOptions { - +export interface IApiPropertyItemOptions + extends IApiNameMixinOptions, + IApiReleaseTagMixinOptions, + IApiDeclaredItemOptions { propertyTypeTokenRange: IExcerptTokenRange; } @@ -41,9 +40,11 @@ export class ApiPropertyItem extends ApiNameMixin(ApiReleaseTagMixin(ApiDeclared } /** @override */ - public static onDeserializeInto(options: Partial, context: DeserializerContext, - jsonObject: IApiPropertyItemJson): void { - + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiPropertyItemJson + ): void { super.onDeserializeInto(options, context, jsonObject); options.propertyTypeTokenRange = jsonObject.propertyTypeTokenRange; diff --git a/apps/api-extractor-model/src/mixins/ApiItemContainerMixin.ts b/apps/api-extractor-model/src/mixins/ApiItemContainerMixin.ts index c92c50f93f5..dac72b8ba39 100644 --- a/apps/api-extractor-model/src/mixins/ApiItemContainerMixin.ts +++ b/apps/api-extractor-model/src/mixins/ApiItemContainerMixin.ts @@ -7,7 +7,7 @@ import { IApiItemJson, IApiItemOptions, IApiItemConstructor, - ApiItemKind + ApiItemKind, } from '../items/ApiItem'; import { ApiNameMixin } from './ApiNameMixin'; import { DeserializerContext } from '../model/DeserializerContext'; @@ -100,8 +100,10 @@ export interface ApiItemContainerMixin extends ApiItem { * * @public */ -export function ApiItemContainerMixin(baseClass: TBaseClass): - TBaseClass & (new (...args: any[]) => ApiItemContainerMixin) { // eslint-disable-line @typescript-eslint/no-explicit-any +export function ApiItemContainerMixin( + baseClass: TBaseClass +): TBaseClass & (new (...args: any[]) => ApiItemContainerMixin) { + // eslint-disable-line @typescript-eslint/no-explicit-any abstract class MixedClass extends baseClass implements ApiItemContainerMixin { public readonly [_members]: ApiItem[]; @@ -114,7 +116,7 @@ export function ApiItemContainerMixin(ba // For members of this container that do NOT extend ApiNameMixin, this stores the list of members // that share a common ApiItemKind. Examples include overloaded constructors or index signatures. - public [_membersByKind]: Map | undefined; // key is ApiItemKind + public [_membersByKind]: Map | undefined; // key is ApiItemKind // eslint-disable-next-line @typescript-eslint/no-explicit-any public constructor(...args: any[]) { @@ -132,9 +134,11 @@ export function ApiItemContainerMixin(ba } /** @override */ - public static onDeserializeInto(options: Partial, - context: DeserializerContext, jsonObject: IApiItemContainerJson): void { - + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiItemContainerJson + ): void { baseClass.onDeserializeInto(options, context, jsonObject); options.members = []; @@ -154,13 +158,17 @@ export function ApiItemContainerMixin(ba public addMember(member: ApiItem): void { if (this[_membersByContainerKey].has(member.containerKey)) { - throw new Error(`Another member has already been added with the same name (${member.displayName})` + - ` and containerKey (${member.containerKey})`); + throw new Error( + `Another member has already been added with the same name (${member.displayName})` + + ` and containerKey (${member.containerKey})` + ); } const existingParent: ApiItem | undefined = member.parent; if (existingParent !== undefined) { - throw new Error(`This item has already been added to another container: "${existingParent.displayName}"`); + throw new Error( + `This item has already been added to another container: "${existingParent.displayName}"` + ); } this[_members].push(member); diff --git a/apps/api-extractor-model/src/mixins/ApiNameMixin.ts b/apps/api-extractor-model/src/mixins/ApiNameMixin.ts index 840bb43b7c8..499154cb511 100644 --- a/apps/api-extractor-model/src/mixins/ApiNameMixin.ts +++ b/apps/api-extractor-model/src/mixins/ApiNameMixin.ts @@ -56,8 +56,10 @@ export interface ApiNameMixin extends ApiItem { * * @public */ -export function ApiNameMixin(baseClass: TBaseClass): - TBaseClass & (new (...args: any[]) => ApiNameMixin) { // eslint-disable-line @typescript-eslint/no-explicit-any +export function ApiNameMixin( + baseClass: TBaseClass +): TBaseClass & (new (...args: any[]) => ApiNameMixin) { + // eslint-disable-line @typescript-eslint/no-explicit-any abstract class MixedClass extends baseClass implements ApiNameMixin { public readonly [_name]: string; @@ -71,9 +73,11 @@ export function ApiNameMixin(baseClass: } /** @override */ - public static onDeserializeInto(options: Partial, context: DeserializerContext, - jsonObject: IApiNameMixinJson): void { - + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiNameMixinJson + ): void { baseClass.onDeserializeInto(options, context, jsonObject); options.name = jsonObject.name; diff --git a/apps/api-extractor-model/src/mixins/ApiParameterListMixin.ts b/apps/api-extractor-model/src/mixins/ApiParameterListMixin.ts index b29c1f097f2..4af940fb17a 100644 --- a/apps/api-extractor-model/src/mixins/ApiParameterListMixin.ts +++ b/apps/api-extractor-model/src/mixins/ApiParameterListMixin.ts @@ -96,8 +96,10 @@ export interface ApiParameterListMixin extends ApiItem { * * @public */ -export function ApiParameterListMixin(baseClass: TBaseClass): - TBaseClass & (new (...args: any[]) => ApiParameterListMixin) { // eslint-disable-line @typescript-eslint/no-explicit-any +export function ApiParameterListMixin( + baseClass: TBaseClass +): TBaseClass & (new (...args: any[]) => ApiParameterListMixin) { + // eslint-disable-line @typescript-eslint/no-explicit-any abstract class MixedClass extends baseClass implements ApiParameterListMixin { public readonly [_overloadIndex]: number; @@ -115,11 +117,10 @@ export function ApiParameterListMixin(ba if (this instanceof ApiDeclaredItem) { if (options.parameters) { for (const parameterOptions of options.parameters) { - const parameter: Parameter = new Parameter({ name: parameterOptions.parameterName, parameterTypeExcerpt: this.buildExcerpt(parameterOptions.parameterTypeTokenRange), - parent: this + parent: this, }); this[_parameters].push(parameter); @@ -131,9 +132,11 @@ export function ApiParameterListMixin(ba } /** @override */ - public static onDeserializeInto(options: Partial, context: DeserializerContext, - jsonObject: IApiParameterListJson): void { - + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiParameterListJson + ): void { baseClass.onDeserializeInto(options, context, jsonObject); options.overloadIndex = jsonObject.overloadIndex; @@ -158,7 +161,7 @@ export function ApiParameterListMixin(ba for (const parameter of this.parameters) { parameterObjects.push({ parameterName: parameter.name, - parameterTypeTokenRange: parameter.parameterTypeExcerpt.tokenRange + parameterTypeTokenRange: parameter.parameterTypeExcerpt.tokenRange, }); } diff --git a/apps/api-extractor-model/src/mixins/ApiReleaseTagMixin.ts b/apps/api-extractor-model/src/mixins/ApiReleaseTagMixin.ts index 0326f061841..e8e9088bd1e 100644 --- a/apps/api-extractor-model/src/mixins/ApiReleaseTagMixin.ts +++ b/apps/api-extractor-model/src/mixins/ApiReleaseTagMixin.ts @@ -58,8 +58,10 @@ export interface ApiReleaseTagMixin extends ApiItem { * * @public */ -export function ApiReleaseTagMixin(baseClass: TBaseClass): - TBaseClass & (new (...args: any[]) => ApiReleaseTagMixin) { // eslint-disable-line @typescript-eslint/no-explicit-any +export function ApiReleaseTagMixin( + baseClass: TBaseClass +): TBaseClass & (new (...args: any[]) => ApiReleaseTagMixin) { + // eslint-disable-line @typescript-eslint/no-explicit-any abstract class MixedClass extends baseClass implements ApiReleaseTagMixin { public [_releaseTag]: ReleaseTag; @@ -73,9 +75,11 @@ export function ApiReleaseTagMixin(baseC } /** @override */ - public static onDeserializeInto(options: Partial, context: DeserializerContext, - jsonObject: IApiReleaseTagMixinJson): void { - + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiReleaseTagMixinJson + ): void { baseClass.onDeserializeInto(options, context, jsonObject); const deserializedReleaseTag: ReleaseTag | undefined = ReleaseTag[jsonObject.releaseTag]; diff --git a/apps/api-extractor-model/src/mixins/ApiReturnTypeMixin.ts b/apps/api-extractor-model/src/mixins/ApiReturnTypeMixin.ts index 3c935f5616f..ec8ed6c779e 100644 --- a/apps/api-extractor-model/src/mixins/ApiReturnTypeMixin.ts +++ b/apps/api-extractor-model/src/mixins/ApiReturnTypeMixin.ts @@ -55,8 +55,10 @@ export interface ApiReturnTypeMixin extends ApiItem { * * @public */ -export function ApiReturnTypeMixin(baseClass: TBaseClass): - TBaseClass & (new (...args: any[]) => ApiReturnTypeMixin) { // eslint-disable-line @typescript-eslint/no-explicit-any +export function ApiReturnTypeMixin( + baseClass: TBaseClass +): TBaseClass & (new (...args: any[]) => ApiReturnTypeMixin) { + // eslint-disable-line @typescript-eslint/no-explicit-any abstract class MixedClass extends baseClass implements ApiReturnTypeMixin { public [_returnTypeExcerpt]: Excerpt; @@ -75,9 +77,11 @@ export function ApiReturnTypeMixin(baseC } /** @override */ - public static onDeserializeInto(options: Partial, context: DeserializerContext, - jsonObject: IApiReturnTypeMixinJson): void { - + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiReturnTypeMixinJson + ): void { baseClass.onDeserializeInto(options, context, jsonObject); options.returnTypeTokenRange = jsonObject.returnTypeTokenRange; diff --git a/apps/api-extractor-model/src/mixins/ApiStaticMixin.ts b/apps/api-extractor-model/src/mixins/ApiStaticMixin.ts index 6f18b405631..b764d172551 100644 --- a/apps/api-extractor-model/src/mixins/ApiStaticMixin.ts +++ b/apps/api-extractor-model/src/mixins/ApiStaticMixin.ts @@ -52,8 +52,10 @@ export interface ApiStaticMixin extends ApiItem { * * @public */ -export function ApiStaticMixin(baseClass: TBaseClass): - TBaseClass & (new (...args: any[]) => ApiStaticMixin) { // eslint-disable-line @typescript-eslint/no-explicit-any +export function ApiStaticMixin( + baseClass: TBaseClass +): TBaseClass & (new (...args: any[]) => ApiStaticMixin) { + // eslint-disable-line @typescript-eslint/no-explicit-any abstract class MixedClass extends baseClass implements ApiStaticMixin { public [_isStatic]: boolean; @@ -67,9 +69,11 @@ export function ApiStaticMixin(baseClass } /** @override */ - public static onDeserializeInto(options: Partial, context: DeserializerContext, - jsonObject: IApiStaticMixinJson): void { - + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiStaticMixinJson + ): void { baseClass.onDeserializeInto(options, context, jsonObject); options.isStatic = jsonObject.isStatic; diff --git a/apps/api-extractor-model/src/mixins/ApiTypeParameterListMixin.ts b/apps/api-extractor-model/src/mixins/ApiTypeParameterListMixin.ts index 5c0bd73c96b..fc8bd6fc728 100644 --- a/apps/api-extractor-model/src/mixins/ApiTypeParameterListMixin.ts +++ b/apps/api-extractor-model/src/mixins/ApiTypeParameterListMixin.ts @@ -66,8 +66,10 @@ export interface ApiTypeParameterListMixin extends ApiItem { * * @public */ -export function ApiTypeParameterListMixin(baseClass: TBaseClass): - TBaseClass & (new (...args: any[]) => ApiTypeParameterListMixin) { // eslint-disable-line @typescript-eslint/no-explicit-any +export function ApiTypeParameterListMixin( + baseClass: TBaseClass +): TBaseClass & (new (...args: any[]) => ApiTypeParameterListMixin) { + // eslint-disable-line @typescript-eslint/no-explicit-any abstract class MixedClass extends baseClass implements ApiTypeParameterListMixin { public readonly [_typeParameters]: TypeParameter[]; @@ -83,26 +85,29 @@ export function ApiTypeParameterListMixin, context: DeserializerContext, - jsonObject: IApiTypeParameterListMixinJson): void { - + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiTypeParameterListMixinJson + ): void { baseClass.onDeserializeInto(options, context, jsonObject); options.typeParameters = jsonObject.typeParameters || []; @@ -118,13 +123,11 @@ export function ApiTypeParameterListMixin 0) { diff --git a/apps/api-extractor-model/src/mixins/Excerpt.ts b/apps/api-extractor-model/src/mixins/Excerpt.ts index 24156848bd3..3854d3058b9 100644 --- a/apps/api-extractor-model/src/mixins/Excerpt.ts +++ b/apps/api-extractor-model/src/mixins/Excerpt.ts @@ -14,7 +14,7 @@ export const enum ExcerptTokenKind { /** * A reference to an API declaration */ - Reference = 'Reference' + Reference = 'Reference', } /** @@ -137,8 +137,11 @@ export class Excerpt { this.tokens = tokens; this.tokenRange = tokenRange; - if (this.tokenRange.startIndex < 0 || this.tokenRange.endIndex > this.tokens.length - || this.tokenRange.startIndex > this.tokenRange.endIndex) { + if ( + this.tokenRange.startIndex < 0 || + this.tokenRange.endIndex > this.tokens.length || + this.tokenRange.startIndex > this.tokenRange.endIndex + ) { throw new Error('Invalid token range'); } @@ -150,7 +153,7 @@ export class Excerpt { */ public get text(): string { if (this._text === undefined) { - this._text = this.spannedTokens.map(x => x.text).join(''); + this._text = this.spannedTokens.map((x) => x.text).join(''); } return this._text; } diff --git a/apps/api-extractor-model/src/model/ApiCallSignature.ts b/apps/api-extractor-model/src/model/ApiCallSignature.ts index aadd9e2a41d..d85ad06b7c1 100644 --- a/apps/api-extractor-model/src/model/ApiCallSignature.ts +++ b/apps/api-extractor-model/src/model/ApiCallSignature.ts @@ -7,19 +7,21 @@ import { IApiDeclaredItemOptions, ApiDeclaredItem } from '../items/ApiDeclaredIt import { IApiParameterListMixinOptions, ApiParameterListMixin } from '../mixins/ApiParameterListMixin'; import { IApiReleaseTagMixinOptions, ApiReleaseTagMixin } from '../mixins/ApiReleaseTagMixin'; import { IApiReturnTypeMixinOptions, ApiReturnTypeMixin } from '../mixins/ApiReturnTypeMixin'; -import { IApiTypeParameterListMixinOptions, ApiTypeParameterListMixin } from '../mixins/ApiTypeParameterListMixin'; +import { + IApiTypeParameterListMixinOptions, + ApiTypeParameterListMixin, +} from '../mixins/ApiTypeParameterListMixin'; /** * Constructor options for {@link ApiCallSignature}. * @public */ -export interface IApiCallSignatureOptions extends - IApiTypeParameterListMixinOptions, - IApiParameterListMixinOptions, - IApiReleaseTagMixinOptions, - IApiReturnTypeMixinOptions, - IApiDeclaredItemOptions { -} +export interface IApiCallSignatureOptions + extends IApiTypeParameterListMixinOptions, + IApiParameterListMixinOptions, + IApiReleaseTagMixinOptions, + IApiReturnTypeMixinOptions, + IApiDeclaredItemOptions {} /** * Represents a TypeScript function call signature. @@ -50,9 +52,9 @@ export interface IApiCallSignatureOptions extends * * @public */ -export class ApiCallSignature extends ApiTypeParameterListMixin(ApiParameterListMixin(ApiReleaseTagMixin( - ApiReturnTypeMixin(ApiDeclaredItem)))) { - +export class ApiCallSignature extends ApiTypeParameterListMixin( + ApiParameterListMixin(ApiReleaseTagMixin(ApiReturnTypeMixin(ApiDeclaredItem))) +) { public constructor(options: IApiCallSignatureOptions) { super(options); } @@ -75,10 +77,8 @@ export class ApiCallSignature extends ApiTypeParameterListMixin(ApiParameterList public buildCanonicalReference(): DeclarationReference { const parent: DeclarationReference = this.parent ? this.parent.canonicalReference - // .withMeaning() requires some kind of component - : DeclarationReference.empty().addNavigationStep(Navigation.Members, '(parent)'); - return parent - .withMeaning(Meaning.CallSignature) - .withOverloadIndex(this.overloadIndex); + : // .withMeaning() requires some kind of component + DeclarationReference.empty().addNavigationStep(Navigation.Members, '(parent)'); + return parent.withMeaning(Meaning.CallSignature).withOverloadIndex(this.overloadIndex); } } diff --git a/apps/api-extractor-model/src/model/ApiClass.ts b/apps/api-extractor-model/src/model/ApiClass.ts index 654bb398641..16782a8b18b 100644 --- a/apps/api-extractor-model/src/model/ApiClass.ts +++ b/apps/api-extractor-model/src/model/ApiClass.ts @@ -1,7 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { DeclarationReference, Meaning, Navigation, Component } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; +import { + DeclarationReference, + Meaning, + Navigation, + Component, +} from '@microsoft/tsdoc/lib/beta/DeclarationReference'; import { ApiItemKind } from '../items/ApiItem'; import { ApiDeclaredItem, IApiDeclaredItemOptions, IApiDeclaredItemJson } from '../items/ApiDeclaredItem'; import { ApiItemContainerMixin, IApiItemContainerMixinOptions } from '../mixins/ApiItemContainerMixin'; @@ -9,28 +14,28 @@ import { ApiReleaseTagMixin, IApiReleaseTagMixinOptions } from '../mixins/ApiRel import { IExcerptTokenRange } from '../mixins/Excerpt'; import { HeritageType } from './HeritageType'; import { IApiNameMixinOptions, ApiNameMixin } from '../mixins/ApiNameMixin'; -import { ApiTypeParameterListMixin, IApiTypeParameterListMixinOptions, IApiTypeParameterListMixinJson - } from '../mixins/ApiTypeParameterListMixin'; +import { + ApiTypeParameterListMixin, + IApiTypeParameterListMixinOptions, + IApiTypeParameterListMixinJson, +} from '../mixins/ApiTypeParameterListMixin'; import { DeserializerContext } from './DeserializerContext'; /** * Constructor options for {@link ApiClass}. * @public */ -export interface IApiClassOptions extends - IApiItemContainerMixinOptions, - IApiNameMixinOptions, - IApiReleaseTagMixinOptions, - IApiDeclaredItemOptions, - IApiTypeParameterListMixinOptions { - +export interface IApiClassOptions + extends IApiItemContainerMixinOptions, + IApiNameMixinOptions, + IApiReleaseTagMixinOptions, + IApiDeclaredItemOptions, + IApiTypeParameterListMixinOptions { extendsTokenRange: IExcerptTokenRange | undefined; implementsTokenRanges: IExcerptTokenRange[]; } -export interface IApiClassJson extends - IApiDeclaredItemJson, - IApiTypeParameterListMixinJson { +export interface IApiClassJson extends IApiDeclaredItemJson, IApiTypeParameterListMixinJson { extendsTokenRange?: IExcerptTokenRange; implementsTokenRanges: IExcerptTokenRange[]; } @@ -51,9 +56,9 @@ export interface IApiClassJson extends * * @public */ -export class ApiClass extends ApiItemContainerMixin(ApiNameMixin(ApiTypeParameterListMixin(ApiReleaseTagMixin( - ApiDeclaredItem)))) { - +export class ApiClass extends ApiItemContainerMixin( + ApiNameMixin(ApiTypeParameterListMixin(ApiReleaseTagMixin(ApiDeclaredItem))) +) { /** * The base class that this class inherits from (using the `extends` keyword), or undefined if there is no base class. */ @@ -80,9 +85,11 @@ export class ApiClass extends ApiItemContainerMixin(ApiNameMixin(ApiTypeParamete } /** @override */ - public static onDeserializeInto(options: Partial, context: DeserializerContext, - jsonObject: IApiClassJson): void { - + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiClassJson + ): void { super.onDeserializeInto(options, context, jsonObject); options.extendsTokenRange = jsonObject.extendsTokenRange; @@ -115,7 +122,7 @@ export class ApiClass extends ApiItemContainerMixin(ApiNameMixin(ApiTypeParamete jsonObject.extendsTokenRange = this.extendsType.excerpt.tokenRange; } - jsonObject.implementsTokenRanges = this.implementsTypes.map(x => x.excerpt.tokenRange); + jsonObject.implementsTokenRanges = this.implementsTypes.map((x) => x.excerpt.tokenRange); } /** @beta @override */ diff --git a/apps/api-extractor-model/src/model/ApiConstructSignature.ts b/apps/api-extractor-model/src/model/ApiConstructSignature.ts index 66eb5f2fa08..1f51ab0295d 100644 --- a/apps/api-extractor-model/src/model/ApiConstructSignature.ts +++ b/apps/api-extractor-model/src/model/ApiConstructSignature.ts @@ -7,19 +7,21 @@ import { IApiDeclaredItemOptions, ApiDeclaredItem } from '../items/ApiDeclaredIt import { IApiParameterListMixinOptions, ApiParameterListMixin } from '../mixins/ApiParameterListMixin'; import { IApiReleaseTagMixinOptions, ApiReleaseTagMixin } from '../mixins/ApiReleaseTagMixin'; import { IApiReturnTypeMixinOptions, ApiReturnTypeMixin } from '../mixins/ApiReturnTypeMixin'; -import { ApiTypeParameterListMixin, IApiTypeParameterListMixinOptions } from '../mixins/ApiTypeParameterListMixin'; +import { + ApiTypeParameterListMixin, + IApiTypeParameterListMixinOptions, +} from '../mixins/ApiTypeParameterListMixin'; /** * Constructor options for {@link ApiConstructor}. * @public */ -export interface IApiConstructSignatureOptions extends - IApiTypeParameterListMixinOptions, - IApiParameterListMixinOptions, - IApiReleaseTagMixinOptions, - IApiReturnTypeMixinOptions, - IApiDeclaredItemOptions { -} +export interface IApiConstructSignatureOptions + extends IApiTypeParameterListMixinOptions, + IApiParameterListMixinOptions, + IApiReleaseTagMixinOptions, + IApiReturnTypeMixinOptions, + IApiDeclaredItemOptions {} /** * Represents a TypeScript construct signature that belongs to an `ApiInterface`. @@ -63,9 +65,9 @@ export interface IApiConstructSignatureOptions extends * * @public */ -export class ApiConstructSignature extends ApiTypeParameterListMixin(ApiParameterListMixin(ApiReleaseTagMixin( - ApiReturnTypeMixin(ApiDeclaredItem)))) { - +export class ApiConstructSignature extends ApiTypeParameterListMixin( + ApiParameterListMixin(ApiReleaseTagMixin(ApiReturnTypeMixin(ApiDeclaredItem))) +) { public constructor(options: IApiConstructSignatureOptions) { super(options); } @@ -88,10 +90,8 @@ export class ApiConstructSignature extends ApiTypeParameterListMixin(ApiParamete public buildCanonicalReference(): DeclarationReference { const parent: DeclarationReference = this.parent ? this.parent.canonicalReference - // .withMeaning() requires some kind of component - : DeclarationReference.empty().addNavigationStep(Navigation.Members, '(parent)'); - return parent - .withMeaning(Meaning.ConstructSignature) - .withOverloadIndex(this.overloadIndex); + : // .withMeaning() requires some kind of component + DeclarationReference.empty().addNavigationStep(Navigation.Members, '(parent)'); + return parent.withMeaning(Meaning.ConstructSignature).withOverloadIndex(this.overloadIndex); } } diff --git a/apps/api-extractor-model/src/model/ApiConstructor.ts b/apps/api-extractor-model/src/model/ApiConstructor.ts index ec5a57db401..73500ddeb26 100644 --- a/apps/api-extractor-model/src/model/ApiConstructor.ts +++ b/apps/api-extractor-model/src/model/ApiConstructor.ts @@ -11,11 +11,10 @@ import { IApiReleaseTagMixinOptions, ApiReleaseTagMixin } from '../mixins/ApiRel * Constructor options for {@link ApiConstructor}. * @public */ -export interface IApiConstructorOptions extends - IApiParameterListMixinOptions, - IApiReleaseTagMixinOptions, - IApiDeclaredItemOptions { -} +export interface IApiConstructorOptions + extends IApiParameterListMixinOptions, + IApiReleaseTagMixinOptions, + IApiDeclaredItemOptions {} /** * Represents a TypeScript class constructor declaration that belongs to an `ApiClass`. @@ -45,7 +44,6 @@ export interface IApiConstructorOptions extends * @public */ export class ApiConstructor extends ApiParameterListMixin(ApiReleaseTagMixin(ApiDeclaredItem)) { - public constructor(options: IApiConstructorOptions) { super(options); } @@ -68,10 +66,8 @@ export class ApiConstructor extends ApiParameterListMixin(ApiReleaseTagMixin(Api public buildCanonicalReference(): DeclarationReference { const parent: DeclarationReference = this.parent ? this.parent.canonicalReference - // .withMeaning() requires some kind of component - : DeclarationReference.empty().addNavigationStep(Navigation.Members, '(parent)'); - return parent - .withMeaning(Meaning.Constructor) - .withOverloadIndex(this.overloadIndex); + : // .withMeaning() requires some kind of component + DeclarationReference.empty().addNavigationStep(Navigation.Members, '(parent)'); + return parent.withMeaning(Meaning.Constructor).withOverloadIndex(this.overloadIndex); } } diff --git a/apps/api-extractor-model/src/model/ApiEntryPoint.ts b/apps/api-extractor-model/src/model/ApiEntryPoint.ts index a95b84f47ac..ef68669c203 100644 --- a/apps/api-extractor-model/src/model/ApiEntryPoint.ts +++ b/apps/api-extractor-model/src/model/ApiEntryPoint.ts @@ -11,8 +11,7 @@ import { ApiPackage } from './ApiPackage'; * Constructor options for {@link ApiEntryPoint}. * @public */ -export interface IApiEntryPointOptions extends IApiItemContainerMixinOptions, IApiNameMixinOptions { -} +export interface IApiEntryPointOptions extends IApiItemContainerMixinOptions, IApiNameMixinOptions {} /** * Represents the entry point for an NPM package. @@ -75,7 +74,6 @@ export class ApiEntryPoint extends ApiItemContainerMixin(ApiNameMixin(ApiItem)) /** @beta @override */ public buildCanonicalReference(): DeclarationReference { - if (this.parent instanceof ApiPackage) { return DeclarationReference.package(this.parent.name, this.importPath); } diff --git a/apps/api-extractor-model/src/model/ApiEnum.ts b/apps/api-extractor-model/src/model/ApiEnum.ts index 8e7f07d456f..5bf58757c18 100644 --- a/apps/api-extractor-model/src/model/ApiEnum.ts +++ b/apps/api-extractor-model/src/model/ApiEnum.ts @@ -1,7 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { DeclarationReference, Meaning, Navigation, Component } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; +import { + DeclarationReference, + Meaning, + Navigation, + Component, +} from '@microsoft/tsdoc/lib/beta/DeclarationReference'; import { ApiItemKind } from '../items/ApiItem'; import { ApiDeclaredItem, IApiDeclaredItemOptions } from '../items/ApiDeclaredItem'; import { ApiReleaseTagMixin, IApiReleaseTagMixinOptions } from '../mixins/ApiReleaseTagMixin'; @@ -13,12 +18,11 @@ import { IApiNameMixinOptions, ApiNameMixin } from '../mixins/ApiNameMixin'; * Constructor options for {@link ApiEnum}. * @public */ -export interface IApiEnumOptions extends - IApiItemContainerMixinOptions, - IApiNameMixinOptions, - IApiReleaseTagMixinOptions, - IApiDeclaredItemOptions { -} +export interface IApiEnumOptions + extends IApiItemContainerMixinOptions, + IApiNameMixinOptions, + IApiReleaseTagMixinOptions, + IApiDeclaredItemOptions {} /** * Represents a TypeScript enum declaration. @@ -41,7 +45,6 @@ export interface IApiEnumOptions extends * @public */ export class ApiEnum extends ApiItemContainerMixin(ApiNameMixin(ApiReleaseTagMixin(ApiDeclaredItem))) { - public constructor(options: IApiEnumOptions) { super(options); } diff --git a/apps/api-extractor-model/src/model/ApiEnumMember.ts b/apps/api-extractor-model/src/model/ApiEnumMember.ts index 6c19afc3a5c..ec985d376df 100644 --- a/apps/api-extractor-model/src/model/ApiEnumMember.ts +++ b/apps/api-extractor-model/src/model/ApiEnumMember.ts @@ -1,7 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { DeclarationReference, Meaning, Navigation, Component } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; +import { + DeclarationReference, + Meaning, + Navigation, + Component, +} from '@microsoft/tsdoc/lib/beta/DeclarationReference'; import { ApiItemKind } from '../items/ApiItem'; import { ApiDeclaredItem, IApiDeclaredItemOptions, IApiDeclaredItemJson } from '../items/ApiDeclaredItem'; import { ApiReleaseTagMixin, IApiReleaseTagMixinOptions } from '../mixins/ApiReleaseTagMixin'; @@ -13,11 +18,10 @@ import { DeserializerContext } from './DeserializerContext'; * Constructor options for {@link ApiEnumMember}. * @public */ -export interface IApiEnumMemberOptions extends - IApiNameMixinOptions, - IApiReleaseTagMixinOptions, - IApiDeclaredItemOptions { - +export interface IApiEnumMemberOptions + extends IApiNameMixinOptions, + IApiReleaseTagMixinOptions, + IApiDeclaredItemOptions { initializerTokenRange: IExcerptTokenRange; } @@ -63,9 +67,11 @@ export class ApiEnumMember extends ApiNameMixin(ApiReleaseTagMixin(ApiDeclaredIt } /** @override */ - public static onDeserializeInto(options: Partial, context: DeserializerContext, - jsonObject: IApiEnumMemberJson): void { - + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiEnumMemberJson + ): void { super.onDeserializeInto(options, context, jsonObject); options.initializerTokenRange = jsonObject.initializerTokenRange; diff --git a/apps/api-extractor-model/src/model/ApiFunction.ts b/apps/api-extractor-model/src/model/ApiFunction.ts index 07e872cf261..1bb2d342801 100644 --- a/apps/api-extractor-model/src/model/ApiFunction.ts +++ b/apps/api-extractor-model/src/model/ApiFunction.ts @@ -1,27 +1,34 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { DeclarationReference, Meaning, Navigation, Component } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; +import { + DeclarationReference, + Meaning, + Navigation, + Component, +} from '@microsoft/tsdoc/lib/beta/DeclarationReference'; import { ApiItemKind } from '../items/ApiItem'; import { IApiDeclaredItemOptions, ApiDeclaredItem } from '../items/ApiDeclaredItem'; import { IApiParameterListMixinOptions, ApiParameterListMixin } from '../mixins/ApiParameterListMixin'; import { IApiReleaseTagMixinOptions, ApiReleaseTagMixin } from '../mixins/ApiReleaseTagMixin'; import { IApiReturnTypeMixinOptions, ApiReturnTypeMixin } from '../mixins/ApiReturnTypeMixin'; import { IApiNameMixinOptions, ApiNameMixin } from '../mixins/ApiNameMixin'; -import { IApiTypeParameterListMixinOptions, ApiTypeParameterListMixin } from '../mixins/ApiTypeParameterListMixin'; +import { + IApiTypeParameterListMixinOptions, + ApiTypeParameterListMixin, +} from '../mixins/ApiTypeParameterListMixin'; /** * Constructor options for {@link ApiFunction}. * @public */ -export interface IApiFunctionOptions extends - IApiNameMixinOptions, - IApiTypeParameterListMixinOptions, - IApiParameterListMixinOptions, - IApiReleaseTagMixinOptions, - IApiReturnTypeMixinOptions, - IApiDeclaredItemOptions { -} +export interface IApiFunctionOptions + extends IApiNameMixinOptions, + IApiTypeParameterListMixinOptions, + IApiParameterListMixinOptions, + IApiReleaseTagMixinOptions, + IApiReturnTypeMixinOptions, + IApiDeclaredItemOptions {} /** * Represents a TypeScript function declaration. @@ -44,9 +51,9 @@ export interface IApiFunctionOptions extends * * @public */ -export class ApiFunction extends ApiNameMixin(ApiTypeParameterListMixin(ApiParameterListMixin(ApiReleaseTagMixin( - ApiReturnTypeMixin(ApiDeclaredItem))))) { - +export class ApiFunction extends ApiNameMixin( + ApiTypeParameterListMixin(ApiParameterListMixin(ApiReleaseTagMixin(ApiReturnTypeMixin(ApiDeclaredItem)))) +) { public constructor(options: IApiFunctionOptions) { super(options); } diff --git a/apps/api-extractor-model/src/model/ApiIndexSignature.ts b/apps/api-extractor-model/src/model/ApiIndexSignature.ts index 4fde269fe15..a33d7fbeffd 100644 --- a/apps/api-extractor-model/src/model/ApiIndexSignature.ts +++ b/apps/api-extractor-model/src/model/ApiIndexSignature.ts @@ -12,12 +12,11 @@ import { IApiReturnTypeMixinOptions, ApiReturnTypeMixin } from '../mixins/ApiRet * Constructor options for {@link ApiIndexSignature}. * @public */ -export interface IApiIndexSignatureOptions extends - IApiParameterListMixinOptions, - IApiReleaseTagMixinOptions, - IApiReturnTypeMixinOptions, - IApiDeclaredItemOptions { -} +export interface IApiIndexSignatureOptions + extends IApiParameterListMixinOptions, + IApiReleaseTagMixinOptions, + IApiReturnTypeMixinOptions, + IApiDeclaredItemOptions {} /** * Represents a TypeScript index signature. @@ -41,7 +40,9 @@ export interface IApiIndexSignatureOptions extends * * @public */ -export class ApiIndexSignature extends ApiParameterListMixin(ApiReleaseTagMixin(ApiReturnTypeMixin(ApiDeclaredItem))) { +export class ApiIndexSignature extends ApiParameterListMixin( + ApiReleaseTagMixin(ApiReturnTypeMixin(ApiDeclaredItem)) +) { public constructor(options: IApiIndexSignatureOptions) { super(options); } @@ -64,10 +65,8 @@ export class ApiIndexSignature extends ApiParameterListMixin(ApiReleaseTagMixin( public buildCanonicalReference(): DeclarationReference { const parent: DeclarationReference = this.parent ? this.parent.canonicalReference - // .withMeaning() requires some kind of component - : DeclarationReference.empty().addNavigationStep(Navigation.Members, '(parent)'); - return parent - .withMeaning(Meaning.IndexSignature) - .withOverloadIndex(this.overloadIndex); + : // .withMeaning() requires some kind of component + DeclarationReference.empty().addNavigationStep(Navigation.Members, '(parent)'); + return parent.withMeaning(Meaning.IndexSignature).withOverloadIndex(this.overloadIndex); } } diff --git a/apps/api-extractor-model/src/model/ApiInterface.ts b/apps/api-extractor-model/src/model/ApiInterface.ts index a16eff138a8..7637fe07c7e 100644 --- a/apps/api-extractor-model/src/model/ApiInterface.ts +++ b/apps/api-extractor-model/src/model/ApiInterface.ts @@ -1,40 +1,53 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { DeclarationReference, Meaning, Navigation, Component } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; +import { + DeclarationReference, + Meaning, + Navigation, + Component, +} from '@microsoft/tsdoc/lib/beta/DeclarationReference'; import { ApiItemKind } from '../items/ApiItem'; -import { ApiItemContainerMixin, IApiItemContainerMixinOptions, IApiItemContainerJson - } from '../mixins/ApiItemContainerMixin'; +import { + ApiItemContainerMixin, + IApiItemContainerMixinOptions, + IApiItemContainerJson, +} from '../mixins/ApiItemContainerMixin'; import { ApiDeclaredItem, IApiDeclaredItemOptions, IApiDeclaredItemJson } from '../items/ApiDeclaredItem'; -import { IApiReleaseTagMixinOptions, ApiReleaseTagMixin, IApiReleaseTagMixinJson } from '../mixins/ApiReleaseTagMixin'; +import { + IApiReleaseTagMixinOptions, + ApiReleaseTagMixin, + IApiReleaseTagMixinJson, +} from '../mixins/ApiReleaseTagMixin'; import { IExcerptTokenRange } from '../mixins/Excerpt'; import { HeritageType } from './HeritageType'; import { IApiNameMixinOptions, ApiNameMixin, IApiNameMixinJson } from '../mixins/ApiNameMixin'; -import { IApiTypeParameterListMixinOptions, IApiTypeParameterListMixinJson, ApiTypeParameterListMixin - } from '../mixins/ApiTypeParameterListMixin'; +import { + IApiTypeParameterListMixinOptions, + IApiTypeParameterListMixinJson, + ApiTypeParameterListMixin, +} from '../mixins/ApiTypeParameterListMixin'; import { DeserializerContext } from './DeserializerContext'; /** * Constructor options for {@link ApiInterface}. * @public */ -export interface IApiInterfaceOptions extends - IApiItemContainerMixinOptions, - IApiNameMixinOptions, - IApiTypeParameterListMixinOptions, - IApiReleaseTagMixinOptions, - IApiDeclaredItemOptions { - +export interface IApiInterfaceOptions + extends IApiItemContainerMixinOptions, + IApiNameMixinOptions, + IApiTypeParameterListMixinOptions, + IApiReleaseTagMixinOptions, + IApiDeclaredItemOptions { extendsTokenRanges: IExcerptTokenRange[]; } -export interface IApiInterfaceJson extends - IApiItemContainerJson, - IApiNameMixinJson, - IApiTypeParameterListMixinJson, - IApiReleaseTagMixinJson, - IApiDeclaredItemJson { - +export interface IApiInterfaceJson + extends IApiItemContainerJson, + IApiNameMixinJson, + IApiTypeParameterListMixinJson, + IApiReleaseTagMixinJson, + IApiDeclaredItemJson { extendsTokenRanges: IExcerptTokenRange[]; } @@ -55,9 +68,9 @@ export interface IApiInterfaceJson extends * * @public */ -export class ApiInterface extends ApiItemContainerMixin(ApiNameMixin(ApiTypeParameterListMixin(ApiReleaseTagMixin( - ApiDeclaredItem)))) { - +export class ApiInterface extends ApiItemContainerMixin( + ApiNameMixin(ApiTypeParameterListMixin(ApiReleaseTagMixin(ApiDeclaredItem))) +) { private readonly _extendsTypes: HeritageType[] = []; public constructor(options: IApiInterfaceOptions) { @@ -73,9 +86,11 @@ export class ApiInterface extends ApiItemContainerMixin(ApiNameMixin(ApiTypePara } /** @override */ - public static onDeserializeInto(options: Partial, context: DeserializerContext, - jsonObject: IApiInterfaceJson): void { - + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiInterfaceJson + ): void { super.onDeserializeInto(options, context, jsonObject); options.extendsTokenRanges = jsonObject.extendsTokenRanges; @@ -102,7 +117,7 @@ export class ApiInterface extends ApiItemContainerMixin(ApiNameMixin(ApiTypePara public serializeInto(jsonObject: Partial): void { super.serializeInto(jsonObject); - jsonObject.extendsTokenRanges = this.extendsTypes.map(x => x.excerpt.tokenRange); + jsonObject.extendsTokenRanges = this.extendsTypes.map((x) => x.excerpt.tokenRange); } /** @beta @override */ diff --git a/apps/api-extractor-model/src/model/ApiMethod.ts b/apps/api-extractor-model/src/model/ApiMethod.ts index e241a9cca38..54d49ee769e 100644 --- a/apps/api-extractor-model/src/model/ApiMethod.ts +++ b/apps/api-extractor-model/src/model/ApiMethod.ts @@ -1,7 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { DeclarationReference, Meaning, Navigation, Component } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; +import { + DeclarationReference, + Meaning, + Navigation, + Component, +} from '@microsoft/tsdoc/lib/beta/DeclarationReference'; import { ApiItemKind } from '../items/ApiItem'; import { ApiStaticMixin, IApiStaticMixinOptions } from '../mixins/ApiStaticMixin'; import { IApiDeclaredItemOptions, ApiDeclaredItem } from '../items/ApiDeclaredItem'; @@ -9,21 +14,23 @@ import { IApiParameterListMixinOptions, ApiParameterListMixin } from '../mixins/ import { IApiReleaseTagMixinOptions, ApiReleaseTagMixin } from '../mixins/ApiReleaseTagMixin'; import { ApiReturnTypeMixin, IApiReturnTypeMixinOptions } from '../mixins/ApiReturnTypeMixin'; import { IApiNameMixinOptions, ApiNameMixin } from '../mixins/ApiNameMixin'; -import { ApiTypeParameterListMixin, IApiTypeParameterListMixinOptions } from '../mixins/ApiTypeParameterListMixin'; +import { + ApiTypeParameterListMixin, + IApiTypeParameterListMixinOptions, +} from '../mixins/ApiTypeParameterListMixin'; /** * Constructor options for {@link ApiMethod}. * @public */ -export interface IApiMethodOptions extends - IApiNameMixinOptions, - IApiTypeParameterListMixinOptions, - IApiParameterListMixinOptions, - IApiReleaseTagMixinOptions, - IApiReturnTypeMixinOptions, - IApiStaticMixinOptions, - IApiDeclaredItemOptions { -} +export interface IApiMethodOptions + extends IApiNameMixinOptions, + IApiTypeParameterListMixinOptions, + IApiParameterListMixinOptions, + IApiReleaseTagMixinOptions, + IApiReturnTypeMixinOptions, + IApiStaticMixinOptions, + IApiDeclaredItemOptions {} /** * Represents a TypeScript member function declaration that belongs to an `ApiClass`. @@ -46,9 +53,11 @@ export interface IApiMethodOptions extends * * @public */ -export class ApiMethod extends ApiNameMixin(ApiTypeParameterListMixin(ApiParameterListMixin( - ApiReleaseTagMixin(ApiReturnTypeMixin(ApiStaticMixin(ApiDeclaredItem)))))) { - +export class ApiMethod extends ApiNameMixin( + ApiTypeParameterListMixin( + ApiParameterListMixin(ApiReleaseTagMixin(ApiReturnTypeMixin(ApiStaticMixin(ApiDeclaredItem)))) + ) +) { public constructor(options: IApiMethodOptions) { super(options); } diff --git a/apps/api-extractor-model/src/model/ApiMethodSignature.ts b/apps/api-extractor-model/src/model/ApiMethodSignature.ts index 143f0a48b64..ab5b94cac61 100644 --- a/apps/api-extractor-model/src/model/ApiMethodSignature.ts +++ b/apps/api-extractor-model/src/model/ApiMethodSignature.ts @@ -1,24 +1,31 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { DeclarationReference, Meaning, Navigation, Component } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; +import { + DeclarationReference, + Meaning, + Navigation, + Component, +} from '@microsoft/tsdoc/lib/beta/DeclarationReference'; import { ApiItemKind } from '../items/ApiItem'; import { ApiDeclaredItem, IApiDeclaredItemOptions } from '../items/ApiDeclaredItem'; import { ApiParameterListMixin, IApiParameterListMixinOptions } from '../mixins/ApiParameterListMixin'; import { ApiReleaseTagMixin, IApiReleaseTagMixinOptions } from '../mixins/ApiReleaseTagMixin'; import { IApiReturnTypeMixinOptions, ApiReturnTypeMixin } from '../mixins/ApiReturnTypeMixin'; import { IApiNameMixinOptions, ApiNameMixin } from '../mixins/ApiNameMixin'; -import { IApiTypeParameterListMixinOptions, ApiTypeParameterListMixin } from '../mixins/ApiTypeParameterListMixin'; +import { + IApiTypeParameterListMixinOptions, + ApiTypeParameterListMixin, +} from '../mixins/ApiTypeParameterListMixin'; /** @public */ -export interface IApiMethodSignatureOptions extends - IApiNameMixinOptions, - IApiTypeParameterListMixinOptions, - IApiParameterListMixinOptions, - IApiReleaseTagMixinOptions, - IApiReturnTypeMixinOptions, - IApiDeclaredItemOptions { -} +export interface IApiMethodSignatureOptions + extends IApiNameMixinOptions, + IApiTypeParameterListMixinOptions, + IApiParameterListMixinOptions, + IApiReleaseTagMixinOptions, + IApiReturnTypeMixinOptions, + IApiDeclaredItemOptions {} /** * Represents a TypeScript member function declaration that belongs to an `ApiInterface`. @@ -41,9 +48,9 @@ export interface IApiMethodSignatureOptions extends * * @public */ -export class ApiMethodSignature extends ApiNameMixin(ApiTypeParameterListMixin(ApiParameterListMixin( - ApiReleaseTagMixin(ApiReturnTypeMixin(ApiDeclaredItem))))) { - +export class ApiMethodSignature extends ApiNameMixin( + ApiTypeParameterListMixin(ApiParameterListMixin(ApiReleaseTagMixin(ApiReturnTypeMixin(ApiDeclaredItem)))) +) { public constructor(options: IApiMethodSignatureOptions) { super(options); } diff --git a/apps/api-extractor-model/src/model/ApiModel.ts b/apps/api-extractor-model/src/model/ApiModel.ts index 8ac3b3d26bb..6d16f12f4d5 100644 --- a/apps/api-extractor-model/src/model/ApiModel.ts +++ b/apps/api-extractor-model/src/model/ApiModel.ts @@ -55,7 +55,7 @@ export class ApiModel extends ApiItemContainerMixin(ApiItem) { private _packagesByName: Map | undefined = undefined; private _apiItemsByCanonicalReference: Map | undefined = undefined; public constructor() { - super({ }); + super({}); this._resolver = new ModelReferenceResolver(this); } @@ -157,10 +157,12 @@ export class ApiModel extends ApiItemContainerMixin(ApiItem) { const result: IResolveDeclarationReferenceResult = { resolvedApiItem: undefined, - errorMessage: undefined + errorMessage: undefined, }; - const apiItem: ApiItem | undefined = this._apiItemsByCanonicalReference.get(declarationReference.toString()); + const apiItem: ApiItem | undefined = this._apiItemsByCanonicalReference.get( + declarationReference.toString() + ); if (!apiItem) { result.errorMessage = `${declarationReference.toString()} can not be located`; @@ -171,8 +173,10 @@ export class ApiModel extends ApiItemContainerMixin(ApiItem) { return result; } else { // NOTE: The "instanceof DeclarationReference" test assumes a specific version of the @microsoft/tsdoc package. - throw new Error('The "declarationReference" parameter must be an instance of' - + ' DocDeclarationReference or DeclarationReference'); + throw new Error( + 'The "declarationReference" parameter must be an instance of' + + ' DocDeclarationReference or DeclarationReference' + ); } } diff --git a/apps/api-extractor-model/src/model/ApiNamespace.ts b/apps/api-extractor-model/src/model/ApiNamespace.ts index 6745f00733d..140ea1a033b 100644 --- a/apps/api-extractor-model/src/model/ApiNamespace.ts +++ b/apps/api-extractor-model/src/model/ApiNamespace.ts @@ -1,7 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { DeclarationReference, Meaning, Navigation, Component } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; +import { + DeclarationReference, + Meaning, + Navigation, + Component, +} from '@microsoft/tsdoc/lib/beta/DeclarationReference'; import { ApiItemKind } from '../items/ApiItem'; import { ApiItemContainerMixin, IApiItemContainerMixinOptions } from '../mixins/ApiItemContainerMixin'; import { IApiDeclaredItemOptions, ApiDeclaredItem } from '../items/ApiDeclaredItem'; @@ -12,12 +17,11 @@ import { IApiNameMixinOptions, ApiNameMixin } from '../mixins/ApiNameMixin'; * Constructor options for {@link ApiClass}. * @public */ -export interface IApiNamespaceOptions extends - IApiItemContainerMixinOptions, - IApiNameMixinOptions, - IApiReleaseTagMixinOptions, - IApiDeclaredItemOptions { -} +export interface IApiNamespaceOptions + extends IApiItemContainerMixinOptions, + IApiNameMixinOptions, + IApiReleaseTagMixinOptions, + IApiDeclaredItemOptions {} /** * Represents a TypeScript namespace declaration. @@ -42,7 +46,6 @@ export interface IApiNamespaceOptions extends * @public */ export class ApiNamespace extends ApiItemContainerMixin(ApiNameMixin(ApiReleaseTagMixin(ApiDeclaredItem))) { - public constructor(options: IApiNamespaceOptions) { super(options); } diff --git a/apps/api-extractor-model/src/model/ApiPackage.ts b/apps/api-extractor-model/src/model/ApiPackage.ts index fa6f5255c24..012ea7429e5 100644 --- a/apps/api-extractor-model/src/model/ApiPackage.ts +++ b/apps/api-extractor-model/src/model/ApiPackage.ts @@ -4,7 +4,12 @@ import { DeclarationReference } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; import { ApiItem, ApiItemKind, IApiItemJson } from '../items/ApiItem'; import { ApiItemContainerMixin, IApiItemContainerMixinOptions } from '../mixins/ApiItemContainerMixin'; -import { JsonFile, IJsonFileSaveOptions, PackageJsonLookup, IPackageJson } from '@rushstack/node-core-library'; +import { + JsonFile, + IJsonFileSaveOptions, + PackageJsonLookup, + IPackageJson, +} from '@rushstack/node-core-library'; import { ApiDocumentedItem, IApiDocumentedItemOptions } from '../items/ApiDocumentedItem'; import { ApiEntryPoint } from './ApiEntryPoint'; import { IApiNameMixinOptions, ApiNameMixin } from '../mixins/ApiNameMixin'; @@ -14,11 +19,10 @@ import { DeserializerContext, ApiJsonSchemaVersion } from './DeserializerContext * Constructor options for {@link ApiPackage}. * @public */ -export interface IApiPackageOptions extends - IApiItemContainerMixinOptions, - IApiNameMixinOptions, - IApiDocumentedItemOptions { -} +export interface IApiPackageOptions + extends IApiItemContainerMixinOptions, + IApiNameMixinOptions, + IApiDocumentedItemOptions {} export interface IApiPackageMetadataJson { /** @@ -101,7 +105,6 @@ export interface IApiPackageSaveOptions extends IJsonFileSaveOptions { * @public */ export class ApiPackage extends ApiItemContainerMixin(ApiNameMixin(ApiDocumentedItem)) { - public constructor(options: IApiPackageOptions) { super(options); } @@ -109,27 +112,31 @@ export class ApiPackage extends ApiItemContainerMixin(ApiNameMixin(ApiDocumented public static loadFromJsonFile(apiJsonFilename: string): ApiPackage { const jsonObject: IApiPackageJson = JsonFile.load(apiJsonFilename); - if (!jsonObject - || !jsonObject.metadata - || typeof jsonObject.metadata.schemaVersion !== 'number') { - throw new Error(`Error loading ${apiJsonFilename}:` - + `\nThe file format is not recognized; the "metadata.schemaVersion" field is missing or invalid`); + if (!jsonObject || !jsonObject.metadata || typeof jsonObject.metadata.schemaVersion !== 'number') { + throw new Error( + `Error loading ${apiJsonFilename}:` + + `\nThe file format is not recognized; the "metadata.schemaVersion" field is missing or invalid` + ); } const schemaVersion: number = jsonObject.metadata.schemaVersion; if (schemaVersion < ApiJsonSchemaVersion.OLDEST_SUPPORTED) { - throw new Error(`Error loading ${apiJsonFilename}:` - + `\nThe file format is version ${schemaVersion},` - + ` whereas ${ApiJsonSchemaVersion.OLDEST_SUPPORTED} is the oldest version supported by this tool`); + throw new Error( + `Error loading ${apiJsonFilename}:` + + `\nThe file format is version ${schemaVersion},` + + ` whereas ${ApiJsonSchemaVersion.OLDEST_SUPPORTED} is the oldest version supported by this tool` + ); } let oldestForwardsCompatibleVersion: number = schemaVersion; if (jsonObject.metadata.oldestForwardsCompatibleVersion) { // Sanity check if (jsonObject.metadata.oldestForwardsCompatibleVersion > schemaVersion) { - throw new Error(`Error loading ${apiJsonFilename}:` - + `\nInvalid file format; "oldestForwardsCompatibleVersion" cannot be newer than "schemaVersion"`); + throw new Error( + `Error loading ${apiJsonFilename}:` + + `\nInvalid file format; "oldestForwardsCompatibleVersion" cannot be newer than "schemaVersion"` + ); } oldestForwardsCompatibleVersion = jsonObject.metadata.oldestForwardsCompatibleVersion; } @@ -142,9 +149,11 @@ export class ApiPackage extends ApiItemContainerMixin(ApiNameMixin(ApiDocumented if (versionToDeserialize > ApiJsonSchemaVersion.LATEST) { // Nope, still too new - throw new Error(`Error loading ${apiJsonFilename}:` - + `\nThe file format version ${schemaVersion} was written by a newer release of` - + ` the api-extractor-model library; you may need to upgrade your software`); + throw new Error( + `Error loading ${apiJsonFilename}:` + + `\nThe file format version ${schemaVersion} was written by a newer release of` + + ` the api-extractor-model library; you may need to upgrade your software` + ); } } @@ -152,7 +161,7 @@ export class ApiPackage extends ApiItemContainerMixin(ApiNameMixin(ApiDocumented apiJsonFilename, toolPackage: jsonObject.metadata.toolPackage, toolVersion: jsonObject.metadata.toolVersion, - versionToDeserialize: versionToDeserialize + versionToDeserialize: versionToDeserialize, }); return ApiItem.deserialize(jsonObject, context) as ApiPackage; @@ -199,8 +208,8 @@ export class ApiPackage extends ApiItemContainerMixin(ApiNameMixin(ApiDocumented // the version is bumped. Instead we write a placeholder string. toolVersion: options.testMode ? '[test mode]' : options.toolVersion || packageJson.version, schemaVersion: ApiJsonSchemaVersion.LATEST, - oldestForwardsCompatibleVersion: ApiJsonSchemaVersion.OLDEST_FORWARDS_COMPATIBLE - } + oldestForwardsCompatibleVersion: ApiJsonSchemaVersion.OLDEST_FORWARDS_COMPATIBLE, + }, } as IApiPackageJson; this.serializeInto(jsonObject); JsonFile.save(jsonObject, apiJsonFilename, options); diff --git a/apps/api-extractor-model/src/model/ApiProperty.ts b/apps/api-extractor-model/src/model/ApiProperty.ts index 909a9f815ef..f1e3a0c1c67 100644 --- a/apps/api-extractor-model/src/model/ApiProperty.ts +++ b/apps/api-extractor-model/src/model/ApiProperty.ts @@ -1,7 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { DeclarationReference, Meaning, Navigation, Component } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; +import { + DeclarationReference, + Meaning, + Navigation, + Component, +} from '@microsoft/tsdoc/lib/beta/DeclarationReference'; import { ApiItemKind } from '../items/ApiItem'; import { ApiStaticMixin, IApiStaticMixinOptions } from '../mixins/ApiStaticMixin'; import { ApiPropertyItem, IApiPropertyItemOptions } from '../items/ApiPropertyItem'; @@ -10,9 +15,7 @@ import { ApiPropertyItem, IApiPropertyItemOptions } from '../items/ApiPropertyIt * Constructor options for {@link ApiProperty}. * @public */ -export interface IApiPropertyOptions extends IApiPropertyItemOptions, - IApiStaticMixinOptions { -} +export interface IApiPropertyOptions extends IApiPropertyItemOptions, IApiStaticMixinOptions {} /** * Represents a TypeScript property declaration that belongs to an `ApiClass`. @@ -49,7 +52,6 @@ export interface IApiPropertyOptions extends IApiPropertyItemOptions, * @public */ export class ApiProperty extends ApiStaticMixin(ApiPropertyItem) { - public constructor(options: IApiPropertyOptions) { super(options); } diff --git a/apps/api-extractor-model/src/model/ApiPropertySignature.ts b/apps/api-extractor-model/src/model/ApiPropertySignature.ts index b0f98f63cb0..d34fd1290bb 100644 --- a/apps/api-extractor-model/src/model/ApiPropertySignature.ts +++ b/apps/api-extractor-model/src/model/ApiPropertySignature.ts @@ -1,7 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { DeclarationReference, Meaning, Navigation, Component } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; +import { + DeclarationReference, + Meaning, + Navigation, + Component, +} from '@microsoft/tsdoc/lib/beta/DeclarationReference'; import { ApiItemKind } from '../items/ApiItem'; import { ApiPropertyItem, IApiPropertyItemOptions } from '../items/ApiPropertyItem'; @@ -9,8 +14,7 @@ import { ApiPropertyItem, IApiPropertyItemOptions } from '../items/ApiPropertyIt * Constructor options for {@link ApiPropertySignature}. * @public */ -export interface IApiPropertySignatureOptions extends IApiPropertyItemOptions { -} +export interface IApiPropertySignatureOptions extends IApiPropertyItemOptions {} /** * Represents a TypeScript property declaration that belongs to an `ApiInterface`. @@ -35,7 +39,6 @@ export interface IApiPropertySignatureOptions extends IApiPropertyItemOptions { * @public */ export class ApiPropertySignature extends ApiPropertyItem { - public constructor(options: IApiPropertySignatureOptions) { super(options); } diff --git a/apps/api-extractor-model/src/model/ApiTypeAlias.ts b/apps/api-extractor-model/src/model/ApiTypeAlias.ts index 47e61c354c9..0005393f32e 100644 --- a/apps/api-extractor-model/src/model/ApiTypeAlias.ts +++ b/apps/api-extractor-model/src/model/ApiTypeAlias.ts @@ -1,31 +1,37 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { DeclarationReference, Meaning, Navigation, Component } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; +import { + DeclarationReference, + Meaning, + Navigation, + Component, +} from '@microsoft/tsdoc/lib/beta/DeclarationReference'; import { Excerpt, IExcerptTokenRange } from '../mixins/Excerpt'; import { ApiItemKind } from '../items/ApiItem'; import { ApiDeclaredItem, IApiDeclaredItemOptions, IApiDeclaredItemJson } from '../items/ApiDeclaredItem'; import { ApiReleaseTagMixin, IApiReleaseTagMixinOptions } from '../mixins/ApiReleaseTagMixin'; import { IApiNameMixinOptions, ApiNameMixin } from '../mixins/ApiNameMixin'; -import { ApiTypeParameterListMixin, IApiTypeParameterListMixinOptions, IApiTypeParameterListMixinJson - } from '../mixins/ApiTypeParameterListMixin'; +import { + ApiTypeParameterListMixin, + IApiTypeParameterListMixinOptions, + IApiTypeParameterListMixinJson, +} from '../mixins/ApiTypeParameterListMixin'; import { DeserializerContext } from './DeserializerContext'; /** * Constructor options for {@link ApiTypeAlias}. * @public */ -export interface IApiTypeAliasOptions extends - IApiNameMixinOptions, - IApiReleaseTagMixinOptions, - IApiDeclaredItemOptions, - IApiTypeParameterListMixinOptions { +export interface IApiTypeAliasOptions + extends IApiNameMixinOptions, + IApiReleaseTagMixinOptions, + IApiDeclaredItemOptions, + IApiTypeParameterListMixinOptions { typeTokenRange: IExcerptTokenRange; } -export interface IApiTypeAliasJson extends - IApiDeclaredItemJson, - IApiTypeParameterListMixinJson { +export interface IApiTypeAliasJson extends IApiDeclaredItemJson, IApiTypeParameterListMixinJson { typeTokenRange: IExcerptTokenRange; } @@ -55,7 +61,9 @@ export interface IApiTypeAliasJson extends * * @public */ -export class ApiTypeAlias extends ApiTypeParameterListMixin(ApiNameMixin(ApiReleaseTagMixin(ApiDeclaredItem))) { +export class ApiTypeAlias extends ApiTypeParameterListMixin( + ApiNameMixin(ApiReleaseTagMixin(ApiDeclaredItem)) +) { /** * An {@link Excerpt} that describes the type of the alias. * @@ -76,9 +84,11 @@ export class ApiTypeAlias extends ApiTypeParameterListMixin(ApiNameMixin(ApiRele } /** @override */ - public static onDeserializeInto(options: Partial, context: DeserializerContext, - jsonObject: IApiTypeAliasJson): void { - + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiTypeAliasJson + ): void { super.onDeserializeInto(options, context, jsonObject); options.typeTokenRange = jsonObject.typeTokenRange; diff --git a/apps/api-extractor-model/src/model/ApiVariable.ts b/apps/api-extractor-model/src/model/ApiVariable.ts index d2323611a29..45735ae92f3 100644 --- a/apps/api-extractor-model/src/model/ApiVariable.ts +++ b/apps/api-extractor-model/src/model/ApiVariable.ts @@ -1,7 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { DeclarationReference, Meaning, Navigation, Component } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; +import { + DeclarationReference, + Meaning, + Navigation, + Component, +} from '@microsoft/tsdoc/lib/beta/DeclarationReference'; import { ApiItemKind } from '../items/ApiItem'; import { ApiDeclaredItem, IApiDeclaredItemOptions, IApiDeclaredItemJson } from '../items/ApiDeclaredItem'; import { ApiReleaseTagMixin, IApiReleaseTagMixinOptions } from '../mixins/ApiReleaseTagMixin'; @@ -13,11 +18,10 @@ import { DeserializerContext } from './DeserializerContext'; * Constructor options for {@link ApiVariable}. * @public */ -export interface IApiVariableOptions extends - IApiNameMixinOptions, - IApiReleaseTagMixinOptions, - IApiDeclaredItemOptions { - +export interface IApiVariableOptions + extends IApiNameMixinOptions, + IApiReleaseTagMixinOptions, + IApiDeclaredItemOptions { variableTypeTokenRange: IExcerptTokenRange; } @@ -58,9 +62,11 @@ export class ApiVariable extends ApiNameMixin(ApiReleaseTagMixin(ApiDeclaredItem } /** @override */ - public static onDeserializeInto(options: Partial, context: DeserializerContext, - jsonObject: IApiVariableJson): void { - + public static onDeserializeInto( + options: Partial, + context: DeserializerContext, + jsonObject: IApiVariableJson + ): void { super.onDeserializeInto(options, context, jsonObject); options.variableTypeTokenRange = jsonObject.variableTypeTokenRange; diff --git a/apps/api-extractor-model/src/model/Deserializer.ts b/apps/api-extractor-model/src/model/Deserializer.ts index 50a22c0146f..76ac908ec30 100644 --- a/apps/api-extractor-model/src/model/Deserializer.ts +++ b/apps/api-extractor-model/src/model/Deserializer.ts @@ -27,7 +27,7 @@ import { DeserializerContext } from './DeserializerContext'; export class Deserializer { public static deserialize(context: DeserializerContext, jsonObject: IApiItemJson): ApiItem { - const options: Partial = { }; + const options: Partial = {}; switch (jsonObject.kind) { case ApiItemKind.Class: diff --git a/apps/api-extractor-model/src/model/DeserializerContext.ts b/apps/api-extractor-model/src/model/DeserializerContext.ts index 62fa4f81391..514d1d0586d 100644 --- a/apps/api-extractor-model/src/model/DeserializerContext.ts +++ b/apps/api-extractor-model/src/model/DeserializerContext.ts @@ -48,7 +48,7 @@ export enum ApiJsonSchemaVersion { * if the older library would not be able to deserialize your new file format. Adding a nonessential field * is generally okay. Removing, modifying, or reinterpreting existing fields is NOT safe. */ - OLDEST_FORWARDS_COMPATIBLE = V_1001 + OLDEST_FORWARDS_COMPATIBLE = V_1001, } export class DeserializerContext { diff --git a/apps/api-extractor-model/src/model/ModelReferenceResolver.ts b/apps/api-extractor-model/src/model/ModelReferenceResolver.ts index 49608560616..b45b987f3df 100644 --- a/apps/api-extractor-model/src/model/ModelReferenceResolver.ts +++ b/apps/api-extractor-model/src/model/ModelReferenceResolver.ts @@ -42,12 +42,13 @@ export class ModelReferenceResolver { this._apiModel = apiModel; } - public resolve(declarationReference: DocDeclarationReference, - contextApiItem: ApiItem | undefined): IResolveDeclarationReferenceResult { - + public resolve( + declarationReference: DocDeclarationReference, + contextApiItem: ApiItem | undefined + ): IResolveDeclarationReferenceResult { const result: IResolveDeclarationReferenceResult = { resolvedApiItem: undefined, - errorMessage: undefined + errorMessage: undefined, }; let apiPackage: ApiPackage | undefined = undefined; @@ -66,8 +67,9 @@ export class ModelReferenceResolver { } if (apiPackage === undefined) { - result.errorMessage = `The reference does not include a package name, and the package could not be inferred` - + ` from the context`; + result.errorMessage = + `The reference does not include a package name, and the package could not be inferred` + + ` from the context`; return result; } } @@ -85,7 +87,7 @@ export class ModelReferenceResolver { // Now search for the member reference for (const memberReference of declarationReference.memberReferences) { if (memberReference.memberSymbol !== undefined) { - result.errorMessage = `Symbols are not yet supported in declaration references` ; + result.errorMessage = `Symbols are not yet supported in declaration references`; return result; } @@ -98,14 +100,15 @@ export class ModelReferenceResolver { if (!ApiItemContainerMixin.isBaseClassOf(currentItem)) { // For example, {@link MyClass.myMethod.X} is invalid because methods cannot contain members - result.errorMessage = `Unable to resolve ${JSON.stringify(identifier)} because ${JSON.stringify(currentItem)}` - + ` cannot act as a container`; + result.errorMessage = + `Unable to resolve ${JSON.stringify(identifier)} because ${JSON.stringify(currentItem)}` + + ` cannot act as a container`; return result; } const foundMembers: ReadonlyArray = currentItem.findMembersByName(identifier); if (foundMembers.length === 0) { - result.errorMessage = `The member reference ${JSON.stringify(identifier)} was not found` ; + result.errorMessage = `The member reference ${JSON.stringify(identifier)} was not found`; return result; } if (foundMembers.length > 1) { @@ -122,8 +125,9 @@ export class ModelReferenceResolver { } if (selectedMembers.length === 0) { - result.errorMessage = `An overload for ${JSON.stringify(identifier)} was not found that matches` - + ` the TSDoc selector ":${selectorOverloadIndex}"`; + result.errorMessage = + `An overload for ${JSON.stringify(identifier)} was not found that matches` + + ` the TSDoc selector ":${selectorOverloadIndex}"`; return result; } @@ -134,7 +138,7 @@ export class ModelReferenceResolver { } // TODO: Support other TSDoc selectors - result.errorMessage = `The member reference ${JSON.stringify(identifier)} was ambiguous` ; + result.errorMessage = `The member reference ${JSON.stringify(identifier)} was ambiguous`; return result; } @@ -143,5 +147,4 @@ export class ModelReferenceResolver { result.resolvedApiItem = currentItem; return result; } - } diff --git a/apps/api-extractor-model/src/model/Parameter.ts b/apps/api-extractor-model/src/model/Parameter.ts index 383e895dd0f..c214d7da987 100644 --- a/apps/api-extractor-model/src/model/Parameter.ts +++ b/apps/api-extractor-model/src/model/Parameter.ts @@ -63,5 +63,4 @@ export class Parameter { } } } - } diff --git a/apps/api-extractor-model/src/model/TypeParameter.ts b/apps/api-extractor-model/src/model/TypeParameter.ts index 160caa014d8..365c5025c66 100644 --- a/apps/api-extractor-model/src/model/TypeParameter.ts +++ b/apps/api-extractor-model/src/model/TypeParameter.ts @@ -97,5 +97,4 @@ export class TypeParameter { } } } - } diff --git a/apps/api-extractor-model/tsconfig.json b/apps/api-extractor-model/tsconfig.json index 824a88b71e5..46bc07fdda9 100644 --- a/apps/api-extractor-model/tsconfig.json +++ b/apps/api-extractor-model/tsconfig.json @@ -2,9 +2,6 @@ "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "jest", - "node" - ] + "types": ["jest", "node"] } } diff --git a/apps/api-extractor/.eslintrc.js b/apps/api-extractor/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/apps/api-extractor/.eslintrc.js +++ b/apps/api-extractor/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/apps/api-extractor/config/api-extractor.json b/apps/api-extractor/config/api-extractor.json index 3e8571b570b..aa9d8f810fd 100644 --- a/apps/api-extractor/config/api-extractor.json +++ b/apps/api-extractor/config/api-extractor.json @@ -15,6 +15,6 @@ "dtsRollup": { "enabled": true, - "untrimmedFilePath": "/dist/rollup.d.ts", + "untrimmedFilePath": "/dist/rollup.d.ts" } } diff --git a/apps/api-extractor/config/jest.json b/apps/api-extractor/config/jest.json index b4a7ec97a56..902b00ea176 100644 --- a/apps/api-extractor/config/jest.json +++ b/apps/api-extractor/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": true -} \ No newline at end of file +} diff --git a/apps/api-extractor/src/aedoc/PackageDocComment.ts b/apps/api-extractor/src/aedoc/PackageDocComment.ts index c6bc4360ef0..ea0ea4d9def 100644 --- a/apps/api-extractor/src/aedoc/PackageDocComment.ts +++ b/apps/api-extractor/src/aedoc/PackageDocComment.ts @@ -9,9 +9,10 @@ export class PackageDocComment { /** * For the given source file, see if it starts with a TSDoc comment containing the `@packageDocumentation` tag. */ - public static tryFindInSourceFile(sourceFile: ts.SourceFile, - collector: Collector): ts.TextRange | undefined { - + public static tryFindInSourceFile( + sourceFile: ts.SourceFile, + collector: Collector + ): ts.TextRange | undefined { // The @packageDocumentation comment is special because it is not attached to an AST // definition. Instead, it is part of the "trivia" tokens that the compiler treats // as irrelevant white space. @@ -47,8 +48,8 @@ export class PackageDocComment { // wrong place? This sanity check helps people to figure out why there comment isn't working. for (const statement of sourceFile.statements) { const ranges: ts.CommentRange[] = []; - ranges.push(...ts.getLeadingCommentRanges(sourceFile.text, statement.getFullStart()) || []); - ranges.push(...ts.getTrailingCommentRanges(sourceFile.text, statement.getEnd()) || []); + ranges.push(...(ts.getLeadingCommentRanges(sourceFile.text, statement.getFullStart()) || [])); + ranges.push(...(ts.getTrailingCommentRanges(sourceFile.text, statement.getEnd()) || [])); for (const commentRange of ranges) { const commentBody: string = sourceFile.text.substring(commentRange.pos, commentRange.end); @@ -57,7 +58,8 @@ export class PackageDocComment { collector.messageRouter.addAnalyzerIssueForPosition( ExtractorMessageId.MisplacedPackageTag, 'The @packageDocumentation comment must appear at the top of entry point *.d.ts file', - sourceFile, commentRange.pos + sourceFile, + commentRange.pos ); break; } @@ -67,5 +69,4 @@ export class PackageDocComment { return packageCommentRange; } - } diff --git a/apps/api-extractor/src/analyzer/AstDeclaration.ts b/apps/api-extractor/src/analyzer/AstDeclaration.ts index 10e906081ae..c77999a4878 100644 --- a/apps/api-extractor/src/analyzer/AstDeclaration.ts +++ b/apps/api-extractor/src/analyzer/AstDeclaration.ts @@ -238,21 +238,21 @@ export class AstDeclaration { switch (kind) { case ts.SyntaxKind.CallSignature: case ts.SyntaxKind.ClassDeclaration: - case ts.SyntaxKind.ConstructSignature: // Example: "new(x: number): IMyClass" - case ts.SyntaxKind.Constructor: // Example: "constructor(x: number)" + case ts.SyntaxKind.ConstructSignature: // Example: "new(x: number): IMyClass" + case ts.SyntaxKind.Constructor: // Example: "constructor(x: number)" case ts.SyntaxKind.EnumDeclaration: case ts.SyntaxKind.EnumMember: - case ts.SyntaxKind.FunctionDeclaration: // Example: "(x: number): number" + case ts.SyntaxKind.FunctionDeclaration: // Example: "(x: number): number" case ts.SyntaxKind.GetAccessor: case ts.SyntaxKind.SetAccessor: - case ts.SyntaxKind.IndexSignature: // Example: "[key: string]: string" + case ts.SyntaxKind.IndexSignature: // Example: "[key: string]: string" case ts.SyntaxKind.InterfaceDeclaration: case ts.SyntaxKind.MethodDeclaration: case ts.SyntaxKind.MethodSignature: - case ts.SyntaxKind.ModuleDeclaration: // Used for both "module" and "namespace" declarations + case ts.SyntaxKind.ModuleDeclaration: // Used for both "module" and "namespace" declarations case ts.SyntaxKind.PropertyDeclaration: case ts.SyntaxKind.PropertySignature: - case ts.SyntaxKind.TypeAliasDeclaration: // Example: "type Shape = Circle | Square" + case ts.SyntaxKind.TypeAliasDeclaration: // Example: "type Shape = Circle | Square" case ts.SyntaxKind.VariableDeclaration: return true; @@ -268,5 +268,4 @@ export class AstDeclaration { return false; } - } diff --git a/apps/api-extractor/src/analyzer/AstImport.ts b/apps/api-extractor/src/analyzer/AstImport.ts index 7d7a6b5fb7a..b3d9b3dab8f 100644 --- a/apps/api-extractor/src/analyzer/AstImport.ts +++ b/apps/api-extractor/src/analyzer/AstImport.ts @@ -26,7 +26,7 @@ export enum AstImportKind { /** * An import statement such as `import x = require("y");`. */ - EqualsImport + EqualsImport, } /** diff --git a/apps/api-extractor/src/analyzer/AstReferenceResolver.ts b/apps/api-extractor/src/analyzer/AstReferenceResolver.ts index 724f97148d4..475f799d1da 100644 --- a/apps/api-extractor/src/analyzer/AstReferenceResolver.ts +++ b/apps/api-extractor/src/analyzer/AstReferenceResolver.ts @@ -52,8 +52,10 @@ export class AstReferenceResolver { public resolve(declarationReference: tsdoc.DocDeclarationReference): AstDeclaration | ResolverFailure { // Is it referring to the working package? - if (declarationReference.packageName !== undefined - && declarationReference.packageName !== this._workingPackage.name) { + if ( + declarationReference.packageName !== undefined && + declarationReference.packageName !== this._workingPackage.name + ) { return new ResolverFailure('External package references are not supported'); } @@ -63,7 +65,8 @@ export class AstReferenceResolver { } const astModule: AstModule = this._astSymbolTable.fetchAstModuleFromWorkingPackage( - this._workingPackage.entryPointSourceFile); + this._workingPackage.entryPointSourceFile + ); if (declarationReference.memberReferences.length === 0) { return new ResolverFailure('Package references are not supported'); @@ -77,18 +80,25 @@ export class AstReferenceResolver { } const rootAstEntity: AstEntity | undefined = this._astSymbolTable.tryGetExportOfAstModule( - exportName, astModule); + exportName, + astModule + ); if (rootAstEntity === undefined) { - return new ResolverFailure(`The package "${this._workingPackage.name}" does not have an export "${exportName}"`); + return new ResolverFailure( + `The package "${this._workingPackage.name}" does not have an export "${exportName}"` + ); } if (rootAstEntity instanceof AstImport) { return new ResolverFailure('Reexported declarations are not supported'); } - let currentDeclaration: AstDeclaration | ResolverFailure = this._selectDeclaration(rootAstEntity.astDeclarations, - rootMemberReference, rootAstEntity.localName); + let currentDeclaration: AstDeclaration | ResolverFailure = this._selectDeclaration( + rootAstEntity.astDeclarations, + rootMemberReference, + rootAstEntity.localName + ); if (currentDeclaration instanceof ResolverFailure) { return currentDeclaration; @@ -102,13 +112,18 @@ export class AstReferenceResolver { return memberName; } - const matchingChildren: ReadonlyArray = currentDeclaration.findChildrenWithName(memberName); + const matchingChildren: ReadonlyArray = currentDeclaration.findChildrenWithName( + memberName + ); if (matchingChildren.length === 0) { return new ResolverFailure(`No member was found with name "${memberName}"`); } - const selectedDeclaration: AstDeclaration | ResolverFailure = this._selectDeclaration(matchingChildren, - memberReference, memberName); + const selectedDeclaration: AstDeclaration | ResolverFailure = this._selectDeclaration( + matchingChildren, + memberReference, + memberName + ); if (selectedDeclaration instanceof ResolverFailure) { return selectedDeclaration; @@ -130,9 +145,11 @@ export class AstReferenceResolver { return memberReference.memberIdentifier.identifier; } - private _selectDeclaration(astDeclarations: ReadonlyArray, - memberReference: tsdoc.DocMemberReference, astSymbolName: string): AstDeclaration | ResolverFailure { - + private _selectDeclaration( + astDeclarations: ReadonlyArray, + memberReference: tsdoc.DocMemberReference, + astSymbolName: string + ): AstDeclaration | ResolverFailure { const memberSelector: tsdoc.DocMemberSelector | undefined = memberReference.selector; if (memberSelector === undefined) { @@ -141,13 +158,17 @@ export class AstReferenceResolver { } else { // 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); + const nonAncillaryMatch: AstDeclaration | undefined = this._tryDisambiguateAncillaryMatches( + astDeclarations + ); if (nonAncillaryMatch) { return nonAncillaryMatch; } - return new ResolverFailure(`The reference is ambiguous because "${astSymbolName}"` - + ` has more than one declaration; you need to add a TSDoc member reference selector`); + return new ResolverFailure( + `The reference is ambiguous because "${astSymbolName}"` + + ` has more than one declaration; you need to add a TSDoc member reference selector` + ); } } @@ -161,9 +182,11 @@ export class AstReferenceResolver { return new ResolverFailure(`The selector "${memberSelector.selector}" is not a supported selector type`); } - private _selectUsingSystemSelector(astDeclarations: ReadonlyArray, - memberSelector: tsdoc.DocMemberSelector, astSymbolName: string): AstDeclaration | ResolverFailure { - + private _selectUsingSystemSelector( + astDeclarations: ReadonlyArray, + memberSelector: tsdoc.DocMemberSelector, + astSymbolName: string + ): AstDeclaration | ResolverFailure { const selectorName: string = memberSelector.selector; let selectorSyntaxKind: ts.SyntaxKind; @@ -194,10 +217,14 @@ export class AstReferenceResolver { return new ResolverFailure(`Unsupported system selector "${selectorName}"`); } - const matches: AstDeclaration[] = astDeclarations.filter(x => x.declaration.kind === selectorSyntaxKind); + const matches: AstDeclaration[] = astDeclarations.filter( + (x) => x.declaration.kind === selectorSyntaxKind + ); if (matches.length === 0) { - return new ResolverFailure(`A declaration for "${astSymbolName}" was not found that matches the` - + ` TSDoc selector "${selectorName}"`); + return new ResolverFailure( + `A declaration for "${astSymbolName}" was not found that matches the` + + ` TSDoc selector "${selectorName}"` + ); } if (matches.length > 1) { // If we found multiple matches, but the extra ones are all ancillary declarations, @@ -207,15 +234,18 @@ export class AstReferenceResolver { return nonAncillaryMatch; } - return new ResolverFailure(`More than one declaration "${astSymbolName}" matches the` - + ` TSDoc selector "${selectorName}"`); + return new ResolverFailure( + `More than one declaration "${astSymbolName}" matches the` + ` TSDoc selector "${selectorName}"` + ); } return matches[0]; } - private _selectUsingIndexSelector(astDeclarations: ReadonlyArray, - memberSelector: tsdoc.DocMemberSelector, astSymbolName: string): AstDeclaration | ResolverFailure { - + private _selectUsingIndexSelector( + astDeclarations: ReadonlyArray, + memberSelector: tsdoc.DocMemberSelector, + astSymbolName: string + ): AstDeclaration | ResolverFailure { const selectorOverloadIndex: number = parseInt(memberSelector.selector); const matches: AstDeclaration[] = []; @@ -227,8 +257,10 @@ export class AstReferenceResolver { } if (matches.length === 0) { - return new ResolverFailure(`An overload for "${astSymbolName}" was not found that matches the` - + ` TSDoc selector ":${selectorOverloadIndex}"`); + return new ResolverFailure( + `An overload for "${astSymbolName}" was not found that matches the` + + ` TSDoc selector ":${selectorOverloadIndex}"` + ); } if (matches.length > 1) { // If we found multiple matches, but the extra ones are all ancillary declarations, @@ -238,8 +270,10 @@ export class AstReferenceResolver { return nonAncillaryMatch; } - return new ResolverFailure(`More than one declaration for "${astSymbolName}" matches the` - + ` TSDoc selector ":${selectorOverloadIndex}"`); + return new ResolverFailure( + `More than one declaration for "${astSymbolName}" matches the` + + ` TSDoc selector ":${selectorOverloadIndex}"` + ); } return matches[0]; } @@ -248,7 +282,9 @@ 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(matches: ReadonlyArray): AstDeclaration | undefined { + private _tryDisambiguateAncillaryMatches( + matches: ReadonlyArray + ): AstDeclaration | undefined { let result: AstDeclaration | undefined = undefined; for (const match of matches) { diff --git a/apps/api-extractor/src/analyzer/AstSymbolTable.ts b/apps/api-extractor/src/analyzer/AstSymbolTable.ts index d708272ddff..7575fa5d203 100644 --- a/apps/api-extractor/src/analyzer/AstSymbolTable.ts +++ b/apps/api-extractor/src/analyzer/AstSymbolTable.ts @@ -80,32 +80,35 @@ export class AstSymbolTable { /** * A mapping from ts.Declaration --> AstDeclaration */ - private readonly _astDeclarationsByDeclaration: Map - = new Map(); + private 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 _entitiesByIdentifierNode: Map - = new Map(); - - public constructor(program: ts.Program, typeChecker: ts.TypeChecker, packageJsonLookup: PackageJsonLookup, - bundledPackageNames: Set, messageRouter: MessageRouter) { - + private readonly _entitiesByIdentifierNode: Map = new Map< + ts.Identifier, + AstEntity | undefined + >(); + + public constructor( + program: ts.Program, + typeChecker: ts.TypeChecker, + packageJsonLookup: PackageJsonLookup, + bundledPackageNames: Set, + messageRouter: 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, - { - analyze: this.analyze.bind(this), - fetchAstSymbol: this._fetchAstSymbol.bind(this) - } - ); + this._exportAnalyzer = new ExportAnalyzer(this._program, this._typeChecker, bundledPackageNames, { + analyze: this.analyze.bind(this), + fetchAstSymbol: this._fetchAstSymbol.bind(this), + }); this._alreadyWarnedGlobalNames = new Set(); } @@ -172,14 +175,12 @@ export class AstSymbolTable { // get analyzed. rootAstSymbol.forEachDeclarationRecursive((astDeclaration: AstDeclaration) => { for (const referencedAstEntity of astDeclaration.referencedAstEntities) { - // Walk up to the root of the tree, looking for any imports along the way if (referencedAstEntity instanceof AstSymbol) { if (!referencedAstEntity.isExternal) { this.analyze(referencedAstEntity); } } - } }); } @@ -238,7 +239,9 @@ export class AstSymbolTable { public static getLocalNameForSymbol(symbol: ts.Symbol): string { // TypeScript binds well-known ECMAScript symbols like "[Symbol.iterator]" as "__@iterator". // Decode it back into "[Symbol.iterator]". - const wellKnownSymbolName: string | undefined = TypeScriptHelpers.tryDecodeWellKnownSymbolName(symbol.escapedName); + const wellKnownSymbolName: string | undefined = TypeScriptHelpers.tryDecodeWellKnownSymbolName( + symbol.escapedName + ); if (wellKnownSymbolName) { return wellKnownSymbolName; } @@ -311,17 +314,21 @@ export class AstSymbolTable { // Is this a reference to another AstSymbol? case ts.SyntaxKind.TypeReference: // general type references case ts.SyntaxKind.ExpressionWithTypeArguments: // special case for e.g. the "extends" keyword - case ts.SyntaxKind.ComputedPropertyName: // used for EcmaScript "symbols", e.g. "[toPrimitive]". + case ts.SyntaxKind.ComputedPropertyName: // used for EcmaScript "symbols", e.g. "[toPrimitive]". case ts.SyntaxKind.TypeQuery: // represents for "typeof X" as a type { // Sometimes the type reference will involve multiple identifiers, e.g. "a.b.C". // In this case, we only need to worry about importing the first identifier, // so do a depth-first search for it: const identifierNode: ts.Identifier | undefined = TypeScriptHelpers.findFirstChildNode( - node, ts.SyntaxKind.Identifier); + node, + ts.SyntaxKind.Identifier + ); if (identifierNode) { - let referencedAstEntity: AstEntity | undefined = this._entitiesByIdentifierNode.get(identifierNode); + let referencedAstEntity: AstEntity | undefined = this._entitiesByIdentifierNode.get( + identifierNode + ); if (!referencedAstEntity) { const symbol: ts.Symbol | undefined = this._typeChecker.getSymbolAtLocation(identifierNode); if (!symbol) { @@ -354,8 +361,11 @@ export class AstSymbolTable { 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)); + this._messageRouter.logDiagnostic( + `Ignoring reference to global variable "${identifierNode.text}"` + + ` in ` + + SourceFileLocationFormatter.formatDeclaration(identifierNode) + ); } } } else { @@ -364,8 +374,10 @@ export class AstSymbolTable { throw new InternalError(`Unable to follow symbol for "${identifierNode.text}"`); } } else { - referencedAstEntity = this._exportAnalyzer.fetchReferencedAstEntity(symbol, - governingAstDeclaration.astSymbol.isExternal); + referencedAstEntity = this._exportAnalyzer.fetchReferencedAstEntity( + symbol, + governingAstDeclaration.astSymbol.isExternal + ); this._entitiesByIdentifierNode.set(identifierNode, referencedAstEntity); } @@ -388,7 +400,10 @@ export class AstSymbolTable { let referencedAstEntity: AstEntity | undefined = undefined; if (symbol === governingAstDeclaration.astSymbol.followedSymbol) { - referencedAstEntity = this._fetchEntityForIdentifierNode(identifierNode, governingAstDeclaration); + referencedAstEntity = this._fetchEntityForIdentifierNode( + identifierNode, + governingAstDeclaration + ); } this._entitiesByIdentifierNode.set(identifierNode, referencedAstEntity); @@ -398,17 +413,20 @@ export class AstSymbolTable { } // Is this node declaring a new AstSymbol? - const newGoverningAstDeclaration: AstDeclaration | undefined = this._fetchAstDeclaration(node, - governingAstDeclaration.astSymbol.isExternal); + const newGoverningAstDeclaration: AstDeclaration | undefined = this._fetchAstDeclaration( + node, + governingAstDeclaration.astSymbol.isExternal + ); for (const childNode of node.getChildren()) { this._analyzeChildTree(childNode, newGoverningAstDeclaration || governingAstDeclaration); } } - private _fetchEntityForIdentifierNode(identifierNode: ts.Identifier, - governingAstDeclaration: AstDeclaration): AstEntity | undefined { - + private _fetchEntityForIdentifierNode( + identifierNode: ts.Identifier, + governingAstDeclaration: AstDeclaration + ): AstEntity | undefined { let referencedAstEntity: AstEntity | undefined = this._entitiesByIdentifierNode.get(identifierNode); if (!referencedAstEntity) { const symbol: ts.Symbol | undefined = this._typeChecker.getSymbolAtLocation(identifierNode); @@ -416,8 +434,10 @@ export class AstSymbolTable { throw new Error('Symbol not found for identifier: ' + identifierNode.getText()); } - referencedAstEntity = this._exportAnalyzer.fetchReferencedAstEntity(symbol, - governingAstDeclaration.astSymbol.isExternal); + referencedAstEntity = this._exportAnalyzer.fetchReferencedAstEntity( + symbol, + governingAstDeclaration.astSymbol.isExternal + ); this._entitiesByIdentifierNode.set(identifierNode, referencedAstEntity); } @@ -429,8 +449,10 @@ export class AstSymbolTable { return undefined; } - const symbol: ts.Symbol | undefined = TypeScriptHelpers.getSymbolForDeclaration(node as ts.Declaration, - this._typeChecker); + const symbol: ts.Symbol | undefined = TypeScriptHelpers.getSymbolForDeclaration( + node as ts.Declaration, + this._typeChecker + ); if (!symbol) { throw new InternalError('Unable to find symbol for node'); } @@ -439,7 +461,7 @@ export class AstSymbolTable { followedSymbol: symbol, isExternal: isExternal, includeNominalAnalysis: true, - addIfMissing: true + addIfMissing: true, }); if (!astSymbol) { @@ -466,8 +488,11 @@ export class AstSymbolTable { const arbitraryDeclaration: ts.Declaration = followedSymbol.declarations[0]; // eslint-disable-next-line no-bitwise - if (followedSymbol.flags & (ts.SymbolFlags.TypeParameter | ts.SymbolFlags.TypeLiteral | ts.SymbolFlags.Transient) - && !TypeScriptInternals.isLateBoundSymbol(followedSymbol)) { + if ( + followedSymbol.flags & + (ts.SymbolFlags.TypeParameter | ts.SymbolFlags.TypeLiteral | ts.SymbolFlags.Transient) && + !TypeScriptInternals.isLateBoundSymbol(followedSymbol) + ) { return undefined; } @@ -512,9 +537,11 @@ export class AstSymbolTable { if (!nominalAnalysis) { for (const declaration of followedSymbol.declarations || []) { if (!AstDeclaration.isSupportedSyntaxKind(declaration.kind)) { - throw new InternalError(`The "${followedSymbol.name}" symbol has a` - + ` ts.SyntaxKind.${ts.SyntaxKind[declaration.kind]} declaration which is not (yet?)` - + ` supported by API Extractor`); + throw new InternalError( + `The "${followedSymbol.name}" symbol has a` + + ` ts.SyntaxKind.${ts.SyntaxKind[declaration.kind]} declaration which is not (yet?)` + + ` supported by API Extractor` + ); } } @@ -530,28 +557,30 @@ export class AstSymbolTable { // - but P1 and P2 may be different (e.g. merged namespaces containing merged interfaces) // Is there a parent AstSymbol? First we check to see if there is a parent declaration: - const arbitraryParentDeclaration: ts.Node | undefined - = this._tryFindFirstAstDeclarationParent(followedSymbol.declarations[0]); + const arbitraryParentDeclaration: ts.Node | undefined = this._tryFindFirstAstDeclarationParent( + followedSymbol.declarations[0] + ); if (arbitraryParentDeclaration) { const parentSymbol: ts.Symbol = TypeScriptHelpers.getSymbolForDeclaration( arbitraryParentDeclaration as ts.Declaration, - this._typeChecker); + this._typeChecker + ); parentAstSymbol = this._fetchAstSymbol({ followedSymbol: parentSymbol, isExternal: options.isExternal, includeNominalAnalysis: false, - addIfMissing: true + addIfMissing: true, }); if (!parentAstSymbol) { - throw new InternalError('Unable to construct a parent AstSymbol for ' - + followedSymbol.name); + throw new InternalError('Unable to construct a parent AstSymbol for ' + followedSymbol.name); } } } - const localName: string | undefined = options.localName || AstSymbolTable.getLocalNameForSymbol(followedSymbol); + const localName: string | undefined = + options.localName || AstSymbolTable.getLocalNameForSymbol(followedSymbol); astSymbol = new AstSymbol({ followedSymbol: followedSymbol, @@ -559,7 +588,7 @@ export class AstSymbolTable { isExternal: options.isExternal, nominalAnalysis: nominalAnalysis, parentAstSymbol: parentAstSymbol, - rootAstSymbol: parentAstSymbol ? parentAstSymbol.rootAstSymbol : undefined + rootAstSymbol: parentAstSymbol ? parentAstSymbol.rootAstSymbol : undefined, }); this._astSymbolsBySymbol.set(followedSymbol, astSymbol); @@ -567,7 +596,6 @@ export class AstSymbolTable { // Okay, now while creating the declarations we will wire them up to the // their corresponding parent declarations for (const declaration of followedSymbol.declarations || []) { - let parentAstDeclaration: AstDeclaration | undefined = undefined; if (parentAstSymbol) { const parentDeclaration: ts.Node | undefined = this._tryFindFirstAstDeclarationParent(declaration); @@ -583,16 +611,21 @@ export class AstSymbolTable { } const astDeclaration: AstDeclaration = new AstDeclaration({ - declaration, astSymbol, parent: parentAstDeclaration}); + declaration, + astSymbol, + parent: parentAstDeclaration, + }); this._astDeclarationsByDeclaration.set(declaration, astDeclaration); } } if (options.isExternal !== astSymbol.isExternal) { - throw new InternalError(`Cannot assign isExternal=${options.isExternal} for` - + ` the symbol ${astSymbol.localName} because it was previously registered` - + ` with isExternal=${astSymbol.isExternal}`); + throw new InternalError( + `Cannot assign isExternal=${options.isExternal} for` + + ` the symbol ${astSymbol.localName} because it was previously registered` + + ` with isExternal=${astSymbol.isExternal}` + ); } return astSymbol; diff --git a/apps/api-extractor/src/analyzer/ExportAnalyzer.ts b/apps/api-extractor/src/analyzer/ExportAnalyzer.ts index 2d91d250a25..049d3a10889 100644 --- a/apps/api-extractor/src/analyzer/ExportAnalyzer.ts +++ b/apps/api-extractor/src/analyzer/ExportAnalyzer.ts @@ -66,16 +66,19 @@ export class ExportAnalyzer { private readonly _bundledPackageNames: Set; private readonly _astSymbolTable: IAstSymbolTable; - private readonly _astModulesByModuleSymbol: Map - = new Map(); + private readonly _astModulesByModuleSymbol: Map = new Map(); // Used with isImportableAmbientSourceFile() private readonly _importableAmbientSourceFiles: Set = new Set(); private readonly _astImportsByKey: Map = new Map(); - public constructor(program: ts.Program, typeChecker: ts.TypeChecker, bundledPackageNames: Set, - astSymbolTable: IAstSymbolTable) { + public constructor( + program: ts.Program, + typeChecker: ts.TypeChecker, + bundledPackageNames: Set, + astSymbolTable: IAstSymbolTable + ) { this._program = program; this._typeChecker = typeChecker; this._bundledPackageNames = bundledPackageNames; @@ -88,9 +91,10 @@ export class ExportAnalyzer { * @param moduleReference - contextual information about the import statement that took us to this source file. * or `undefined` if this source file is the initial entry point */ - public fetchAstModuleFromSourceFile(sourceFile: ts.SourceFile, - moduleReference: IAstModuleReference | undefined): AstModule { - + public fetchAstModuleFromSourceFile( + sourceFile: ts.SourceFile, + moduleReference: IAstModuleReference | undefined + ): AstModule { const moduleSymbol: ts.Symbol = this._getModuleSymbolFromSourceFile(sourceFile, moduleReference); // Don't traverse into a module that we already processed before: @@ -98,7 +102,6 @@ export class ExportAnalyzer { // even if m2 and m3 both have "export * from 'm4'". 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.) let externalModulePath: string | undefined = undefined; if (moduleReference !== undefined) { @@ -109,19 +112,23 @@ export class ExportAnalyzer { } } - astModule = new AstModule({ sourceFile, moduleSymbol, externalModulePath }); + astModule = new AstModule({ sourceFile, moduleSymbol, externalModulePath }); 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)) { - if (externalModulePath === undefined) { - throw new InternalError('Failed assertion: externalModulePath=undefined but astModule.isExternal=true'); + throw new InternalError( + 'Failed assertion: externalModulePath=undefined but astModule.isExternal=true' + ); } - const followedSymbol: ts.Symbol = TypeScriptHelpers.followAliases(exportedSymbol, this._typeChecker); + const followedSymbol: ts.Symbol = TypeScriptHelpers.followAliases( + exportedSymbol, + this._typeChecker + ); // Ignore virtual symbols that don't have any declarations if (TypeScriptHelpers.hasAnyDeclarations(followedSymbol)) { @@ -129,12 +136,14 @@ export class ExportAnalyzer { followedSymbol: followedSymbol, isExternal: astModule.isExternal, includeNominalAnalysis: true, - addIfMissing: true + addIfMissing: true, }); if (!astSymbol) { - throw new Error(`Unsupported export ${JSON.stringify(exportedSymbol.name)}:\n` - + SourceFileLocationFormatter.formatDeclaration(followedSymbol.declarations[0])); + throw new Error( + `Unsupported export ${JSON.stringify(exportedSymbol.name)}:\n` + + SourceFileLocationFormatter.formatDeclaration(followedSymbol.declarations[0]) + ); } astModule.cachedExportedEntities.set(exportedSymbol.name, astSymbol); @@ -146,13 +155,16 @@ export class ExportAnalyzer { if (moduleSymbol.exports) { // The "export * from 'module-name';" declarations are all attached to a single virtual symbol // whose name is InternalSymbolName.ExportStar - const exportStarSymbol: ts.Symbol | undefined = moduleSymbol.exports.get(ts.InternalSymbolName.ExportStar); + const exportStarSymbol: ts.Symbol | undefined = moduleSymbol.exports.get( + ts.InternalSymbolName.ExportStar + ); if (exportStarSymbol) { for (const exportStarDeclaration of exportStarSymbol.getDeclarations() || []) { if (ts.isExportDeclaration(exportStarDeclaration)) { - - const starExportedModule: AstModule | undefined = this._fetchSpecifierAstModule(exportStarDeclaration, - exportStarSymbol); + const starExportedModule: AstModule | undefined = this._fetchSpecifierAstModule( + exportStarDeclaration, + exportStarSymbol + ); if (starExportedModule !== undefined) { astModule.starExportedModules.add(starExportedModule); @@ -164,7 +176,6 @@ export class ExportAnalyzer { } } } - } } @@ -179,11 +190,14 @@ 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(sourceFile: ts.SourceFile, - moduleReference: IAstModuleReference | undefined): ts.Symbol { - - const moduleSymbol: ts.Symbol | undefined = TypeScriptInternals.tryGetSymbolForDeclaration(sourceFile, - this._typeChecker); + private _getModuleSymbolFromSourceFile( + sourceFile: ts.SourceFile, + moduleReference: IAstModuleReference | undefined + ): ts.Symbol { + const moduleSymbol: ts.Symbol | undefined = TypeScriptInternals.tryGetSymbolForDeclaration( + sourceFile, + this._typeChecker + ); if (moduleSymbol !== undefined) { // This is the normal case. The SourceFile acts is a module and has a symbol. return moduleSymbol; @@ -197,7 +211,9 @@ export class ExportAnalyzer { if ((moduleReference.moduleSpecifierSymbol.flags & ts.SymbolFlags.Alias) !== 0) { // 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); + moduleReference.moduleSpecifierSymbol, + this._typeChecker + ); if (followedSymbol === undefined) { // This is a workaround for a compiler bug where getImmediateAliasedSymbol() sometimes returns undefined @@ -234,8 +250,7 @@ export class ExportAnalyzer { if (entryPointAstModule.astModuleExportInfo === undefined) { const astModuleExportInfo: AstModuleExportInfo = new AstModuleExportInfo(); - this._collectAllExportsRecursive(astModuleExportInfo, entryPointAstModule, - new Set()); + this._collectAllExportsRecursive(astModuleExportInfo, entryPointAstModule, new Set()); entryPointAstModule.astModuleExportInfo = astModuleExportInfo; } @@ -280,9 +295,11 @@ export class ExportAnalyzer { return this._importableAmbientSourceFiles.has(sourceFile); } - private _collectAllExportsRecursive(astModuleExportInfo: AstModuleExportInfo, astModule: AstModule, - visitedAstModules: Set): void { - + private _collectAllExportsRecursive( + astModuleExportInfo: AstModuleExportInfo, + astModule: AstModule, + visitedAstModules: Set + ): void { if (visitedAstModules.has(astModule)) { return; } @@ -327,16 +344,18 @@ export class ExportAnalyzer { * refers to. For example, if a particular interface describes the return value of a function, this API can help * us determine a TSDoc declaration reference for that symbol (if the symbol is exported). */ - public fetchReferencedAstEntity(symbol: ts.Symbol, referringModuleIsExternal: boolean): AstEntity | undefined { + public fetchReferencedAstEntity( + symbol: ts.Symbol, + referringModuleIsExternal: boolean + ): AstEntity | undefined { let current: ts.Symbol = symbol; if (referringModuleIsExternal) { current = TypeScriptHelpers.followAliases(symbol, this._typeChecker); } else { - for (; ;) { + for (;;) { // 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); if (matchedAstEntity !== undefined) { @@ -348,11 +367,15 @@ export class ExportAnalyzer { } } - if (!(current.flags & ts.SymbolFlags.Alias)) { // eslint-disable-line no-bitwise + if (!(current.flags & ts.SymbolFlags.Alias)) { + // eslint-disable-line no-bitwise break; } - const currentAlias: ts.Symbol = TypeScriptInternals.getImmediateAliasedSymbol(current, this._typeChecker); + const currentAlias: ts.Symbol = TypeScriptInternals.getImmediateAliasedSymbol( + current, + this._typeChecker + ); // Stop if we reach the end of the chain if (!currentAlias || currentAlias === current) { break; @@ -367,15 +390,19 @@ export class ExportAnalyzer { followedSymbol: current, isExternal: referringModuleIsExternal, includeNominalAnalysis: false, - addIfMissing: true + addIfMissing: true, }); return astSymbol; } - private _tryMatchExportDeclaration(declaration: ts.Declaration, declarationSymbol: ts.Symbol): AstEntity | undefined { - const exportDeclaration: ts.ExportDeclaration | undefined - = TypeScriptHelpers.findFirstParent(declaration, ts.SyntaxKind.ExportDeclaration); + private _tryMatchExportDeclaration( + declaration: ts.Declaration, + declarationSymbol: ts.Symbol + ): AstEntity | undefined { + const exportDeclaration: ts.ExportDeclaration | undefined = TypeScriptHelpers.findFirstParent< + ts.ExportDeclaration + >(declaration, ts.SyntaxKind.ExportDeclaration); if (exportDeclaration) { let exportName: string | undefined = undefined; @@ -405,14 +432,16 @@ export class ExportAnalyzer { // Ignore "export { A }" without a module specifier if (exportDeclaration.moduleSpecifier) { - const externalModulePath: string | undefined = this._tryGetExternalModulePath(exportDeclaration, - declarationSymbol); + const externalModulePath: string | undefined = this._tryGetExternalModulePath( + exportDeclaration, + declarationSymbol + ); if (externalModulePath !== undefined) { return this._fetchAstImport(declarationSymbol, { importKind: AstImportKind.NamedImport, modulePath: externalModulePath, - exportName: exportName + exportName: exportName, }); } @@ -423,13 +452,19 @@ export class ExportAnalyzer { return undefined; } - private _tryMatchImportDeclaration(declaration: ts.Declaration, declarationSymbol: ts.Symbol): AstEntity | undefined { - const importDeclaration: ts.ImportDeclaration | undefined - = TypeScriptHelpers.findFirstParent(declaration, ts.SyntaxKind.ImportDeclaration); + private _tryMatchImportDeclaration( + declaration: ts.Declaration, + declarationSymbol: ts.Symbol + ): AstEntity | undefined { + const importDeclaration: ts.ImportDeclaration | undefined = TypeScriptHelpers.findFirstParent< + ts.ImportDeclaration + >(declaration, ts.SyntaxKind.ImportDeclaration); if (importDeclaration) { - const externalModulePath: string | undefined = this._tryGetExternalModulePath(importDeclaration, - declarationSymbol); + const externalModulePath: string | undefined = this._tryGetExternalModulePath( + importDeclaration, + declarationSymbol + ); if (declaration.kind === ts.SyntaxKind.NamespaceImport) { // EXAMPLE: @@ -449,8 +484,11 @@ export class ExportAnalyzer { if (externalModulePath === undefined) { // The implementation here only works when importing from an external module. // The full solution is tracked by: https://github.com/microsoft/rushstack/issues/1029 - throw new Error('"import * as ___ from ___;" is not supported yet for local files.' - + '\nFailure in: ' + importDeclaration.getSourceFile().fileName); + throw new Error( + '"import * as ___ from ___;" is not supported yet for local files.' + + '\nFailure in: ' + + importDeclaration.getSourceFile().fileName + ); } // Here importSymbol=undefined because {@inheritDoc} and such are not going to work correctly for @@ -458,7 +496,7 @@ export class ExportAnalyzer { return this._fetchAstImport(undefined, { importKind: AstImportKind.StarImport, exportName: declarationSymbol.name, - modulePath: externalModulePath + modulePath: externalModulePath, }); } @@ -490,7 +528,7 @@ export class ExportAnalyzer { return this._fetchAstImport(declarationSymbol, { importKind: AstImportKind.NamedImport, modulePath: externalModulePath, - exportName: exportName + exportName: exportName, }); } @@ -515,18 +553,23 @@ export class ExportAnalyzer { // SemicolonToken: pre=[;] const importClause: ts.ImportClause = declaration as ts.ImportClause; - const exportName: string = importClause.name ? - importClause.name.getText().trim() : ts.InternalSymbolName.Default; + const exportName: string = importClause.name + ? importClause.name.getText().trim() + : ts.InternalSymbolName.Default; if (externalModulePath !== undefined) { return this._fetchAstImport(declarationSymbol, { importKind: AstImportKind.DefaultImport, modulePath: externalModulePath, - exportName + exportName, }); } - return this._getExportOfSpecifierAstModule(ts.InternalSymbolName.Default, importDeclaration, declarationSymbol); + return this._getExportOfSpecifierAstModule( + ts.InternalSymbolName.Default, + importDeclaration, + declarationSymbol + ); } else { throw new InternalError('Unimplemented import declaration kind: ' + declaration.getText()); } @@ -548,47 +591,58 @@ export class ExportAnalyzer { // SemicolonToken: pre=[;] if (ts.isExternalModuleReference(declaration.moduleReference)) { if (ts.isStringLiteralLike(declaration.moduleReference.expression)) { - const variableName: string = TypeScriptInternals.getTextOfIdentifierOrLiteral( - declaration.name); + const variableName: string = TypeScriptInternals.getTextOfIdentifierOrLiteral(declaration.name); const externalModuleName: string = TypeScriptInternals.getTextOfIdentifierOrLiteral( - declaration.moduleReference.expression); + declaration.moduleReference.expression + ); return this._fetchAstImport(declarationSymbol, { importKind: AstImportKind.EqualsImport, modulePath: externalModuleName, - exportName: variableName + exportName: variableName, }); } } } - const importTypeNode: ts.Node | undefined - = TypeScriptHelpers.findFirstChildNode(declaration, ts.SyntaxKind.ImportType); + const importTypeNode: ts.Node | undefined = TypeScriptHelpers.findFirstChildNode( + declaration, + ts.SyntaxKind.ImportType + ); if (importTypeNode) { - throw new Error('The expression contains an import() type, which is not yet supported by API Extractor:\n' - + SourceFileLocationFormatter.formatDeclaration(importTypeNode)); + throw new Error( + 'The expression contains an import() type, which is not yet supported by API Extractor:\n' + + SourceFileLocationFormatter.formatDeclaration(importTypeNode) + ); } return undefined; } - private _getExportOfSpecifierAstModule(exportName: string, + private _getExportOfSpecifierAstModule( + exportName: string, importOrExportDeclaration: ts.ImportDeclaration | ts.ExportDeclaration, - exportSymbol: ts.Symbol): AstEntity { - - const specifierAstModule: AstModule = this._fetchSpecifierAstModule(importOrExportDeclaration, exportSymbol); + exportSymbol: ts.Symbol + ): AstEntity { + const specifierAstModule: AstModule = this._fetchSpecifierAstModule( + importOrExportDeclaration, + exportSymbol + ); const astEntity: AstEntity = this._getExportOfAstModule(exportName, specifierAstModule); return astEntity; } private _getExportOfAstModule(exportName: string, astModule: AstModule): AstEntity { - const visitedAstModules: Set = new Set(); - const astEntity: AstEntity | undefined = this._tryGetExportOfAstModule(exportName, astModule, - visitedAstModules); + const astEntity: AstEntity | undefined = this._tryGetExportOfAstModule( + exportName, + astModule, + visitedAstModules + ); if (astEntity === undefined) { - throw new InternalError(`Unable to analyze the export ${JSON.stringify(exportName)} in\n` - + astModule.sourceFile.fileName); + throw new InternalError( + `Unable to analyze the export ${JSON.stringify(exportName)} in\n` + astModule.sourceFile.fileName + ); } return astEntity; } @@ -598,13 +652,14 @@ 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(exportName: string, astModule: AstModule, - visitedAstModules: Set): AstEntity | undefined { - + private _tryGetExportOfAstModule( + exportName: string, + astModule: AstModule, + visitedAstModules: Set + ): AstEntity | undefined { if (visitedAstModules.has(astModule)) { return undefined; } @@ -634,14 +689,13 @@ export class ExportAnalyzer { 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, { importKind: AstImportKind.NamedImport, modulePath: starExportedModule.externalModulePath, - exportName: exportName + exportName: exportName, }); } @@ -652,11 +706,14 @@ export class ExportAnalyzer { return undefined; } - private _tryGetExternalModulePath(importOrExportDeclaration: ts.ImportDeclaration | ts.ExportDeclaration, - exportSymbol: ts.Symbol): string | undefined { - - // The name of the module, which could be like "./SomeLocalFile' or like 'external-package/entry/point' - const moduleSpecifier: string | undefined = TypeScriptHelpers.getModuleSpecifier(importOrExportDeclaration); + private _tryGetExternalModulePath( + importOrExportDeclaration: ts.ImportDeclaration | ts.ExportDeclaration, + exportSymbol: ts.Symbol + ): string | undefined { + // The name of the module, which could be like "./SomeLocalFile' or like 'external-package/entry/point' + const moduleSpecifier: string | undefined = TypeScriptHelpers.getModuleSpecifier( + importOrExportDeclaration + ); if (!moduleSpecifier) { throw new InternalError('Unable to parse module specifier'); } @@ -674,38 +731,52 @@ 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(importOrExportDeclaration: ts.ImportDeclaration | ts.ExportDeclaration, - exportSymbol: ts.Symbol): AstModule { - + private _fetchSpecifierAstModule( + importOrExportDeclaration: ts.ImportDeclaration | ts.ExportDeclaration, + exportSymbol: ts.Symbol + ): AstModule { // The name of the module, which could be like "./SomeLocalFile' or like 'external-package/entry/point' - const moduleSpecifier: string | undefined = TypeScriptHelpers.getModuleSpecifier(importOrExportDeclaration); + const moduleSpecifier: string | undefined = TypeScriptHelpers.getModuleSpecifier( + importOrExportDeclaration + ); if (!moduleSpecifier) { throw new InternalError('Unable to parse module specifier'); } const resolvedModule: ts.ResolvedModuleFull | undefined = TypeScriptInternals.getResolvedModule( - importOrExportDeclaration.getSourceFile(), moduleSpecifier); + importOrExportDeclaration.getSourceFile(), + moduleSpecifier + ); if (resolvedModule === undefined) { // This should not happen, since getResolvedModule() specifically looks up names that the compiler // found in export declarations for this source file - throw new InternalError('getResolvedModule() could not resolve module name ' + JSON.stringify(moduleSpecifier)); + throw new InternalError( + 'getResolvedModule() could not resolve module name ' + JSON.stringify(moduleSpecifier) + ); } // 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(resolvedModule.resolvedFileName); + const moduleSourceFile: ts.SourceFile | undefined = this._program.getSourceFile( + resolvedModule.resolvedFileName + ); if (!moduleSourceFile) { // This should not happen, since getResolvedModule() specifically looks up names that the compiler // found in export declarations for this source file - throw new InternalError('getSourceFile() failed to locate ' + JSON.stringify(resolvedModule.resolvedFileName)); + throw new InternalError( + 'getSourceFile() failed to locate ' + JSON.stringify(resolvedModule.resolvedFileName) + ); } const moduleReference: IAstModuleReference = { moduleSpecifier: moduleSpecifier, - moduleSpecifierSymbol: exportSymbol + moduleSpecifierSymbol: exportSymbol, }; - const specifierAstModule: AstModule = this.fetchAstModuleFromSourceFile(moduleSourceFile, moduleReference); + const specifierAstModule: AstModule = this.fetchAstModuleFromSourceFile( + moduleSourceFile, + moduleReference + ); return specifierAstModule; } @@ -726,7 +797,7 @@ export class ExportAnalyzer { followedSymbol: followedSymbol, isExternal: true, includeNominalAnalysis: false, - addIfMissing: true + addIfMissing: true, }); } } diff --git a/apps/api-extractor/src/analyzer/PackageMetadataManager.ts b/apps/api-extractor/src/analyzer/PackageMetadataManager.ts index 8de8edc14cf..8a1e5f844cb 100644 --- a/apps/api-extractor/src/analyzer/PackageMetadataManager.ts +++ b/apps/api-extractor/src/analyzer/PackageMetadataManager.ts @@ -9,7 +9,7 @@ import { JsonFile, NewlineKind, INodePackageJson, - JsonObject + JsonObject, } from '@rushstack/node-core-library'; import { Extractor } from '../api/Extractor'; import { MessageRouter } from '../collector/MessageRouter'; @@ -60,8 +60,10 @@ export class PackageMetadataManager { private readonly _packageJsonLookup: PackageJsonLookup; private readonly _messageRouter: MessageRouter; - private readonly _packageMetadataByPackageJsonPath: Map - = new Map(); + private readonly _packageMetadataByPackageJsonPath: Map = new Map< + string, + PackageMetadata + >(); public constructor(packageJsonLookup: PackageJsonLookup, messageRouter: MessageRouter) { this._packageJsonLookup = packageJsonLookup; @@ -70,9 +72,10 @@ export class PackageMetadataManager { // This feature is still being standardized: https://github.com/microsoft/tsdoc/issues/7 // In the future we will use the @microsoft/tsdoc library to read this file. - private static _resolveTsdocMetadataPathFromPackageJson(packageFolder: string, - packageJson: INodePackageJson): string { - + private static _resolveTsdocMetadataPathFromPackageJson( + packageFolder: string, + packageJson: INodePackageJson + ): string { const tsdocMetadataFilename: string = PackageMetadataManager.tsdocMetadataFilename; let tsdocMetadataRelativePath: string; @@ -85,17 +88,11 @@ export class PackageMetadataManager { } else if (packageJson.typings) { // 2. If package.json contains a field such as "typings": "./path1/path2/index.d.ts", then we look // for the file under "./path1/path2/tsdoc-metadata.json" - tsdocMetadataRelativePath = path.join( - path.dirname(packageJson.typings), - tsdocMetadataFilename - ); + tsdocMetadataRelativePath = path.join(path.dirname(packageJson.typings), tsdocMetadataFilename); } else if (packageJson.main) { // 3. If package.json contains a field such as "main": "./path1/path2/index.js", then we look for // the file under "./path1/path2/tsdoc-metadata.json" - tsdocMetadataRelativePath = path.join( - path.dirname(packageJson.main), - tsdocMetadataFilename - ); + tsdocMetadataRelativePath = path.join(path.dirname(packageJson.main), tsdocMetadataFilename); } else { // 4. If none of the above rules apply, then by default we look for the file under "./tsdoc-metadata.json" // since the default entry point is "./index.js" @@ -103,10 +100,7 @@ export class PackageMetadataManager { } // Always resolve relative to the package folder. - const tsdocMetadataPath: string = path.resolve( - packageFolder, - tsdocMetadataRelativePath - ); + const tsdocMetadataPath: string = path.resolve(packageFolder, tsdocMetadataRelativePath); return tsdocMetadataPath; } @@ -123,10 +117,7 @@ export class PackageMetadataManager { if (tsdocMetadataPath) { return path.resolve(packageFolder, tsdocMetadataPath); } - return PackageMetadataManager._resolveTsdocMetadataPathFromPackageJson( - packageFolder, - packageJson - ); + return PackageMetadataManager._resolveTsdocMetadataPathFromPackageJson(packageFolder, packageJson); } /** @@ -138,9 +129,9 @@ export class PackageMetadataManager { toolPackages: [ { packageName: '@microsoft/api-extractor', - packageVersion: Extractor.version - } - ] + packageVersion: Extractor.version, + }, + ], }; const fileContent: string = @@ -150,7 +141,7 @@ export class PackageMetadataManager { FileSystem.writeFile(tsdocMetadataPath, fileContent, { convertLineEndings: newlineKind, - ensureFolderExists: true + ensureFolderExists: true, }); } @@ -160,13 +151,15 @@ export class PackageMetadataManager { * is returned. The results are cached. */ public tryFetchPackageMetadata(sourceFilePath: string): PackageMetadata | undefined { - const packageJsonFilePath: string | undefined - = this._packageJsonLookup.tryGetPackageJsonFilePathFor(sourceFilePath); + const packageJsonFilePath: string | undefined = this._packageJsonLookup.tryGetPackageJsonFilePathFor( + sourceFilePath + ); if (!packageJsonFilePath) { return undefined; } - let packageMetadata: PackageMetadata | undefined - = this._packageMetadataByPackageJsonPath.get(packageJsonFilePath); + let packageMetadata: PackageMetadata | undefined = this._packageMetadataByPackageJsonPath.get( + packageJsonFilePath + ); if (!packageMetadata) { const packageJson: INodePackageJson = this._packageJsonLookup.loadNodePackageJson(packageJsonFilePath); @@ -181,7 +174,10 @@ export class PackageMetadataManager { ); if (FileSystem.exists(tsdocMetadataPath)) { - this._messageRouter.logVerbose(ConsoleMessageId.FoundTSDocMetadata, 'Found metadata in ' + tsdocMetadataPath); + this._messageRouter.logVerbose( + ConsoleMessageId.FoundTSDocMetadata, + 'Found metadata in ' + tsdocMetadataPath + ); // If the file exists at all, assume it was written by API Extractor aedocSupported = true; } diff --git a/apps/api-extractor/src/analyzer/SourceFileLocationFormatter.ts b/apps/api-extractor/src/analyzer/SourceFileLocationFormatter.ts index b2fab5b5204..55733abe369 100644 --- a/apps/api-extractor/src/analyzer/SourceFileLocationFormatter.ts +++ b/apps/api-extractor/src/analyzer/SourceFileLocationFormatter.ts @@ -8,7 +8,7 @@ import { Path, Text } from '@rushstack/node-core-library'; export interface ISourceFileLocationFormatOptions { sourceFileLine?: number; sourceFileColumn?: number; - workingPackageFolderPath?: string + workingPackageFolderPath?: string; } export class SourceFileLocationFormatter { @@ -23,13 +23,13 @@ export class SourceFileLocationFormatter { return SourceFileLocationFormatter.formatPath(sourceFile.fileName, { sourceFileLine: lineAndCharacter.line + 1, sourceFileColumn: lineAndCharacter.character + 1, - workingPackageFolderPath + workingPackageFolderPath, }); } public static formatPath(sourceFilePath: string, options?: ISourceFileLocationFormatOptions): string { if (!options) { - options = { }; + options = {}; } let result: string = ''; diff --git a/apps/api-extractor/src/analyzer/Span.ts b/apps/api-extractor/src/analyzer/Span.ts index da41839e55e..205af426c75 100644 --- a/apps/api-extractor/src/analyzer/Span.ts +++ b/apps/api-extractor/src/analyzer/Span.ts @@ -359,7 +359,7 @@ export class Span { this._writeModifiedText({ output, - separatorOverride: undefined + separatorOverride: undefined, }); return output.toString(); @@ -368,7 +368,7 @@ export class Span { public writeModifiedText(output: StringBuilder): void { this._writeModifiedText({ output, - separatorOverride: undefined + separatorOverride: undefined, }); } @@ -403,20 +403,18 @@ export class Span { const childCount: number = this.children.length; if (!this.modification.omitChildren) { - if (this.modification.sortChildren && childCount > 1) { // We will only sort the items with a sortKey - const sortedSubset: Span[] = this.children.filter(x => x.modification.sortKey !== undefined); + const sortedSubset: Span[] = this.children.filter((x) => x.modification.sortKey !== undefined); const sortedSubsetCount: number = sortedSubset.length; // Is there at least one of them? if (sortedSubsetCount > 1) { - // Remember the separator for the first and last ones const firstSeparator: string = sortedSubset[0].getLastInnerSeparator(); const lastSeparator: string = sortedSubset[sortedSubsetCount - 1].getLastInnerSeparator(); - Sort.sortBy(sortedSubset, x => x.modification.sortKey); + Sort.sortBy(sortedSubset, (x) => x.modification.sortKey); const childOptions: IWriteModifiedTextOptions = { ...options }; @@ -456,9 +454,9 @@ export class Span { if ( // Only the last child inherits the separatorOverride, because only it can contain // the "last inner separator" span - i < childCount - 1 + i < childCount - 1 || // If this.separator is specified, then we will write separatorOverride below, so don't pass it along - || this.separator + this.separator ) { const childOptions: IWriteModifiedTextOptions = { ...options }; childOptions.separatorOverride = undefined; @@ -508,4 +506,4 @@ export class Span { interface IWriteModifiedTextOptions { output: StringBuilder; separatorOverride: string | undefined; -} \ No newline at end of file +} diff --git a/apps/api-extractor/src/analyzer/StringChecks.ts b/apps/api-extractor/src/analyzer/StringChecks.ts index eec6f81a795..0bad57345c7 100644 --- a/apps/api-extractor/src/analyzer/StringChecks.ts +++ b/apps/api-extractor/src/analyzer/StringChecks.ts @@ -15,16 +15,16 @@ export class StringChecks { * * ```ts * class X { - * public okay: number = 1; - * public "not okay!": number = 2; - * } - * ``` - * - * A precise check is extremely complicated and highly dependent on the ECMAScript standard version - * and how faithfully the interpreter implements it. To keep things simple, `isSafeUnquotedMemberIdentifier()` - * conservatively accepts any identifier that would be valid with ECMAScript 5, and returns false otherwise. - */ - public static isSafeUnquotedMemberIdentifier(identifier: string): boolean { + * public okay: number = 1; + * public "not okay!": number = 2; + * } + * ``` + * + * A precise check is extremely complicated and highly dependent on the ECMAScript standard version + * and how faithfully the interpreter implements it. To keep things simple, `isSafeUnquotedMemberIdentifier()` + * conservatively accepts any identifier that would be valid with ECMAScript 5, and returns false otherwise. + */ + public static isSafeUnquotedMemberIdentifier(identifier: string): boolean { if (identifier.length === 0) { return false; // cannot be empty } diff --git a/apps/api-extractor/src/analyzer/TypeScriptHelpers.ts b/apps/api-extractor/src/analyzer/TypeScriptHelpers.ts index b3759a21878..c9a6a23d777 100644 --- a/apps/api-extractor/src/analyzer/TypeScriptHelpers.ts +++ b/apps/api-extractor/src/analyzer/TypeScriptHelpers.ts @@ -80,8 +80,10 @@ export class TypeScriptHelpers { const firstDeclaration: ts.Declaration = followedSymbol.declarations[0]; // Test 1: Are we inside the sinister "declare global {" construct? - const highestModuleDeclaration: ts.ModuleDeclaration | undefined - = TypeScriptHelpers.findHighestParent(firstDeclaration, ts.SyntaxKind.ModuleDeclaration); + const highestModuleDeclaration: ts.ModuleDeclaration | undefined = TypeScriptHelpers.findHighestParent( + firstDeclaration, + ts.SyntaxKind.ModuleDeclaration + ); if (highestModuleDeclaration) { if (highestModuleDeclaration.name.getText().trim() === 'global') { return true; @@ -106,20 +108,27 @@ export class TypeScriptHelpers { * cannot be found. */ public static getSymbolForDeclaration(declaration: ts.Declaration, checker: ts.TypeChecker): ts.Symbol { - const symbol: ts.Symbol | undefined = TypeScriptInternals.tryGetSymbolForDeclaration(declaration, checker); + const symbol: ts.Symbol | undefined = TypeScriptInternals.tryGetSymbolForDeclaration( + declaration, + checker + ); if (!symbol) { - throw new InternalError('Unable to determine semantic information for declaration:\n' - + SourceFileLocationFormatter.formatDeclaration(declaration)); + throw new InternalError( + 'Unable to determine semantic information for declaration:\n' + + SourceFileLocationFormatter.formatDeclaration(declaration) + ); } return symbol; } // Return name of the module, which could be like "./SomeLocalFile' or like 'external-package/entry/point' - public static getModuleSpecifier(declarationWithModuleSpecifier: ts.ImportDeclaration - | ts.ExportDeclaration): string | undefined { - - if (declarationWithModuleSpecifier.moduleSpecifier - && ts.isStringLiteralLike(declarationWithModuleSpecifier.moduleSpecifier)) { + public static getModuleSpecifier( + declarationWithModuleSpecifier: ts.ImportDeclaration | ts.ExportDeclaration + ): string | undefined { + if ( + declarationWithModuleSpecifier.moduleSpecifier && + ts.isStringLiteralLike(declarationWithModuleSpecifier.moduleSpecifier) + ) { return TypeScriptInternals.getTextOfIdentifierOrLiteral(declarationWithModuleSpecifier.moduleSpecifier); } @@ -139,7 +148,10 @@ export class TypeScriptHelpers { * * Calling _matchAncestor(C, [ExportDeclaration]) would return C. */ - public static matchAncestor(node: ts.Node, kindsToMatch: ts.SyntaxKind[]): T | undefined { + public static matchAncestor( + node: ts.Node, + kindsToMatch: ts.SyntaxKind[] + ): T | undefined { // (slice(0) clones an array) const reversedParentKinds: ts.SyntaxKind[] = kindsToMatch.slice(0).reverse(); @@ -168,7 +180,10 @@ export class TypeScriptHelpers { * Does a depth-first search of the children of the specified node. Returns the first child * with the specified kind, or undefined if there is no match. */ - public static findFirstChildNode(node: ts.Node, kindToMatch: ts.SyntaxKind): T | undefined { + public static findFirstChildNode( + node: ts.Node, + kindToMatch: ts.SyntaxKind + ): T | undefined { for (const child of node.getChildren()) { if (child.kind === kindToMatch) { return child as T; @@ -204,7 +219,10 @@ export class TypeScriptHelpers { * @remarks * Whereas findFirstParent() returns the first match, findHighestParent() returns the last match. */ - public static findHighestParent(node: ts.Node, kindToMatch: ts.SyntaxKind): T | undefined { + public static findHighestParent( + node: ts.Node, + kindToMatch: ts.SyntaxKind + ): T | undefined { let current: ts.Node | undefined = node; let highest: T | undefined = undefined; @@ -249,15 +267,21 @@ export class TypeScriptHelpers { public static tryGetLateBoundName(declarationName: ts.ComputedPropertyName): string | undefined { // Create a node printer that ignores comments and indentation that we can use to convert // declarationName to a string. - const printer: ts.Printer = ts.createPrinter({ removeComments: true }, { - onEmitNode(hint: ts.EmitHint, node: ts.Node | undefined, - emit: (hint: ts.EmitHint, node: ts.Node | undefined) => void): void { - if (node) { - ts.setEmitFlags(declarationName, ts.EmitFlags.NoIndentation | ts.EmitFlags.SingleLine); - } - emit(hint, node); + const printer: ts.Printer = ts.createPrinter( + { removeComments: true }, + { + onEmitNode( + hint: ts.EmitHint, + node: ts.Node | undefined, + emit: (hint: ts.EmitHint, node: ts.Node | undefined) => void + ): void { + if (node) { + ts.setEmitFlags(declarationName, ts.EmitFlags.NoIndentation | ts.EmitFlags.SingleLine); + } + emit(hint, node); + }, } - }); + ); const sourceFile: ts.SourceFile = declarationName.getSourceFile(); const text: string = printer.printNode(ts.EmitHint.Unspecified, declarationName, sourceFile); // clean up any emit flags we've set on any nodes in the tree. diff --git a/apps/api-extractor/src/analyzer/TypeScriptInternals.ts b/apps/api-extractor/src/analyzer/TypeScriptInternals.ts index e177c5c792b..38a4e047bdd 100644 --- a/apps/api-extractor/src/analyzer/TypeScriptInternals.ts +++ b/apps/api-extractor/src/analyzer/TypeScriptInternals.ts @@ -14,7 +14,6 @@ export interface IGlobalVariableAnalyzer { } export class TypeScriptInternals { - public static getImmediateAliasedSymbol(symbol: ts.Symbol, typeChecker: ts.TypeChecker): ts.Symbol { // Compiler internal: // https://github.com/microsoft/TypeScript/blob/v3.2.2/src/compiler/checker.ts @@ -29,12 +28,14 @@ export class TypeScriptInternals { * @returns The associated Symbol. If there is no semantic information (e.g. if the * declaration is an extra semicolon somewhere), then "undefined" is returned. */ - public static tryGetSymbolForDeclaration(declaration: ts.Declaration, checker: ts.TypeChecker): ts.Symbol - | undefined { + public static tryGetSymbolForDeclaration( + declaration: ts.Declaration, + checker: ts.TypeChecker + ): ts.Symbol | undefined { let symbol: ts.Symbol | undefined = (declaration as any).symbol; if (symbol && symbol.escapedName === ts.InternalSymbolName.Computed) { const name: ts.DeclarationName | undefined = ts.getNameOfDeclaration(declaration); - symbol = name && checker.getSymbolAtLocation(name) || symbol; + symbol = (name && checker.getSymbolAtLocation(name)) || symbol; } return symbol; } @@ -45,8 +46,10 @@ export class TypeScriptInternals { */ public static isLateBoundSymbol(symbol: ts.Symbol): boolean { // eslint-disable-next-line no-bitwise - if (symbol.flags & ts.SymbolFlags.Transient && - (symbol as any).checkFlags === (ts as any).CheckFlags.Late) { + if ( + symbol.flags & ts.SymbolFlags.Transient && + (symbol as any).checkFlags === (ts as any).CheckFlags.Late + ) { return true; } return false; @@ -65,7 +68,9 @@ export class TypeScriptInternals { /** * Retrieves the (unescaped) value of an string literal, numeric literal, or identifier. */ - public static getTextOfIdentifierOrLiteral(node: ts.Identifier | ts.StringLiteralLike | ts.NumericLiteral): string { + public static getTextOfIdentifierOrLiteral( + node: ts.Identifier | ts.StringLiteralLike | ts.NumericLiteral + ): string { // Compiler internal: // https://github.com/microsoft/TypeScript/blob/v3.2.2/src/compiler/utilities.ts#L2721 @@ -76,9 +81,10 @@ export class TypeScriptInternals { * Retrieves the (cached) module resolution information for a module name that was exported from a SourceFile. * The compiler populates this cache as part of analyzing the source file. */ - public static getResolvedModule(sourceFile: ts.SourceFile, moduleNameText: string): ts.ResolvedModuleFull - | undefined { - + public static getResolvedModule( + sourceFile: ts.SourceFile, + moduleNameText: string + ): ts.ResolvedModuleFull | undefined { // Compiler internal: // https://github.com/microsoft/TypeScript/blob/v3.2.2/src/compiler/utilities.ts#L218 diff --git a/apps/api-extractor/src/analyzer/test/PackageMetadataManager.test.ts b/apps/api-extractor/src/analyzer/test/PackageMetadataManager.test.ts index 3bb872cb81d..59815374c3c 100644 --- a/apps/api-extractor/src/analyzer/test/PackageMetadataManager.test.ts +++ b/apps/api-extractor/src/analyzer/test/PackageMetadataManager.test.ts @@ -1,4 +1,3 @@ - import * as path from 'path'; import { PackageMetadataManager } from '../PackageMetadataManager'; import { FileSystem, PackageJsonLookup, INodePackageJson, NewlineKind } from '@rushstack/node-core-library'; @@ -9,7 +8,9 @@ function resolveInTestPackage(testPackageName: string, ...args: string[]): strin return path.resolve(__dirname, 'test-data/tsdoc-metadata-path-inference', testPackageName, ...args); } -function getPackageMetadata(testPackageName: string): { packageFolder: string, packageJson: INodePackageJson } { +function getPackageMetadata( + testPackageName: string +): { packageFolder: string; packageJson: INodePackageJson } { const packageFolder: string = resolveInTestPackage(testPackageName); const packageJson: INodePackageJson | undefined = packageJsonLookup.tryLoadPackageJsonFor(packageFolder); if (!packageJson) { @@ -50,42 +51,34 @@ describe('PackageMetadataManager', () => { const tsdocMetadataPath: string = ''; describe('given a package.json where the field "tsdocMetadata" is defined', () => { it('outputs the tsdoc metadata path as given by "tsdocMetadata" relative to the folder of package.json', () => { - const { - packageFolder, - packageJson - } = getPackageMetadata('package-inferred-from-tsdoc-metadata'); - expect(PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath)) - .toBe(path.resolve(packageFolder, packageJson.tsdocMetadata as string)); + const { packageFolder, packageJson } = getPackageMetadata('package-inferred-from-tsdoc-metadata'); + expect( + PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath) + ).toBe(path.resolve(packageFolder, packageJson.tsdocMetadata as string)); }); }); describe('given a package.json where the field "typings" is defined and "tsdocMetadata" is not defined', () => { it('outputs the tsdoc metadata file "tsdoc-metadata.json" in the same folder as the path of "typings"', () => { - const { - packageFolder, - packageJson - } = getPackageMetadata('package-inferred-from-typings'); - expect(PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath)) - .toBe(path.resolve(packageFolder, path.dirname(packageJson.typings!), 'tsdoc-metadata.json')); + const { packageFolder, packageJson } = getPackageMetadata('package-inferred-from-typings'); + expect( + PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath) + ).toBe(path.resolve(packageFolder, path.dirname(packageJson.typings!), 'tsdoc-metadata.json')); }); }); describe('given a package.json where the field "main" is defined but not "typings" nor "tsdocMetadata"', () => { it('outputs the tsdoc metadata file "tsdoc-metadata.json" in the same folder as the path of "main"', () => { - const { - packageFolder, - packageJson - } = getPackageMetadata('package-inferred-from-main'); - expect(PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath)) - .toBe(path.resolve(packageFolder, path.dirname(packageJson.main!), 'tsdoc-metadata.json')); + const { packageFolder, packageJson } = getPackageMetadata('package-inferred-from-main'); + expect( + PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath) + ).toBe(path.resolve(packageFolder, path.dirname(packageJson.main!), 'tsdoc-metadata.json')); }); }); describe('given a package.json where the fields "main", "typings" and "tsdocMetadata" are not defined', () => { it('outputs the tsdoc metadata file "tsdoc-metadata.json" in the folder where package.json is located', () => { - const { - packageFolder, - packageJson - } = getPackageMetadata('package-default'); - expect(PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath)) - .toBe(path.resolve(packageFolder, 'tsdoc-metadata.json')); + const { packageFolder, packageJson } = getPackageMetadata('package-default'); + expect( + PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath) + ).toBe(path.resolve(packageFolder, 'tsdoc-metadata.json')); }); }); }); @@ -93,42 +86,34 @@ describe('PackageMetadataManager', () => { const tsdocMetadataPath: string = 'path/to/custom-tsdoc-metadata.json'; describe('given a package.json where the field "tsdocMetadata" is defined', () => { it('outputs the tsdoc metadata file at the provided path in the folder where package.json is located', () => { - const { - packageFolder, - packageJson - } = getPackageMetadata('package-inferred-from-tsdocMetadata'); - expect(PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath)) - .toBe(path.resolve(packageFolder, tsdocMetadataPath)); + const { packageFolder, packageJson } = getPackageMetadata('package-inferred-from-tsdocMetadata'); + expect( + PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath) + ).toBe(path.resolve(packageFolder, tsdocMetadataPath)); }); }); describe('given a package.json where the field "typings" is defined and "tsdocMetadata" is not defined', () => { it('outputs the tsdoc metadata file at the provided path in the folder where package.json is located', () => { - const { - packageFolder, - packageJson - } = getPackageMetadata('package-inferred-from-typings'); - expect(PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath)) - .toBe(path.resolve(packageFolder, tsdocMetadataPath)); + const { packageFolder, packageJson } = getPackageMetadata('package-inferred-from-typings'); + expect( + PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath) + ).toBe(path.resolve(packageFolder, tsdocMetadataPath)); }); }); describe('given a package.json where the field "main" is defined but not "typings" nor "tsdocMetadata"', () => { it('outputs the tsdoc metadata file at the provided path in the folder where package.json is located', () => { - const { - packageFolder, - packageJson - } = getPackageMetadata('package-inferred-from-main'); - expect(PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath)) - .toBe(path.resolve(packageFolder, tsdocMetadataPath)); + const { packageFolder, packageJson } = getPackageMetadata('package-inferred-from-main'); + expect( + PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath) + ).toBe(path.resolve(packageFolder, tsdocMetadataPath)); }); }); describe('given a package.json where the fields "main", "typings" and "tsdocMetadata" are not defined', () => { it('outputs the tsdoc metadata file at the provided path in the folder where package.json is located', () => { - const { - packageFolder, - packageJson - } = getPackageMetadata('package-default'); - expect(PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath)) - .toBe(path.resolve(packageFolder, tsdocMetadataPath)); + const { packageFolder, packageJson } = getPackageMetadata('package-default'); + expect( + PackageMetadataManager.resolveTsdocMetadataPath(packageFolder, packageJson, tsdocMetadataPath) + ).toBe(path.resolve(packageFolder, tsdocMetadataPath)); }); }); }); diff --git a/apps/api-extractor/src/api/CompilerState.ts b/apps/api-extractor/src/api/CompilerState.ts index e56bff07b8d..4ee0004baf4 100644 --- a/apps/api-extractor/src/api/CompilerState.ts +++ b/apps/api-extractor/src/api/CompilerState.ts @@ -5,9 +5,7 @@ import * as path from 'path'; import * as ts from 'typescript'; import colors = require('colors'); -import { - JsonFile -} from '@rushstack/node-core-library'; +import { JsonFile } from '@rushstack/node-core-library'; import { ExtractorConfig } from './ExtractorConfig'; import { IExtractorInvokeOptions } from './Extractor'; @@ -45,8 +43,10 @@ export class CompilerState { /** * Create a compiler state for use with the specified `IExtractorInvokeOptions`. */ - public static create(extractorConfig: ExtractorConfig, options?: ICompilerStateCreateOptions): CompilerState { - + public static create( + extractorConfig: ExtractorConfig, + options?: ICompilerStateCreateOptions + ): CompilerState { let tsconfig: {} | undefined = extractorConfig.overrideTsconfig; let configBasePath: string = extractorConfig.projectFolder; if (!tsconfig) { @@ -55,18 +55,16 @@ export class CompilerState { configBasePath = path.resolve(path.dirname(extractorConfig.tsconfigFilePath)); } - const commandLine: ts.ParsedCommandLine = ts.parseJsonConfigFileContent( - tsconfig, - ts.sys, - configBasePath - ); + const commandLine: ts.ParsedCommandLine = ts.parseJsonConfigFileContent(tsconfig, ts.sys, configBasePath); if (!commandLine.options.skipLibCheck && extractorConfig.skipLibCheck) { commandLine.options.skipLibCheck = true; - console.log(colors.cyan( - 'API Extractor was invoked with skipLibCheck. This is not recommended and may cause ' + - 'incorrect type analysis.' - )); + console.log( + colors.cyan( + 'API Extractor was invoked with skipLibCheck. This is not recommended and may cause ' + + 'incorrect type analysis.' + ) + ); } const inputFilePaths: string[] = commandLine.fileNames.concat(extractorConfig.mainEntryPointFilePath); @@ -87,11 +85,11 @@ export class CompilerState { } return new CompilerState({ - program + program, }); } - /** + /** * Given a list of absolute file paths, return a list containing only the declaration * files. Duplicates are also eliminated. * @@ -128,9 +126,10 @@ export class CompilerState { return analysisFilePaths; } - private static _createCompilerHost(commandLine: ts.ParsedCommandLine, - options: IExtractorInvokeOptions | undefined): ts.CompilerHost { - + private static _createCompilerHost( + commandLine: ts.ParsedCommandLine, + options: IExtractorInvokeOptions | undefined + ): ts.CompilerHost { // Create a default CompilerHost that we will override const compilerHost: ts.CompilerHost = ts.createCompilerHost(commandLine.options); diff --git a/apps/api-extractor/src/api/ConsoleMessageId.ts b/apps/api-extractor/src/api/ConsoleMessageId.ts index 82d04b07ce7..33b00062212 100644 --- a/apps/api-extractor/src/api/ConsoleMessageId.ts +++ b/apps/api-extractor/src/api/ConsoleMessageId.ts @@ -63,5 +63,5 @@ export const enum ConsoleMessageId { /** * Used for the information printed when the "--diagnostics" flag is enabled. */ - Diagnostics = 'console-diagnostics' + Diagnostics = 'console-diagnostics', } diff --git a/apps/api-extractor/src/api/Extractor.ts b/apps/api-extractor/src/api/Extractor.ts index d25c412babf..d063bcc5fd2 100644 --- a/apps/api-extractor/src/api/Extractor.ts +++ b/apps/api-extractor/src/api/Extractor.ts @@ -3,12 +3,7 @@ import * as path from 'path'; import * as ts from 'typescript'; -import { - FileSystem, - NewlineKind, - PackageJsonLookup, - IPackageJson -} from '@rushstack/node-core-library'; +import { FileSystem, NewlineKind, PackageJsonLookup, IPackageJson } from '@rushstack/node-core-library'; import { ExtractorConfig } from './ExtractorConfig'; import { Collector } from '../collector/Collector'; @@ -171,7 +166,10 @@ export class Extractor { /** * Load the api-extractor.json config file from the specified path, and then invoke API Extractor. */ - public static loadConfigAndInvoke(configFilePath: string, options?: IExtractorInvokeOptions): ExtractorResult { + public static loadConfigAndInvoke( + configFilePath: string, + options?: IExtractorInvokeOptions + ): ExtractorResult { const extractorConfig: ExtractorConfig = ExtractorConfig.loadFileAndPrepare(configFilePath); return Extractor.invoke(extractorConfig, options); @@ -181,9 +179,8 @@ export class Extractor { * Invoke API Extractor using an already prepared `ExtractorConfig` object. */ public static invoke(extractorConfig: ExtractorConfig, options?: IExtractorInvokeOptions): ExtractorResult { - if (!options) { - options = { }; + options = {}; } const localBuild: boolean = options.localBuild || false; @@ -198,9 +195,9 @@ export class Extractor { const messageRouter: MessageRouter = new MessageRouter({ workingPackageFolder: extractorConfig.packageFolder, messageCallback: options.messageCallback, - messagesConfig: extractorConfig.messages || { }, + messagesConfig: extractorConfig.messages || {}, showVerboseMessages: !!options.showVerboseMessages, - showDiagnostics: !!options.showDiagnostics + showDiagnostics: !!options.showDiagnostics, }); if (messageRouter.showDiagnostics) { @@ -209,7 +206,9 @@ export class Extractor { messageRouter.logDiagnosticFooter(); messageRouter.logDiagnosticHeader('Compiler options'); - const serializedOptions: object = MessageRouter.buildJsonDumpObject((compilerState.program as ts.Program).getCompilerOptions()); + const serializedOptions: object = MessageRouter.buildJsonDumpObject( + (compilerState.program as ts.Program).getCompilerOptions() + ); messageRouter.logDiagnostic(JSON.stringify(serializedOptions, undefined, 2)); messageRouter.logDiagnosticFooter(); } @@ -217,7 +216,7 @@ export class Extractor { const collector: Collector = new Collector({ program: compilerState.program as ts.Program, messageRouter, - extractorConfig: extractorConfig + extractorConfig: extractorConfig, }); collector.analyze(); @@ -233,14 +232,17 @@ export class Extractor { } if (extractorConfig.docModelEnabled) { - messageRouter.logVerbose(ConsoleMessageId.WritingDocModelFile, 'Writing: ' + extractorConfig.apiJsonFilePath); + messageRouter.logVerbose( + ConsoleMessageId.WritingDocModelFile, + 'Writing: ' + extractorConfig.apiJsonFilePath + ); apiPackage.saveToJsonFile(extractorConfig.apiJsonFilePath, { toolPackage: Extractor.packageName, toolVersion: Extractor.version, newlineConversion: extractorConfig.newlineKind, ensureFolderExists: true, - testMode: extractorConfig.testMode + testMode: extractorConfig.testMode, }); } @@ -248,47 +250,59 @@ export class Extractor { if (extractorConfig.apiReportEnabled) { const actualApiReportPath: string = extractorConfig.reportTempFilePath; - const actualApiReportShortPath: string = extractorConfig._getShortFilePath(extractorConfig.reportTempFilePath); + const actualApiReportShortPath: string = extractorConfig._getShortFilePath( + extractorConfig.reportTempFilePath + ); const expectedApiReportPath: string = extractorConfig.reportFilePath; - const expectedApiReportShortPath: string = extractorConfig._getShortFilePath(extractorConfig.reportFilePath); + const expectedApiReportShortPath: string = extractorConfig._getShortFilePath( + extractorConfig.reportFilePath + ); const actualApiReportContent: string = ApiReportGenerator.generateReviewFileContent(collector); // Write the actual file FileSystem.writeFile(actualApiReportPath, actualApiReportContent, { ensureFolderExists: true, - convertLineEndings: extractorConfig.newlineKind + convertLineEndings: extractorConfig.newlineKind, }); // Compare it against the expected file if (FileSystem.exists(expectedApiReportPath)) { const expectedApiReportContent: string = FileSystem.readFile(expectedApiReportPath); - if (!ApiReportGenerator.areEquivalentApiFileContents(actualApiReportContent, expectedApiReportContent)) { + if ( + !ApiReportGenerator.areEquivalentApiFileContents(actualApiReportContent, expectedApiReportContent) + ) { apiReportChanged = true; if (!localBuild) { // For a production build, issue a warning that will break the CI build. - messageRouter.logWarning(ConsoleMessageId.ApiReportNotCopied, - 'You have changed the public API signature for this project.' - + ` Please copy the file "${actualApiReportShortPath}" to "${expectedApiReportShortPath}",` - + ` or perform a local build (which does this automatically).` - + ` See the Git repo documentation for more info.`); + messageRouter.logWarning( + ConsoleMessageId.ApiReportNotCopied, + 'You have changed the public API signature for this project.' + + ` Please copy the file "${actualApiReportShortPath}" to "${expectedApiReportShortPath}",` + + ` or perform a local build (which does this automatically).` + + ` See the Git repo documentation for more info.` + ); } else { // For a local build, just copy the file automatically. - messageRouter.logWarning(ConsoleMessageId.ApiReportCopied, - 'You have changed the public API signature for this project.' - + ` Updating ${expectedApiReportShortPath}`); + messageRouter.logWarning( + ConsoleMessageId.ApiReportCopied, + 'You have changed the public API signature for this project.' + + ` Updating ${expectedApiReportShortPath}` + ); FileSystem.writeFile(expectedApiReportPath, actualApiReportContent, { ensureFolderExists: true, - convertLineEndings: extractorConfig.newlineKind + convertLineEndings: extractorConfig.newlineKind, }); } - } else { - messageRouter.logVerbose(ConsoleMessageId.ApiReportUnchanged, - `The API report is up to date: ${actualApiReportShortPath}`); + } else { + messageRouter.logVerbose( + ConsoleMessageId.ApiReportUnchanged, + `The API report is up to date: ${actualApiReportShortPath}` + ); } } else { // The target file does not exist, so we are setting up the API review file for the first time. @@ -300,25 +314,29 @@ export class Extractor { if (!localBuild) { // For a production build, issue a warning that will break the CI build. - messageRouter.logWarning(ConsoleMessageId.ApiReportNotCopied, - 'The API report file is missing.' - + ` Please copy the file "${actualApiReportShortPath}" to "${expectedApiReportShortPath}",` - + ` or perform a local build (which does this automatically).` - + ` See the Git repo documentation for more info.`); + messageRouter.logWarning( + ConsoleMessageId.ApiReportNotCopied, + 'The API report file is missing.' + + ` Please copy the file "${actualApiReportShortPath}" to "${expectedApiReportShortPath}",` + + ` or perform a local build (which does this automatically).` + + ` See the Git repo documentation for more info.` + ); } else { const expectedApiReportFolder: string = path.dirname(expectedApiReportPath); if (!FileSystem.exists(expectedApiReportFolder)) { - messageRouter.logError(ConsoleMessageId.ApiReportFolderMissing, - 'Unable to create the API report file. Please make sure the target folder exists:\n' - + expectedApiReportFolder + messageRouter.logError( + ConsoleMessageId.ApiReportFolderMissing, + 'Unable to create the API report file. Please make sure the target folder exists:\n' + + expectedApiReportFolder ); } else { FileSystem.writeFile(expectedApiReportPath, actualApiReportContent, { - convertLineEndings: extractorConfig.newlineKind + convertLineEndings: extractorConfig.newlineKind, }); - messageRouter.logWarning(ConsoleMessageId.ApiReportCreated, - 'The API report file was missing, so a new file was created. Please add this file to Git:\n' - + expectedApiReportPath + messageRouter.logWarning( + ConsoleMessageId.ApiReportCreated, + 'The API report file was missing, so a new file was created. Please add this file to Git:\n' + + expectedApiReportPath ); } } @@ -327,17 +345,31 @@ export class Extractor { if (extractorConfig.rollupEnabled) { Extractor._generateRollupDtsFile( - collector, extractorConfig.publicTrimmedFilePath, DtsRollupKind.PublicRelease, extractorConfig.newlineKind); + collector, + extractorConfig.publicTrimmedFilePath, + DtsRollupKind.PublicRelease, + extractorConfig.newlineKind + ); Extractor._generateRollupDtsFile( - collector, extractorConfig.betaTrimmedFilePath, DtsRollupKind.BetaRelease, extractorConfig.newlineKind); + collector, + extractorConfig.betaTrimmedFilePath, + DtsRollupKind.BetaRelease, + extractorConfig.newlineKind + ); Extractor._generateRollupDtsFile( - collector, extractorConfig.untrimmedFilePath, DtsRollupKind.InternalRelease, extractorConfig.newlineKind); + collector, + extractorConfig.untrimmedFilePath, + DtsRollupKind.InternalRelease, + extractorConfig.newlineKind + ); } if (extractorConfig.tsdocMetadataEnabled) { // Write the tsdoc-metadata.json file for this project PackageMetadataManager.writeTsdocMetadataFile( - extractorConfig.tsdocMetadataFilePath, extractorConfig.newlineKind); + extractorConfig.tsdocMetadataFilePath, + extractorConfig.newlineKind + ); } // Show all the messages that we collected during analysis @@ -359,15 +391,21 @@ export class Extractor { succeeded, apiReportChanged, errorCount: messageRouter.errorCount, - warningCount: messageRouter.warningCount + warningCount: messageRouter.warningCount, }); } private static _generateRollupDtsFile( - collector: Collector, outputPath: string, dtsKind: DtsRollupKind, newlineKind: NewlineKind + collector: Collector, + outputPath: string, + dtsKind: DtsRollupKind, + newlineKind: NewlineKind ): void { if (outputPath !== '') { - collector.messageRouter.logVerbose(ConsoleMessageId.WritingDtsRollup, `Writing package typings: ${outputPath}`); + collector.messageRouter.logVerbose( + ConsoleMessageId.WritingDtsRollup, + `Writing package typings: ${outputPath}` + ); DtsRollupGenerator.writeTypingsFile(collector, outputPath, dtsKind, newlineKind); } } diff --git a/apps/api-extractor/src/api/ExtractorConfig.ts b/apps/api-extractor/src/api/ExtractorConfig.ts index 5c3010653bf..8cf83576e47 100644 --- a/apps/api-extractor/src/api/ExtractorConfig.ts +++ b/apps/api-extractor/src/api/ExtractorConfig.ts @@ -15,12 +15,9 @@ import { Text, InternalError, Path, - NewlineKind + NewlineKind, } from '@rushstack/node-core-library'; -import { - IConfigFile, - IExtractorMessagesConfig -} from './IConfigFile'; +import { IConfigFile, IExtractorMessagesConfig } from './IConfigFile'; import { PackageMetadataManager } from '../analyzer/PackageMetadataManager'; import { MessageRouter } from '../collector/MessageRouter'; @@ -98,7 +95,7 @@ interface IExtractorConfigParameters { mainEntryPointFilePath: string; bundledPackages: string[]; tsconfigFilePath: string; - overrideTsconfig: { } | undefined; + overrideTsconfig: {} | undefined; skipLibCheck: boolean; apiReportEnabled: boolean; reportFilePath: string; @@ -126,15 +123,17 @@ export class ExtractorConfig { * The JSON Schema for API Extractor config file (api-extractor.schema.json). */ public static readonly jsonSchema: JsonSchema = JsonSchema.fromFile( - path.join(__dirname, '../schemas/api-extractor.schema.json')); + path.join(__dirname, '../schemas/api-extractor.schema.json') + ); /** * The config file name "api-extractor.json". */ public static readonly FILENAME: string = 'api-extractor.json'; - private static readonly _defaultConfig: Partial = JsonFile.load(path.join(__dirname, - '../schemas/api-extractor-defaults.json')); + private static readonly _defaultConfig: Partial = JsonFile.load( + path.join(__dirname, '../schemas/api-extractor-defaults.json') + ); private static readonly _declarationFileExtensionRegExp: RegExp = /\.d\.ts$/i; @@ -163,7 +162,7 @@ export class ExtractorConfig { public readonly tsconfigFilePath: string; /** {@inheritDoc IConfigCompiler.overrideTsconfig} */ - public readonly overrideTsconfig: { } | undefined; + public readonly overrideTsconfig: {} | undefined; /** {@inheritDoc IConfigCompiler.skipLibCheck} */ public readonly skipLibCheck: boolean; @@ -277,12 +276,13 @@ export class ExtractorConfig { const packageJsonLookup: PackageJsonLookup = new PackageJsonLookup(); const packageJsonFullPath: string | undefined = packageJsonLookup.tryGetPackageJsonFilePathFor( - configObjectFullPath); + configObjectFullPath + ); const extractorConfig: ExtractorConfig = ExtractorConfig.prepare({ configObject, configObjectFullPath, - packageJsonFullPath + packageJsonFullPath, }); return extractorConfig; @@ -301,14 +301,16 @@ export class ExtractorConfig { const visitedPaths: Set = new Set(); let currentConfigFilePath: string = path.resolve(process.cwd(), jsonFilePath); - let configObject: Partial = { }; + let configObject: Partial = {}; try { do { // Check if this file was already processed. if (visitedPaths.has(currentConfigFilePath)) { - throw new Error(`The API Extractor "extends" setting contains a cycle.` - + ` This file is included twice: "${currentConfigFilePath}"`); + throw new Error( + `The API Extractor "extends" setting contains a cycle.` + + ` This file is included twice: "${currentConfigFilePath}"` + ); } visitedPaths.add(currentConfigFilePath); @@ -331,12 +333,9 @@ export class ExtractorConfig { // // Resolve "my-package" from the perspective of the current folder. try { - extendsField = resolve.sync( - extendsField, - { - basedir: currentConfigFolderPath - } - ); + extendsField = resolve.sync(extendsField, { + basedir: currentConfigFolderPath, + }); } catch (e) { throw new Error(`Error resolving NodeJS path "${extendsField}": ${e.message}`); } @@ -353,7 +352,6 @@ export class ExtractorConfig { currentConfigFilePath = extendsField; } while (currentConfigFilePath); - } catch (e) { throw new Error(`Error loading ${currentConfigFilePath}:\n` + e.message); } @@ -367,69 +365,103 @@ export class ExtractorConfig { return configObject as IConfigFile; } - private static _resolveConfigFileRelativePaths(configFile: IConfigFile, currentConfigFolderPath: string): void { - + private static _resolveConfigFileRelativePaths( + configFile: IConfigFile, + currentConfigFolderPath: string + ): void { if (configFile.projectFolder) { configFile.projectFolder = ExtractorConfig._resolveConfigFileRelativePath( - 'projectFolder', configFile.projectFolder, currentConfigFolderPath); + 'projectFolder', + configFile.projectFolder, + currentConfigFolderPath + ); } if (configFile.mainEntryPointFilePath) { configFile.mainEntryPointFilePath = ExtractorConfig._resolveConfigFileRelativePath( - 'mainEntryPointFilePath', configFile.mainEntryPointFilePath, currentConfigFolderPath); + 'mainEntryPointFilePath', + configFile.mainEntryPointFilePath, + currentConfigFolderPath + ); } if (configFile.compiler) { if (configFile.compiler.tsconfigFilePath) { configFile.compiler.tsconfigFilePath = ExtractorConfig._resolveConfigFileRelativePath( - 'tsconfigFilePath', configFile.compiler.tsconfigFilePath, currentConfigFolderPath); + 'tsconfigFilePath', + configFile.compiler.tsconfigFilePath, + currentConfigFolderPath + ); } } if (configFile.apiReport) { if (configFile.apiReport.reportFolder) { configFile.apiReport.reportFolder = ExtractorConfig._resolveConfigFileRelativePath( - 'reportFolder', configFile.apiReport.reportFolder, currentConfigFolderPath); + 'reportFolder', + configFile.apiReport.reportFolder, + currentConfigFolderPath + ); } if (configFile.apiReport.reportTempFolder) { configFile.apiReport.reportTempFolder = ExtractorConfig._resolveConfigFileRelativePath( - 'reportTempFolder', configFile.apiReport.reportTempFolder, currentConfigFolderPath); + 'reportTempFolder', + configFile.apiReport.reportTempFolder, + currentConfigFolderPath + ); } } if (configFile.docModel) { if (configFile.docModel.apiJsonFilePath) { configFile.docModel.apiJsonFilePath = ExtractorConfig._resolveConfigFileRelativePath( - 'apiJsonFilePath', configFile.docModel.apiJsonFilePath, currentConfigFolderPath); + 'apiJsonFilePath', + configFile.docModel.apiJsonFilePath, + currentConfigFolderPath + ); } } if (configFile.dtsRollup) { if (configFile.dtsRollup.untrimmedFilePath) { configFile.dtsRollup.untrimmedFilePath = ExtractorConfig._resolveConfigFileRelativePath( - 'untrimmedFilePath', configFile.dtsRollup.untrimmedFilePath, currentConfigFolderPath); + 'untrimmedFilePath', + configFile.dtsRollup.untrimmedFilePath, + currentConfigFolderPath + ); } if (configFile.dtsRollup.betaTrimmedFilePath) { configFile.dtsRollup.betaTrimmedFilePath = ExtractorConfig._resolveConfigFileRelativePath( - 'betaTrimmedFilePath', configFile.dtsRollup.betaTrimmedFilePath, currentConfigFolderPath); + 'betaTrimmedFilePath', + configFile.dtsRollup.betaTrimmedFilePath, + currentConfigFolderPath + ); } if (configFile.dtsRollup.publicTrimmedFilePath) { configFile.dtsRollup.publicTrimmedFilePath = ExtractorConfig._resolveConfigFileRelativePath( - 'publicTrimmedFilePath', configFile.dtsRollup.publicTrimmedFilePath, currentConfigFolderPath); + 'publicTrimmedFilePath', + configFile.dtsRollup.publicTrimmedFilePath, + currentConfigFolderPath + ); } } if (configFile.tsdocMetadata) { if (configFile.tsdocMetadata.tsdocMetadataFilePath) { configFile.tsdocMetadata.tsdocMetadataFilePath = ExtractorConfig._resolveConfigFileRelativePath( - 'tsdocMetadataFilePath', configFile.tsdocMetadata.tsdocMetadataFilePath, currentConfigFolderPath); + 'tsdocMetadataFilePath', + configFile.tsdocMetadata.tsdocMetadataFilePath, + currentConfigFolderPath + ); } } } - private static _resolveConfigFileRelativePath(fieldName: string, fieldValue: string, - currentConfigFolderPath: string): string { - + private static _resolveConfigFileRelativePath( + fieldName: string, + fieldValue: string, + currentConfigFolderPath: string + ): string { if (!path.isAbsolute(fieldValue)) { if (fieldValue.indexOf('') !== 0) { // If the path is not absolute and does not start with "", then resolve it relative @@ -451,7 +483,9 @@ export class ExtractorConfig { const configObject: Partial = options.configObject; if (configObject.extends) { - throw new Error('The IConfigFile.extends field must be expanded before calling ExtractorConfig.prepare()'); + throw new Error( + 'The IConfigFile.extends field must be expanded before calling ExtractorConfig.prepare()' + ); } if (options.configObjectFullPath) { @@ -486,7 +520,6 @@ export class ExtractorConfig { } try { - if (!configObject.compiler) { // A merged configuration should have this throw new Error('The "compiler" section is missing'); @@ -500,8 +533,10 @@ export class ExtractorConfig { let projectFolder: string; if (configObject.projectFolder.trim() === '') { if (!options.configObjectFullPath) { - throw new Error('The "projectFolder" setting uses the "" token, but it cannot be expanded because' - + ' the "configObjectFullPath" setting was not specified'); + throw new Error( + 'The "projectFolder" setting uses the "" token, but it cannot be expanded because' + + ' the "configObjectFullPath" setting was not specified' + ); } // "The default value for `projectFolder` is the token ``, which means the folder is determined @@ -510,7 +545,7 @@ export class ExtractorConfig { // this way, then an error will be reported." let currentFolder: string = path.dirname(options.configObjectFullPath); - for (; ; ) { + for (;;) { const tsconfigPath: string = path.join(currentFolder, 'tsconfig.json'); if (FileSystem.exists(tsconfigPath)) { projectFolder = currentFolder; @@ -518,8 +553,10 @@ export class ExtractorConfig { } const parentFolder: string = path.dirname(currentFolder); if (parentFolder === '' || parentFolder === currentFolder) { - throw new Error('The "projectFolder" setting uses the "" token, but a tsconfig.json file cannot be' - + ' found in this folder or any parent folder.'); + throw new Error( + 'The "projectFolder" setting uses the "" token, but a tsconfig.json file cannot be' + + ' found in this folder or any parent folder.' + ); } currentFolder = parentFolder; } @@ -536,7 +573,7 @@ export class ExtractorConfig { const tokenContext: IExtractorConfigTokenContext = { unscopedPackageName: 'unknown-package', packageName: 'unknown-package', - projectFolder: projectFolder + projectFolder: projectFolder, }; if (packageJson) { @@ -548,11 +585,16 @@ export class ExtractorConfig { // A merged configuration should have this throw new Error('The "mainEntryPointFilePath" setting is missing'); } - const mainEntryPointFilePath: string = ExtractorConfig._resolvePathWithTokens('mainEntryPointFilePath', - configObject.mainEntryPointFilePath, tokenContext); + const mainEntryPointFilePath: string = ExtractorConfig._resolvePathWithTokens( + 'mainEntryPointFilePath', + configObject.mainEntryPointFilePath, + tokenContext + ); if (!ExtractorConfig.hasDtsFileExtension(mainEntryPointFilePath)) { - throw new Error('The "mainEntryPointFilePath" value is not a declaration file: ' + mainEntryPointFilePath); + throw new Error( + 'The "mainEntryPointFilePath" value is not a declaration file: ' + mainEntryPointFilePath + ); } if (!FileSystem.exists(mainEntryPointFilePath)) { @@ -566,8 +608,11 @@ export class ExtractorConfig { } } - const tsconfigFilePath: string = ExtractorConfig._resolvePathWithTokens('tsconfigFilePath', - configObject.compiler.tsconfigFilePath, tokenContext); + const tsconfigFilePath: string = ExtractorConfig._resolvePathWithTokens( + 'tsconfigFilePath', + configObject.compiler.tsconfigFilePath, + tokenContext + ); if (configObject.compiler.overrideTsconfig === undefined) { if (!tsconfigFilePath) { @@ -584,8 +629,11 @@ export class ExtractorConfig { if (configObject.apiReport) { apiReportEnabled = !!configObject.apiReport.enabled; - const reportFilename: string = ExtractorConfig._expandStringWithTokens('reportFileName', - configObject.apiReport.reportFileName || '', tokenContext); + const reportFilename: string = ExtractorConfig._expandStringWithTokens( + 'reportFileName', + configObject.apiReport.reportFileName || '', + tokenContext + ); if (!reportFilename) { // A merged configuration should have this @@ -596,10 +644,16 @@ export class ExtractorConfig { throw new Error(`The "reportFilename" setting contains invalid characters: "${reportFilename}"`); } - const reportFolder: string = ExtractorConfig._resolvePathWithTokens('reportFolder', - configObject.apiReport.reportFolder, tokenContext); - const reportTempFolder: string = ExtractorConfig._resolvePathWithTokens('reportTempFolder', - configObject.apiReport.reportTempFolder, tokenContext); + const reportFolder: string = ExtractorConfig._resolvePathWithTokens( + 'reportFolder', + configObject.apiReport.reportFolder, + tokenContext + ); + const reportTempFolder: string = ExtractorConfig._resolvePathWithTokens( + 'reportTempFolder', + configObject.apiReport.reportTempFolder, + tokenContext + ); reportFilePath = path.join(reportFolder, reportFilename); reportTempFilePath = path.join(reportTempFolder, reportFilename); @@ -609,8 +663,11 @@ export class ExtractorConfig { let apiJsonFilePath: string = ''; if (configObject.docModel) { docModelEnabled = !!configObject.docModel.enabled; - apiJsonFilePath = ExtractorConfig._resolvePathWithTokens('apiJsonFilePath', - configObject.docModel.apiJsonFilePath, tokenContext); + apiJsonFilePath = ExtractorConfig._resolvePathWithTokens( + 'apiJsonFilePath', + configObject.docModel.apiJsonFilePath, + tokenContext + ); } let tsdocMetadataEnabled: boolean = false; @@ -623,25 +680,34 @@ export class ExtractorConfig { if (tsdocMetadataFilePath.trim() === '') { if (!packageJson) { - throw new Error('The "" token cannot be used with the "tsdocMetadataFilePath" setting because' - + ' the "packageJson" option was not provided'); + throw new Error( + 'The "" token cannot be used with the "tsdocMetadataFilePath" setting because' + + ' the "packageJson" option was not provided' + ); } if (!packageJsonFullPath) { - throw new Error('The "" token cannot be used with "tsdocMetadataFilePath" because' - + 'the "packageJsonFullPath" option was not provided'); + throw new Error( + 'The "" token cannot be used with "tsdocMetadataFilePath" because' + + 'the "packageJsonFullPath" option was not provided' + ); } tsdocMetadataFilePath = PackageMetadataManager.resolveTsdocMetadataPath( path.dirname(packageJsonFullPath), packageJson ); } else { - tsdocMetadataFilePath = ExtractorConfig._resolvePathWithTokens('tsdocMetadataFilePath', - configObject.tsdocMetadata.tsdocMetadataFilePath, tokenContext); + tsdocMetadataFilePath = ExtractorConfig._resolvePathWithTokens( + 'tsdocMetadataFilePath', + configObject.tsdocMetadata.tsdocMetadataFilePath, + tokenContext + ); } if (!tsdocMetadataFilePath) { - throw new Error('The "tsdocMetadata.enabled" setting is enabled,' - + ' but "tsdocMetadataFilePath" is not specified'); + throw new Error( + 'The "tsdocMetadata.enabled" setting is enabled,' + + ' but "tsdocMetadataFilePath" is not specified' + ); } } } @@ -654,12 +720,21 @@ export class ExtractorConfig { if (configObject.dtsRollup) { rollupEnabled = !!configObject.dtsRollup.enabled; - untrimmedFilePath = ExtractorConfig._resolvePathWithTokens('untrimmedFilePath', - configObject.dtsRollup.untrimmedFilePath, tokenContext); - betaTrimmedFilePath = ExtractorConfig._resolvePathWithTokens('betaTrimmedFilePath', - configObject.dtsRollup.betaTrimmedFilePath, tokenContext); - publicTrimmedFilePath = ExtractorConfig._resolvePathWithTokens('publicTrimmedFilePath', - configObject.dtsRollup.publicTrimmedFilePath, tokenContext); + untrimmedFilePath = ExtractorConfig._resolvePathWithTokens( + 'untrimmedFilePath', + configObject.dtsRollup.untrimmedFilePath, + tokenContext + ); + betaTrimmedFilePath = ExtractorConfig._resolvePathWithTokens( + 'betaTrimmedFilePath', + configObject.dtsRollup.betaTrimmedFilePath, + tokenContext + ); + publicTrimmedFilePath = ExtractorConfig._resolvePathWithTokens( + 'publicTrimmedFilePath', + configObject.dtsRollup.publicTrimmedFilePath, + tokenContext + ); omitTrimmingComments = !!configObject.dtsRollup.omitTrimmingComments; } @@ -698,18 +773,19 @@ export class ExtractorConfig { tsdocMetadataEnabled, tsdocMetadataFilePath, newlineKind, - messages: configObject.messages || { }, - testMode: !!configObject.testMode + messages: configObject.messages || {}, + testMode: !!configObject.testMode, }); - } catch (e) { throw new Error(`Error parsing ${filenameForErrors}:\n` + e.message); } } - private static _resolvePathWithTokens(fieldName: string, value: string | undefined, - tokenContext: IExtractorConfigTokenContext): string { - + private static _resolvePathWithTokens( + fieldName: string, + value: string | undefined, + tokenContext: IExtractorConfigTokenContext + ): string { value = ExtractorConfig._expandStringWithTokens(fieldName, value, tokenContext); if (value !== '') { value = path.resolve(tokenContext.projectFolder, value); @@ -717,8 +793,11 @@ export class ExtractorConfig { return value; } - private static _expandStringWithTokens(fieldName: string, value: string | undefined, - tokenContext: IExtractorConfigTokenContext): string { + private static _expandStringWithTokens( + fieldName: string, + value: string | undefined, + tokenContext: IExtractorConfigTokenContext + ): string { value = value ? value.trim() : ''; if (value !== '') { value = Text.replaceAll(value, '', tokenContext.unscopedPackageName); @@ -732,8 +811,10 @@ export class ExtractorConfig { if (value.indexOf(projectFolderToken) >= 0) { // If after all replacements, "" appears somewhere in the string, report an error - throw new Error(`The "${fieldName}" value incorrectly uses the "" token.` - + ` It must appear at the start of the string.`); + throw new Error( + `The "${fieldName}" value incorrectly uses the "" token.` + + ` It must appear at the start of the string.` + ); } if (value.indexOf('') >= 0) { diff --git a/apps/api-extractor/src/api/ExtractorLogLevel.ts b/apps/api-extractor/src/api/ExtractorLogLevel.ts index 40a687aa3a0..74a1b7dbdfb 100644 --- a/apps/api-extractor/src/api/ExtractorLogLevel.ts +++ b/apps/api-extractor/src/api/ExtractorLogLevel.ts @@ -45,5 +45,5 @@ export const enum ExtractorLogLevel { /** * The message will be discarded entirely. */ - None = 'none' + None = 'none', } diff --git a/apps/api-extractor/src/api/ExtractorMessage.ts b/apps/api-extractor/src/api/ExtractorMessage.ts index be5e8d37e57..58e2940de16 100644 --- a/apps/api-extractor/src/api/ExtractorMessage.ts +++ b/apps/api-extractor/src/api/ExtractorMessage.ts @@ -13,7 +13,6 @@ import { SourceFileLocationFormatter } from '../analyzer/SourceFileLocationForma * @public */ export interface IExtractorMessageProperties { - /** * A declaration can have multiple names if it is exported more than once. * If an `ExtractorMessage` applies to a specific export name, this property can indicate that. @@ -65,7 +64,7 @@ export const enum ExtractorMessageCategory { * These strings begin with the prefix "console-". * Example: `console-writing-typings-file` */ - Console = 'console' + Console = 'console', } /** @@ -138,7 +137,7 @@ export class ExtractorMessage { this.sourceFilePath = options.sourceFilePath; this.sourceFileLine = options.sourceFileLine; this.sourceFileColumn = options.sourceFileColumn; - this.properties = options.properties || { }; + this.properties = options.properties || {}; this._handled = false; this._logLevel = options.logLevel || ExtractorLogLevel.None; @@ -162,7 +161,9 @@ export class ExtractorMessage { public set handled(value: boolean) { if (this._handled && !value) { - throw new Error('One a message has been marked as handled, the "handled" property cannot be set to false'); + throw new Error( + 'One a message has been marked as handled, the "handled" property cannot be set to false' + ); } this._handled = value; } @@ -213,7 +214,7 @@ export class ExtractorMessage { result += SourceFileLocationFormatter.formatPath(this.sourceFilePath, { sourceFileLine: this.sourceFileLine, sourceFileColumn: this.sourceFileColumn, - workingPackageFolderPath + workingPackageFolderPath, }); if (result.length > 0) { diff --git a/apps/api-extractor/src/api/ExtractorMessageId.ts b/apps/api-extractor/src/api/ExtractorMessageId.ts index 6caf70a2496..c4ba32355cc 100644 --- a/apps/api-extractor/src/api/ExtractorMessageId.ts +++ b/apps/api-extractor/src/api/ExtractorMessageId.ts @@ -114,5 +114,5 @@ export const allExtractorMessageIds: Set = new Set([ 'ae-cyclic-inherit-doc', 'ae-unresolved-link', 'ae-setter-with-docs', - 'ae-missing-getter' + 'ae-missing-getter', ]); diff --git a/apps/api-extractor/src/api/IConfigFile.ts b/apps/api-extractor/src/api/IConfigFile.ts index e37281b3879..3eee451e1c5 100644 --- a/apps/api-extractor/src/api/IConfigFile.ts +++ b/apps/api-extractor/src/api/IConfigFile.ts @@ -33,7 +33,7 @@ export interface IConfigCompiler { * * If omitted, then the tsconfig.json file will instead be read from the projectFolder. */ - overrideTsconfig?: { }; + overrideTsconfig?: {}; /** * This option causes the compiler to be invoked with the `--skipLibCheck` option. diff --git a/apps/api-extractor/src/cli/ApiExtractorCommandLine.ts b/apps/api-extractor/src/cli/ApiExtractorCommandLine.ts index 60e04681d43..705de0890f6 100644 --- a/apps/api-extractor/src/cli/ApiExtractorCommandLine.ts +++ b/apps/api-extractor/src/cli/ApiExtractorCommandLine.ts @@ -16,30 +16,32 @@ export class ApiExtractorCommandLine extends CommandLineParser { public constructor() { super({ toolFilename: 'api-extractor', - toolDescription: 'API Extractor helps you build better TypeScript libraries. It analyzes the main entry' - + ' point for your package, collects the inventory of exported declarations, and then generates three kinds' - + ' of output: an API report file (.api.md) to facilitate reviews, a declaration rollup (.d.ts) to be' - + ' 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.' + toolDescription: + 'API Extractor helps you build better TypeScript libraries. It analyzes the main entry' + + ' point for your package, collects the inventory of exported declarations, and then generates three kinds' + + ' of output: an API report file (.api.md) to facilitate reviews, a declaration rollup (.d.ts) to be' + + ' 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(); } - protected onDefineParameters(): void { // override + protected onDefineParameters(): void { + // override this._debugParameter = this.defineFlagParameter({ parameterLongName: '--debug', parameterShortName: '-d', - description: 'Show the full call stack if an error occurs while executing the tool' + description: 'Show the full call stack if an error occurs while executing the tool', }); } - protected onExecute(): Promise { // override + protected onExecute(): Promise { + // override if (this._debugParameter.value) { InternalError.breakInDebugger = true; } return super.onExecute().catch((error) => { - if (this._debugParameter.value) { console.error(os.EOL + error.stack); } else { diff --git a/apps/api-extractor/src/cli/InitAction.ts b/apps/api-extractor/src/cli/InitAction.ts index 120918d1a2f..8c69223110f 100644 --- a/apps/api-extractor/src/cli/InitAction.ts +++ b/apps/api-extractor/src/cli/InitAction.ts @@ -10,22 +10,24 @@ import { ApiExtractorCommandLine } from './ApiExtractorCommandLine'; import { ExtractorConfig } from '../api/ExtractorConfig'; export class InitAction extends CommandLineAction { - public constructor(parser: ApiExtractorCommandLine) { super({ actionName: 'init', summary: `Create an ${ExtractorConfig.FILENAME} config file`, - documentation: `Use this command when setting up API Extractor for a new project. It writes an` - + ` ${ExtractorConfig.FILENAME} config file template with code comments that describe all the settings.` - + ` The file will be written in the current directory.` + documentation: + `Use this command when setting up API Extractor for a new project. It writes an` + + ` ${ExtractorConfig.FILENAME} config file template with code comments that describe all the settings.` + + ` The file will be written in the current directory.`, }); } - protected onDefineParameters(): void { // override + protected onDefineParameters(): void { + // override // No parameters yet } - protected onExecute(): Promise { // override + protected onExecute(): Promise { + // override const inputFilePath: string = path.resolve(__dirname, '../schemas/api-extractor-template.json'); const outputFilePath: string = path.resolve(ExtractorConfig.FILENAME); @@ -38,11 +40,13 @@ export class InitAction extends CommandLineAction { console.log(colors.green('Writing file: ') + outputFilePath); FileSystem.copyFile({ sourcePath: inputFilePath, - destinationPath: outputFilePath + destinationPath: outputFilePath, }); - console.log('\nThe recommended location for this file is in the project\'s "config" subfolder,\n' - + 'or else in the top-level folder with package.json.'); + console.log( + '\nThe recommended location for this file is in the project\'s "config" subfolder,\n' + + 'or else in the top-level folder with package.json.' + ); return Promise.resolve(); } diff --git a/apps/api-extractor/src/cli/RunAction.ts b/apps/api-extractor/src/cli/RunAction.ts index 7866391c531..8304796348e 100644 --- a/apps/api-extractor/src/cli/RunAction.ts +++ b/apps/api-extractor/src/cli/RunAction.ts @@ -4,16 +4,12 @@ import * as colors from 'colors'; import * as os from 'os'; import * as path from 'path'; -import { - PackageJsonLookup, - FileSystem, - IPackageJson -} from '@rushstack/node-core-library'; +import { PackageJsonLookup, FileSystem, IPackageJson } from '@rushstack/node-core-library'; import { CommandLineAction, CommandLineStringParameter, - CommandLineFlagParameter + CommandLineFlagParameter, } from '@rushstack/ts-command-line'; import { Extractor, ExtractorResult } from '../api/Extractor'; @@ -33,51 +29,56 @@ export class RunAction extends CommandLineAction { super({ actionName: 'run', summary: 'Invoke API Extractor on a project', - documentation: 'Invoke API Extractor on a project' + documentation: 'Invoke API Extractor on a project', }); } - protected onDefineParameters(): void { // override + protected onDefineParameters(): void { + // override this._configFileParameter = this.defineStringParameter({ parameterLongName: '--config', parameterShortName: '-c', argumentName: 'FILE', - description: `Use the specified ${ExtractorConfig.FILENAME} file path, rather than guessing its location` + description: `Use the specified ${ExtractorConfig.FILENAME} file path, rather than guessing its location`, }); this._localParameter = this.defineFlagParameter({ parameterLongName: '--local', parameterShortName: '-l', - description: 'Indicates that API Extractor is running as part of a local build,' - + ' e.g. on a developer\'s machine. This disables certain validation that would' - + ' normally be performed for a ship/production build. For example, the *.api.md' - + ' report file is automatically copied in a local build.' + description: + 'Indicates that API Extractor is running as part of a local build,' + + " e.g. on a developer's machine. This disables certain validation that would" + + ' normally be performed for a ship/production build. For example, the *.api.md' + + ' report file is automatically copied in a local build.', }); this._verboseParameter = this.defineFlagParameter({ parameterLongName: '--verbose', parameterShortName: '-v', - description: 'Show additional informational messages in the output.' + description: 'Show additional informational messages in the output.', }); this._diagnosticsParameter = this.defineFlagParameter({ parameterLongName: '--diagnostics', - description: 'Show diagnostic messages used for troubleshooting problems with API Extractor.' - + ' This flag also enables the "--verbose" flag.' + description: + 'Show diagnostic messages used for troubleshooting problems with API Extractor.' + + ' This flag also enables the "--verbose" flag.', }); this._typescriptCompilerFolder = this.defineStringParameter({ parameterLongName: '--typescript-compiler-folder', argumentName: 'PATH', - description: 'API Extractor uses its own TypeScript compiler engine to analyze your project. If your project' - + ' is built with a significantly different TypeScript version, sometimes API Extractor may report compilation' - + ' errors due to differences in the system typings (e.g. lib.dom.d.ts). You can use the' - + ' "--typescriptCompilerFolder" option to specify the folder path where you installed the TypeScript package,' - + ' and API Extractor\'s compiler will use those system typings instead.' + description: + 'API Extractor uses its own TypeScript compiler engine to analyze your project. If your project' + + ' is built with a significantly different TypeScript version, sometimes API Extractor may report compilation' + + ' errors due to differences in the system typings (e.g. lib.dom.d.ts). You can use the' + + ' "--typescriptCompilerFolder" option to specify the folder path where you installed the TypeScript package,' + + " and API Extractor's compiler will use those system typings instead.", }); } - protected onExecute(): Promise { // override + protected onExecute(): Promise { + // override const lookup: PackageJsonLookup = new PackageJsonLookup(); let configFilename: string; @@ -96,8 +97,8 @@ export class RunAction extends CommandLineAction { ); } else if (typescriptCompilerPackageJson.name !== 'typescript') { throw new Error( - `The path specified in the ${this._typescriptCompilerFolder.longName} parameter is not a TypeScript` - + ' compiler package.' + `The path specified in the ${this._typescriptCompilerFolder.longName} parameter is not a TypeScript` + + ' compiler package.' ); } } else { @@ -124,7 +125,9 @@ export class RunAction extends CommandLineAction { configFilename = path.join(baseFolder, 'config', ExtractorConfig.FILENAME); if (FileSystem.exists(configFilename)) { if (FileSystem.exists(path.join(baseFolder, ExtractorConfig.FILENAME))) { - throw new Error(`Found conflicting ${ExtractorConfig.FILENAME} files in "." and "./config" folders`); + throw new Error( + `Found conflicting ${ExtractorConfig.FILENAME} files in "." and "./config" folders` + ); } } else { // Otherwise try the top-level folder @@ -144,17 +147,15 @@ export class RunAction extends CommandLineAction { const extractorConfig: ExtractorConfig = ExtractorConfig.prepare({ configObject: configObject, configObjectFullPath: configObjectFullPath, - packageJsonFullPath: lookup.tryGetPackageJsonFilePathFor(configObjectFullPath) + packageJsonFullPath: lookup.tryGetPackageJsonFilePathFor(configObjectFullPath), }); - const extractorResult: ExtractorResult = Extractor.invoke(extractorConfig, - { - localBuild: this._localParameter.value, - showVerboseMessages: this._verboseParameter.value, - showDiagnostics: this._diagnosticsParameter.value, - typescriptCompilerFolder: typescriptCompilerFolder - } - ); + const extractorResult: ExtractorResult = Extractor.invoke(extractorConfig, { + localBuild: this._localParameter.value, + showVerboseMessages: this._verboseParameter.value, + showDiagnostics: this._diagnosticsParameter.value, + typescriptCompilerFolder: typescriptCompilerFolder, + }); if (extractorResult.succeeded) { console.log(os.EOL + 'API Extractor completed successfully'); diff --git a/apps/api-extractor/src/collector/Collector.ts b/apps/api-extractor/src/collector/Collector.ts index cb184ccf7fe..7dd86c45de9 100644 --- a/apps/api-extractor/src/collector/Collector.ts +++ b/apps/api-extractor/src/collector/Collector.ts @@ -3,15 +3,8 @@ import * as ts from 'typescript'; import * as tsdoc from '@microsoft/tsdoc'; -import { - PackageJsonLookup, - Sort, - InternalError -} from '@rushstack/node-core-library'; -import { - ReleaseTag, - AedocDefinitions -} from '@microsoft/api-extractor-model'; +import { PackageJsonLookup, Sort, InternalError } from '@rushstack/node-core-library'; +import { ReleaseTag, AedocDefinitions } from '@microsoft/api-extractor-model'; import { ExtractorMessageId } from '../api/ExtractorMessageId'; @@ -77,7 +70,10 @@ export class Collector { private _astEntryPoint: AstModule | undefined; private readonly _entities: CollectorEntity[] = []; - private readonly _entitiesByAstEntity: Map = new Map(); + private readonly _entitiesByAstEntity: Map = new Map< + AstEntity, + CollectorEntity + >(); private readonly _starExportedExternalModulePaths: string[] = []; @@ -94,7 +90,8 @@ export class Collector { this.extractorConfig = options.extractorConfig; const entryPointSourceFile: ts.SourceFile | undefined = options.program.getSourceFile( - this.extractorConfig.mainEntryPointFilePath); + this.extractorConfig.mainEntryPointFilePath + ); if (!entryPointSourceFile) { throw new Error('Unable to load file: ' + this.extractorConfig.mainEntryPointFilePath); @@ -109,7 +106,7 @@ export class Collector { this.workingPackage = new WorkingPackage({ packageFolder: this.extractorConfig.packageFolder, packageJson: this.extractorConfig.packageJson, - entryPointSourceFile + entryPointSourceFile, }); this.messageRouter = options.messageRouter; @@ -122,8 +119,13 @@ export class Collector { const bundledPackageNames: Set = new Set(this.extractorConfig.bundledPackages); - this.astSymbolTable = new AstSymbolTable(this.program, this.typeChecker, this.packageJsonLookup, - bundledPackageNames, this.messageRouter); + this.astSymbolTable = new AstSymbolTable( + this.program, + this.typeChecker, + this.packageJsonLookup, + bundledPackageNames, + this.messageRouter + ); this.astReferenceResolver = new AstReferenceResolver(this); this._cachedOverloadIndexesByDeclaration = new Map(); @@ -196,20 +198,25 @@ export class Collector { const entryPointSourceFile: ts.SourceFile = this.workingPackage.entryPointSourceFile; const astEntryPoint: AstModule = this.astSymbolTable.fetchAstModuleFromWorkingPackage( - entryPointSourceFile); + entryPointSourceFile + ); this._astEntryPoint = astEntryPoint; const packageDocCommentTextRange: ts.TextRange | undefined = PackageDocComment.tryFindInSourceFile( - entryPointSourceFile, this); + entryPointSourceFile, + this + ); if (packageDocCommentTextRange) { - const range: tsdoc.TextRange = tsdoc.TextRange.fromStringRange(entryPointSourceFile.text, - packageDocCommentTextRange.pos, packageDocCommentTextRange.end); + const range: tsdoc.TextRange = tsdoc.TextRange.fromStringRange( + entryPointSourceFile.text, + packageDocCommentTextRange.pos, + packageDocCommentTextRange.end + ); this.workingPackage.tsdocParserContext = this._tsdocParser.parseRange(range); - this.messageRouter.addTsdocMessages(this.workingPackage.tsdocParserContext, - entryPointSourceFile); + this.messageRouter.addTsdocMessages(this.workingPackage.tsdocParserContext, entryPointSourceFile); this.workingPackage.tsdocComment = this.workingPackage.tsdocParserContext!.docComment; } @@ -218,7 +225,9 @@ export class Collector { // Create a CollectorEntity for each top-level export - const astModuleExportInfo: AstModuleExportInfo = this.astSymbolTable.fetchAstModuleExportInfo(astEntryPoint); + const astModuleExportInfo: AstModuleExportInfo = this.astSymbolTable.fetchAstModuleExportInfo( + astEntryPoint + ); for (const [exportName, astEntity] of astModuleExportInfo.exportedLocalEntities) { this._createCollectorEntity(astEntity, exportName); @@ -245,7 +254,7 @@ export class Collector { } } - Sort.sortBy(this._entities, x => x.getSortKey()); + Sort.sortBy(this._entities, (x) => x.getSortKey()); Sort.sortSet(this._dtsTypeReferenceDirectives); Sort.sortSet(this._dtsLibReferenceDirectives); this._starExportedExternalModulePaths.sort(); @@ -299,7 +308,8 @@ export class Collector { if (astEntity instanceof AstSymbol) { return this.fetchSymbolMetadata(astEntity); } - if (astEntity.astSymbol) { // astImport + if (astEntity.astSymbol) { + // astImport return this.fetchSymbolMetadata(astEntity.astSymbol); } return undefined; @@ -395,7 +405,10 @@ export class Collector { } } - private _createEntityForIndirectReferences(astEntity: AstEntity, alreadySeenAstEntities: Set): void { + private _createEntityForIndirectReferences( + astEntity: AstEntity, + alreadySeenAstEntities: Set + ): void { if (alreadySeenAstEntities.has(astEntity)) { return; } @@ -459,12 +472,14 @@ export class Collector { // Ensure that each entity has a unique nameForEmit for (const entity of this._entities) { - // What name would we ideally want to emit it as? let idealNameForEmit: string; // If this entity is exported exactly once, then we prefer the exported name - if (entity.singleExportName !== undefined && entity.singleExportName !== ts.InternalSymbolName.Default) { + if ( + entity.singleExportName !== undefined && + entity.singleExportName !== ts.InternalSymbolName.Default + ) { idealNameForEmit = entity.singleExportName; } else { // otherwise use the local name @@ -528,7 +543,7 @@ export class Collector { // Update this last when we're sure no exceptions were thrown astSymbol.symbolMetadata = new SymbolMetadata({ - maxEffectiveReleaseTag + maxEffectiveReleaseTag, }); } @@ -536,7 +551,9 @@ export class Collector { // Initialize DeclarationMetadata for each declaration for (const astDeclaration of astSymbol.astDeclarations) { if (astDeclaration.declarationMetadata) { - throw new InternalError('AstDeclaration.declarationMetadata is not expected to have been initialized yet'); + throw new InternalError( + 'AstDeclaration.declarationMetadata is not expected to have been initialized yet' + ); } const metadata: InternalDeclarationMetadata = new InternalDeclarationMetadata(); @@ -547,7 +564,6 @@ export class Collector { // Detect ancillary declarations for (const astDeclaration of astSymbol.astDeclarations) { - // For a getter/setter pair, make the setter ancillary to the getter if (astDeclaration.declaration.kind === ts.SyntaxKind.SetAccessor) { let foundGetter: boolean = false; @@ -564,38 +580,49 @@ export class Collector { this.messageRouter.addAnalyzerIssue( ExtractorMessageId.MissingGetter, `The property "${astDeclaration.astSymbol.localName}" has a setter but no getter.`, - astDeclaration); + astDeclaration + ); } } - } } - private _addAncillaryDeclaration(mainAstDeclaration: AstDeclaration, ancillaryAstDeclaration: AstDeclaration): void { + private _addAncillaryDeclaration( + mainAstDeclaration: AstDeclaration, + ancillaryAstDeclaration: AstDeclaration + ): void { const mainMetadata: InternalDeclarationMetadata = mainAstDeclaration.declarationMetadata as InternalDeclarationMetadata; const ancillaryMetadata: InternalDeclarationMetadata = ancillaryAstDeclaration.declarationMetadata as InternalDeclarationMetadata; if (mainMetadata.ancillaryDeclarations.indexOf(ancillaryAstDeclaration) >= 0) { - return; // already added + return; // already added } if (mainAstDeclaration.astSymbol !== ancillaryAstDeclaration.astSymbol) { - throw new InternalError('Invalid call to _addAncillaryDeclaration() because declarations do not' - + ' belong to the same symbol'); + throw new InternalError( + 'Invalid call to _addAncillaryDeclaration() because declarations do not' + + ' belong to the same symbol' + ); } if (mainMetadata.isAncillary) { - throw new InternalError('Invalid call to _addAncillaryDeclaration() because the target is ancillary itself'); + throw new InternalError( + 'Invalid call to _addAncillaryDeclaration() because the target is ancillary itself' + ); } if (ancillaryMetadata.isAncillary) { - throw new InternalError('Invalid call to _addAncillaryDeclaration() because source is already ancillary' - + ' to another declaration'); + throw new InternalError( + 'Invalid call to _addAncillaryDeclaration() because source is already ancillary' + + ' to another declaration' + ); } if (mainAstDeclaration.apiItemMetadata || ancillaryAstDeclaration.apiItemMetadata) { - throw new InternalError('Invalid call to _addAncillaryDeclaration() because the API item metadata' - + ' has already been constructed'); + throw new InternalError( + 'Invalid call to _addAncillaryDeclaration() because the API item metadata' + + ' has already been constructed' + ); } ancillaryMetadata.isAncillary = true; @@ -605,13 +632,14 @@ export class Collector { private _calculateApiItemMetadata(astDeclaration: AstDeclaration): void { const declarationMetadata: InternalDeclarationMetadata = astDeclaration.declarationMetadata as InternalDeclarationMetadata; if (declarationMetadata.isAncillary) { - if (astDeclaration.declaration.kind === ts.SyntaxKind.SetAccessor) { if (declarationMetadata.tsdocParserContext) { - this.messageRouter.addAnalyzerIssue(ExtractorMessageId.SetterWithDocs, - `The doc comment for the property "${astDeclaration.astSymbol.localName}"` - + ` must appear on the getter, not the setter.`, - astDeclaration); + this.messageRouter.addAnalyzerIssue( + ExtractorMessageId.SetterWithDocs, + `The doc comment for the property "${astDeclaration.astSymbol.localName}"` + + ` must appear on the getter, not the setter.`, + astDeclaration + ); } } @@ -628,7 +656,7 @@ export class Collector { isSealed: false, isVirtual: false, isPreapproved: false, - releaseTagSameAsParent: false + releaseTagSameAsParent: false, }; const parserContext: tsdoc.ParserContext | undefined = declarationMetadata.tsdocParserContext; @@ -664,11 +692,13 @@ export class Collector { } if (extraReleaseTags) { - if (!astDeclaration.astSymbol.isExternal) { // for now, don't report errors for external code + if (!astDeclaration.astSymbol.isExternal) { + // for now, don't report errors for external code this.messageRouter.addAnalyzerIssue( ExtractorMessageId.ExtraReleaseTag, 'The doc comment should not contain more than one release tag', - astDeclaration); + astDeclaration + ); } } @@ -691,8 +721,8 @@ export class Collector { } else { this.messageRouter.addAnalyzerIssue( ExtractorMessageId.PreapprovedBadReleaseTag, - `The @preapproved tag cannot be applied to "${astDeclaration.astSymbol.localName}"` - + ` without an @internal release tag`, + `The @preapproved tag cannot be applied to "${astDeclaration.astSymbol.localName}"` + + ` without an @internal release tag`, astDeclaration ); } @@ -700,8 +730,8 @@ export class Collector { default: this.messageRouter.addAnalyzerIssue( ExtractorMessageId.PreapprovedUnsupportedType, - `The @preapproved tag cannot be applied to "${astDeclaration.astSymbol.localName}"` - + ` because it is not a supported declaration type`, + `The @preapproved tag cannot be applied to "${astDeclaration.astSymbol.localName}"` + + ` because it is not a supported declaration type`, astDeclaration ); break; @@ -712,18 +742,20 @@ export class Collector { // This needs to be set regardless of whether or not a parserContext exists if (astDeclaration.parent) { const parentApiItemMetadata: ApiItemMetadata = this.fetchApiItemMetadata(astDeclaration.parent); - options.effectiveReleaseTag = options.declaredReleaseTag === ReleaseTag.None - ? parentApiItemMetadata.effectiveReleaseTag - : options.declaredReleaseTag; + options.effectiveReleaseTag = + options.declaredReleaseTag === ReleaseTag.None + ? parentApiItemMetadata.effectiveReleaseTag + : options.declaredReleaseTag; - options.releaseTagSameAsParent = + options.releaseTagSameAsParent = parentApiItemMetadata.effectiveReleaseTag === options.effectiveReleaseTag; } else { options.effectiveReleaseTag = options.declaredReleaseTag; } if (options.effectiveReleaseTag === ReleaseTag.None) { - if (!astDeclaration.astSymbol.isExternal) { // for now, don't report errors for external code + if (!astDeclaration.astSymbol.isExternal) { + // for now, don't report errors for external code // Don't report missing release tags for forgotten exports const astSymbol: AstSymbol = astDeclaration.astSymbol; const entity: CollectorEntity | undefined = this._entitiesByAstEntity.get(astSymbol.rootAstSymbol); @@ -733,8 +765,8 @@ export class Collector { if (astSymbol.rootAstSymbol.localName !== '_default') { this.messageRouter.addAnalyzerIssue( ExtractorMessageId.MissingReleaseTag, - `"${entity.astEntity.localName}" is exported by the package, but it is missing ` - + `a release tag (@alpha, @beta, @public, or @internal)`, + `"${entity.astEntity.localName}" is exported by the package, but it is missing ` + + `a release tag (@alpha, @beta, @public, or @internal)`, astSymbol ); } @@ -773,8 +805,10 @@ export class Collector { // // But _getReleaseTagForDeclaration() still receives a node corresponding to "x", so we need to walk upwards // and find the containing statement in order for getJSDocCommentRanges() to read the comment that we expect. - const statement: ts.VariableStatement | undefined = TypeScriptHelpers.findFirstParent(declaration, - ts.SyntaxKind.VariableStatement) as ts.VariableStatement | undefined; + const statement: ts.VariableStatement | undefined = TypeScriptHelpers.findFirstParent( + declaration, + ts.SyntaxKind.VariableStatement + ) as ts.VariableStatement | undefined; if (statement !== undefined) { // For a compound declaration, fall back to looking for C instead of A if (statement.declarationList.declarations.length === 1) { @@ -784,7 +818,8 @@ export class Collector { } const sourceFileText: string = declaration.getSourceFile().text; - const ranges: ts.CommentRange[] = TypeScriptInternals.getJSDocCommentRanges(nodeForComment, sourceFileText) || []; + const ranges: ts.CommentRange[] = + TypeScriptInternals.getJSDocCommentRanges(nodeForComment, sourceFileText) || []; if (ranges.length === 0) { return undefined; @@ -794,8 +829,11 @@ export class Collector { // the last one preceding it const range: ts.TextRange = ranges[ranges.length - 1]; - const tsdocTextRange: tsdoc.TextRange = tsdoc.TextRange.fromStringRange(sourceFileText, - range.pos, range.end); + const tsdocTextRange: tsdoc.TextRange = tsdoc.TextRange.fromStringRange( + sourceFileText, + range.pos, + range.end + ); const parserContext: tsdoc.ParserContext = this._tsdocParser.parseRange(tsdocTextRange); @@ -818,15 +856,20 @@ export class Collector { seenFilenames.add(sourceFile.fileName); for (const typeReferenceDirective of sourceFile.typeReferenceDirectives) { - const name: string = sourceFile.text.substring(typeReferenceDirective.pos, typeReferenceDirective.end); + const name: string = sourceFile.text.substring( + typeReferenceDirective.pos, + typeReferenceDirective.end + ); this._dtsTypeReferenceDirectives.add(name); } for (const libReferenceDirective of sourceFile.libReferenceDirectives) { - const name: string = sourceFile.text.substring(libReferenceDirective.pos, libReferenceDirective.end); + const name: string = sourceFile.text.substring( + libReferenceDirective.pos, + libReferenceDirective.end + ); this._dtsLibReferenceDirectives.add(name); } - } } } diff --git a/apps/api-extractor/src/collector/CollectorEntity.ts b/apps/api-extractor/src/collector/CollectorEntity.ts index f23fd22f1a5..a4e9f3f330b 100644 --- a/apps/api-extractor/src/collector/CollectorEntity.ts +++ b/apps/api-extractor/src/collector/CollectorEntity.ts @@ -73,7 +73,7 @@ export class CollectorEntity { * In all other cases, it is undefined. */ public get singleExportName(): string | undefined { - return this._singleExportName; + return this._singleExportName; } /** diff --git a/apps/api-extractor/src/collector/MessageRouter.ts b/apps/api-extractor/src/collector/MessageRouter.ts index 864986dc86b..4c8936886c2 100644 --- a/apps/api-extractor/src/collector/MessageRouter.ts +++ b/apps/api-extractor/src/collector/MessageRouter.ts @@ -13,13 +13,10 @@ import { ExtractorMessage, ExtractorMessageCategory, IExtractorMessageOptions, - IExtractorMessageProperties + IExtractorMessageProperties, } from '../api/ExtractorMessage'; import { ExtractorMessageId, allExtractorMessageIds } from '../api/ExtractorMessageId'; -import { - IExtractorMessagesConfig, - IConfigMessageReportingRule -} from '../api/IConfigFile'; +import { IExtractorMessagesConfig, IConfigMessageReportingRule } from '../api/IConfigFile'; import { SourceMapper } from './SourceMapper'; import { ExtractorLogLevel } from '../api/ExtractorLogLevel'; import { ConsoleMessageId } from '../api/ConsoleMessageId'; @@ -38,7 +35,8 @@ export interface IMessageRouterOptions { } export class MessageRouter { - public static readonly DIAGNOSTICS_LINE: string = '============================================================'; + public static readonly DIAGNOSTICS_LINE: string = + '============================================================'; private readonly _workingPackageFolder: string | undefined; private readonly _messageCallback: ((message: ExtractorMessage) => void) | undefined; @@ -53,12 +51,15 @@ export class MessageRouter { // Normalized representation of the routing rules from api-extractor.json private _reportingRuleByMessageId: Map = new Map(); - private _compilerDefaultRule: IReportingRule = { logLevel: ExtractorLogLevel.None, - addToApiReportFile: false }; - private _extractorDefaultRule: IReportingRule = { logLevel: ExtractorLogLevel.None, - addToApiReportFile: false }; - private _tsdocDefaultRule: IReportingRule = { logLevel: ExtractorLogLevel.None, - addToApiReportFile: false }; + private _compilerDefaultRule: IReportingRule = { + logLevel: ExtractorLogLevel.None, + addToApiReportFile: false, + }; + private _extractorDefaultRule: IReportingRule = { + logLevel: ExtractorLogLevel.None, + addToApiReportFile: false, + }; + private _tsdocDefaultRule: IReportingRule = { logLevel: ExtractorLogLevel.None, addToApiReportFile: false }; public errorCount: number = 0; public warningCount: number = 0; @@ -95,13 +96,16 @@ export class MessageRouter { if (messagesConfig.compilerMessageReporting) { for (const messageId of Object.getOwnPropertyNames(messagesConfig.compilerMessageReporting)) { const reportingRule: IReportingRule = MessageRouter._getNormalizedRule( - messagesConfig.compilerMessageReporting[messageId]); + messagesConfig.compilerMessageReporting[messageId] + ); if (messageId === 'default') { 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.`); + 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); } @@ -111,16 +115,21 @@ export class MessageRouter { if (messagesConfig.extractorMessageReporting) { for (const messageId of Object.getOwnPropertyNames(messagesConfig.extractorMessageReporting)) { const reportingRule: IReportingRule = MessageRouter._getNormalizedRule( - messagesConfig.extractorMessageReporting[messageId]); + messagesConfig.extractorMessageReporting[messageId] + ); if (messageId === 'default') { this._extractorDefaultRule = reportingRule; } else if (!/^ae-/.test(messageId)) { - throw new Error(`Error in API Extractor config: The messages.extractorMessageReporting table contains` - + ` an invalid entry "${messageId}". The name should begin with the "ae-" prefix.`); + throw new Error( + `Error in API Extractor config: The messages.extractorMessageReporting table contains` + + ` an invalid entry "${messageId}". The name should begin with the "ae-" prefix.` + ); } else if (!allExtractorMessageIds.has(messageId)) { - throw new Error(`Error in API Extractor config: The messages.extractorMessageReporting table contains` - + ` an unrecognized identifier "${messageId}". Is it spelled correctly?`); + throw new Error( + `Error in API Extractor config: The messages.extractorMessageReporting table contains` + + ` an unrecognized identifier "${messageId}". Is it spelled correctly?` + ); } else { this._reportingRuleByMessageId.set(messageId, reportingRule); } @@ -130,16 +139,21 @@ export class MessageRouter { if (messagesConfig.tsdocMessageReporting) { for (const messageId of Object.getOwnPropertyNames(messagesConfig.tsdocMessageReporting)) { const reportingRule: IReportingRule = MessageRouter._getNormalizedRule( - messagesConfig.tsdocMessageReporting[messageId]); + messagesConfig.tsdocMessageReporting[messageId] + ); if (messageId === 'default') { 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.`); + 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 (!AedocDefinitions.tsdocConfiguration.isKnownMessageId(messageId)) { - throw new Error(`Error in API Extractor config: The messages.tsdocMessageReporting table contains` - + ` an unrecognized identifier "${messageId}". Is it spelled correctly?`); + 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); } @@ -150,7 +164,7 @@ export class MessageRouter { private static _getNormalizedRule(rule: IConfigMessageReportingRule): IReportingRule { return { logLevel: rule.logLevel || 'none', - addToApiReportFile: rule.addToApiReportFile || false + addToApiReportFile: rule.addToApiReportFile || false, }; } @@ -165,20 +179,21 @@ export class MessageRouter { switch (diagnostic.category) { case ts.DiagnosticCategory.Suggestion: case ts.DiagnosticCategory.Message: - return; // ignore noise + return; // ignore noise } const messageText: string = `${diagnostic.messageText}`; const options: IExtractorMessageOptions = { category: ExtractorMessageCategory.Compiler, messageId: `TS${diagnostic.code}`, - text: messageText + text: messageText, }; if (diagnostic.file) { const sourceFile: ts.SourceFile = diagnostic.file; const lineAndCharacter: ts.LineAndCharacter = sourceFile.getLineAndCharacterOfPosition( - diagnostic.start || 0); + diagnostic.start || 0 + ); options.sourceFilePath = sourceFile.fileName; options.sourceFileLine = lineAndCharacter.line + 1; @@ -193,9 +208,12 @@ export class MessageRouter { /** * Add a message from the API Extractor analysis */ - public addAnalyzerIssue(messageId: ExtractorMessageId, messageText: string, - astDeclarationOrSymbol: AstDeclaration | AstSymbol, properties?: IExtractorMessageProperties): void { - + public addAnalyzerIssue( + messageId: ExtractorMessageId, + messageText: string, + astDeclarationOrSymbol: AstDeclaration | AstSymbol, + properties?: IExtractorMessageProperties + ): void { let astDeclaration: AstDeclaration; if (astDeclarationOrSymbol instanceof AstDeclaration) { astDeclaration = astDeclarationOrSymbol; @@ -204,8 +222,12 @@ export class MessageRouter { } const extractorMessage: ExtractorMessage = this.addAnalyzerIssueForPosition( - messageId, messageText, astDeclaration.declaration.getSourceFile(), - astDeclaration.declaration.getStart(), properties); + messageId, + messageText, + astDeclaration.declaration.getSourceFile(), + astDeclaration.declaration.getStart(), + properties + ); this._associateMessageWithAstDeclaration(extractorMessage, astDeclaration); } @@ -214,12 +236,15 @@ export class MessageRouter { * Add all messages produced from an invocation of the TSDoc parser, assuming they refer to * code in the specified source file. */ - public addTsdocMessages(parserContext: tsdoc.ParserContext, sourceFile: ts.SourceFile, - astDeclaration?: AstDeclaration): void { - + public addTsdocMessages( + parserContext: tsdoc.ParserContext, + sourceFile: ts.SourceFile, + astDeclaration?: AstDeclaration + ): void { for (const message of parserContext.log.messages) { const lineAndCharacter: ts.LineAndCharacter = sourceFile.getLineAndCharacterOfPosition( - message.textRange.pos); + message.textRange.pos + ); const options: IExtractorMessageOptions = { category: ExtractorMessageCategory.TSDoc, @@ -227,7 +252,7 @@ export class MessageRouter { text: message.unformattedText, sourceFilePath: sourceFile.fileName, sourceFileLine: lineAndCharacter.line + 1, - sourceFileColumn: lineAndCharacter.character + 1 + sourceFileColumn: lineAndCharacter.character + 1, }; this._sourceMapper.updateExtractorMessageOptions(options); @@ -274,7 +299,7 @@ export class MessageRouter { return outputArray; } - const outputObject: object = { }; + const outputObject: object = {}; for (const key of Object.getOwnPropertyNames(input)) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const value: any = input[key]; @@ -295,11 +320,13 @@ export class MessageRouter { /** * Record this message in _associatedMessagesForAstDeclaration */ - private _associateMessageWithAstDeclaration(extractorMessage: ExtractorMessage, - astDeclaration: AstDeclaration): void { - - let associatedMessages: ExtractorMessage[] | undefined - = this._associatedMessagesForAstDeclaration.get(astDeclaration); + private _associateMessageWithAstDeclaration( + extractorMessage: ExtractorMessage, + astDeclaration: AstDeclaration + ): void { + let associatedMessages: ExtractorMessage[] | undefined = this._associatedMessagesForAstDeclaration.get( + astDeclaration + ); if (!associatedMessages) { associatedMessages = []; @@ -311,11 +338,14 @@ export class MessageRouter { /** * Add a message for a location in an arbitrary source file. */ - public addAnalyzerIssueForPosition(messageId: ExtractorMessageId, messageText: string, - sourceFile: ts.SourceFile, pos: number, properties?: IExtractorMessageProperties): ExtractorMessage { - - const lineAndCharacter: ts.LineAndCharacter = sourceFile.getLineAndCharacterOfPosition( - pos); + public addAnalyzerIssueForPosition( + messageId: ExtractorMessageId, + messageText: string, + sourceFile: ts.SourceFile, + pos: number, + properties?: IExtractorMessageProperties + ): ExtractorMessage { + const lineAndCharacter: ts.LineAndCharacter = sourceFile.getLineAndCharacterOfPosition(pos); const options: IExtractorMessageOptions = { category: ExtractorMessageCategory.Extractor, @@ -324,7 +354,7 @@ export class MessageRouter { sourceFilePath: sourceFile.fileName, sourceFileLine: lineAndCharacter.line + 1, sourceFileColumn: lineAndCharacter.character + 1, - properties + properties, }; this._sourceMapper.updateExtractorMessageOptions(options); @@ -342,22 +372,19 @@ export class MessageRouter { public fetchAssociatedMessagesForReviewFile(astDeclaration: AstDeclaration): ExtractorMessage[] { const messagesForApiReportFile: ExtractorMessage[] = []; - const associatedMessages: ExtractorMessage[] = this._associatedMessagesForAstDeclaration.get(astDeclaration) || []; + const associatedMessages: ExtractorMessage[] = + this._associatedMessagesForAstDeclaration.get(astDeclaration) || []; for (const associatedMessage of associatedMessages) { - // 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); if (reportingRule.addToApiReportFile) { - // Include it in the result, and record that it went to the API report file messagesForApiReportFile.push(associatedMessage); associatedMessage.handled = true; } } - } this._sortMessagesForOutput(messagesForApiReportFile); @@ -372,20 +399,16 @@ export class MessageRouter { const messagesForApiReportFile: ExtractorMessage[] = []; for (const unassociatedMessage of this.messages) { - // 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); if (reportingRule.addToApiReportFile) { - // Include it in the result, and record that it went to the API report file messagesForApiReportFile.push(unassociatedMessage); unassociatedMessage.handled = true; } } - } this._sortMessagesForOutput(messagesForApiReportFile); @@ -414,44 +437,68 @@ export class MessageRouter { } } - public logError(messageId: ConsoleMessageId, message: string, properties?: IExtractorMessageProperties): void { - this._handleMessage(new ExtractorMessage({ - category: ExtractorMessageCategory.Console, - messageId, - text: message, - properties, - logLevel: ExtractorLogLevel.Error - })); + public logError( + messageId: ConsoleMessageId, + message: string, + properties?: IExtractorMessageProperties + ): void { + this._handleMessage( + new ExtractorMessage({ + category: ExtractorMessageCategory.Console, + messageId, + text: message, + properties, + logLevel: ExtractorLogLevel.Error, + }) + ); } - public logWarning(messageId: ConsoleMessageId, message: string, properties?: IExtractorMessageProperties): void { - this._handleMessage(new ExtractorMessage({ - category: ExtractorMessageCategory.Console, - messageId, - text: message, - properties, - logLevel: ExtractorLogLevel.Warning - })); + public logWarning( + messageId: ConsoleMessageId, + message: string, + properties?: IExtractorMessageProperties + ): void { + this._handleMessage( + new ExtractorMessage({ + category: ExtractorMessageCategory.Console, + messageId, + text: message, + properties, + logLevel: ExtractorLogLevel.Warning, + }) + ); } - public logInfo(messageId: ConsoleMessageId, message: string, properties?: IExtractorMessageProperties): void { - this._handleMessage(new ExtractorMessage({ - category: ExtractorMessageCategory.Console, - messageId, - text: message, - properties, - logLevel: ExtractorLogLevel.Info - })); + public logInfo( + messageId: ConsoleMessageId, + message: string, + properties?: IExtractorMessageProperties + ): void { + this._handleMessage( + new ExtractorMessage({ + category: ExtractorMessageCategory.Console, + messageId, + text: message, + properties, + logLevel: ExtractorLogLevel.Info, + }) + ); } - public logVerbose(messageId: ConsoleMessageId, message: string, properties?: IExtractorMessageProperties): void { - this._handleMessage(new ExtractorMessage({ - category: ExtractorMessageCategory.Console, - messageId, - text: message, - properties, - logLevel: ExtractorLogLevel.Verbose - })); + public logVerbose( + messageId: ConsoleMessageId, + message: string, + properties?: IExtractorMessageProperties + ): void { + this._handleMessage( + new ExtractorMessage({ + category: ExtractorMessageCategory.Console, + messageId, + text: message, + properties, + logLevel: ExtractorLogLevel.Verbose, + }) + ); } public logDiagnosticHeader(title: string): void { diff --git a/apps/api-extractor/src/collector/SourceMapper.ts b/apps/api-extractor/src/collector/SourceMapper.ts index 58ba28d2246..5f7daaa0d50 100644 --- a/apps/api-extractor/src/collector/SourceMapper.ts +++ b/apps/api-extractor/src/collector/SourceMapper.ts @@ -26,8 +26,7 @@ interface IOriginalFileInfo { 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(); + private _sourceMapByFilePath: Map = new Map(); // Cache the FileSystem.exists() result for mapped .ts files private _originalFileInfoByPath: Map = new Map(); @@ -74,14 +73,14 @@ export class SourceMapper { // The "source-map" package inexplicably uses 1-based line numbers but 0-based column numbers. // Fix that up proactively so we don't have to deal with it later. generatedColumn: mappingItem.generatedColumn + 1, - originalColumn: mappingItem.originalColumn + 1 + originalColumn: mappingItem.originalColumn + 1, }); }, this, SourceMapConsumer.GENERATED_ORDER ); - sourceMap = { sourceMapConsumer, mappingItems}; + sourceMap = { sourceMapConsumer, mappingItems }; } else { // No source map for this filename sourceMap = null; // eslint-disable-line @rushstack/no-null @@ -108,10 +107,11 @@ export class SourceMapper { options.sourceFileColumn = 1; } - const nearestMappingItem: MappingItem | undefined = SourceMapper._findNearestMappingItem(sourceMap.mappingItems, + const nearestMappingItem: MappingItem | undefined = SourceMapper._findNearestMappingItem( + sourceMap.mappingItems, { line: options.sourceFileLine, - column: options.sourceFileColumn + column: options.sourceFileColumn, } ); @@ -120,23 +120,27 @@ export class SourceMapper { return; } - const mappedFilePath: string = path.resolve(path.dirname(options.sourceFilePath), nearestMappingItem.source); + const mappedFilePath: string = path.resolve( + path.dirname(options.sourceFilePath), + nearestMappingItem.source + ); // Does the mapped filename exist? Use a cache to remember the answer. let originalFileInfo: IOriginalFileInfo | undefined = this._originalFileInfoByPath.get(mappedFilePath); if (originalFileInfo === undefined) { originalFileInfo = { fileExists: FileSystem.exists(mappedFilePath), - maxColumnForLine: [] + maxColumnForLine: [], }; if (originalFileInfo.fileExists) { // Read the file and measure the length of each line - originalFileInfo.maxColumnForLine = - FileSystem.readFile(mappedFilePath, { convertLineEndings: NewlineKind.Lf }) + originalFileInfo.maxColumnForLine = FileSystem.readFile(mappedFilePath, { + convertLineEndings: NewlineKind.Lf, + }) .split('\n') - .map(x => x.length + 1); // +1 since columns are 1-based - originalFileInfo.maxColumnForLine.unshift(0); // Extra item since lines are 1-based + .map((x) => x.length + 1); // +1 since columns are 1-based + originalFileInfo.maxColumnForLine.unshift(0); // Extra item since lines are 1-based } this._originalFileInfoByPath.set(mappedFilePath, originalFileInfo); @@ -151,15 +155,17 @@ export class SourceMapper { // the delta and apply it to the original position. const guessedPosition: Position = { line: nearestMappingItem.originalLine + options.sourceFileLine - nearestMappingItem.generatedLine, - column: nearestMappingItem.originalColumn + options.sourceFileColumn - nearestMappingItem.generatedColumn + column: + nearestMappingItem.originalColumn + options.sourceFileColumn - nearestMappingItem.generatedColumn, }; // Verify that the result is not out of bounds, in cause our heuristic failed - if (guessedPosition.line >= 1 - && guessedPosition.line < originalFileInfo.maxColumnForLine.length - && guessedPosition.column >= 1 - && guessedPosition.column <= originalFileInfo.maxColumnForLine[guessedPosition.line]) { - + if ( + guessedPosition.line >= 1 && + guessedPosition.line < originalFileInfo.maxColumnForLine.length && + guessedPosition.column >= 1 && + guessedPosition.column <= originalFileInfo.maxColumnForLine[guessedPosition.line] + ) { options.sourceFilePath = mappedFilePath; options.sourceFileLine = guessedPosition.line; options.sourceFileColumn = guessedPosition.column; @@ -174,7 +180,10 @@ export class SourceMapper { // The `mappingItems` array is sorted by generatedLine/generatedColumn (GENERATED_ORDER). // The _findNearestMappingItem() lookup is a simple binary search that returns the previous item // if there is no exact match. - private static _findNearestMappingItem(mappingItems: MappingItem[], position: Position): MappingItem | undefined { + private static _findNearestMappingItem( + mappingItems: MappingItem[], + position: Position + ): MappingItem | undefined { if (mappingItems.length === 0) { return undefined; } diff --git a/apps/api-extractor/src/collector/SymbolMetadata.ts b/apps/api-extractor/src/collector/SymbolMetadata.ts index ee942f80fab..d28d731cc4d 100644 --- a/apps/api-extractor/src/collector/SymbolMetadata.ts +++ b/apps/api-extractor/src/collector/SymbolMetadata.ts @@ -19,7 +19,7 @@ export class SymbolMetadata { // `ApiItemMetadata.effectiveReleaseTag` value that is most public. public readonly maxEffectiveReleaseTag: ReleaseTag; - public constructor (options: ISymbolMetadataOptions) { + public constructor(options: ISymbolMetadataOptions) { this.maxEffectiveReleaseTag = options.maxEffectiveReleaseTag; } } diff --git a/apps/api-extractor/src/collector/VisitorState.ts b/apps/api-extractor/src/collector/VisitorState.ts index 11af8582286..74b8feb5289 100644 --- a/apps/api-extractor/src/collector/VisitorState.ts +++ b/apps/api-extractor/src/collector/VisitorState.ts @@ -20,5 +20,5 @@ export enum VisitorState { /** * We are finished vising the node and all its references. */ - Visited = 2 + Visited = 2, } diff --git a/apps/api-extractor/src/collector/WorkingPackage.ts b/apps/api-extractor/src/collector/WorkingPackage.ts index 3ae47076705..7cd76fad9c8 100644 --- a/apps/api-extractor/src/collector/WorkingPackage.ts +++ b/apps/api-extractor/src/collector/WorkingPackage.ts @@ -4,9 +4,7 @@ import * as ts from 'typescript'; import * as tsdoc from '@microsoft/tsdoc'; -import { - INodePackageJson -} from '@rushstack/node-core-library'; +import { INodePackageJson } from '@rushstack/node-core-library'; /** * Constructor options for WorkingPackage diff --git a/apps/api-extractor/src/enhancers/DocCommentEnhancer.ts b/apps/api-extractor/src/enhancers/DocCommentEnhancer.ts index f25afd093a9..382933cdb27 100644 --- a/apps/api-extractor/src/enhancers/DocCommentEnhancer.ts +++ b/apps/api-extractor/src/enhancers/DocCommentEnhancer.ts @@ -65,7 +65,6 @@ export class DocCommentEnhancer { } private _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 @@ -86,9 +85,9 @@ export class DocCommentEnhancer { new tsdoc.DocPlainText({ configuration, text: 'Constructs a new instance of the ' }), new tsdoc.DocCodeSpan({ configuration, - code: classDeclaration.astSymbol.localName + code: classDeclaration.astSymbol.localName, }), - new tsdoc.DocPlainText({ configuration, text: ' class' }) + new tsdoc.DocPlainText({ configuration, text: ' class' }), ]); } @@ -106,8 +105,8 @@ export class DocCommentEnhancer { configuration, blockTag: new tsdoc.DocBlockTag({ configuration, - tagName: tsdoc.StandardTags.remarks.tagName - }) + tagName: tsdoc.StandardTags.remarks.tagName, + }), }); } @@ -115,17 +114,17 @@ export class DocCommentEnhancer { new tsdoc.DocParagraph({ configuration }, [ new tsdoc.DocPlainText({ configuration, - text: `The constructor for this class is marked as internal. Third-party code should not` - + ` call the constructor directly or create subclasses that extend the ` + text: + `The constructor for this class is marked as internal. Third-party code should not` + + ` call the constructor directly or create subclasses that extend the `, }), new tsdoc.DocCodeSpan({ configuration, - code: classDeclaration.astSymbol.localName + code: classDeclaration.astSymbol.localName, }), - new tsdoc.DocPlainText({ configuration, text: ' class.' }) + new tsdoc.DocPlainText({ configuration, text: ' class.' }), ]) ); - } return; } @@ -133,7 +132,9 @@ export class DocCommentEnhancer { if (metadata.tsdocComment) { // Require the summary to contain at least 10 non-spacing characters metadata.needsDocumentation = !tsdoc.PlainTextEmitter.hasAnyTextContent( - metadata.tsdocComment.summarySection, 10); + metadata.tsdocComment.summarySection, + 10 + ); } else { metadata.needsDocumentation = true; } @@ -149,22 +150,24 @@ export class DocCommentEnhancer { private _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 (node.codeDestination.packageName === undefined - || node.codeDestination.packageName === this._collector.workingPackage.name) { - - const referencedAstDeclaration: AstDeclaration | ResolverFailure = this._collector.astReferenceResolver - .resolve(node.codeDestination); + if ( + node.codeDestination.packageName === undefined || + node.codeDestination.packageName === this._collector.workingPackage.name + ) { + const referencedAstDeclaration: + | AstDeclaration + | ResolverFailure = this._collector.astReferenceResolver.resolve(node.codeDestination); if (referencedAstDeclaration instanceof ResolverFailure) { - this._collector.messageRouter.addAnalyzerIssue(ExtractorMessageId.UnresolvedLink, + this._collector.messageRouter.addAnalyzerIssue( + ExtractorMessageId.UnresolvedLink, 'The @link reference could not be resolved: ' + referencedAstDeclaration.reason, - astDeclaration); + astDeclaration + ); } - } } } @@ -176,38 +179,51 @@ export class DocCommentEnhancer { /** * Follow an `{@inheritDoc ___}` reference and copy the content that we find in the referenced comment. */ - private _applyInheritDoc(astDeclaration: AstDeclaration, docComment: tsdoc.DocComment, - inheritDocTag: tsdoc.DocInheritDocTag): void { - + private _applyInheritDoc( + astDeclaration: AstDeclaration, + docComment: tsdoc.DocComment, + inheritDocTag: tsdoc.DocInheritDocTag + ): void { if (!inheritDocTag.declarationReference) { - this._collector.messageRouter.addAnalyzerIssue(ExtractorMessageId.UnresolvedInheritDocBase, + this._collector.messageRouter.addAnalyzerIssue( + ExtractorMessageId.UnresolvedInheritDocBase, 'The @inheritDoc tag needs a TSDoc declaration reference; signature matching is not supported yet', - astDeclaration); + astDeclaration + ); return; } // Is it referring to the working package? - if (!(inheritDocTag.declarationReference.packageName === undefined - || inheritDocTag.declarationReference.packageName === this._collector.workingPackage.name)) { - + if ( + !( + inheritDocTag.declarationReference.packageName === undefined || + inheritDocTag.declarationReference.packageName === this._collector.workingPackage.name + ) + ) { // It's referencing an external package, so skip this inheritDoc tag, 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 return; } - const referencedAstDeclaration: AstDeclaration | ResolverFailure = this._collector.astReferenceResolver - .resolve(inheritDocTag.declarationReference); + const referencedAstDeclaration: + | AstDeclaration + | ResolverFailure = this._collector.astReferenceResolver.resolve(inheritDocTag.declarationReference); if (referencedAstDeclaration instanceof ResolverFailure) { - this._collector.messageRouter.addAnalyzerIssue(ExtractorMessageId.UnresolvedInheritDocReference, - 'The @inheritDoc reference could not be resolved: ' + referencedAstDeclaration.reason, astDeclaration); + this._collector.messageRouter.addAnalyzerIssue( + ExtractorMessageId.UnresolvedInheritDocReference, + 'The @inheritDoc reference could not be resolved: ' + referencedAstDeclaration.reason, + astDeclaration + ); return; } this._analyzeApiItem(referencedAstDeclaration); - const referencedMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(referencedAstDeclaration); + const referencedMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata( + referencedAstDeclaration + ); if (referencedMetadata.tsdocComment) { this._copyInheritedDocs(docComment, referencedMetadata.tsdocComment); @@ -232,5 +248,4 @@ export class DocCommentEnhancer { targetDocComment.inheritDocTag = undefined; } - } diff --git a/apps/api-extractor/src/enhancers/ValidationEnhancer.ts b/apps/api-extractor/src/enhancers/ValidationEnhancer.ts index 94bed1b2588..5e6ed43b75e 100644 --- a/apps/api-extractor/src/enhancers/ValidationEnhancer.ts +++ b/apps/api-extractor/src/enhancers/ValidationEnhancer.ts @@ -14,7 +14,6 @@ import { ExtractorMessageId } from '../api/ExtractorMessageId'; import { ReleaseTag } from '@microsoft/api-extractor-model'; export class ValidationEnhancer { - public static analyze(collector: Collector): void { const alreadyWarnedSymbols: Set = new Set(); @@ -39,7 +38,6 @@ export class ValidationEnhancer { astSymbol: AstSymbol, symbolMetadata: SymbolMetadata ): void { - let needsUnderscore: boolean = false; if (symbolMetadata.maxEffectiveReleaseTag === ReleaseTag.Internal) { @@ -82,8 +80,8 @@ export class ValidationEnhancer { if (exportName[0] !== '_') { collector.messageRouter.addAnalyzerIssue( ExtractorMessageId.InternalMissingUnderscore, - `The name "${exportName}" should be prefixed with an underscore` - + ` because the declaration is marked as @internal`, + `The name "${exportName}" should be prefixed with an underscore` + + ` because the declaration is marked as @internal`, astSymbol, { exportName } ); @@ -150,7 +148,7 @@ export class ValidationEnhancer { collector.messageRouter.addAnalyzerIssue( ExtractorMessageId.InternalMixedReleaseTag, `Mixed release tags are not allowed for "${astSymbol.localName}" because one of its declarations` + - ` is marked as @internal`, + ` is marked as @internal`, astSymbol ); } @@ -166,7 +164,6 @@ export class ValidationEnhancer { const declarationReleaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; for (const referencedEntity of astDeclaration.referencedAstEntities) { - if (referencedEntity instanceof AstSymbol) { // If this is e.g. a member of a namespace, then we need to be checking the top-level scope to see // whether it's exported. @@ -182,15 +179,19 @@ export class ValidationEnhancer { const referencedReleaseTag: ReleaseTag = referencedMetadata.maxEffectiveReleaseTag; if (ReleaseTag.compare(declarationReleaseTag, referencedReleaseTag) > 0) { - collector.messageRouter.addAnalyzerIssue(ExtractorMessageId.IncompatibleReleaseTags, - `The symbol "${astDeclaration.astSymbol.localName}"` - + ` is marked as ${ReleaseTag.getTagName(declarationReleaseTag)},` - + ` but its signature references "${referencedEntity.localName}"` - + ` which is marked as ${ReleaseTag.getTagName(referencedReleaseTag)}`, - astDeclaration); + collector.messageRouter.addAnalyzerIssue( + ExtractorMessageId.IncompatibleReleaseTags, + `The symbol "${astDeclaration.astSymbol.localName}"` + + ` is marked as ${ReleaseTag.getTagName(declarationReleaseTag)},` + + ` but its signature references "${referencedEntity.localName}"` + + ` which is marked as ${ReleaseTag.getTagName(referencedReleaseTag)}`, + astDeclaration + ); } } else { - const entryPointFilename: string = path.basename(collector.workingPackage.entryPointSourceFile.fileName); + const entryPointFilename: string = path.basename( + collector.workingPackage.entryPointSourceFile.fileName + ); if (!alreadyWarnedSymbols.has(referencedEntity)) { alreadyWarnedSymbols.add(referencedEntity); @@ -198,15 +199,14 @@ export class ValidationEnhancer { // The main usage scenario for ECMAScript symbols is to attach private data to a JavaScript object, // so as a special case, we do NOT report them as forgotten exports. if (!ValidationEnhancer._isEcmaScriptSymbol(referencedEntity)) { - - collector.messageRouter.addAnalyzerIssue(ExtractorMessageId.ForgottenExport, - `The symbol "${rootSymbol.localName}" needs to be exported` - + ` by the entry point ${entryPointFilename}`, - astDeclaration); + collector.messageRouter.addAnalyzerIssue( + ExtractorMessageId.ForgottenExport, + `The symbol "${rootSymbol.localName}" needs to be exported` + + ` by the entry point ${entryPointFilename}`, + astDeclaration + ); } - } - } } } @@ -243,5 +243,4 @@ export class ValidationEnhancer { return false; } - } diff --git a/apps/api-extractor/src/generators/ApiModelGenerator.ts b/apps/api-extractor/src/generators/ApiModelGenerator.ts index aaaeb3935fb..5e05e682ee4 100644 --- a/apps/api-extractor/src/generators/ApiModelGenerator.ts +++ b/apps/api-extractor/src/generators/ApiModelGenerator.ts @@ -30,7 +30,7 @@ import { ApiVariable, ApiTypeAlias, ApiCallSignature, - IApiTypeParameterOptions + IApiTypeParameterOptions, } from '@microsoft/api-extractor-model'; import { Collector } from '../collector/Collector'; @@ -53,7 +53,8 @@ export class ApiModelGenerator { collector.packageJsonLookup, collector.workingPackage.name, collector.program, - collector.typeChecker); + collector.typeChecker + ); } public get apiModel(): ApiModel { @@ -65,7 +66,7 @@ export class ApiModelGenerator { const apiPackage: ApiPackage = new ApiPackage({ name: this._collector.workingPackage.name, - docComment: packageDocComment + docComment: packageDocComment, }); this._apiModel.addMember(apiPackage); @@ -91,9 +92,11 @@ export class ApiModelGenerator { return apiPackage; } - private _processDeclaration(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processDeclaration( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { if ((astDeclaration.modifierFlags & ts.ModifierFlags.Private) !== 0) { return; // trim out private declarations } @@ -174,25 +177,31 @@ export class ApiModelGenerator { break; default: - // ignore unknown types + // ignore unknown types } } - private _processChildDeclarations(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { + private _processChildDeclarations( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { for (const childDeclaration of astDeclaration.children) { this._processDeclaration(childDeclaration, undefined, parentApiItem); } } - private _processApiCallSignature(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiCallSignature( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const overloadIndex: number = this._collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiCallSignature.getContainerKey(overloadIndex); - let apiCallSignature: ApiCallSignature | undefined = parentApiItem.tryGetMemberByKey(containerKey) as - ApiCallSignature; + let apiCallSignature: ApiCallSignature | undefined = parentApiItem.tryGetMemberByKey( + containerKey + ) as ApiCallSignature; if (apiCallSignature === undefined) { const callSignature: ts.CallSignatureDeclaration = astDeclaration.declaration as ts.CallSignatureDeclaration; @@ -202,10 +211,15 @@ export class ApiModelGenerator { const returnTypeTokenRange: IExcerptTokenRange = ExcerptBuilder.createEmptyTokenRange(); nodesToCapture.push({ node: callSignature.type, tokenRange: returnTypeTokenRange }); - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters(nodesToCapture, - callSignature.typeParameters); + const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + nodesToCapture, + callSignature.typeParameters + ); - const parameters: IApiParameterOptions[] = this._captureParameters(nodesToCapture, callSignature.parameters); + const parameters: IApiParameterOptions[] = this._captureParameters( + nodesToCapture, + callSignature.parameters + ); const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodesToCapture); const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); @@ -219,28 +233,34 @@ export class ApiModelGenerator { parameters, overloadIndex, excerptTokens, - returnTypeTokenRange + returnTypeTokenRange, }); parentApiItem.addMember(apiCallSignature); } } - private _processApiConstructor(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiConstructor( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const overloadIndex: number = this._collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiConstructor.getContainerKey(overloadIndex); - let apiConstructor: ApiConstructor | undefined = parentApiItem.tryGetMemberByKey(containerKey) as ApiConstructor; + let apiConstructor: ApiConstructor | undefined = parentApiItem.tryGetMemberByKey( + containerKey + ) as ApiConstructor; if (apiConstructor === undefined) { const constructorDeclaration: ts.ConstructorDeclaration = astDeclaration.declaration as ts.ConstructorDeclaration; const nodesToCapture: IExcerptBuilderNodeToCapture[] = []; - const parameters: IApiParameterOptions[] = this._captureParameters(nodesToCapture, - constructorDeclaration.parameters); + const parameters: IApiParameterOptions[] = this._captureParameters( + nodesToCapture, + constructorDeclaration.parameters + ); const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodesToCapture); const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); @@ -252,16 +272,18 @@ export class ApiModelGenerator { releaseTag, parameters, overloadIndex, - excerptTokens + excerptTokens, }); parentApiItem.addMember(apiConstructor); } } - private _processApiClass(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiClass( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const name: string = exportedName ? exportedName : astDeclaration.astSymbol.localName; const containerKey: string = ApiClass.getContainerKey(name); @@ -272,8 +294,10 @@ export class ApiModelGenerator { const nodesToCapture: IExcerptBuilderNodeToCapture[] = []; - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters(nodesToCapture, - classDeclaration.typeParameters); + const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + nodesToCapture, + classDeclaration.typeParameters + ); let extendsTokenRange: IExcerptTokenRange | undefined = undefined; const implementsTokenRanges: IExcerptTokenRange[] = []; @@ -282,13 +306,13 @@ export class ApiModelGenerator { if (heritageClause.token === ts.SyntaxKind.ExtendsKeyword) { extendsTokenRange = ExcerptBuilder.createEmptyTokenRange(); if (heritageClause.types.length > 0) { - nodesToCapture.push({ node: heritageClause.types[0], tokenRange: extendsTokenRange}); + nodesToCapture.push({ node: heritageClause.types[0], tokenRange: extendsTokenRange }); } } else if (heritageClause.token === ts.SyntaxKind.ImplementsKeyword) { for (const heritageType of heritageClause.types) { const implementsTokenRange: IExcerptTokenRange = ExcerptBuilder.createEmptyTokenRange(); implementsTokenRanges.push(implementsTokenRange); - nodesToCapture.push({ node: heritageType, tokenRange: implementsTokenRange}); + nodesToCapture.push({ node: heritageType, tokenRange: implementsTokenRange }); } } } @@ -305,7 +329,7 @@ export class ApiModelGenerator { excerptTokens, typeParameters, extendsTokenRange, - implementsTokenRanges + implementsTokenRanges, }); parentApiItem.addMember(apiClass); @@ -314,28 +338,35 @@ export class ApiModelGenerator { this._processChildDeclarations(astDeclaration, exportedName, apiClass); } - private _processApiConstructSignature(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiConstructSignature( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const overloadIndex: number = this._collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiConstructSignature.getContainerKey(overloadIndex); - let apiConstructSignature: ApiConstructSignature | undefined = parentApiItem.tryGetMemberByKey(containerKey) as - ApiConstructSignature; + let apiConstructSignature: ApiConstructSignature | undefined = parentApiItem.tryGetMemberByKey( + containerKey + ) as ApiConstructSignature; if (apiConstructSignature === undefined) { - const constructSignature: ts.ConstructSignatureDeclaration = astDeclaration.declaration as - ts.ConstructSignatureDeclaration; + const constructSignature: ts.ConstructSignatureDeclaration = astDeclaration.declaration as ts.ConstructSignatureDeclaration; const nodesToCapture: IExcerptBuilderNodeToCapture[] = []; const returnTypeTokenRange: IExcerptTokenRange = ExcerptBuilder.createEmptyTokenRange(); nodesToCapture.push({ node: constructSignature.type, tokenRange: returnTypeTokenRange }); - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters(nodesToCapture, - constructSignature.typeParameters); + const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + nodesToCapture, + constructSignature.typeParameters + ); - const parameters: IApiParameterOptions[] = this._captureParameters(nodesToCapture, constructSignature.parameters); + const parameters: IApiParameterOptions[] = this._captureParameters( + nodesToCapture, + constructSignature.parameters + ); const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodesToCapture); const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); @@ -349,16 +380,18 @@ export class ApiModelGenerator { parameters, overloadIndex, excerptTokens, - returnTypeTokenRange + returnTypeTokenRange, }); parentApiItem.addMember(apiConstructSignature); } } - private _processApiEnum(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiEnum( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const name: string = exportedName ? exportedName : astDeclaration.astSymbol.localName; const containerKey: string = ApiEnum.getContainerKey(name); @@ -377,13 +410,17 @@ export class ApiModelGenerator { this._processChildDeclarations(astDeclaration, exportedName, apiEnum); } - private _processApiEnumMember(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiEnumMember( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const name: string = exportedName ? exportedName : astDeclaration.astSymbol.localName; const containerKey: string = ApiEnumMember.getContainerKey(name); - let apiEnumMember: ApiEnumMember | undefined = parentApiItem.tryGetMemberByKey(containerKey) as ApiEnumMember; + let apiEnumMember: ApiEnumMember | undefined = parentApiItem.tryGetMemberByKey( + containerKey + ) as ApiEnumMember; if (apiEnumMember === undefined) { const enumMember: ts.EnumMember = astDeclaration.declaration as ts.EnumMember; @@ -403,23 +440,24 @@ export class ApiModelGenerator { docComment, releaseTag, excerptTokens, - initializerTokenRange + initializerTokenRange, }); parentApiItem.addMember(apiEnumMember); } } - private _processApiFunction(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiFunction( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const name: string = exportedName ? exportedName : astDeclaration.astSymbol.localName; const overloadIndex: number = this._collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiFunction.getContainerKey(name, overloadIndex); - let apiFunction: ApiFunction | undefined = parentApiItem.tryGetMemberByKey(containerKey) as - ApiFunction; + let apiFunction: ApiFunction | undefined = parentApiItem.tryGetMemberByKey(containerKey) as ApiFunction; if (apiFunction === undefined) { const functionDeclaration: ts.FunctionDeclaration = astDeclaration.declaration as ts.FunctionDeclaration; @@ -429,11 +467,15 @@ export class ApiModelGenerator { const returnTypeTokenRange: IExcerptTokenRange = ExcerptBuilder.createEmptyTokenRange(); nodesToCapture.push({ node: functionDeclaration.type, tokenRange: returnTypeTokenRange }); - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters(nodesToCapture, - functionDeclaration.typeParameters); + const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + nodesToCapture, + functionDeclaration.typeParameters + ); - const parameters: IApiParameterOptions[] = this._captureParameters(nodesToCapture, - functionDeclaration.parameters); + const parameters: IApiParameterOptions[] = this._captureParameters( + nodesToCapture, + functionDeclaration.parameters + ); const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodesToCapture); const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); @@ -451,21 +493,24 @@ export class ApiModelGenerator { parameters, overloadIndex, excerptTokens, - returnTypeTokenRange + returnTypeTokenRange, }); parentApiItem.addMember(apiFunction); } } - private _processApiIndexSignature(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiIndexSignature( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const overloadIndex: number = this._collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiIndexSignature.getContainerKey(overloadIndex); - let apiIndexSignature: ApiIndexSignature | undefined = parentApiItem.tryGetMemberByKey(containerKey) as - ApiIndexSignature; + let apiIndexSignature: ApiIndexSignature | undefined = parentApiItem.tryGetMemberByKey( + containerKey + ) as ApiIndexSignature; if (apiIndexSignature === undefined) { const indexSignature: ts.IndexSignatureDeclaration = astDeclaration.declaration as ts.IndexSignatureDeclaration; @@ -475,7 +520,10 @@ export class ApiModelGenerator { const returnTypeTokenRange: IExcerptTokenRange = ExcerptBuilder.createEmptyTokenRange(); nodesToCapture.push({ node: indexSignature.type, tokenRange: returnTypeTokenRange }); - const parameters: IApiParameterOptions[] = this._captureParameters(nodesToCapture, indexSignature.parameters); + const parameters: IApiParameterOptions[] = this._captureParameters( + nodesToCapture, + indexSignature.parameters + ); const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodesToCapture); const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); @@ -488,28 +536,34 @@ export class ApiModelGenerator { parameters, overloadIndex, excerptTokens, - returnTypeTokenRange + returnTypeTokenRange, }); parentApiItem.addMember(apiIndexSignature); } } - private _processApiInterface(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiInterface( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const name: string = exportedName ? exportedName : astDeclaration.astSymbol.localName; const containerKey: string = ApiInterface.getContainerKey(name); - let apiInterface: ApiInterface | undefined = parentApiItem.tryGetMemberByKey(containerKey) as ApiInterface; + let apiInterface: ApiInterface | undefined = parentApiItem.tryGetMemberByKey( + containerKey + ) as ApiInterface; if (apiInterface === undefined) { const interfaceDeclaration: ts.InterfaceDeclaration = astDeclaration.declaration as ts.InterfaceDeclaration; const nodesToCapture: IExcerptBuilderNodeToCapture[] = []; - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters(nodesToCapture, - interfaceDeclaration.typeParameters); + const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + nodesToCapture, + interfaceDeclaration.typeParameters + ); const extendsTokenRanges: IExcerptTokenRange[] = []; @@ -518,7 +572,7 @@ export class ApiModelGenerator { for (const heritageType of heritageClause.types) { const extendsTokenRange: IExcerptTokenRange = ExcerptBuilder.createEmptyTokenRange(); extendsTokenRanges.push(extendsTokenRange); - nodesToCapture.push({ node: heritageType, tokenRange: extendsTokenRange}); + nodesToCapture.push({ node: heritageType, tokenRange: extendsTokenRange }); } } } @@ -534,7 +588,7 @@ export class ApiModelGenerator { releaseTag, excerptTokens, typeParameters, - extendsTokenRanges + extendsTokenRanges, }); parentApiItem.addMember(apiInterface); @@ -543,9 +597,11 @@ export class ApiModelGenerator { this._processChildDeclarations(astDeclaration, exportedName, apiInterface); } - private _processApiMethod(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiMethod( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const name: string = exportedName ? exportedName : astDeclaration.astSymbol.localName; const isStatic: boolean = (astDeclaration.modifierFlags & ts.ModifierFlags.Static) !== 0; @@ -562,10 +618,15 @@ export class ApiModelGenerator { const returnTypeTokenRange: IExcerptTokenRange = ExcerptBuilder.createEmptyTokenRange(); nodesToCapture.push({ node: methodDeclaration.type, tokenRange: returnTypeTokenRange }); - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters(nodesToCapture, - methodDeclaration.typeParameters); + const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + nodesToCapture, + methodDeclaration.typeParameters + ); - const parameters: IApiParameterOptions[] = this._captureParameters(nodesToCapture, methodDeclaration.parameters); + const parameters: IApiParameterOptions[] = this._captureParameters( + nodesToCapture, + methodDeclaration.parameters + ); const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodesToCapture); const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); @@ -584,23 +645,26 @@ export class ApiModelGenerator { parameters, overloadIndex, excerptTokens, - returnTypeTokenRange + returnTypeTokenRange, }); parentApiItem.addMember(apiMethod); } } - private _processApiMethodSignature(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiMethodSignature( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const name: string = exportedName ? exportedName : astDeclaration.astSymbol.localName; const overloadIndex: number = this._collector.getOverloadIndex(astDeclaration); const containerKey: string = ApiMethodSignature.getContainerKey(name, overloadIndex); - let apiMethodSignature: ApiMethodSignature | undefined = parentApiItem.tryGetMemberByKey(containerKey) as - ApiMethodSignature; + let apiMethodSignature: ApiMethodSignature | undefined = parentApiItem.tryGetMemberByKey( + containerKey + ) as ApiMethodSignature; if (apiMethodSignature === undefined) { const methodSignature: ts.MethodSignature = astDeclaration.declaration as ts.MethodSignature; @@ -610,10 +674,15 @@ export class ApiModelGenerator { const returnTypeTokenRange: IExcerptTokenRange = ExcerptBuilder.createEmptyTokenRange(); nodesToCapture.push({ node: methodSignature.type, tokenRange: returnTypeTokenRange }); - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters(nodesToCapture, - methodSignature.typeParameters); + const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + nodesToCapture, + methodSignature.typeParameters + ); - const parameters: IApiParameterOptions[] = this._captureParameters(nodesToCapture, methodSignature.parameters); + const parameters: IApiParameterOptions[] = this._captureParameters( + nodesToCapture, + methodSignature.parameters + ); const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, nodesToCapture); const apiItemMetadata: ApiItemMetadata = this._collector.fetchApiItemMetadata(astDeclaration); @@ -628,20 +697,24 @@ export class ApiModelGenerator { parameters, overloadIndex, excerptTokens, - returnTypeTokenRange + returnTypeTokenRange, }); parentApiItem.addMember(apiMethodSignature); } } - private _processApiNamespace(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiNamespace( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const name: string = exportedName ? exportedName : astDeclaration.astSymbol.localName; const containerKey: string = ApiNamespace.getContainerKey(name); - let apiNamespace: ApiNamespace | undefined = parentApiItem.tryGetMemberByKey(containerKey) as ApiNamespace; + let apiNamespace: ApiNamespace | undefined = parentApiItem.tryGetMemberByKey( + containerKey + ) as ApiNamespace; if (apiNamespace === undefined) { const excerptTokens: IExcerptToken[] = this._buildExcerptTokens(astDeclaration, []); @@ -656,17 +729,18 @@ export class ApiModelGenerator { this._processChildDeclarations(astDeclaration, exportedName, apiNamespace); } - private _processApiProperty(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiProperty( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const name: string = exportedName ? exportedName : astDeclaration.astSymbol.localName; const isStatic: boolean = (astDeclaration.modifierFlags & ts.ModifierFlags.Static) !== 0; const containerKey: string = ApiProperty.getContainerKey(name, isStatic); - let apiProperty: ApiProperty | undefined - = parentApiItem.tryGetMemberByKey(containerKey) as ApiProperty; + let apiProperty: ApiProperty | undefined = parentApiItem.tryGetMemberByKey(containerKey) as ApiProperty; if (apiProperty === undefined) { const propertyDeclaration: ts.PropertyDeclaration = astDeclaration.declaration as ts.PropertyDeclaration; @@ -681,7 +755,14 @@ export class ApiModelGenerator { const docComment: tsdoc.DocComment | undefined = apiItemMetadata.tsdocComment; const releaseTag: ReleaseTag = apiItemMetadata.effectiveReleaseTag; - apiProperty = new ApiProperty({ name, docComment, releaseTag, isStatic, excerptTokens, propertyTypeTokenRange }); + apiProperty = new ApiProperty({ + name, + docComment, + releaseTag, + isStatic, + excerptTokens, + propertyTypeTokenRange, + }); parentApiItem.addMember(apiProperty); } else { // If the property was already declared before (via a merged interface declaration), @@ -689,14 +770,17 @@ export class ApiModelGenerator { } } - private _processApiPropertySignature(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiPropertySignature( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const name: string = exportedName ? exportedName : astDeclaration.astSymbol.localName; const containerKey: string = ApiPropertySignature.getContainerKey(name); - let apiPropertySignature: ApiPropertySignature | undefined - = parentApiItem.tryGetMemberByKey(containerKey) as ApiPropertySignature; + let apiPropertySignature: ApiPropertySignature | undefined = parentApiItem.tryGetMemberByKey( + containerKey + ) as ApiPropertySignature; if (apiPropertySignature === undefined) { const propertySignature: ts.PropertySignature = astDeclaration.declaration as ts.PropertySignature; @@ -716,7 +800,7 @@ export class ApiModelGenerator { docComment, releaseTag, excerptTokens, - propertyTypeTokenRange + propertyTypeTokenRange, }); parentApiItem.addMember(apiPropertySignature); @@ -726,23 +810,28 @@ export class ApiModelGenerator { } } - private _processApiTypeAlias(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiTypeAlias( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const name: string = exportedName ? exportedName : astDeclaration.astSymbol.localName; const containerKey: string = ApiTypeAlias.getContainerKey(name); - let apiTypeAlias: ApiTypeAlias | undefined = parentApiItem.tryGetMemberByKey(containerKey) as - ApiTypeAlias; + let apiTypeAlias: ApiTypeAlias | undefined = parentApiItem.tryGetMemberByKey( + containerKey + ) as ApiTypeAlias; if (apiTypeAlias === undefined) { const typeAliasDeclaration: ts.TypeAliasDeclaration = astDeclaration.declaration as ts.TypeAliasDeclaration; const nodesToCapture: IExcerptBuilderNodeToCapture[] = []; - const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters(nodesToCapture, - typeAliasDeclaration.typeParameters); + const typeParameters: IApiTypeParameterOptions[] = this._captureTypeParameters( + nodesToCapture, + typeAliasDeclaration.typeParameters + ); const typeTokenRange: IExcerptTokenRange = ExcerptBuilder.createEmptyTokenRange(); nodesToCapture.push({ node: typeAliasDeclaration.type, tokenRange: typeTokenRange }); @@ -758,22 +847,23 @@ export class ApiModelGenerator { typeParameters, releaseTag, excerptTokens, - typeTokenRange + typeTokenRange, }); parentApiItem.addMember(apiTypeAlias); } } - private _processApiVariable(astDeclaration: AstDeclaration, exportedName: string | undefined, - parentApiItem: ApiItemContainerMixin): void { - + private _processApiVariable( + astDeclaration: AstDeclaration, + exportedName: string | undefined, + parentApiItem: ApiItemContainerMixin + ): void { const name: string = exportedName ? exportedName : astDeclaration.astSymbol.localName; const containerKey: string = ApiVariable.getContainerKey(name); - let apiVariable: ApiVariable | undefined = parentApiItem.tryGetMemberByKey(containerKey) as - ApiVariable; + let apiVariable: ApiVariable | undefined = parentApiItem.tryGetMemberByKey(containerKey) as ApiVariable; if (apiVariable === undefined) { const variableDeclaration: ts.VariableDeclaration = astDeclaration.declaration as ts.VariableDeclaration; @@ -797,9 +887,10 @@ export class ApiModelGenerator { /** * @param nodesToCapture - A list of child nodes whose token ranges we want to capture */ - private _buildExcerptTokens(astDeclaration: AstDeclaration, - nodesToCapture: IExcerptBuilderNodeToCapture[]): IExcerptToken[] { - + private _buildExcerptTokens( + astDeclaration: AstDeclaration, + nodesToCapture: IExcerptBuilderNodeToCapture[] + ): IExcerptToken[] { const excerptTokens: IExcerptToken[] = []; // Build the main declaration @@ -810,15 +901,21 @@ export class ApiModelGenerator { // Add any ancillary declarations for (const ancillaryDeclaration of declarationMetadata.ancillaryDeclarations) { ExcerptBuilder.addBlankLine(excerptTokens); - ExcerptBuilder.addDeclaration(excerptTokens, ancillaryDeclaration, nodesToCapture, this._referenceGenerator); + ExcerptBuilder.addDeclaration( + excerptTokens, + ancillaryDeclaration, + nodesToCapture, + this._referenceGenerator + ); } return excerptTokens; } - private _captureTypeParameters(nodesToCapture: IExcerptBuilderNodeToCapture[], typeParameterNodes: - ts.NodeArray | undefined): IApiTypeParameterOptions[] { - + private _captureTypeParameters( + nodesToCapture: IExcerptBuilderNodeToCapture[], + typeParameterNodes: ts.NodeArray | undefined + ): IApiTypeParameterOptions[] { const typeParameters: IApiTypeParameterOptions[] = []; if (typeParameterNodes) { for (const typeParameter of typeParameterNodes) { @@ -831,23 +928,24 @@ export class ApiModelGenerator { typeParameters.push({ typeParameterName: typeParameter.name.getText().trim(), constraintTokenRange, - defaultTypeTokenRange + defaultTypeTokenRange, }); } } return typeParameters; } - private _captureParameters(nodesToCapture: IExcerptBuilderNodeToCapture[], - parameterNodes: ts.NodeArray): IApiParameterOptions[] { - + private _captureParameters( + nodesToCapture: IExcerptBuilderNodeToCapture[], + parameterNodes: ts.NodeArray + ): IApiParameterOptions[] { const parameters: IApiParameterOptions[] = []; for (const parameter of parameterNodes) { const parameterTypeTokenRange: IExcerptTokenRange = ExcerptBuilder.createEmptyTokenRange(); nodesToCapture.push({ node: parameter.type, tokenRange: parameterTypeTokenRange }); parameters.push({ parameterName: parameter.name.getText().trim(), - parameterTypeTokenRange + parameterTypeTokenRange, }); } return parameters; diff --git a/apps/api-extractor/src/generators/ApiReportGenerator.ts b/apps/api-extractor/src/generators/ApiReportGenerator.ts index 2d76419f6c7..98c8b615745 100644 --- a/apps/api-extractor/src/generators/ApiReportGenerator.ts +++ b/apps/api-extractor/src/generators/ApiReportGenerator.ts @@ -27,7 +27,10 @@ export class ApiReportGenerator { * might be introduced by a tool, e.g. Git newline normalization or an editor that strips * whitespace when saving. */ - public static areEquivalentApiFileContents(actualFileContent: string, expectedFileContent: string): boolean { + public static areEquivalentApiFileContents( + actualFileContent: string, + expectedFileContent: string + ): boolean { // NOTE: "\s" also matches "\r" and "\n" const normalizedActual: string = actualFileContent.replace(/[\s]+/g, ' '); const normalizedExpected: string = expectedFileContent.replace(/[\s]+/g, ' '); @@ -37,12 +40,14 @@ export class ApiReportGenerator { public static generateReviewFileContent(collector: Collector): string { const stringWriter: StringWriter = new StringWriter(); - stringWriter.writeLine([ - `## API Report File for "${collector.workingPackage.name}"`, - ``, - `> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).`, - `` - ].join('\n')); + stringWriter.writeLine( + [ + `## API Report File for "${collector.workingPackage.name}"`, + ``, + `> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).`, + ``, + ].join('\n') + ); // Write the opening delimiter for the Markdown code fence stringWriter.writeLine('```ts\n'); @@ -63,7 +68,6 @@ export class ApiReportGenerator { // Emit the regular declarations for (const entity of collector.entities) { if (entity.exported) { - // First, collect the list of export names for this symbol. When reporting messages with // ExtractorMessage.properties.exportName, this will enable us to emit the warning comments alongside // the associated export statement. @@ -82,10 +86,10 @@ export class ApiReportGenerator { if (entity.astEntity instanceof AstSymbol) { // Emit all the declarations for this entity for (const astDeclaration of entity.astEntity.astDeclarations || []) { - // Get the messages associated with this declaration - const fetchedMessages: ExtractorMessage[] = collector.messageRouter - .fetchAssociatedMessagesForReviewFile(astDeclaration); + const fetchedMessages: ExtractorMessage[] = collector.messageRouter.fetchAssociatedMessagesForReviewFile( + astDeclaration + ); // Peel off the messages associated with an export statement and store them // in IExportToEmit.associatedMessages (to be processed later). The remaining messages will @@ -93,7 +97,9 @@ export class ApiReportGenerator { const messagesToReport: ExtractorMessage[] = []; for (const message of fetchedMessages) { if (message.properties.exportName) { - const exportToEmit: IExportToEmit | undefined = exportsToEmit.get(message.properties.exportName); + const exportToEmit: IExportToEmit | undefined = exportsToEmit.get( + message.properties.exportName + ); if (exportToEmit) { exportToEmit.associatedMessages.push(message); continue; @@ -102,7 +108,9 @@ export class ApiReportGenerator { messagesToReport.push(message); } - stringWriter.write(ApiReportGenerator._getAedocSynopsis(collector, astDeclaration, messagesToReport)); + stringWriter.write( + ApiReportGenerator._getAedocSynopsis(collector, astDeclaration, messagesToReport) + ); const span: Span = new Span(astDeclaration.declaration); @@ -122,8 +130,10 @@ export class ApiReportGenerator { for (const exportToEmit of exportsToEmit.values()) { // Write any associated messages for (const message of exportToEmit.associatedMessages) { - ApiReportGenerator._writeLineAsComments(stringWriter, - 'Warning: ' + message.formatMessageWithoutLocation()); + ApiReportGenerator._writeLineAsComments( + stringWriter, + 'Warning: ' + message.formatMessageWithoutLocation() + ); } DtsEmitHelpers.emitNamedExport(stringWriter, exportToEmit.exportName, entity); @@ -135,22 +145,25 @@ export class ApiReportGenerator { DtsEmitHelpers.emitStarExports(stringWriter, collector); // Write the unassociated warnings at the bottom of the file - const unassociatedMessages: ExtractorMessage[] = collector.messageRouter - .fetchUnassociatedMessagesForReviewFile(); + const unassociatedMessages: ExtractorMessage[] = collector.messageRouter.fetchUnassociatedMessagesForReviewFile(); if (unassociatedMessages.length > 0) { stringWriter.writeLine(); ApiReportGenerator._writeLineAsComments(stringWriter, 'Warnings were encountered during analysis:'); ApiReportGenerator._writeLineAsComments(stringWriter, ''); for (const unassociatedMessage of unassociatedMessages) { - ApiReportGenerator._writeLineAsComments(stringWriter, unassociatedMessage.formatMessageWithLocation( - collector.workingPackage.packageFolder - )); + ApiReportGenerator._writeLineAsComments( + stringWriter, + unassociatedMessage.formatMessageWithLocation(collector.workingPackage.packageFolder) + ); } } if (collector.workingPackage.tsdocComment === undefined) { stringWriter.writeLine(); - ApiReportGenerator._writeLineAsComments(stringWriter, '(No @packageDocumentation comment for this package)'); + ApiReportGenerator._writeLineAsComments( + stringWriter, + '(No @packageDocumentation comment for this package)' + ); } // Write the closing delimiter for the Markdown code fence @@ -163,11 +176,16 @@ export class ApiReportGenerator { /** * Before writing out a declaration, _modifySpan() applies various fixups to make it nice. */ - private static _modifySpan(collector: Collector, span: Span, entity: CollectorEntity, - astDeclaration: AstDeclaration, insideTypeLiteral: boolean): void { - + private static _modifySpan( + collector: Collector, + span: Span, + entity: CollectorEntity, + astDeclaration: AstDeclaration, + insideTypeLiteral: boolean + ): void { // Should we process this declaration at all? - if ((astDeclaration.modifierFlags & ts.ModifierFlags.Private) !== 0) { // eslint-disable-line no-bitwise + if ((astDeclaration.modifierFlags & ts.ModifierFlags.Private) !== 0) { + // eslint-disable-line no-bitwise span.modification.skipAll(); return; } @@ -228,7 +246,7 @@ export class ApiReportGenerator { } break; - case ts.SyntaxKind.VariableDeclaration: + case ts.SyntaxKind.VariableDeclaration: if (!span.parent) { // The VariableDeclaration node is part of a VariableDeclarationList, however // the Entry.followedSymbol points to the VariableDeclaration part because @@ -237,14 +255,17 @@ export class ApiReportGenerator { // Since we are emitting a separate declaration for each one, we need to look upwards // in the ts.Node tree and write a copy of the enclosing VariableDeclarationList // content (e.g. "var" from "var x=1, y=2"). - const list: ts.VariableDeclarationList | undefined = TypeScriptHelpers.matchAncestor(span.node, - [ts.SyntaxKind.VariableDeclarationList, ts.SyntaxKind.VariableDeclaration]); + const list: ts.VariableDeclarationList | undefined = TypeScriptHelpers.matchAncestor(span.node, [ + ts.SyntaxKind.VariableDeclarationList, + ts.SyntaxKind.VariableDeclaration, + ]); if (!list) { // This should not happen unless the compiler API changes somehow throw new InternalError('Unsupported variable declaration'); } - const listPrefix: string = list.getSourceFile().text - .substring(list.getStart(), list.declarations[0].getStart()); + const listPrefix: string = list + .getSourceFile() + .text.substring(list.getStart(), list.declarations[0].getStart()); span.modification.prefix = listPrefix + span.modification.prefix; span.modification.suffix = ';'; @@ -285,21 +306,31 @@ export class ApiReportGenerator { let childAstDeclaration: AstDeclaration = astDeclaration; if (AstDeclaration.isSupportedSyntaxKind(child.kind)) { - childAstDeclaration = collector.astSymbolTable.getChildAstDeclarationByNode(child.node, astDeclaration); + childAstDeclaration = collector.astSymbolTable.getChildAstDeclarationByNode( + child.node, + astDeclaration + ); if (sortChildren) { span.modification.sortChildren = true; child.modification.sortKey = Collector.getSortKeyIgnoringUnderscore( - childAstDeclaration.astSymbol.localName); + childAstDeclaration.astSymbol.localName + ); } if (!insideTypeLiteral) { - const messagesToReport: ExtractorMessage[] = collector.messageRouter - .fetchAssociatedMessagesForReviewFile(childAstDeclaration); - const aedocSynopsis: string = ApiReportGenerator._getAedocSynopsis(collector, childAstDeclaration, - messagesToReport); - const indentedAedocSynopsis: string = ApiReportGenerator._addIndentAfterNewlines(aedocSynopsis, - child.getIndent()); + const messagesToReport: ExtractorMessage[] = collector.messageRouter.fetchAssociatedMessagesForReviewFile( + childAstDeclaration + ); + const aedocSynopsis: string = ApiReportGenerator._getAedocSynopsis( + collector, + childAstDeclaration, + messagesToReport + ); + const indentedAedocSynopsis: string = ApiReportGenerator._addIndentAfterNewlines( + aedocSynopsis, + child.getIndent() + ); child.modification.prefix = indentedAedocSynopsis + child.modification.prefix; } @@ -348,9 +379,7 @@ export class ApiReportGenerator { let skipRest: boolean = false; for (const child of span.children) { - if (skipRest - || child.kind === ts.SyntaxKind.SyntaxList - || child.kind === ts.SyntaxKind.JSDocComment) { + if (skipRest || child.kind === ts.SyntaxKind.SyntaxList || child.kind === ts.SyntaxKind.JSDocComment) { child.modification.skipAll(); } if (child.kind === ts.SyntaxKind.Identifier) { @@ -366,12 +395,18 @@ export class ApiReportGenerator { * whether the item has been documented, and any warnings that were detected * by the analysis. */ - private static _getAedocSynopsis(collector: Collector, astDeclaration: AstDeclaration, - messagesToReport: ExtractorMessage[]): string { + private static _getAedocSynopsis( + collector: Collector, + astDeclaration: AstDeclaration, + messagesToReport: ExtractorMessage[] + ): string { const stringWriter: StringWriter = new StringWriter(); for (const message of messagesToReport) { - ApiReportGenerator._writeLineAsComments(stringWriter, 'Warning: ' + message.formatMessageWithoutLocation()); + ApiReportGenerator._writeLineAsComments( + stringWriter, + 'Warning: ' + message.formatMessageWithoutLocation() + ); } if (!collector.isAncillaryDeclaration(astDeclaration)) { @@ -436,5 +471,4 @@ export class ApiReportGenerator { } return Text.replaceAll(text, '\n', '\n' + indent); } - } diff --git a/apps/api-extractor/src/generators/DeclarationReferenceGenerator.ts b/apps/api-extractor/src/generators/DeclarationReferenceGenerator.ts index 77b2b8383f2..5d05d4bf732 100644 --- a/apps/api-extractor/src/generators/DeclarationReferenceGenerator.ts +++ b/apps/api-extractor/src/generators/DeclarationReferenceGenerator.ts @@ -8,7 +8,7 @@ import { ModuleSource, GlobalSource, Navigation, - Meaning + Meaning, } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; import { PackageJsonLookup, INodePackageJson, InternalError } from '@rushstack/node-core-library'; import { TypeScriptHelpers } from '../analyzer/TypeScriptHelpers'; @@ -22,9 +22,12 @@ export class DeclarationReferenceGenerator { private _program: ts.Program; private _typeChecker: ts.TypeChecker; - public constructor(packageJsonLookup: PackageJsonLookup, workingPackageName: string, program: ts.Program, - typeChecker: ts.TypeChecker) { - + public constructor( + packageJsonLookup: PackageJsonLookup, + workingPackageName: string, + program: ts.Program, + typeChecker: ts.TypeChecker + ) { this._packageJsonLookup = packageJsonLookup; this._workingPackageName = workingPackageName; this._program = program; @@ -38,50 +41,81 @@ export class DeclarationReferenceGenerator { const symbol: ts.Symbol | undefined = this._typeChecker.getSymbolAtLocation(node); if (symbol !== undefined) { const isExpression: boolean = DeclarationReferenceGenerator._isInExpressionContext(node); - return this.getDeclarationReferenceForSymbol(symbol, isExpression ? ts.SymbolFlags.Value : ts.SymbolFlags.Type) - || this.getDeclarationReferenceForSymbol(symbol, isExpression ? ts.SymbolFlags.Type : ts.SymbolFlags.Value) - || this.getDeclarationReferenceForSymbol(symbol, ts.SymbolFlags.Namespace); + return ( + this.getDeclarationReferenceForSymbol( + symbol, + isExpression ? ts.SymbolFlags.Value : ts.SymbolFlags.Type + ) || + this.getDeclarationReferenceForSymbol( + symbol, + isExpression ? ts.SymbolFlags.Type : ts.SymbolFlags.Value + ) || + this.getDeclarationReferenceForSymbol(symbol, ts.SymbolFlags.Namespace) + ); } } /** * Gets the DeclarationReference for a TypeScript Symbol for a given meaning. */ - public getDeclarationReferenceForSymbol(symbol: ts.Symbol, meaning: ts.SymbolFlags - ): DeclarationReference | undefined { + public getDeclarationReferenceForSymbol( + symbol: ts.Symbol, + meaning: ts.SymbolFlags + ): DeclarationReference | undefined { return this._symbolToDeclarationReference(symbol, meaning, /*includeModuleSymbols*/ false); } private static _isInExpressionContext(node: ts.Node): boolean { switch (node.parent.kind) { - case ts.SyntaxKind.TypeQuery: return true; - case ts.SyntaxKind.QualifiedName: return DeclarationReferenceGenerator._isInExpressionContext(node.parent); - default: return false; + case ts.SyntaxKind.TypeQuery: + return true; + case ts.SyntaxKind.QualifiedName: + return DeclarationReferenceGenerator._isInExpressionContext(node.parent); + default: + return false; } } private static _isExternalModuleSymbol(symbol: ts.Symbol): boolean { - return !!(symbol.flags & ts.SymbolFlags.ValueModule) - && symbol.valueDeclaration !== undefined - && ts.isSourceFile(symbol.valueDeclaration); + return ( + !!(symbol.flags & ts.SymbolFlags.ValueModule) && + symbol.valueDeclaration !== undefined && + ts.isSourceFile(symbol.valueDeclaration) + ); } private static _isSameSymbol(left: ts.Symbol | undefined, right: ts.Symbol): boolean { - return left === right - || !!(left && left.valueDeclaration && right.valueDeclaration && left.valueDeclaration === right.valueDeclaration); + return ( + left === right || + !!( + left && + left.valueDeclaration && + right.valueDeclaration && + left.valueDeclaration === right.valueDeclaration + ) + ); } private static _getNavigationToSymbol(symbol: ts.Symbol): Navigation | 'global' { const parent: ts.Symbol | undefined = TypeScriptInternals.getSymbolParent(symbol); // First, try to determine navigation to symbol via its parent. if (parent) { - if (parent.exports && DeclarationReferenceGenerator._isSameSymbol(parent.exports.get(symbol.escapedName), symbol)) { + if ( + parent.exports && + DeclarationReferenceGenerator._isSameSymbol(parent.exports.get(symbol.escapedName), symbol) + ) { return Navigation.Exports; } - if (parent.members && DeclarationReferenceGenerator._isSameSymbol(parent.members.get(symbol.escapedName), symbol)) { + if ( + parent.members && + DeclarationReferenceGenerator._isSameSymbol(parent.members.get(symbol.escapedName), symbol) + ) { return Navigation.Members; } - if (parent.globalExports && DeclarationReferenceGenerator._isSameSymbol(parent.globalExports.get(symbol.escapedName), symbol)) { + if ( + parent.globalExports && + DeclarationReferenceGenerator._isSameSymbol(parent.globalExports.get(symbol.escapedName), symbol) + ) { return 'global'; } } @@ -105,11 +139,12 @@ export class DeclarationReferenceGenerator { // enum members are exports return Navigation.Exports; } - if (ts.isExportSpecifier(declaration) - || ts.isExportAssignment(declaration) - || ts.isExportSpecifier(declaration) - || ts.isExportDeclaration(declaration) - || ts.isNamedExports(declaration) + if ( + ts.isExportSpecifier(declaration) || + ts.isExportAssignment(declaration) || + ts.isExportSpecifier(declaration) || + ts.isExportDeclaration(declaration) || + ts.isNamedExports(declaration) ) { return Navigation.Exports; } @@ -175,9 +210,11 @@ export class DeclarationReferenceGenerator { return undefined; } - private _symbolToDeclarationReference(symbol: ts.Symbol, meaning: ts.SymbolFlags, includeModuleSymbols: boolean - ): DeclarationReference | undefined { - + private _symbolToDeclarationReference( + symbol: ts.Symbol, + meaning: ts.SymbolFlags, + includeModuleSymbols: boolean + ): DeclarationReference | undefined { let followedSymbol: ts.Symbol = symbol; if (followedSymbol.flags & ts.SymbolFlags.ExportValue) { followedSymbol = this._typeChecker.getExportSymbolOfSymbol(followedSymbol); @@ -191,9 +228,9 @@ export class DeclarationReferenceGenerator { return undefined; } const sourceFile: ts.SourceFile | undefined = - followedSymbol.declarations - && followedSymbol.declarations[0] - && followedSymbol.declarations[0].getSourceFile(); + followedSymbol.declarations && + followedSymbol.declarations[0] && + followedSymbol.declarations[0].getSourceFile(); return new DeclarationReference(this._sourceFileToModuleSource(sourceFile)); } @@ -205,13 +242,17 @@ export class DeclarationReferenceGenerator { const parent: ts.Symbol | undefined = TypeScriptInternals.getSymbolParent(followedSymbol); let parentRef: DeclarationReference | undefined; if (parent) { - parentRef = this._symbolToDeclarationReference(parent, ts.SymbolFlags.Namespace, /*includeModuleSymbols*/ true); + parentRef = this._symbolToDeclarationReference( + parent, + ts.SymbolFlags.Namespace, + /*includeModuleSymbols*/ true + ); } else { // this may be a local symbol in a module... const sourceFile: ts.SourceFile | undefined = - followedSymbol.declarations - && followedSymbol.declarations[0] - && followedSymbol.declarations[0].getSourceFile(); + followedSymbol.declarations && + followedSymbol.declarations[0] && + followedSymbol.declarations[0].getSourceFile(); if (sourceFile && ts.isExternalModule(sourceFile)) { parentRef = new DeclarationReference(this._sourceFileToModuleSource(sourceFile)); } else { @@ -227,7 +268,9 @@ export class DeclarationReferenceGenerator { if (followedSymbol.escapedName === ts.InternalSymbolName.Constructor) { localName = 'constructor'; } else { - const wellKnownName: string | undefined = TypeScriptHelpers.tryDecodeWellKnownSymbolName(followedSymbol.escapedName); + const wellKnownName: string | undefined = TypeScriptHelpers.tryDecodeWellKnownSymbolName( + followedSymbol.escapedName + ); if (wellKnownName) { // TypeScript binds well-known ECMAScript symbols like 'Symbol.iterator' as '__@iterator'. // This converts a string like '__@iterator' into the property name '[Symbol.iterator]'. @@ -246,7 +289,9 @@ export class DeclarationReferenceGenerator { } } - let navigation: Navigation | 'global' = DeclarationReferenceGenerator._getNavigationToSymbol(followedSymbol); + let navigation: Navigation | 'global' = DeclarationReferenceGenerator._getNavigationToSymbol( + followedSymbol + ); if (navigation === 'global') { if (parentRef.source !== GlobalSource.instance) { parentRef = new DeclarationReference(GlobalSource.instance); @@ -261,8 +306,9 @@ export class DeclarationReferenceGenerator { private _getPackageName(sourceFile: ts.SourceFile): string { if (this._program.isSourceFileFromExternalLibrary(sourceFile)) { - const packageJson: INodePackageJson | undefined = this._packageJsonLookup - .tryLoadNodePackageJsonFor(sourceFile.fileName); + const packageJson: INodePackageJson | undefined = this._packageJsonLookup.tryLoadNodePackageJsonFor( + sourceFile.fileName + ); if (packageJson && packageJson.name) { return packageJson.name; @@ -279,4 +325,3 @@ export class DeclarationReferenceGenerator { return GlobalSource.instance; } } - diff --git a/apps/api-extractor/src/generators/DtsEmitHelpers.ts b/apps/api-extractor/src/generators/DtsEmitHelpers.ts index e4621ca4eee..fe05d8fc057 100644 --- a/apps/api-extractor/src/generators/DtsEmitHelpers.ts +++ b/apps/api-extractor/src/generators/DtsEmitHelpers.ts @@ -13,7 +13,11 @@ import { Collector } from '../collector/Collector'; * Some common code shared between DtsRollupGenerator and ApiReportGenerator. */ export class DtsEmitHelpers { - public static emitImport(stringWriter: StringWriter, collectorEntity: CollectorEntity, astImport: AstImport): void { + public static emitImport( + stringWriter: StringWriter, + collectorEntity: CollectorEntity, + astImport: AstImport + ): void { switch (astImport.importKind) { case AstImportKind.DefaultImport: if (collectorEntity.nameForEmit !== astImport.exportName) { @@ -42,9 +46,11 @@ export class DtsEmitHelpers { } } - public static emitNamedExport(stringWriter: StringWriter, exportName: string, - collectorEntity: CollectorEntity): void { - + public static emitNamedExport( + stringWriter: StringWriter, + exportName: string, + collectorEntity: CollectorEntity + ): void { if (exportName === ts.InternalSymbolName.Default) { stringWriter.writeLine(`export default ${collectorEntity.nameForEmit};`); } else if (collectorEntity.nameForEmit !== exportName) { diff --git a/apps/api-extractor/src/generators/DtsRollupGenerator.ts b/apps/api-extractor/src/generators/DtsRollupGenerator.ts index dca08949d42..fd79fdbfb2b 100644 --- a/apps/api-extractor/src/generators/DtsRollupGenerator.ts +++ b/apps/api-extractor/src/generators/DtsRollupGenerator.ts @@ -42,7 +42,7 @@ export enum DtsRollupKind { * This output file will contain all definitions that are reachable from the entry point, * except definitions marked as \@beta, \@alpha, or \@internal. */ - PublicRelease + PublicRelease, } export class DtsRollupGenerator { @@ -52,7 +52,10 @@ export class DtsRollupGenerator { * @param dtsFilename - The *.d.ts output filename */ public static writeTypingsFile( - collector: Collector, dtsFilename: string, dtsKind: DtsRollupKind, newlineKind: NewlineKind + collector: Collector, + dtsFilename: string, + dtsKind: DtsRollupKind, + newlineKind: NewlineKind ): void { const stringWriter: StringWriter = new StringWriter(); @@ -60,13 +63,15 @@ export class DtsRollupGenerator { FileSystem.writeFile(dtsFilename, stringWriter.toString(), { convertLineEndings: newlineKind, - ensureFolderExists: true + ensureFolderExists: true, }); } - private static _generateTypingsFileContent(collector: Collector, stringWriter: StringWriter, - dtsKind: DtsRollupKind): void { - + private static _generateTypingsFileContent( + collector: Collector, + stringWriter: StringWriter, + dtsKind: DtsRollupKind + ): void { if (collector.workingPackage.tsdocParserContext) { stringWriter.writeLine(collector.workingPackage.tsdocParserContext.sourceRange.toString()); stringWriter.writeLine(); @@ -91,7 +96,8 @@ export class DtsRollupGenerator { // and it was marked as `@internal`, then don't emit it. const symbolMetadata: SymbolMetadata | undefined = collector.tryFetchMetadataForAstEntity(astImport); const maxEffectiveReleaseTag: ReleaseTag = symbolMetadata - ? symbolMetadata.maxEffectiveReleaseTag : ReleaseTag.None; + ? symbolMetadata.maxEffectiveReleaseTag + : ReleaseTag.None; if (this._shouldIncludeReleaseTag(maxEffectiveReleaseTag, dtsKind)) { DtsEmitHelpers.emitImport(stringWriter, entity, astImport); @@ -101,9 +107,12 @@ export class DtsRollupGenerator { // Emit the regular declarations for (const entity of collector.entities) { - const symbolMetadata: SymbolMetadata | undefined = collector.tryFetchMetadataForAstEntity(entity.astEntity); + const symbolMetadata: SymbolMetadata | undefined = collector.tryFetchMetadataForAstEntity( + entity.astEntity + ); const maxEffectiveReleaseTag: ReleaseTag = symbolMetadata - ? symbolMetadata.maxEffectiveReleaseTag : ReleaseTag.None; + ? symbolMetadata.maxEffectiveReleaseTag + : ReleaseTag.None; if (!this._shouldIncludeReleaseTag(maxEffectiveReleaseTag, dtsKind)) { if (!collector.extractorConfig.omitTrimmingComments) { @@ -121,7 +130,9 @@ export class DtsRollupGenerator { if (!this._shouldIncludeReleaseTag(apiItemMetadata.effectiveReleaseTag, dtsKind)) { if (!collector.extractorConfig.omitTrimmingComments) { stringWriter.writeLine(); - stringWriter.writeLine(`/* Excluded declaration from this release type: ${entity.nameForEmit} */`); + stringWriter.writeLine( + `/* Excluded declaration from this release type: ${entity.nameForEmit} */` + ); } continue; } else { @@ -151,9 +162,13 @@ export class DtsRollupGenerator { /** * Before writing out a declaration, _modifySpan() applies various fixups to make it nice. */ - private static _modifySpan(collector: Collector, span: Span, entity: CollectorEntity, - astDeclaration: AstDeclaration, dtsKind: DtsRollupKind): void { - + private static _modifySpan( + collector: Collector, + span: Span, + entity: CollectorEntity, + astDeclaration: AstDeclaration, + dtsKind: DtsRollupKind + ): void { const previousSpan: Span | undefined = span.previousSibling; let recurseChildren: boolean = true; @@ -217,14 +232,17 @@ export class DtsRollupGenerator { // Since we are emitting a separate declaration for each one, we need to look upwards // in the ts.Node tree and write a copy of the enclosing VariableDeclarationList // content (e.g. "var" from "var x=1, y=2"). - const list: ts.VariableDeclarationList | undefined = TypeScriptHelpers.matchAncestor(span.node, - [ts.SyntaxKind.VariableDeclarationList, ts.SyntaxKind.VariableDeclaration]); + const list: ts.VariableDeclarationList | undefined = TypeScriptHelpers.matchAncestor(span.node, [ + ts.SyntaxKind.VariableDeclarationList, + ts.SyntaxKind.VariableDeclaration, + ]); if (!list) { // This should not happen unless the compiler API changes somehow throw new InternalError('Unsupported variable declaration'); } - const listPrefix: string = list.getSourceFile().text - .substring(list.getStart(), list.declarations[0].getStart()); + const listPrefix: string = list + .getSourceFile() + .text.substring(list.getStart(), list.declarations[0].getStart()); span.modification.prefix = 'declare ' + listPrefix + span.modification.prefix; span.modification.suffix = ';'; @@ -275,8 +293,12 @@ export class DtsRollupGenerator { // Should we trim this node? let trimmed: boolean = false; if (AstDeclaration.isSupportedSyntaxKind(child.kind)) { - childAstDeclaration = collector.astSymbolTable.getChildAstDeclarationByNode(child.node, astDeclaration); - const releaseTag: ReleaseTag = collector.fetchApiItemMetadata(childAstDeclaration).effectiveReleaseTag; + childAstDeclaration = collector.astSymbolTable.getChildAstDeclarationByNode( + child.node, + astDeclaration + ); + const releaseTag: ReleaseTag = collector.fetchApiItemMetadata(childAstDeclaration) + .effectiveReleaseTag; if (!this._shouldIncludeReleaseTag(releaseTag, dtsKind)) { let nodeToTrim: Span = child; @@ -284,8 +306,9 @@ export class DtsRollupGenerator { // If we are trimming a variable statement, then we need to trim the outer VariableDeclarationList // as well. if (child.kind === ts.SyntaxKind.VariableDeclaration) { - const variableStatement: Span | undefined - = child.findFirstParent(ts.SyntaxKind.VariableStatement); + const variableStatement: Span | undefined = child.findFirstParent( + ts.SyntaxKind.VariableStatement + ); if (variableStatement !== undefined) { nodeToTrim = variableStatement; } @@ -332,13 +355,14 @@ export class DtsRollupGenerator { } private static _shouldIncludeReleaseTag(releaseTag: ReleaseTag, dtsKind: DtsRollupKind): boolean { - switch (dtsKind) { case DtsRollupKind.InternalRelease: return true; case DtsRollupKind.BetaRelease: // NOTE: If the release tag is "None", then we don't have enough information to trim it - return releaseTag === ReleaseTag.Beta || releaseTag === ReleaseTag.Public || releaseTag === ReleaseTag.None; + return ( + releaseTag === ReleaseTag.Beta || releaseTag === ReleaseTag.Public || releaseTag === ReleaseTag.None + ); case DtsRollupKind.PublicRelease: return releaseTag === ReleaseTag.Public || releaseTag === ReleaseTag.None; } diff --git a/apps/api-extractor/src/generators/ExcerptBuilder.ts b/apps/api-extractor/src/generators/ExcerptBuilder.ts index 1266d70e63a..7f4ad949e89 100644 --- a/apps/api-extractor/src/generators/ExcerptBuilder.ts +++ b/apps/api-extractor/src/generators/ExcerptBuilder.ts @@ -3,11 +3,7 @@ import * as ts from 'typescript'; import { DeclarationReference } from '@microsoft/tsdoc/lib/beta/DeclarationReference'; -import { - ExcerptTokenKind, - IExcerptToken, - IExcerptTokenRange -} from '@microsoft/api-extractor-model'; +import { ExcerptTokenKind, IExcerptToken, IExcerptTokenRange } from '@microsoft/api-extractor-model'; import { Span } from '../analyzer/Span'; import { DeclarationReferenceGenerator } from './DeclarationReferenceGenerator'; @@ -82,9 +78,12 @@ export class ExcerptBuilder { * @param excerptTokens - The target token list to append to * @param nodesToCapture - A list of child nodes whose token ranges we want to capture */ - public static addDeclaration(excerptTokens: IExcerptToken[], astDeclaration: AstDeclaration, - nodesToCapture: IExcerptBuilderNodeToCapture[], referenceGenerator: DeclarationReferenceGenerator): void { - + public static addDeclaration( + excerptTokens: IExcerptToken[], + astDeclaration: AstDeclaration, + nodesToCapture: IExcerptBuilderNodeToCapture[], + referenceGenerator: DeclarationReferenceGenerator + ): void { let stopBeforeChildKind: ts.SyntaxKind | undefined = undefined; switch (astDeclaration.declaration.kind) { @@ -114,7 +113,7 @@ export class ExcerptBuilder { startingNode: span.node, stopBeforeChildKind, tokenRangesByNode, - disableMergingForNextToken: false + disableMergingForNextToken: false, }); } @@ -149,11 +148,15 @@ export class ExcerptBuilder { } if (canonicalReference) { - ExcerptBuilder._appendToken(excerptTokens, ExcerptTokenKind.Reference, - span.prefix, state, canonicalReference); + ExcerptBuilder._appendToken( + excerptTokens, + ExcerptTokenKind.Reference, + span.prefix, + state, + canonicalReference + ); } else { - ExcerptBuilder._appendToken(excerptTokens, ExcerptTokenKind.Content, - span.prefix, state); + ExcerptBuilder._appendToken(excerptTokens, ExcerptTokenKind.Content, span.prefix, state); } } @@ -190,24 +193,32 @@ export class ExcerptBuilder { return true; } - private static _appendToken(excerptTokens: IExcerptToken[], excerptTokenKind: ExcerptTokenKind, - text: string, state: IBuildSpanState, canonicalReference?: DeclarationReference): void { - + private static _appendToken( + excerptTokens: IExcerptToken[], + excerptTokenKind: ExcerptTokenKind, + text: string, + state: IBuildSpanState, + canonicalReference?: DeclarationReference + ): void { if (text.length === 0) { return; } if (excerptTokenKind !== ExcerptTokenKind.Content) { - if (excerptTokenKind === ExcerptTokenKind.Reference && excerptTokens.length > 1 - && !state.disableMergingForNextToken) { + if ( + excerptTokenKind === ExcerptTokenKind.Reference && + excerptTokens.length > 1 && + !state.disableMergingForNextToken + ) { // If the previous two tokens were a Reference and a '.', then concatenate // all three tokens as a qualified name Reference. const previousTokenM1: IExcerptToken = excerptTokens[excerptTokens.length - 1]; const previousTokenM2: IExcerptToken = excerptTokens[excerptTokens.length - 2]; - if (previousTokenM1.kind === ExcerptTokenKind.Content - && previousTokenM1.text.trim() === '.' - && previousTokenM2.kind === ExcerptTokenKind.Reference) { - + if ( + previousTokenM1.kind === ExcerptTokenKind.Content && + previousTokenM1.text.trim() === '.' && + previousTokenM2.kind === ExcerptTokenKind.Reference + ) { previousTokenM2.text += '.' + text; if (canonicalReference !== undefined) { previousTokenM2.canonicalReference = canonicalReference.toString(); @@ -266,5 +277,4 @@ export class ExcerptBuilder { return false; } } - } diff --git a/apps/api-extractor/src/index.ts b/apps/api-extractor/src/index.ts index e6d162ea6e9..c36a4f57129 100644 --- a/apps/api-extractor/src/index.ts +++ b/apps/api-extractor/src/index.ts @@ -13,23 +13,16 @@ export { ConsoleMessageId } from './api/ConsoleMessageId'; export { CompilerState, ICompilerStateCreateOptions } from './api/CompilerState'; -export { - Extractor, - IExtractorInvokeOptions, - ExtractorResult -} from './api/Extractor'; +export { Extractor, IExtractorInvokeOptions, ExtractorResult } from './api/Extractor'; -export { - IExtractorConfigPrepareOptions, - ExtractorConfig -} from './api/ExtractorConfig'; +export { IExtractorConfigPrepareOptions, ExtractorConfig } from './api/ExtractorConfig'; export { ExtractorLogLevel } from './api/ExtractorLogLevel'; export { ExtractorMessage, IExtractorMessageProperties, - ExtractorMessageCategory + ExtractorMessageCategory, } from './api/ExtractorMessage'; export { ExtractorMessageId } from './api/ExtractorMessageId'; @@ -43,5 +36,5 @@ export { IConfigMessageReportingRule, IConfigMessageReportingTable, IExtractorMessagesConfig, - IConfigFile + IConfigFile, } from './api/IConfigFile'; diff --git a/apps/api-extractor/src/schemas/api-extractor-defaults.json b/apps/api-extractor/src/schemas/api-extractor-defaults.json index d732795edbf..22358fe1b34 100644 --- a/apps/api-extractor/src/schemas/api-extractor-defaults.json +++ b/apps/api-extractor/src/schemas/api-extractor-defaults.json @@ -3,7 +3,7 @@ // ("mainEntryPointFilePath" is required) - "bundledPackages": [ ], + "bundledPackages": [], "newlineKind": "crlf", diff --git a/apps/api-extractor/src/schemas/api-extractor-template.json b/apps/api-extractor/src/schemas/api-extractor-template.json index edd97d910bb..e47c7f6d7d7 100644 --- a/apps/api-extractor/src/schemas/api-extractor-template.json +++ b/apps/api-extractor/src/schemas/api-extractor-template.json @@ -60,7 +60,7 @@ * This would direct API Extractor to embed those types directly in the .d.ts rollup, as if they had been * local files for library1. */ - "bundledPackages": [ ], + "bundledPackages": [], /** * Determines how the TypeScript compiler engine will be invoked by API Extractor. @@ -78,7 +78,6 @@ * DEFAULT VALUE: "/tsconfig.json" */ // "tsconfigFilePath": "/tsconfig.json", - /** * Provides a compiler configuration that will be used instead of reading the tsconfig.json file from disk. * The object must conform to the TypeScript tsconfig schema: @@ -92,7 +91,6 @@ // "overrideTsconfig": { // . . . // } - /** * This option causes the compiler to be invoked with the --skipLibCheck option. This option is not recommended * and may cause API Extractor to produce incomplete or incorrect declarations, but it may be required when @@ -111,7 +109,7 @@ /** * (REQUIRED) Whether to generate an API report. */ - "enabled": true, + "enabled": true /** * The filename for the API report files. It will be combined with "reportFolder" or "reportTempFolder" to produce @@ -162,7 +160,7 @@ /** * (REQUIRED) Whether to generate a doc model file. */ - "enabled": true, + "enabled": true /** * The output path for the doc model file. The file extension should be ".api.json". @@ -183,7 +181,7 @@ /** * (REQUIRED) Whether to generate the .d.ts rollup file. */ - "enabled": true, + "enabled": true /** * Specifies the output path for a .d.ts rollup file to be generated without any trimming. @@ -211,7 +209,6 @@ */ // "betaTrimmedFilePath": "/dist/-beta.d.ts", - /** * Specifies the output path for a .d.ts rollup file to be generated with trimming for a "public" release. * This file will include only declarations that are marked as "@public". @@ -246,7 +243,6 @@ * DEFAULT VALUE: true */ // "enabled": true, - /** * Specifies where the TSDoc metadata file should be written. * @@ -303,7 +299,7 @@ * * DEFAULT VALUE: "warning" */ - "logLevel": "warning", + "logLevel": "warning" /** * When addToApiReportFile is true: If API Extractor is configured to write an API report file (.api.md), @@ -313,7 +309,7 @@ * DEFAULT VALUE: false */ // "addToApiReportFile": false - }, + } // "TS2551": { // "logLevel": "warning", @@ -332,9 +328,9 @@ */ "extractorMessageReporting": { "default": { - "logLevel": "warning", + "logLevel": "warning" // "addToApiReportFile": false - }, + } // "ae-extra-release-tag": { // "logLevel": "warning", @@ -353,7 +349,7 @@ */ "tsdocMessageReporting": { "default": { - "logLevel": "warning", + "logLevel": "warning" // "addToApiReportFile": false } @@ -365,5 +361,4 @@ // . . . } } - } diff --git a/apps/api-extractor/src/schemas/api-extractor.schema.json b/apps/api-extractor/src/schemas/api-extractor.schema.json index 153b3739000..3bf3914a9c5 100644 --- a/apps/api-extractor/src/schemas/api-extractor.schema.json +++ b/apps/api-extractor/src/schemas/api-extractor.schema.json @@ -74,9 +74,8 @@ "description": "Specifies the folder where the temporary report file is written. The file name portion is determined by the \"reportFileName\" setting. After the temporary file is written to disk, it is compared with the file in the \"reportFolder\". If they are different, a production build will fail. The path is resolved relative to the folder of the config file that contains the setting; to change this, prepend a folder token such as \"\".", "type": "string" } - }, - "required": [ "enabled" ], + "required": ["enabled"], "additionalProperties": false }, @@ -93,7 +92,7 @@ "type": "string" } }, - "required": [ "enabled" ], + "required": ["enabled"], "additionalProperties": false }, @@ -122,7 +121,7 @@ "type": "boolean" } }, - "required": [ "enabled" ], + "required": ["enabled"], "additionalProperties": false }, @@ -174,12 +173,12 @@ "type": "boolean" } }, - "required": [ "mainEntryPointFilePath" ], + "required": ["mainEntryPointFilePath"], "additionalProperties": false, "definitions": { "extractorMessageReportingTable": { - "type":"object", + "type": "object", "description": "Specifies a table of reporting rules for different message identifiers, and also the default rule used for identifiers that do not appear in the table. The key is a message identifier for the associated type of message, or \"default\" to specify the default policy. For example, the key might be \"TS2551\" (a compiler message), \"tsdoc-link-tag-unescaped-text\" (a TSDOc message), or \"ae-extra-release-tag\" (a message related to the API Extractor analysis).", "patternProperties": { ".+": { @@ -189,7 +188,7 @@ "logLevel": { "type": "string", "description": "Specifies whether the message should be written to the the tool's output log. Note that the \"addToApiReportFile\" property may supersede this option.", - "enum": [ "error", "warning", "none" ] + "enum": ["error", "warning", "none"] }, "addToApiReportFile": { "type": "boolean", @@ -197,7 +196,7 @@ } }, "additionalProperties": false, - "required": [ "logLevel" ] + "required": ["logLevel"] } }, "additionalProperties": false diff --git a/apps/api-extractor/src/start.ts b/apps/api-extractor/src/start.ts index 8fce9a0b64a..4cb57170a6e 100644 --- a/apps/api-extractor/src/start.ts +++ b/apps/api-extractor/src/start.ts @@ -7,8 +7,10 @@ import * as colors from 'colors'; import { ApiExtractorCommandLine } from './cli/ApiExtractorCommandLine'; import { Extractor } from './api/Extractor'; -console.log(os.EOL + colors.bold(`api-extractor ${Extractor.version} ` - + colors.cyan(' - https://api-extractor.com/') + os.EOL)); +console.log( + os.EOL + + colors.bold(`api-extractor ${Extractor.version} ` + colors.cyan(' - https://api-extractor.com/') + os.EOL) +); const parser: ApiExtractorCommandLine = new ApiExtractorCommandLine(); diff --git a/apps/api-extractor/tsconfig.json b/apps/api-extractor/tsconfig.json index 824a88b71e5..46bc07fdda9 100644 --- a/apps/api-extractor/tsconfig.json +++ b/apps/api-extractor/tsconfig.json @@ -2,9 +2,6 @@ "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "jest", - "node" - ] + "types": ["jest", "node"] } } diff --git a/apps/rush-buildxl/.eslintrc.js b/apps/rush-buildxl/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/apps/rush-buildxl/.eslintrc.js +++ b/apps/rush-buildxl/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/apps/rush-buildxl/config/jest.json b/apps/rush-buildxl/config/jest.json index b4a7ec97a56..902b00ea176 100644 --- a/apps/rush-buildxl/config/jest.json +++ b/apps/rush-buildxl/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": true -} \ No newline at end of file +} diff --git a/apps/rush-buildxl/src/cli/RushBuildXLCommandLineParser.ts b/apps/rush-buildxl/src/cli/RushBuildXLCommandLineParser.ts index 2b6ee11c295..d12c20a87b4 100644 --- a/apps/rush-buildxl/src/cli/RushBuildXLCommandLineParser.ts +++ b/apps/rush-buildxl/src/cli/RushBuildXLCommandLineParser.ts @@ -13,7 +13,7 @@ export class RushBuildXLCommandLineParser extends CommandLineParser { public constructor(terminal: Terminal) { super({ toolFilename: 'rush-buildlx', - toolDescription: 'This experimental tool allows Rush to interact with BuildXL.' + toolDescription: 'This experimental tool allows Rush to interact with BuildXL.', }); this._terminal = terminal; @@ -22,9 +22,12 @@ export class RushBuildXLCommandLineParser extends CommandLineParser { this.addAction(new GenerateAction(this._terminal)); } - protected onDefineParameters(): void { /* no global parameters */ } + protected onDefineParameters(): void { + /* no global parameters */ + } - protected onExecute(): Promise { // override + protected onExecute(): Promise { + // override return super.onExecute().catch((error) => { this._terminal.writeErrorLine(); this._terminal.writeErrorLine('ERROR: ' + error.message.trim()); diff --git a/apps/rush-buildxl/src/cli/actions/CleanAction.ts b/apps/rush-buildxl/src/cli/actions/CleanAction.ts index dc416d068da..11df18566f8 100644 --- a/apps/rush-buildxl/src/cli/actions/CleanAction.ts +++ b/apps/rush-buildxl/src/cli/actions/CleanAction.ts @@ -3,10 +3,7 @@ import * as path from 'path'; import { CommandLineAction } from '@rushstack/ts-command-line'; -import { - Terminal, - FileSystem -} from '@rushstack/node-core-library'; +import { Terminal, FileSystem } from '@rushstack/node-core-library'; import { RushConfiguration } from '@microsoft/rush-lib'; export class CleanAction extends CommandLineAction { @@ -16,7 +13,7 @@ export class CleanAction extends CommandLineAction { super({ actionName: 'clean', summary: 'Cleans up generated BuildXL configuration for the current Rush repository.', - documentation: 'Cleans up generated BuildXL configuration for the current Rush repository.' + documentation: 'Cleans up generated BuildXL configuration for the current Rush repository.', }); this._terminal = terminal; diff --git a/apps/rush-buildxl/src/cli/actions/GenerateAction.ts b/apps/rush-buildxl/src/cli/actions/GenerateAction.ts index 48052120334..17ced3e258f 100644 --- a/apps/rush-buildxl/src/cli/actions/GenerateAction.ts +++ b/apps/rush-buildxl/src/cli/actions/GenerateAction.ts @@ -14,7 +14,7 @@ export class GenerateAction extends CommandLineAction { super({ actionName: 'generate', summary: 'Generates a BuildXL configuration for the current Rush repository.', - documentation: 'Generates a BuildXL configuration for the current Rush repository.' + documentation: 'Generates a BuildXL configuration for the current Rush repository.', }); this._terminal = terminal; @@ -29,10 +29,10 @@ export class GenerateAction extends CommandLineAction { throw new Error('Environment variable BUILDXL_BIN not defined'); } - const generator: BxlModulesGenerator = - new BxlModulesGenerator( - RushConfiguration.loadFromDefaultLocation(), - process.env.BUILDXL_BIN); + const generator: BxlModulesGenerator = new BxlModulesGenerator( + RushConfiguration.loadFromDefaultLocation(), + process.env.BUILDXL_BIN + ); await generator.run(); this._terminal.writeLine(`Successfully generated BuildXL configuration.`); diff --git a/apps/rush-buildxl/src/logic/BxlConfig.ts b/apps/rush-buildxl/src/logic/BxlConfig.ts index d2ee5ac1dec..bed1b62024f 100644 --- a/apps/rush-buildxl/src/logic/BxlConfig.ts +++ b/apps/rush-buildxl/src/logic/BxlConfig.ts @@ -11,7 +11,12 @@ export class BxlConfig { private _modules: BxlModule[]; private _commonRushConfigFolder: string; - public constructor(bxlRoot: string, modulesFolder: string, modules: BxlModule[], commonRushConfigFolder: string) { + public constructor( + bxlRoot: string, + modulesFolder: string, + modules: BxlModule[], + commonRushConfigFolder: string + ) { this._bxlRoot = bxlRoot; this._modulesFolder = modulesFolder; this._modules = modules; @@ -23,8 +28,7 @@ export class BxlConfig { } public async writeFile(): Promise { - const contents: string = -`config({ + const contents: string = `config({ modules: [ f\`${this._modules[0].configFilePath}\`, ], diff --git a/apps/rush-buildxl/src/logic/BxlModule.ts b/apps/rush-buildxl/src/logic/BxlModule.ts index 9d98ab2dc9c..5ae97740b81 100644 --- a/apps/rush-buildxl/src/logic/BxlModule.ts +++ b/apps/rush-buildxl/src/logic/BxlModule.ts @@ -35,8 +35,7 @@ export class BxlModule { } public async writeFile(): Promise { - const contents: string = -`import { Cmd, Transformer } from "Sdk.Transformers"; + const contents: string = `import { Cmd, Transformer } from "Sdk.Transformers"; export const cmdTool: Transformer.ToolDefinition = { exe: f\`\${Environment.getPathValue("COMSPEC")}\`, diff --git a/apps/rush-buildxl/src/logic/BxlModuleConfig.ts b/apps/rush-buildxl/src/logic/BxlModuleConfig.ts index c66bda23269..f0afd218a35 100644 --- a/apps/rush-buildxl/src/logic/BxlModuleConfig.ts +++ b/apps/rush-buildxl/src/logic/BxlModuleConfig.ts @@ -21,8 +21,7 @@ export class BxlModuleConfig { } public async writeFile(): Promise { - const contents: string = -`package({ + const contents: string = `package({ name: "${this._name}", nameResolutionSemantics: NameResolutionSemantics.implicitProjectReferences, projects: [ @@ -32,4 +31,4 @@ export class BxlModuleConfig { FileSystem.writeFile(this.moduleConfigFilePath, contents, { ensureFolderExists: true }); } -} \ No newline at end of file +} diff --git a/apps/rush-buildxl/src/logic/BxlModulesGenerator.ts b/apps/rush-buildxl/src/logic/BxlModulesGenerator.ts index 4f9f94f73d6..662d40f88d3 100644 --- a/apps/rush-buildxl/src/logic/BxlModulesGenerator.ts +++ b/apps/rush-buildxl/src/logic/BxlModulesGenerator.ts @@ -22,9 +22,11 @@ export class BxlModulesGenerator { path.resolve(this._rushConfiguration.commonTempFolder, 'bxl', 'modules') ); const rushJsonFilePath: string = this._normalizePathSeparator(this._rushConfiguration.rushJsonFile); - const commonRushConfigFolder: string = this._normalizePathSeparator(this._rushConfiguration.commonRushConfigFolder); + const commonRushConfigFolder: string = this._normalizePathSeparator( + this._rushConfiguration.commonRushConfigFolder + ); - const modules: BxlModule[] = this._rushConfiguration.projects.map((project) => { + const modules: BxlModule[] = this._rushConfiguration.projects.map((project) => { const name: string = this._packageNameToModuleName(project.packageName); const moduleRoot: string = path.resolve(modulesRoot, name); const projDir: string = this._normalizePathSeparator(project.projectFolder); @@ -32,10 +34,15 @@ export class BxlModulesGenerator { return new BxlModule(name, projDir, rushJsonFilePath, moduleRoot); }); - const bxlConfig: BxlConfig = new BxlConfig(this._buildXLRoot, modulesRoot, modules, commonRushConfigFolder); + const bxlConfig: BxlConfig = new BxlConfig( + this._buildXLRoot, + modulesRoot, + modules, + commonRushConfigFolder + ); // Write individual module dsc files - const tasks: Promise[] = modules.map(module => module.writeFile()); + const tasks: Promise[] = modules.map((module) => module.writeFile()); await Promise.all(tasks); // Write config.dsc @@ -49,4 +56,4 @@ export class BxlModulesGenerator { private _normalizePathSeparator(str: string): string { return str.replace(/\\/g, '/'); } -} \ No newline at end of file +} diff --git a/apps/rush-buildxl/src/start.ts b/apps/rush-buildxl/src/start.ts index 492c1497328..86a0054b228 100644 --- a/apps/rush-buildxl/src/start.ts +++ b/apps/rush-buildxl/src/start.ts @@ -1,10 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - Terminal, - ConsoleTerminalProvider -} from '@rushstack/node-core-library'; +import { Terminal, ConsoleTerminalProvider } from '@rushstack/node-core-library'; import { RushBuildXLCommandLineParser } from './cli/RushBuildXLCommandLineParser'; diff --git a/apps/rush-buildxl/tsconfig.json b/apps/rush-buildxl/tsconfig.json index 76f0d945025..8f1cbebe335 100644 --- a/apps/rush-buildxl/tsconfig.json +++ b/apps/rush-buildxl/tsconfig.json @@ -1,9 +1,6 @@ { "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "jest", - "node" - ] + "types": ["jest", "node"] } } diff --git a/apps/rush-lib/.eslintrc.js b/apps/rush-lib/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/apps/rush-lib/.eslintrc.js +++ b/apps/rush-lib/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/apps/rush-lib/__mocks__/child_process.js b/apps/rush-lib/__mocks__/child_process.js index b08594fb498..a8957ecd4a1 100644 --- a/apps/rush-lib/__mocks__/child_process.js +++ b/apps/rush-lib/__mocks__/child_process.js @@ -17,7 +17,7 @@ function normalizeSpawnMockConfig(maybeConfig) { const config = maybeConfig || {}; return { emitError: typeof config.emitError !== 'undefined' ? config.emitError : false, - returnCode: typeof config.returnCode !== 'undefined' ? config.returnCode : 0 + returnCode: typeof config.returnCode !== 'undefined' ? config.returnCode : 0, }; } @@ -44,14 +44,14 @@ function spawn(file, args, options) { stdout: new EventEmitter(), stderr: new EventEmitter(), on: cpEmitter.on, - emit: cpEmitter.emit + emit: cpEmitter.emit, }); setTimeout(() => { - cp.stdout.emit('data', `${file} ${args}: Mock task is spawned`) + cp.stdout.emit('data', `${file} ${args}: Mock task is spawned`); if (spawnMockConfig.emitError) { - cp.stderr.emit('data', `${file} ${args}: A mock error occurred in the task`) + cp.stderr.emit('data', `${file} ${args}: A mock error occurred in the task`); } cp.emit('close', spawnMockConfig.returnCode); diff --git a/apps/rush-lib/assets/rush-deploy-init/scenario-template.json b/apps/rush-lib/assets/rush-deploy-init/scenario-template.json index 74edda32b1e..0f40616e3ba 100644 --- a/apps/rush-lib/assets/rush-deploy-init/scenario-template.json +++ b/apps/rush-lib/assets/rush-deploy-init/scenario-template.json @@ -3,7 +3,7 @@ * The scenario files are located under the "common/config/deploy-scenarios" folder. * For full documentation, please see https://rushjs.io */ - { +{ "$schema": "https://developer.microsoft.com/json-schemas/rush/v5/deploy-scenario.schema.json", /** @@ -15,9 +15,7 @@ * The "deploymentProjectNames" array normally contains exactly one item. However, if "enableSubdeployments" * is true, then multiple projects can be specified, and each item create a separate subdeployment. */ - "deploymentProjectNames": [ - "[%PROJECT_NAME_TO_DEPLOY%]" - ], + "deploymentProjectNames": ["[%PROJECT_NAME_TO_DEPLOY%]"], /** * Subdeployments are an optional feature that enables multiple deployments to be processed with a single diff --git a/apps/rush-lib/assets/rush-init/common/config/rush/command-line.json b/apps/rush-lib/assets/rush-init/common/config/rush/command-line.json index 533d17ccfef..4717bf02007 100644 --- a/apps/rush-lib/assets/rush-init/common/config/rush/command-line.json +++ b/apps/rush-lib/assets/rush-init/common/config/rush/command-line.json @@ -170,7 +170,7 @@ * (Required) A list of custom commands and/or built-in Rush commands that this parameter may * be used with. The parameter will be appended to the shell command that Rush invokes. */ - "associatedCommands": [ "build", "rebuild" ] + "associatedCommands": ["build", "rebuild"] }, { @@ -182,7 +182,7 @@ "longName": "--my-string", "description": "A custom string parameter for the \"my-global-command\" custom command", - "associatedCommands": [ "my-global-command" ], + "associatedCommands": ["my-global-command"], /** * The name of the argument, which will be shown in the command-line help. @@ -209,12 +209,12 @@ "longName": "--my-choice", "description": "A custom choice parameter for the \"my-global-command\" custom command", - "associatedCommands": [ "my-global-command" ], + "associatedCommands": ["my-global-command"], /** * If true, this parameter must be included with the command. The default is false. */ - "required": false, + "required": false, /** * Normally if a parameter is omitted from the command line, it will not be passed diff --git a/apps/rush-lib/assets/rush-init/common/config/rush/common-versions.json b/apps/rush-lib/assets/rush-init/common/config/rush/common-versions.json index 33a8251abfc..e70e5b7ffd4 100644 --- a/apps/rush-lib/assets/rush-init/common/config/rush/common-versions.json +++ b/apps/rush-lib/assets/rush-init/common/config/rush/common-versions.json @@ -19,7 +19,6 @@ * will recalculate all version selections. */ "preferredVersions": { - /** * When someone asks for "^1.0.0" make sure they get "1.2.3" when working in this repo, * instead of the latest version. @@ -51,14 +50,14 @@ * USUAL VERSION (WHICH IS INFERRED BY LOOKING AT ALL PROJECTS IN THE REPO). * This design avoids unnecessary churn in this file. */ - "allowedAlternativeVersions": { - + "allowedAlternativeVersions": { /** * For example, allow some projects to use an older TypeScript compiler * (in addition to whatever "usual" version is being used by other projects in the repo): */ /*[LINE "HYPOTHETICAL"]*/ "typescript": [ - /*[LINE "HYPOTHETICAL"]*/ "~2.4.0" - /*[LINE "HYPOTHETICAL"]*/ ] + /*[LINE "HYPOTHETICAL"]*/ "~2.4.0" + /*[LINE "HYPOTHETICAL"]*/ + ] } } diff --git a/apps/rush-lib/assets/rush-init/common/config/rush/experiments.json b/apps/rush-lib/assets/rush-init/common/config/rush/experiments.json index 797a547c50b..193935e0bf9 100644 --- a/apps/rush-lib/assets/rush-init/common/config/rush/experiments.json +++ b/apps/rush-lib/assets/rush-init/common/config/rush/experiments.json @@ -6,23 +6,23 @@ "$schema": "https://developer.microsoft.com/json-schemas/rush/v5/experiments.schema.json", /** - * Rush 5.14.0 improved incremental builds to ignore spurious changes in the pnpm-lock.json file. - * This optimization is enabled by default. If you encounter a problem where "rush build" is neglecting - * to build some projects, please open a GitHub issue. As a workaround you can uncomment this line - * to temporarily restore the old behavior where everything must be rebuilt whenever pnpm-lock.json - * is modified. - */ + * Rush 5.14.0 improved incremental builds to ignore spurious changes in the pnpm-lock.json file. + * This optimization is enabled by default. If you encounter a problem where "rush build" is neglecting + * to build some projects, please open a GitHub issue. As a workaround you can uncomment this line + * to temporarily restore the old behavior where everything must be rebuilt whenever pnpm-lock.json + * is modified. + */ /*[LINE "HYPOTHETICAL"]*/ "legacyIncrementalBuildDependencyDetection": true, /** - * By default, rush passes --no-prefer-frozen-lockfile to 'pnpm install'. - * Set this option to true to pass '--frozen-lockfile' instead. - */ + * By default, rush passes --no-prefer-frozen-lockfile to 'pnpm install'. + * Set this option to true to pass '--frozen-lockfile' instead. + */ /*[LINE "HYPOTHETICAL"]*/ "usePnpmFrozenLockfileForRushInstall": true, /** - * If true, the chmod field in temporary project tar headers will not be normalized. - * This normalization can help ensure consistent tarball integrity across platforms. - */ + * If true, the chmod field in temporary project tar headers will not be normalized. + * This normalization can help ensure consistent tarball integrity across platforms. + */ /*[LINE "HYPOTHETICAL"]*/ "noChmodFieldInTarHeaderNormalization": true } diff --git a/apps/rush-lib/assets/rush-init/common/config/rush/pnpmfile.js b/apps/rush-lib/assets/rush-init/common/config/rush/pnpmfile.js index e93d4a4b0ed..29688e2a7bd 100644 --- a/apps/rush-lib/assets/rush-init/common/config/rush/pnpmfile.js +++ b/apps/rush-lib/assets/rush-init/common/config/rush/pnpmfile.js @@ -1,4 +1,4 @@ -"use strict"; +'use strict'; /** * When using the PNPM package manager, you can use pnpmfile.js to workaround @@ -14,8 +14,8 @@ */ module.exports = { hooks: { - readPackage - } + readPackage, + }, }; /** @@ -27,12 +27,12 @@ module.exports = { * The return value is the updated object. */ function readPackage(packageJson, context) { - /*[LINE "HYPOTHETICAL"]*/ // The karma types have a missing dependency on typings from the log4js package. /*[LINE "HYPOTHETICAL"]*/ if (packageJson.name === '@types/karma') { - /*[LINE "HYPOTHETICAL"]*/ context.log('Fixed up dependencies for @types/karma'); - /*[LINE "HYPOTHETICAL"]*/ packageJson.dependencies['log4js'] = '0.6.38'; - /*[LINE "HYPOTHETICAL"]*/ } + /*[LINE "HYPOTHETICAL"]*/ context.log('Fixed up dependencies for @types/karma'); + /*[LINE "HYPOTHETICAL"]*/ packageJson.dependencies['log4js'] = '0.6.38'; + /*[LINE "HYPOTHETICAL"]*/ + } return packageJson; } diff --git a/apps/rush-lib/assets/rush-init/common/config/rush/version-policies.json b/apps/rush-lib/assets/rush-init/common/config/rush/version-policies.json index aefb14ac0c3..b641acabece 100644 --- a/apps/rush-lib/assets/rush-init/common/config/rush/version-policies.json +++ b/apps/rush-lib/assets/rush-init/common/config/rush/version-policies.json @@ -3,11 +3,11 @@ * For full documentation, please see https://rushjs.io */ - /** - * A list of version policy definitions. A "version policy" is a custom package versioning - * strategy that affects "rush change", "rush version", and "rush publish". The strategy applies - * to a set of projects that are specified using the "versionPolicyName" field in rush.json. - */ +/** + * A list of version policy definitions. A "version policy" is a custom package versioning + * strategy that affects "rush change", "rush version", and "rush publish". The strategy applies + * to a set of projects that are specified using the "versionPolicyName" field in rush.json. + */ [ /*[BEGIN "DEMO"]*/ { diff --git a/apps/rush-lib/assets/rush-init/rush.json b/apps/rush-lib/assets/rush-init/rush.json index d01cd0aab1a..98e9a716f1d 100644 --- a/apps/rush-lib/assets/rush-init/rush.json +++ b/apps/rush-lib/assets/rush-init/rush.json @@ -64,7 +64,6 @@ */ /*[LINE "DEMO"]*/ "strictPeerDependencies": true, - /** * Configures the strategy used to select versions during installation. * @@ -95,7 +94,7 @@ * * The default value is false. */ - /*[LINE "HYPOTHETICAL"]*/ "preventManualShrinkwrapChanges": true + /*[LINE "HYPOTHETICAL"]*/ "preventManualShrinkwrapChanges": true }, /** @@ -109,16 +108,16 @@ "nodeSupportedVersionRange": ">=10.13.0 <11.0.0", /** - * Odd-numbered major versions of Node.js are experimental. Even-numbered releases - * spend six months in a stabilization period before the first Long Term Support (LTS) version. - * For example, 8.9.0 was the first LTS version of Node.js 8. Pre-LTS versions are not recommended - * for production usage because they frequently have bugs. They may cause Rush itself - * to malfunction. - * - * Rush normally prints a warning if it detects a pre-LTS Node.js version. If you are testing - * pre-LTS versions in preparation for supporting the first LTS version, you can use this setting - * to disable Rush's warning. - */ + * Odd-numbered major versions of Node.js are experimental. Even-numbered releases + * spend six months in a stabilization period before the first Long Term Support (LTS) version. + * For example, 8.9.0 was the first LTS version of Node.js 8. Pre-LTS versions are not recommended + * for production usage because they frequently have bugs. They may cause Rush itself + * to malfunction. + * + * Rush normally prints a warning if it detects a pre-LTS Node.js version. If you are testing + * pre-LTS versions in preparation for supporting the first LTS version, you can use this setting + * to disable Rush's warning. + */ /*[LINE "HYPOTHETICAL"]*/ "suppressNodeLtsWarning": false, /** @@ -132,7 +131,7 @@ * version. In those cases, you will need to add an entry to the "allowedAlternativeVersions" * section of the common-versions.json. */ - /*[LINE "HYPOTHETICAL"]*/ "ensureConsistentVersions": true, + /*[LINE "HYPOTHETICAL"]*/ "ensureConsistentVersions": true, /** * Large monorepos can become intimidating for newcomers if project folder paths don't follow @@ -197,8 +196,8 @@ "reviewCategories": [ // Some example categories: "production", // projects that ship to production - "tools", // non-shipping projects that are part of the developer toolchain - "prototypes" // experiments that should mostly be ignored by the review process + "tools", // non-shipping projects that are part of the developer toolchain + "prototypes" // experiments that should mostly be ignored by the review process ], /** @@ -207,7 +206,7 @@ * if the underlying package was already approved, this would imply that the typings * are also approved. */ - /*[LINE "HYPOTHETICAL"]*/ "ignoredNpmScopes": [ "@types" ] + /*[LINE "HYPOTHETICAL"]*/ "ignoredNpmScopes": ["@types"] }, /*[END "DEMO"]*/ @@ -228,10 +227,7 @@ * RegExp escapes need two backspashes, and ordinary periods should be "\\.". */ /*[BEGIN "DEMO"]*/ - "allowedEmailRegExps": [ - "[^@]+@users\\.noreply\\.github\\.com", - "travis@example\\.org" - ], + "allowedEmailRegExps": ["[^@]+@users\\.noreply\\.github\\.com", "travis@example\\.org"], /*[END "DEMO"]*/ /** @@ -289,9 +285,7 @@ /** * The list of shell commands to run before the Rush installation starts */ - "preRushInstall": [ - /*[LINE "HYPOTHETICAL"]*/ "common/scripts/pre-rush-install.js" - ], + "preRushInstall": [/*[LINE "HYPOTHETICAL"]*/ "common/scripts/pre-rush-install.js"], /** * The list of shell commands to run after the Rush installation finishes @@ -392,9 +386,7 @@ * locally linked because it would create a cyclic dependency; instead, the last published * version will be installed in the Common folder. */ - "cyclicDependencyProjects": [ - /*[LINE "HYPOTHETICAL"]*/ "my-toolchain" - ], + "cyclicDependencyProjects": [/*[LINE "HYPOTHETICAL"]*/ "my-toolchain"], /** * If true, then this project will be ignored by the "rush check" command. diff --git a/apps/rush-lib/config/jest.json b/apps/rush-lib/config/jest.json index b4a7ec97a56..902b00ea176 100644 --- a/apps/rush-lib/config/jest.json +++ b/apps/rush-lib/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": true -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/api/ApprovedPackagesConfiguration.ts b/apps/rush-lib/src/api/ApprovedPackagesConfiguration.ts index c98df729df6..7877a973417 100644 --- a/apps/rush-lib/src/api/ApprovedPackagesConfiguration.ts +++ b/apps/rush-lib/src/api/ApprovedPackagesConfiguration.ts @@ -48,7 +48,8 @@ export class ApprovedPackagesItem { */ export class ApprovedPackagesConfiguration { private static _jsonSchema: JsonSchema = JsonSchema.fromFile( - path.join(__dirname, '../schemas/approved-packages.schema.json')); + path.join(__dirname, '../schemas/approved-packages.schema.json') + ); public items: ApprovedPackagesItem[] = []; @@ -70,7 +71,7 @@ export class ApprovedPackagesConfiguration { this._loadedJson = { // Ensure this comes first in the key ordering $schema: '', - packages: [] + packages: [], }; } @@ -108,8 +109,10 @@ export class ApprovedPackagesConfiguration { this.loadFromFile(); if (!approvedPackagesPolicyEnabled) { - console.log(`Warning: Ignoring "${path.basename(this._jsonFilename)}" because the` - + ` "approvedPackagesPolicy" setting was not specified in rush.json`); + console.log( + `Warning: Ignoring "${path.basename(this._jsonFilename)}" because the` + + ` "approvedPackagesPolicy" setting was not specified in rush.json` + ); } return false; @@ -119,8 +122,10 @@ export class ApprovedPackagesConfiguration { * Loads the configuration data from the filename that was passed to the constructor. */ public loadFromFile(): void { - const approvedPackagesJson: IApprovedPackagesJson = JsonFile.loadAndValidate(this._jsonFilename, - ApprovedPackagesConfiguration._jsonSchema); + const approvedPackagesJson: IApprovedPackagesJson = JsonFile.loadAndValidate( + this._jsonFilename, + ApprovedPackagesConfiguration._jsonSchema + ); this.clear(); @@ -152,7 +157,7 @@ export class ApprovedPackagesConfiguration { const itemJson: IApprovedPackagesItemJson = { name: item.packageName, - allowedCategories: allowedCategories + allowedCategories: allowedCategories, }; this._loadedJson.packages.push(itemJson); @@ -162,19 +167,16 @@ export class ApprovedPackagesConfiguration { let body: string = JsonFile.stringify(this._loadedJson); // Unindent the allowedCategories array to improve readability - body = body.replace( - /("allowedCategories": +\[)([^\]]+)/g, - (substring: string, ...args: string[]) => { - return args[0] + args[1].replace(/\s+/g, ' '); - } - ); + body = body.replace(/("allowedCategories": +\[)([^\]]+)/g, (substring: string, ...args: string[]) => { + return args[0] + args[1].replace(/\s+/g, ' '); + }); // Add a header - body = '// DO NOT ADD COMMENTS IN THIS FILE.' - + ' They will be lost when the Rush tool resaves it.\n' + body; + body = + '// DO NOT ADD COMMENTS IN THIS FILE.' + ' They will be lost when the Rush tool resaves it.\n' + body; FileSystem.writeFile(this._jsonFilename, body, { - convertLineEndings: NewlineKind.CrLf + convertLineEndings: NewlineKind.CrLf, }); } @@ -183,8 +185,11 @@ export class ApprovedPackagesConfiguration { */ private _addItemJson(itemJson: IApprovedPackagesItemJson, jsonFilename: string): void { if (this._itemsByName.has(itemJson.name)) { - throw new Error(`Error loading package review file ${jsonFilename}:` + os.EOL - + ` the name "${itemJson.name}" appears more than once`); + throw new Error( + `Error loading package review file ${jsonFilename}:` + + os.EOL + + ` the name "${itemJson.name}" appears more than once` + ); } const item: ApprovedPackagesItem = new ApprovedPackagesItem(); diff --git a/apps/rush-lib/src/api/ApprovedPackagesPolicy.ts b/apps/rush-lib/src/api/ApprovedPackagesPolicy.ts index 3da76833f48..852bc315247 100644 --- a/apps/rush-lib/src/api/ApprovedPackagesPolicy.ts +++ b/apps/rush-lib/src/api/ApprovedPackagesPolicy.ts @@ -21,7 +21,8 @@ export class ApprovedPackagesPolicy { /** @internal */ public constructor(rushConfiguration: RushConfiguration, rushConfigurationJson: IRushConfigurationJson) { - const approvedPackagesPolicy: IApprovedPackagesPolicyJson = rushConfigurationJson.approvedPackagesPolicy || {}; + const approvedPackagesPolicy: IApprovedPackagesPolicyJson = + rushConfigurationJson.approvedPackagesPolicy || {}; this._enabled = !!rushConfigurationJson.approvedPackagesPolicy; this._ignoredNpmScopes = new Set(approvedPackagesPolicy.ignoredNpmScopes); @@ -29,8 +30,10 @@ export class ApprovedPackagesPolicy { if (this._enabled) { if (!this.reviewCategories.size) { - throw new Error(`The "approvedPackagesPolicy" feature is enabled rush.json, but the reviewCategories` - + ` list is not configured.`); + throw new Error( + `The "approvedPackagesPolicy" feature is enabled rush.json, but the reviewCategories` + + ` list is not configured.` + ); } } diff --git a/apps/rush-lib/src/api/ChangeFile.ts b/apps/rush-lib/src/api/ChangeFile.ts index eb73961481c..be2a7c3158f 100644 --- a/apps/rush-lib/src/api/ChangeFile.ts +++ b/apps/rush-lib/src/api/ChangeFile.ts @@ -8,10 +8,7 @@ import gitInfo = require('git-repo-info'); import { JsonFile } from '@rushstack/node-core-library'; import { RushConfiguration } from './RushConfiguration'; -import { - IChangeFile, - IChangeInfo -} from './ChangeManagement'; +import { IChangeFile, IChangeInfo } from './ChangeManagement'; import { Git } from '../logic/Git'; /** @@ -24,10 +21,7 @@ export class ChangeFile { /** * @internal */ - public constructor( - changeFileData: IChangeFile, - rushConfiguration: RushConfiguration - ) { + public constructor(changeFileData: IChangeFile, rushConfiguration: RushConfiguration) { if (!changeFileData) { throw new Error(`changeFileData does not have a value`); } @@ -70,7 +64,7 @@ export class ChangeFile { public writeSync(): string { const filePath: string = this.generatePath(); JsonFile.save(this._changeFileData, filePath, { - ensureFolderExists: true + ensureFolderExists: true, }); return filePath; } @@ -89,19 +83,21 @@ export class ChangeFile { } // example filename: yourbranchname_2017-05-01-20-20.json - const filename: string = (branch ? - this._escapeFilename(`${branch}_${this._getTimestamp()}.json`) : - `${this._getTimestamp()}.json`); - const filePath: string = path.join(this._rushConfiguration.changesFolder, + const filename: string = branch + ? this._escapeFilename(`${branch}_${this._getTimestamp()}.json`) + : `${this._getTimestamp()}.json`; + const filePath: string = path.join( + this._rushConfiguration.changesFolder, ...this._changeFileData.packageName.split('/'), - filename); + filename + ); return filePath; } /** - * Gets the current time, formatted as YYYY-MM-DD-HH-MM - * Optionally will include seconds - */ + * Gets the current time, formatted as YYYY-MM-DD-HH-MM + * Optionally will include seconds + */ private _getTimestamp(useSeconds: boolean = false): string | undefined { // Create a date string with the current time @@ -139,4 +135,4 @@ export class ChangeFile { const badCharacters: RegExp = /[^a-zA-Z0-9._-]/g; return filename.replace(badCharacters, replacer); } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/api/ChangeManagement.ts b/apps/rush-lib/src/api/ChangeManagement.ts index 980cd8b2a89..b4ab5a13004 100644 --- a/apps/rush-lib/src/api/ChangeManagement.ts +++ b/apps/rush-lib/src/api/ChangeManagement.ts @@ -19,7 +19,7 @@ export enum ChangeType { hotfix = 2, patch = 3, minor = 4, - major = 5 + major = 5, } /** @@ -77,4 +77,4 @@ export interface IChangeInfo { * The type of the package publishing request (patch/minor/major), as provided by the JSON file. */ type?: string; -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/api/ChangeManager.ts b/apps/rush-lib/src/api/ChangeManager.ts index cd612ad286d..b06f78202a3 100644 --- a/apps/rush-lib/src/api/ChangeManager.ts +++ b/apps/rush-lib/src/api/ChangeManager.ts @@ -18,22 +18,25 @@ export class ChangeManager { public static createEmptyChangeFiles( rushConfiguration: RushConfiguration, projectName: string, - emailAddress: string): string | undefined { + emailAddress: string + ): string | undefined { const projectInfo: RushConfigurationProject | undefined = rushConfiguration.getProjectByName(projectName); if (projectInfo && projectInfo.shouldPublish) { - - const changefile: IChangeFile = { // eslint-disable-line @typescript-eslint/no-explicit-any - 'changes': [{ - comment: '', - packageName: projectName, - type: 'none' - }], - 'packageName': projectName, - 'email': emailAddress + const changefile: IChangeFile = { + // eslint-disable-line @typescript-eslint/no-explicit-any + changes: [ + { + comment: '', + packageName: projectName, + type: 'none', + }, + ], + packageName: projectName, + email: emailAddress, }; return new ChangeFile(changefile, rushConfiguration).writeSync(); } return undefined; } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/api/CommandLineConfiguration.ts b/apps/rush-lib/src/api/CommandLineConfiguration.ts index 8bfa4380fd3..22707f94891 100644 --- a/apps/rush-lib/src/api/CommandLineConfiguration.ts +++ b/apps/rush-lib/src/api/CommandLineConfiguration.ts @@ -3,19 +3,11 @@ import * as path from 'path'; -import { - JsonFile, - JsonSchema, - FileSystem -} from '@rushstack/node-core-library'; +import { JsonFile, JsonSchema, FileSystem } from '@rushstack/node-core-library'; import { RushConstants } from '../logic/RushConstants'; -import { - CommandJson, - ICommandLineJson, - ParameterJson -} from './CommandLineJson'; +import { CommandJson, ICommandLineJson, ParameterJson } from './CommandLineJson'; /** * Custom Commands and Options for the Rush Command Line @@ -31,40 +23,42 @@ export class CommandLineConfiguration { public static readonly defaultBuildCommandJson: CommandJson = { commandKind: RushConstants.bulkCommandKind, name: RushConstants.buildCommandName, - summary: 'Build all projects that haven\'t been built, or have changed since they were last built.', - description: 'This command is similar to "rush rebuild", except that "rush build" performs' - + ' an incremental build. In other words, it only builds projects whose source files have changed' - + ' since the last successful build. The analysis requires a Git working tree, and only considers' - + ' source files that are tracked by Git and whose path is under the project folder. (For more details' - + ' about this algorithm, see the documentation for the "package-deps-hash" NPM package.) The incremental' - + ' build state is tracked in a per-project folder called ".rush/temp" which should NOT be added to Git. The' - + ' build command is tracked by the "arguments" field in the "package-deps_build.json" file contained' - + ' therein; a full rebuild is forced whenever the command has changed (e.g. "--production" or not).', + summary: "Build all projects that haven't been built, or have changed since they were last built.", + description: + 'This command is similar to "rush rebuild", except that "rush build" performs' + + ' an incremental build. In other words, it only builds projects whose source files have changed' + + ' since the last successful build. The analysis requires a Git working tree, and only considers' + + ' source files that are tracked by Git and whose path is under the project folder. (For more details' + + ' about this algorithm, see the documentation for the "package-deps-hash" NPM package.) The incremental' + + ' build state is tracked in a per-project folder called ".rush/temp" which should NOT be added to Git. The' + + ' build command is tracked by the "arguments" field in the "package-deps_build.json" file contained' + + ' therein; a full rebuild is forced whenever the command has changed (e.g. "--production" or not).', enableParallelism: true, ignoreMissingScript: false, ignoreDependencyOrder: false, incremental: true, allowWarningsInSuccessfulBuild: false, - safeForSimultaneousRushProcesses: false + safeForSimultaneousRushProcesses: false, }; public static readonly defaultRebuildCommandJson: CommandJson = { commandKind: RushConstants.bulkCommandKind, name: RushConstants.rebuildCommandName, summary: 'Clean and rebuild the entire set of projects', - description: 'This command assumes that the package.json file for each project contains' - + ' a "scripts" entry for "npm run build" that performs a full clean build.' - + ' Rush invokes this script to build each project that is registered in rush.json.' - + ' Projects are built in parallel where possible, but always respecting the dependency' - + ' graph for locally linked projects. The number of simultaneous processes will be' - + ' based on the number of machine cores unless overridden by the --parallelism flag.' - + ' (For an incremental build, see "rush build" instead of "rush rebuild".)', + description: + 'This command assumes that the package.json file for each project contains' + + ' a "scripts" entry for "npm run build" that performs a full clean build.' + + ' Rush invokes this script to build each project that is registered in rush.json.' + + ' Projects are built in parallel where possible, but always respecting the dependency' + + ' graph for locally linked projects. The number of simultaneous processes will be' + + ' based on the number of machine cores unless overridden by the --parallelism flag.' + + ' (For an incremental build, see "rush build" instead of "rush rebuild".)', enableParallelism: true, ignoreMissingScript: false, ignoreDependencyOrder: false, incremental: false, allowWarningsInSuccessfulBuild: false, - safeForSimultaneousRushProcesses: false + safeForSimultaneousRushProcesses: false, }; /** @@ -85,12 +79,14 @@ export class CommandLineConfiguration { // Do some basic validation switch (parameter.parameterKind) { case 'choice': - const alternativeNames: string[] = parameter.alternatives.map(x => x.name); + const alternativeNames: string[] = parameter.alternatives.map((x) => x.name); if (parameter.defaultValue && alternativeNames.indexOf(parameter.defaultValue) < 0) { - throw new Error(`In ${RushConstants.commandLineFilename}, the parameter "${parameter.longName}",` - + ` specifies a default value "${parameter.defaultValue}"` - + ` which is not one of the defined alternatives: "${alternativeNames.toString()}"`); + throw new Error( + `In ${RushConstants.commandLineFilename}, the parameter "${parameter.longName}",` + + ` specifies a default value "${parameter.defaultValue}"` + + ` which is not one of the defined alternatives: "${alternativeNames.toString()}"` + ); } break; } @@ -121,7 +117,7 @@ export class CommandLineConfiguration { case RushConstants.bulkCommandKind: { switch (command.name) { case RushConstants.buildCommandName: { - commandDefaultDefinition = CommandLineConfiguration.defaultBuildCommandJson + commandDefaultDefinition = CommandLineConfiguration.defaultBuildCommandJson; break; } @@ -137,8 +133,8 @@ export class CommandLineConfiguration { // Merge the default parameters into the repo-specified parameters commandLineJson.commands[i] = { ...commandDefaultDefinition, - ...command - } + ...command, + }; } CommandLineConfiguration._jsonSchema.validateObject(commandLineJson, jsonFilename); diff --git a/apps/rush-lib/src/api/CommonVersionsConfiguration.ts b/apps/rush-lib/src/api/CommonVersionsConfiguration.ts index e455bd592f4..2b4a9b5ce13 100644 --- a/apps/rush-lib/src/api/CommonVersionsConfiguration.ts +++ b/apps/rush-lib/src/api/CommonVersionsConfiguration.ts @@ -7,7 +7,7 @@ import { JsonSchema, MapExtensions, ProtectableMap, - FileSystem + FileSystem, } from '@rushstack/node-core-library'; import { PackageNameParsers } from './PackageNameParsers'; import { JsonSchemaUrls } from '../logic/JsonSchemaUrls'; @@ -56,7 +56,8 @@ interface ICommonVersionsJson { */ export class CommonVersionsConfiguration { private static _jsonSchema: JsonSchema = JsonSchema.fromFile( - path.join(__dirname, '../schemas/common-versions.schema.json')); + path.join(__dirname, '../schemas/common-versions.schema.json') + ); private _filePath: string; private _preferredVersions: ProtectableMap; @@ -66,8 +67,9 @@ export class CommonVersionsConfiguration { private _modified: boolean; private constructor(commonVersionsJson: ICommonVersionsJson | undefined, filePath: string) { - this._preferredVersions = new ProtectableMap( - { onSet: this._onSetPreferredVersions.bind(this) }); + this._preferredVersions = new ProtectableMap({ + onSet: this._onSetPreferredVersions.bind(this), + }); if (commonVersionsJson && commonVersionsJson.implicitlyPreferredVersions !== undefined) { this._implicitlyPreferredVersions = commonVersionsJson.implicitlyPreferredVersions; @@ -75,20 +77,28 @@ export class CommonVersionsConfiguration { this._implicitlyPreferredVersions = undefined; } - this._xstitchPreferredVersions = new ProtectableMap( - { onSet: this._onSetPreferredVersions.bind(this) }); + this._xstitchPreferredVersions = new ProtectableMap({ + onSet: this._onSetPreferredVersions.bind(this), + }); - this._allowedAlternativeVersions = new ProtectableMap( - { onSet: this._onSetAllowedAlternativeVersions.bind(this) }); + this._allowedAlternativeVersions = new ProtectableMap({ + onSet: this._onSetAllowedAlternativeVersions.bind(this), + }); if (commonVersionsJson) { try { - CommonVersionsConfiguration._deserializeTable(this.preferredVersions, - commonVersionsJson.preferredVersions); - CommonVersionsConfiguration._deserializeTable(this.xstitchPreferredVersions, - commonVersionsJson.xstitchPreferredVersions); - CommonVersionsConfiguration._deserializeTable(this.allowedAlternativeVersions, - commonVersionsJson.allowedAlternativeVersions); + CommonVersionsConfiguration._deserializeTable( + this.preferredVersions, + commonVersionsJson.preferredVersions + ); + CommonVersionsConfiguration._deserializeTable( + this.xstitchPreferredVersions, + commonVersionsJson.xstitchPreferredVersions + ); + CommonVersionsConfiguration._deserializeTable( + this.allowedAlternativeVersions, + commonVersionsJson.allowedAlternativeVersions + ); } catch (e) { throw new Error(`Error loading "${path.basename(filePath)}": ${e.message}`); } @@ -119,8 +129,8 @@ export class CommonVersionsConfiguration { } } - private static _serializeTable(map: Map): { } { - const table: { } = { }; + private static _serializeTable(map: Map): {} { + const table: {} = {}; const keys: string[] = [...map.keys()]; keys.sort(); @@ -219,18 +229,26 @@ export class CommonVersionsConfiguration { return allPreferredVersions; } - private _onSetPreferredVersions(source: ProtectableMap, key: string, value: string): string { + private _onSetPreferredVersions( + source: ProtectableMap, + key: string, + value: string + ): string { PackageNameParsers.permissive.validate(key); if (source === this._preferredVersions) { if (this._xstitchPreferredVersions.has(key)) { - throw new Error(`The package "${key}" cannot be added to preferredVersions because it was already` - + ` added to xstitchPreferredVersions`); + throw new Error( + `The package "${key}" cannot be added to preferredVersions because it was already` + + ` added to xstitchPreferredVersions` + ); } } else { if (this._preferredVersions.has(key)) { - throw new Error(`The package "${key}" cannot be added to xstitchPreferredVersions because it was already` - + ` added to preferredVersions`); + throw new Error( + `The package "${key}" cannot be added to xstitchPreferredVersions because it was already` + + ` added to preferredVersions` + ); } } @@ -239,7 +257,11 @@ export class CommonVersionsConfiguration { return value; } - private _onSetAllowedAlternativeVersions(source: ProtectableMap, key: string, value: string): string { + private _onSetAllowedAlternativeVersions( + source: ProtectableMap, + key: string, + value: string + ): string { PackageNameParsers.permissive.validate(key); this._modified = true; @@ -249,7 +271,7 @@ export class CommonVersionsConfiguration { private _serialize(): ICommonVersionsJson { const result: ICommonVersionsJson = { - $schema: JsonSchemaUrls.commonVersions + $schema: JsonSchemaUrls.commonVersions, }; if (this._preferredVersions.size) { @@ -257,11 +279,15 @@ export class CommonVersionsConfiguration { } if (this._xstitchPreferredVersions.size) { - result.xstitchPreferredVersions = CommonVersionsConfiguration._serializeTable(this.xstitchPreferredVersions); + result.xstitchPreferredVersions = CommonVersionsConfiguration._serializeTable( + this.xstitchPreferredVersions + ); } if (this._allowedAlternativeVersions.size) { - result.allowedAlternativeVersions = CommonVersionsConfiguration._serializeTable(this.allowedAlternativeVersions); + result.allowedAlternativeVersions = CommonVersionsConfiguration._serializeTable( + this.allowedAlternativeVersions + ); } return result; diff --git a/apps/rush-lib/src/api/EnvironmentConfiguration.ts b/apps/rush-lib/src/api/EnvironmentConfiguration.ts index 1e42a1e14de..65c59d40844 100644 --- a/apps/rush-lib/src/api/EnvironmentConfiguration.ts +++ b/apps/rush-lib/src/api/EnvironmentConfiguration.ts @@ -68,7 +68,7 @@ export const enum EnvironmentVariableNames { * This environment variable can be used to specify the `--target-folder` parameter * for the "rush deploy" command. */ - RUSH_DEPLOY_TARGET_FOLDER = 'RUSH_DEPLOY_TARGET_FOLDER' + RUSH_DEPLOY_TARGET_FOLDER = 'RUSH_DEPLOY_TARGET_FOLDER', } /** @@ -138,12 +138,14 @@ export class EnvironmentConfiguration { if (process.env.hasOwnProperty(envVarName) && envVarName.match(/^RUSH_/i)) { const value: string | undefined = process.env[envVarName]; // Environment variables are only case-insensitive on Windows - const normalizedEnvVarName: string = os.platform() === 'win32' ? envVarName.toUpperCase() : envVarName; + const normalizedEnvVarName: string = + os.platform() === 'win32' ? envVarName.toUpperCase() : envVarName; switch (normalizedEnvVarName) { case EnvironmentVariableNames.RUSH_TEMP_FOLDER: { - EnvironmentConfiguration._rushTempFolderOverride = (value && !options.doNotNormalizePaths) - ? EnvironmentConfiguration._normalizeDeepestParentFolderPath(value) || value - : value; + EnvironmentConfiguration._rushTempFolderOverride = + value && !options.doNotNormalizePaths + ? EnvironmentConfiguration._normalizeDeepestParentFolderPath(value) || value + : value; break; } @@ -158,9 +160,10 @@ export class EnvironmentConfiguration { } case EnvironmentVariableNames.RUSH_PNPM_STORE_PATH: { - EnvironmentConfiguration._pnpmStorePathOverride = (value && !options.doNotNormalizePaths) - ? EnvironmentConfiguration._normalizeDeepestParentFolderPath(value) || value - : value; + EnvironmentConfiguration._pnpmStorePathOverride = + value && !options.doNotNormalizePaths + ? EnvironmentConfiguration._normalizeDeepestParentFolderPath(value) || value + : value; break; } @@ -181,7 +184,7 @@ export class EnvironmentConfiguration { if (unknownEnvVariables.length > 0) { throw new Error( 'The following environment variables were found with the "RUSH_" prefix, but they are not ' + - `recognized by this version of Rush: ${unknownEnvVariables.join(', ')}` + `recognized by this version of Rush: ${unknownEnvVariables.join(', ')}` ); } @@ -221,7 +224,9 @@ export class EnvironmentConfiguration { const parsedPath: path.ParsedPath = path.parse(folderPath); const pathRoot: string = parsedPath.root; const pathWithoutRoot: string = parsedPath.dir.substr(pathRoot.length); - const pathParts: string[] = [...pathWithoutRoot.split(path.sep), parsedPath.name].filter((part) => !!part); + const pathParts: string[] = [...pathWithoutRoot.split(path.sep), parsedPath.name].filter( + (part) => !!part + ); // Starting with all path sections, and eliminating one from the end during each loop iteration, // run trueCasePathSync. If trueCasePathSync returns without exception, we've found a subset diff --git a/apps/rush-lib/src/api/EventHooks.ts b/apps/rush-lib/src/api/EventHooks.ts index 1ff99d0844a..e7cfce9261a 100644 --- a/apps/rush-lib/src/api/EventHooks.ts +++ b/apps/rush-lib/src/api/EventHooks.ts @@ -23,7 +23,7 @@ export enum Event { /** * Post Rush build event */ - postRushBuild = 4 + postRushBuild = 4, } /** @@ -61,4 +61,4 @@ export class EventHooks { public get(event: Event): string[] { return this._hooks.get(event) || []; } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/api/ExperimentsConfiguration.ts b/apps/rush-lib/src/api/ExperimentsConfiguration.ts index 193f663599a..1560a677e76 100644 --- a/apps/rush-lib/src/api/ExperimentsConfiguration.ts +++ b/apps/rush-lib/src/api/ExperimentsConfiguration.ts @@ -2,11 +2,7 @@ // See LICENSE in the project root for license information. import * as path from 'path'; -import { - JsonFile, - JsonSchema, - FileSystem -} from '@rushstack/node-core-library'; +import { JsonFile, JsonSchema, FileSystem } from '@rushstack/node-core-library'; /** * This interface represents the raw experiments.json file which allows repo diff --git a/apps/rush-lib/src/api/LastInstallFlag.ts b/apps/rush-lib/src/api/LastInstallFlag.ts index 4a27a9bc07a..45d83ba1171 100644 --- a/apps/rush-lib/src/api/LastInstallFlag.ts +++ b/apps/rush-lib/src/api/LastInstallFlag.ts @@ -2,7 +2,7 @@ import * as path from 'path'; import * as _ from 'lodash'; import { FileSystem, JsonFile, JsonObject } from '@rushstack/node-core-library'; -import { PackageManagerName } from './packageManager/PackageManager' +import { PackageManagerName } from './packageManager/PackageManager'; export const LAST_INSTALL_FLAG_FILE_NAME: string = 'last-install.flag'; @@ -21,7 +21,7 @@ export class LastInstallFlag { * Creates a new LastInstall flag * @param folderPath - the folder that this flag is managing * @param state - optional, the state that should be managed or compared - */ + */ public constructor(folderPath: string, state: JsonObject = {}) { this._path = path.join(folderPath, LAST_INSTALL_FLAG_FILE_NAME); this._state = state; @@ -61,21 +61,21 @@ export class LastInstallFlag { const pkgManager: PackageManagerName = newState.packageManager; if (pkgManager === 'pnpm') { if ( - ( // Only throw an error if the package manager hasn't changed from PNPM - oldState.packageManager === pkgManager - ) && ( // Throw if the store path changed - oldState.storePath && - oldState.storePath !== newState.storePath - ) + // Only throw an error if the package manager hasn't changed from PNPM + oldState.packageManager === pkgManager && // Throw if the store path changed + oldState.storePath && + oldState.storePath !== newState.storePath ) { const oldStorePath: string = oldState.storePath || ''; const newStorePath: string = newState.storePath || ''; - throw new Error("Current PNPM store path does not match the last one used." + - " This may cause inconsistency in your builds.\n\n" + - "If you wish to install with the new store path, please run \"rush update --purge\"\n\n" + - `Old Path: ${oldStorePath}\n` + - `New Path: ${newStorePath}`); + throw new Error( + 'Current PNPM store path does not match the last one used.' + + ' This may cause inconsistency in your builds.\n\n' + + 'If you wish to install with the new store path, please run "rush update --purge"\n\n' + + `Old Path: ${oldStorePath}\n` + + `New Path: ${newStorePath}` + ); } } } @@ -90,7 +90,7 @@ export class LastInstallFlag { */ public create(): void { JsonFile.save(this._state, this._path, { - ensureFolderExists: true + ensureFolderExists: true, }); } diff --git a/apps/rush-lib/src/api/PackageJsonEditor.ts b/apps/rush-lib/src/api/PackageJsonEditor.ts index f308bc7415c..aa88799d52f 100644 --- a/apps/rush-lib/src/api/PackageJsonEditor.ts +++ b/apps/rush-lib/src/api/PackageJsonEditor.ts @@ -3,11 +3,7 @@ import * as semver from 'semver'; -import { - IPackageJson, - JsonFile, - Sort -} from '@rushstack/node-core-library'; +import { IPackageJson, JsonFile, Sort } from '@rushstack/node-core-library'; /** * @beta @@ -16,7 +12,7 @@ export const enum DependencyType { Regular = 'dependencies', Dev = 'devDependencies', Optional = 'optionalDependencies', - Peer = 'peerDependencies' + Peer = 'peerDependencies', } /** @@ -28,10 +24,7 @@ export class PackageJsonDependency { private _version: string; private _onChange: () => void; - public constructor(name: string, - version: string, - type: DependencyType, - onChange: () => void) { + public constructor(name: string, version: string, type: DependencyType, onChange: () => void) { this._name = name; this._version = version; this._type = type; @@ -93,41 +86,62 @@ export class PackageJsonEditor { try { Object.keys(dependencies || {}).forEach((packageName: string) => { if (Object.prototype.hasOwnProperty.call(optionalDependencies, packageName)) { - throw new Error(`The package "${packageName}" cannot be listed in both ` - + `"dependencies" and "optionalDependencies"`); + throw new Error( + `The package "${packageName}" cannot be listed in both ` + + `"dependencies" and "optionalDependencies"` + ); } if (Object.prototype.hasOwnProperty.call(peerDependencies, packageName)) { - throw new Error(`The package "${packageName}" cannot be listed in both ` - + `"dependencies" and "peerDependencies"`); + throw new Error( + `The package "${packageName}" cannot be listed in both ` + `"dependencies" and "peerDependencies"` + ); } - this._dependencies.set(packageName, - new PackageJsonDependency(packageName, dependencies[packageName], DependencyType.Regular, _onChange)); + this._dependencies.set( + packageName, + new PackageJsonDependency(packageName, dependencies[packageName], DependencyType.Regular, _onChange) + ); }); Object.keys(optionalDependencies || {}).forEach((packageName: string) => { if (Object.prototype.hasOwnProperty.call(peerDependencies, packageName)) { - throw new Error(`The package "${packageName}" cannot be listed in both ` - + `"optionalDependencies" and "peerDependencies"`); + throw new Error( + `The package "${packageName}" cannot be listed in both ` + + `"optionalDependencies" and "peerDependencies"` + ); } - this._dependencies.set(packageName, - new PackageJsonDependency(packageName, optionalDependencies[packageName], DependencyType.Optional, _onChange) + this._dependencies.set( + packageName, + new PackageJsonDependency( + packageName, + optionalDependencies[packageName], + DependencyType.Optional, + _onChange + ) ); }); Object.keys(peerDependencies || {}).forEach((packageName: string) => { - this._dependencies.set(packageName, - new PackageJsonDependency(packageName, peerDependencies[packageName], DependencyType.Peer, _onChange)); + this._dependencies.set( + packageName, + new PackageJsonDependency( + packageName, + peerDependencies[packageName], + DependencyType.Peer, + _onChange + ) + ); }); Object.keys(devDependencies || {}).forEach((packageName: string) => { - this._devDependencies.set(packageName, - new PackageJsonDependency(packageName, devDependencies[packageName], DependencyType.Dev, _onChange)); + this._devDependencies.set( + packageName, + new PackageJsonDependency(packageName, devDependencies[packageName], DependencyType.Dev, _onChange) + ); }); Sort.sortMapKeys(this._dependencies); Sort.sortMapKeys(this._devDependencies); - } catch (e) { throw new Error(`Error loading "${filepath}": ${e.message}`); } @@ -175,7 +189,11 @@ export class PackageJsonEditor { return this._devDependencies.get(packageName); } - public addOrUpdateDependency(packageName: string, newVersion: string, dependencyType: DependencyType): void { + public addOrUpdateDependency( + packageName: string, + newVersion: string, + dependencyType: DependencyType + ): void { const dependency: PackageJsonDependency = new PackageJsonDependency( packageName, newVersion, diff --git a/apps/rush-lib/src/api/PackageNameParsers.ts b/apps/rush-lib/src/api/PackageNameParsers.ts index 8f38ab33dbb..953e9e7d820 100644 --- a/apps/rush-lib/src/api/PackageNameParsers.ts +++ b/apps/rush-lib/src/api/PackageNameParsers.ts @@ -1,22 +1,20 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - PackageNameParser -} from '@rushstack/node-core-library'; +import { PackageNameParser } from '@rushstack/node-core-library'; export class PackageNameParsers { /** * This is the default for `RushConfiguration.packageNameParser`. */ - public static rushDefault: PackageNameParser = new PackageNameParser({ }); + public static rushDefault: PackageNameParser = new PackageNameParser({}); /** * This is the `RushConfiguration.packageNameParser` used when `allowMostlyStandardPackageNames = true` * in rush.json. */ public static mostlyStandard: PackageNameParser = new PackageNameParser({ - allowUpperCase: true + allowUpperCase: true, }); /** diff --git a/apps/rush-lib/src/api/Rush.ts b/apps/rush-lib/src/api/Rush.ts index 8f437d780e4..3dbe8afc1ab 100644 --- a/apps/rush-lib/src/api/Rush.ts +++ b/apps/rush-lib/src/api/Rush.ts @@ -62,7 +62,7 @@ export class Rush { } const parser: RushCommandLineParser = new RushCommandLineParser({ - alreadyReportedNodeTooNewError: options.alreadyReportedNodeTooNewError + alreadyReportedNodeTooNewError: options.alreadyReportedNodeTooNewError, }); parser.execute().catch(console.error); // CommandLineParser.execute() should never reject the promise } @@ -94,24 +94,28 @@ export class Rush { * This function normalizes legacy options to the current {@link ILaunchOptions} object. */ private static _normalizeLaunchOptions(arg: ILaunchOptions): ILaunchOptions { - return (typeof arg === 'boolean') + return typeof arg === 'boolean' ? { isManaged: arg } // In older versions of Rush, this the `launch` functions took a boolean arg for "isManaged" : arg; } private static _printStartupBanner(isManaged: boolean): void { const nodeVersion: string = process.versions.node; - const nodeReleaseLabel: string = (NodeJsCompatibility.isOddNumberedVersion) - ? 'unstable' - : (NodeJsCompatibility.isLtsVersion ? 'LTS' : 'pre-LTS'); + const nodeReleaseLabel: string = NodeJsCompatibility.isOddNumberedVersion + ? 'unstable' + : NodeJsCompatibility.isLtsVersion + ? 'LTS' + : 'pre-LTS'; console.log( EOL + - colors.bold(`Rush Multi-Project Build Tool ${Rush.version}` + colors.yellow(isManaged ? '' : ' (unmanaged)')) + - colors.cyan(` - ${RushConstants.rushWebSiteUrl}`) + - EOL + - `Node.js version is ${nodeVersion} (${nodeReleaseLabel})` + - EOL + colors.bold( + `Rush Multi-Project Build Tool ${Rush.version}` + colors.yellow(isManaged ? '' : ' (unmanaged)') + ) + + colors.cyan(` - ${RushConstants.rushWebSiteUrl}`) + + EOL + + `Node.js version is ${nodeVersion} (${nodeReleaseLabel})` + + EOL ); } } diff --git a/apps/rush-lib/src/api/RushConfiguration.ts b/apps/rush-lib/src/api/RushConfiguration.ts index 513a7ed65ad..31b5a3360f3 100644 --- a/apps/rush-lib/src/api/RushConfiguration.ts +++ b/apps/rush-lib/src/api/RushConfiguration.ts @@ -6,13 +6,7 @@ import * as path from 'path'; import * as fs from 'fs'; import * as semver from 'semver'; -import { - JsonFile, - JsonSchema, - Path, - FileSystem, - PackageNameParser -} from '@rushstack/node-core-library'; +import { JsonFile, JsonSchema, Path, FileSystem, PackageNameParser } from '@rushstack/node-core-library'; import { trueCasePathSync } from 'true-case-path'; import { Rush } from '../api/Rush'; @@ -48,7 +42,7 @@ const knownRushConfigFilenames: string[] = [ RushConstants.nonbrowserApprovedPackagesFilename, RushConstants.versionPoliciesFilename, RushConstants.commandLineFilename, - RushConstants.experimentsFilename + RushConstants.experimentsFilename, ]; /** @@ -114,7 +108,7 @@ export interface IPackageManagerOptionsJsonBase { /** * Environment variables for the package manager */ - environmentVariables?: IConfigurationEnvironment + environmentVariables?: IConfigurationEnvironment; } /** @@ -150,8 +144,7 @@ export interface IConfigurationEnvironmentVariable { * Part of IRushConfigurationJson. * @internal */ -export interface INpmOptionsJson extends IPackageManagerOptionsJsonBase { -} +export interface INpmOptionsJson extends IPackageManagerOptionsJsonBase {} /** * Part of IRushConfigurationJson. @@ -233,7 +226,7 @@ export interface IRushConfigurationJson { */ export interface IRushLinkJson { localLinks: { - [name: string]: string[] + [name: string]: string[]; }; } @@ -253,7 +246,7 @@ export abstract class PackageManagerOptionsConfigurationBase implements IPackage /** * Environment variables for the package manager */ - public readonly environmentVariables?: IConfigurationEnvironment + public readonly environmentVariables?: IConfigurationEnvironment; /** @internal */ protected constructor(json: IPackageManagerOptionsJsonBase) { @@ -365,7 +358,7 @@ export class PnpmOptionsConfiguration extends PackageManagerOptionsConfiguration } this.strictPeerDependencies = !!json.strictPeerDependencies; this.resolutionStrategy = json.resolutionStrategy || 'fewer-dependencies'; - this.preventManualShrinkwrapChanges = !!json.preventManualShrinkwrapChanges + this.preventManualShrinkwrapChanges = !!json.preventManualShrinkwrapChanges; } } @@ -403,12 +396,12 @@ export interface ITryFindRushJsonLocationOptions { /** * Whether to show verbose console messages. Defaults to false. */ - showVerbose?: boolean; // Defaults to false (inverse of old `verbose` parameter) + showVerbose?: boolean; // Defaults to false (inverse of old `verbose` parameter) /** * The folder path where the search will start. Defaults tot he current working directory. */ - startingFolder?: string; // Defaults to cwd + startingFolder?: string; // Defaults to cwd } /** @@ -423,7 +416,9 @@ export type ResolutionStrategy = 'fewer-dependencies' | 'fast'; * @public */ export class RushConfiguration { - private static _jsonSchema: JsonSchema = JsonSchema.fromFile(path.join(__dirname, '../schemas/rush.schema.json')); + private static _jsonSchema: JsonSchema = JsonSchema.fromFile( + path.join(__dirname, '../schemas/rush.schema.json') + ); private _rushJsonFile: string; private _rushJsonFolder: string; @@ -478,7 +473,7 @@ export class RushConfiguration { // Rush hooks private _eventHooks: EventHooks; - private readonly _packageNameParser: PackageNameParser + private readonly _packageNameParser: PackageNameParser; private _telemetryEnabled: boolean; @@ -497,13 +492,16 @@ export class RushConfiguration { if (rushConfigurationJson.nodeSupportedVersionRange) { if (!semver.validRange(rushConfigurationJson.nodeSupportedVersionRange)) { - throw new Error('Error parsing the node-semver expression in the "nodeSupportedVersionRange"' - + ` field from rush.json: "${rushConfigurationJson.nodeSupportedVersionRange}"`); + throw new Error( + 'Error parsing the node-semver expression in the "nodeSupportedVersionRange"' + + ` field from rush.json: "${rushConfigurationJson.nodeSupportedVersionRange}"` + ); } if (!semver.satisfies(process.version, rushConfigurationJson.nodeSupportedVersionRange)) { - const message: string = `Your dev environment is running Node.js version ${process.version} which does` - + ` not meet the requirements for building this repository. (The rush.json configuration` - + ` requires nodeSupportedVersionRange="${rushConfigurationJson.nodeSupportedVersionRange}")`; + const message: string = + `Your dev environment is running Node.js version ${process.version} which does` + + ` not meet the requirements for building this repository. (The rush.json configuration` + + ` requires nodeSupportedVersionRange="${rushConfigurationJson.nodeSupportedVersionRange}")`; if (EnvironmentConfiguration.allowUnsupportedNodeVersion) { console.warn(message); } else { @@ -519,7 +517,8 @@ export class RushConfiguration { this._commonRushConfigFolder = path.join(this._commonFolder, 'config', 'rush'); - this._commonTempFolder = EnvironmentConfiguration.rushTempFolderOverride || + this._commonTempFolder = + EnvironmentConfiguration.rushTempFolderOverride || path.join(this._commonFolder, RushConstants.rushTempFolderName); this._commonScriptsFolder = path.join(this._commonFolder, 'scripts'); @@ -545,8 +544,10 @@ export class RushConfiguration { this._experimentsConfiguration = new ExperimentsConfiguration(experimentsConfigFile); this._npmOptions = new NpmOptionsConfiguration(rushConfigurationJson.npmOptions || {}); - this._pnpmOptions = new PnpmOptionsConfiguration(rushConfigurationJson.pnpmOptions || {}, - this._commonTempFolder); + this._pnpmOptions = new PnpmOptionsConfiguration( + rushConfigurationJson.pnpmOptions || {}, + this._commonTempFolder + ); this._yarnOptions = new YarnOptionsConfiguration(rushConfigurationJson.yarnOptions || {}); // TODO: Add an actual "packageManager" field in rush.json @@ -569,12 +570,16 @@ export class RushConfiguration { } if (packageManagerFields.length === 0) { - throw new Error(`The rush.json configuration must specify one of: npmVersion, pnpmVersion, or yarnVersion`); + throw new Error( + `The rush.json configuration must specify one of: npmVersion, pnpmVersion, or yarnVersion` + ); } if (packageManagerFields.length > 1) { - throw new Error(`The rush.json configuration cannot specify both ${packageManagerFields[0]}` - + ` and ${packageManagerFields[1]} `); + throw new Error( + `The rush.json configuration cannot specify both ${packageManagerFields[0]}` + + ` and ${packageManagerFields[1]} ` + ); } if (this._packageManager === 'npm') { @@ -590,17 +595,23 @@ export class RushConfiguration { this._shrinkwrapFilename = this._packageManagerWrapper.shrinkwrapFilename; - this._tempShrinkwrapFilename = path.join( - this._commonTempFolder, this._shrinkwrapFilename + this._tempShrinkwrapFilename = path.join(this._commonTempFolder, this._shrinkwrapFilename); + this._packageManagerToolFilename = path.resolve( + path.join( + this._commonTempFolder, + `${this.packageManager}-local`, + 'node_modules', + '.bin', + `${this.packageManager}` + ) ); - this._packageManagerToolFilename = path.resolve(path.join( - this._commonTempFolder, `${this.packageManager}-local`, 'node_modules', '.bin', `${this.packageManager}` - )); /// From "C:\repo\common\temp\pnpm-lock.yaml" --> "C:\repo\common\temp\pnpm-lock-preinstall.yaml" const parsedPath: path.ParsedPath = path.parse(this._tempShrinkwrapFilename); - this._tempShrinkwrapPreinstallFilename = path.join(parsedPath.dir, - parsedPath.name + '-preinstall' + parsedPath.ext); + this._tempShrinkwrapPreinstallFilename = path.join( + parsedPath.dir, + parsedPath.name + '-preinstall' + parsedPath.ext + ); RushConfiguration._validateCommonRushConfigFolder( this._commonRushConfigFolder, @@ -608,21 +619,26 @@ export class RushConfiguration { this._shrinkwrapFilename ); - this._projectFolderMinDepth = rushConfigurationJson.projectFolderMinDepth !== undefined - ? rushConfigurationJson.projectFolderMinDepth : 1; + this._projectFolderMinDepth = + rushConfigurationJson.projectFolderMinDepth !== undefined + ? rushConfigurationJson.projectFolderMinDepth + : 1; if (this._projectFolderMinDepth < 1) { throw new Error('Invalid projectFolderMinDepth; the minimum possible value is 1'); } - this._projectFolderMaxDepth = rushConfigurationJson.projectFolderMaxDepth !== undefined - ? rushConfigurationJson.projectFolderMaxDepth : 2; + this._projectFolderMaxDepth = + rushConfigurationJson.projectFolderMaxDepth !== undefined + ? rushConfigurationJson.projectFolderMaxDepth + : 2; if (this._projectFolderMaxDepth < this._projectFolderMinDepth) { throw new Error('The projectFolderMaxDepth cannot be smaller than the projectFolderMinDepth'); } this._allowMostlyStandardPackageNames = !!rushConfigurationJson.allowMostlyStandardPackageNames; this._packageNameParser = this._allowMostlyStandardPackageNames - ? PackageNameParsers.mostlyStandard : PackageNameParsers.rushDefault; + ? PackageNameParsers.mostlyStandard + : PackageNameParsers.rushDefault; this._approvedPackagesPolicy = new ApprovedPackagesPolicy(this, rushConfigurationJson); @@ -637,8 +653,10 @@ export class RushConfiguration { this._gitAllowedEmailRegExps = rushConfigurationJson.gitPolicy.allowedEmailRegExps; if (this._gitSampleEmail.trim().length < 1) { - throw new Error('The rush.json file is missing the "sampleEmail" option, ' + - 'which is required when using "allowedEmailRegExps"'); + throw new Error( + 'The rush.json file is missing the "sampleEmail" option, ' + + 'which is required when using "allowedEmailRegExps"' + ); } } @@ -652,7 +670,6 @@ export class RushConfiguration { this._hotfixChangeEnabled = rushConfigurationJson.hotfixChangeEnabled; } - if (!rushConfigurationJson.repository) { rushConfigurationJson.repository = {}; } @@ -678,21 +695,29 @@ export class RushConfiguration { // We sort the projects array in alphabetical order. This ensures that the packages // are processed in a deterministic order by the various Rush algorithms. const sortedProjectJsons: IRushConfigurationProjectJson[] = rushConfigurationJson.projects.slice(0); - sortedProjectJsons.sort( - (a: IRushConfigurationProjectJson, b: IRushConfigurationProjectJson) => a.packageName.localeCompare(b.packageName) + sortedProjectJsons.sort((a: IRushConfigurationProjectJson, b: IRushConfigurationProjectJson) => + a.packageName.localeCompare(b.packageName) ); - const tempNamesByProject: Map - = RushConfiguration._generateTempNamesForProjects(sortedProjectJsons); + const tempNamesByProject: Map< + IRushConfigurationProjectJson, + string + > = RushConfiguration._generateTempNamesForProjects(sortedProjectJsons); for (const projectJson of sortedProjectJsons) { const tempProjectName: string | undefined = tempNamesByProject.get(projectJson); if (tempProjectName) { - const project: RushConfigurationProject = new RushConfigurationProject(projectJson, this, tempProjectName); + const project: RushConfigurationProject = new RushConfigurationProject( + projectJson, + this, + tempProjectName + ); this._projects.push(project); if (this._projectsByName.get(project.packageName)) { - throw new Error(`The project name "${project.packageName}" was specified more than once` - + ` in the rush.json configuration file.`); + throw new Error( + `The project name "${project.packageName}" was specified more than once` + + ` in the rush.json configuration file.` + ); } this._projectsByName.set(project.packageName, project); } @@ -701,8 +726,10 @@ export class RushConfiguration { for (const project of this._projects) { project.cyclicDependencyProjects.forEach((cyclicDependencyProject: string) => { if (!this.getProjectByName(cyclicDependencyProject)) { - throw new Error(`In rush.json, the "${cyclicDependencyProject}" project does not exist,` - + ` but was referenced by the cyclicDependencyProjects for ${project.packageName}`); + throw new Error( + `In rush.json, the "${cyclicDependencyProject}" project does not exist,` + + ` but was referenced by the cyclicDependencyProjects for ${project.packageName}` + ); } }); @@ -718,9 +745,7 @@ export class RushConfiguration { if (rushConfigurationJson.variants) { for (const variantOptions of rushConfigurationJson.variants) { - const { - variantName - } = variantOptions; + const { variantName } = variantOptions; if (variants[variantName]) { throw new Error(`Duplicate variant named '${variantName}' specified in configuration.`); @@ -760,8 +785,10 @@ export class RushConfiguration { if (expectedRushVersion && semver.valid(expectedRushVersion)) { // Make sure the requested version isn't too old if (semver.lt(expectedRushVersion, MINIMUM_SUPPORTED_RUSH_JSON_VERSION)) { - throw new Error(`${rushJsonBaseName} is version ${expectedRushVersion}, which is too old for this tool. ` + - `The minimum supported version is ${MINIMUM_SUPPORTED_RUSH_JSON_VERSION}.`); + throw new Error( + `${rushJsonBaseName} is version ${expectedRushVersion}, which is too old for this tool. ` + + `The minimum supported version is ${MINIMUM_SUPPORTED_RUSH_JSON_VERSION}.` + ); } // Make sure the requested version isn't too new. @@ -771,14 +798,17 @@ export class RushConfiguration { // // IMPORTANT: Whenever a breaking change is introduced for one of the config files, we must // increment the minor version number for Rush. - if (semver.major(Rush.version) !== semver.major(expectedRushVersion) - || semver.minor(Rush.version) !== semver.minor(expectedRushVersion)) { - + if ( + semver.major(Rush.version) !== semver.major(expectedRushVersion) || + semver.minor(Rush.version) !== semver.minor(expectedRushVersion) + ) { // If the major/minor are different, then make sure it's an older version. if (semver.lt(Rush.version, expectedRushVersion)) { - throw new Error(`Unable to load ${rushJsonBaseName} because its RushVersion is` - + ` ${rushConfigurationJson.rushVersion}, whereas @microsoft/rush-lib is version ${Rush.version}.` - + ` Consider upgrading the library.`); + throw new Error( + `Unable to load ${rushJsonBaseName} because its RushVersion is` + + ` ${rushConfigurationJson.rushVersion}, whereas @microsoft/rush-lib is version ${Rush.version}.` + + ` Consider upgrading the library.` + ); } } } @@ -838,11 +868,13 @@ export class RushConfiguration { * in the Rush common folder. * NOTE: sortedProjectJsons is sorted by the caller. */ - private static _generateTempNamesForProjects(sortedProjectJsons: IRushConfigurationProjectJson[]): - Map { - - const tempNamesByProject: Map = - new Map(); + private static _generateTempNamesForProjects( + sortedProjectJsons: IRushConfigurationProjectJson[] + ): Map { + const tempNamesByProject: Map = new Map< + IRushConfigurationProjectJson, + string + >(); const usedTempNames: Set = new Set(); // NOTE: projectJsons was already sorted in alphabetical order by the caller. @@ -884,7 +916,6 @@ export class RushConfiguration { } for (const filename of FileSystem.readFolder(commonRushConfigFolder)) { - // Ignore things that aren't actual files const stat: fs.Stats = FileSystem.getLinkStatistics(path.join(commonRushConfigFolder, filename)); if (!stat.isFile() && !stat.isSymbolicLink()) { @@ -897,7 +928,7 @@ export class RushConfiguration { continue; } - const knownSet: Set = new Set(knownRushConfigFilenames.map(x => x.toUpperCase())); + const knownSet: Set = new Set(knownRushConfigFilenames.map((x) => x.toUpperCase())); // Add the shrinkwrap filename for the package manager to the known set. knownSet.add(shrinkwrapFilename.toUpperCase()); @@ -909,17 +940,24 @@ export class RushConfiguration { // Is the filename something we know? If not, report an error. if (!knownSet.has(filename.toUpperCase())) { - throw new Error(`An unrecognized file "${filename}" was found in the Rush config folder:` - + ` ${commonRushConfigFolder}`); + throw new Error( + `An unrecognized file "${filename}" was found in the Rush config folder:` + + ` ${commonRushConfigFolder}` + ); } } - const pinnedVersionsFilename: string = path.join(commonRushConfigFolder, RushConstants.pinnedVersionsFilename); + const pinnedVersionsFilename: string = path.join( + commonRushConfigFolder, + RushConstants.pinnedVersionsFilename + ); if (FileSystem.exists(pinnedVersionsFilename)) { - throw new Error('The "pinned-versions.json" config file is no longer supported;' - + ' please move your settings to the "preferredVersions" field of a "common-versions.json" config file.' - + ` (See the ${RushConstants.rushWebSiteUrl} documentation for details.)\n\n` - + pinnedVersionsFilename); + throw new Error( + 'The "pinned-versions.json" config file is no longer supported;' + + ' please move your settings to the "preferredVersions" field of a "common-versions.json" config file.' + + ` (See the ${RushConstants.rushWebSiteUrl} documentation for details.)\n\n` + + pinnedVersionsFilename + ); } } @@ -1254,15 +1292,15 @@ export class RushConfiguration { } /** - * Odd-numbered major versions of Node.js are experimental. Even-numbered releases - * spend six months in a stabilization period before the first Long Term Support (LTS) version. - * For example, 8.9.0 was the first LTS version of Node.js 8. Pre-LTS versions are not recommended - * for production usage because they frequently have bugs. They may cause Rush itself - * to malfunction. - * - * Rush normally prints a warning if it detects a pre-LTS Node.js version. If you are testing - * pre-LTS versions in preparation for supporting the first LTS version, you can use this setting - * to disable Rush's warning. + * Odd-numbered major versions of Node.js are experimental. Even-numbered releases + * spend six months in a stabilization period before the first Long Term Support (LTS) version. + * For example, 8.9.0 was the first LTS version of Node.js 8. Pre-LTS versions are not recommended + * for production usage because they frequently have bugs. They may cause Rush itself + * to malfunction. + * + * Rush normally prints a warning if it detects a pre-LTS Node.js version. If you are testing + * pre-LTS versions in preparation for supporting the first LTS version, you can use this setting + * to disable Rush's warning. */ public get suppressNodeLtsWarning(): boolean { return this._suppressNodeLtsWarning; @@ -1375,9 +1413,11 @@ export class RushConfiguration { * @param variant - The name of the current variant in use by the active command. */ public getCommonVersionsFilePath(variant?: string | undefined): string { - const commonVersionsFilename: string = path.join(this.commonRushConfigFolder, + const commonVersionsFilename: string = path.join( + this.commonRushConfigFolder, ...(variant ? [RushConstants.rushVariantsFolderName, variant] : []), - RushConstants.commonVersionsFilename); + RushConstants.commonVersionsFilename + ); return commonVersionsFilename; } @@ -1399,8 +1439,11 @@ export class RushConfiguration { if (!this._variants[variant]) { throw new Error( `Invalid variant name '${variant}'. The provided variant parameter needs to be ` + - `one of the following from rush.json: ` + - `${Object.keys(this._variants).map((name: string) => `"${name}"`).join(', ')}.`); + `one of the following from rush.json: ` + + `${Object.keys(this._variants) + .map((name: string) => `"${name}"`) + .join(', ')}.` + ); } } @@ -1418,9 +1461,7 @@ export class RushConfiguration { public getPnpmfilePath(variant?: string | undefined): string { const variantConfigFolderPath: string = this._getVariantConfigFolderPath(variant); - return path.join( - variantConfigFolderPath, - RushConstants.pnpmfileFilename); + return path.join(variantConfigFolderPath, RushConstants.pnpmfileFilename); } /** @@ -1505,12 +1546,12 @@ export class RushConfiguration { private _populateDownstreamDependencies( dependencies: { [key: string]: string } | undefined, - packageName: string): void { - + packageName: string + ): void { if (!dependencies) { return; } - Object.keys(dependencies).forEach(dependencyName => { + Object.keys(dependencies).forEach((dependencyName) => { const depProject: RushConfigurationProject | undefined = this._projectsByName.get(dependencyName); if (depProject) { @@ -1524,8 +1565,11 @@ export class RushConfiguration { if (!this._variants[variant]) { throw new Error( `Invalid variant name '${variant}'. The provided variant parameter needs to be ` + - `one of the following from rush.json: ` + - `${Object.keys(this._variants).map((name: string) => `"${name}"`).join(', ')}.`); + `one of the following from rush.json: ` + + `${Object.keys(this._variants) + .map((name: string) => `"${name}"`) + .join(', ')}.` + ); } } diff --git a/apps/rush-lib/src/api/RushConfigurationProject.ts b/apps/rush-lib/src/api/RushConfigurationProject.ts index 43d4ede792f..609b9ad14f3 100644 --- a/apps/rush-lib/src/api/RushConfigurationProject.ts +++ b/apps/rush-lib/src/api/RushConfigurationProject.ts @@ -2,12 +2,7 @@ // See LICENSE in the project root for license information. import * as path from 'path'; -import { - JsonFile, - IPackageJson, - FileSystem, - FileConstants -} from '@rushstack/node-core-library'; +import { JsonFile, IPackageJson, FileSystem, FileConstants } from '@rushstack/node-core-library'; import { RushConfiguration } from '../api/RushConfiguration'; import { VersionPolicy, LockStepVersionPolicy } from './VersionPolicy'; @@ -64,14 +59,18 @@ export class RushConfigurationProject { // For example, the depth of "a/b/c" would be 3. The depth of "a" is 1. const projectFolderDepth: number = projectJson.projectFolder.split('/').length; if (projectFolderDepth < rushConfiguration.projectFolderMinDepth) { - throw new Error(`To keep things organized, this repository has a projectFolderMinDepth policy` - + ` requiring project folders to be at least ${rushConfiguration.projectFolderMinDepth} levels deep.` - + ` Problem folder: "${projectJson.projectFolder}"`); + throw new Error( + `To keep things organized, this repository has a projectFolderMinDepth policy` + + ` requiring project folders to be at least ${rushConfiguration.projectFolderMinDepth} levels deep.` + + ` Problem folder: "${projectJson.projectFolder}"` + ); } if (projectFolderDepth > rushConfiguration.projectFolderMaxDepth) { - throw new Error(`To keep things organized, this repository has a projectFolderMaxDepth policy` - + ` preventing project folders from being deeper than ${rushConfiguration.projectFolderMaxDepth} levels.` - + ` Problem folder: "${projectJson.projectFolder}"`); + throw new Error( + `To keep things organized, this repository has a projectFolderMaxDepth policy` + + ` preventing project folders from being deeper than ${rushConfiguration.projectFolderMaxDepth} levels.` + + ` Problem folder: "${projectJson.projectFolder}"` + ); } this._projectFolder = path.join(rushConfiguration.rushJsonFolder, projectJson.projectFolder); @@ -91,12 +90,16 @@ export class RushConfigurationProject { // If so, then every project needs to have a reviewCategory that was defined // by the reviewCategories array. if (!projectJson.reviewCategory) { - throw new Error(`The "approvedPackagesPolicy" feature is enabled rush.json, but a reviewCategory` + - ` was not specified for the project "${projectJson.packageName}".`); + throw new Error( + `The "approvedPackagesPolicy" feature is enabled rush.json, but a reviewCategory` + + ` was not specified for the project "${projectJson.packageName}".` + ); } if (!rushConfiguration.approvedPackagesPolicy.reviewCategories.has(projectJson.reviewCategory)) { - throw new Error(`The project "${projectJson.packageName}" specifies its reviewCategory as` - + `"${projectJson.reviewCategory}" which is not one of the defined reviewCategories.`); + throw new Error( + `The project "${projectJson.packageName}" specifies its reviewCategory as` + + `"${projectJson.reviewCategory}" which is not one of the defined reviewCategories.` + ); } this._reviewCategory = projectJson.reviewCategory; } @@ -105,8 +108,10 @@ export class RushConfigurationProject { this._packageJson = JsonFile.load(packageJsonFilename); if (this._packageJson.name !== this._packageName) { - throw new Error(`The package name "${this._packageName}" specified in rush.json does not` - + ` match the name "${this._packageJson.name}" from package.json`); + throw new Error( + `The package name "${this._packageName}" specified in rush.json does not` + + ` match the name "${this._packageJson.name}" from package.json` + ); } this._packageJsonEditor = PackageJsonEditor.load(packageJsonFilename); @@ -269,7 +274,8 @@ export class RushConfigurationProject { if (!this._versionPolicy) { if (this.versionPolicyName && this._rushConfiguration.versionPolicyConfiguration) { this._versionPolicy = this._rushConfiguration.versionPolicyConfiguration.getVersionPolicy( - this.versionPolicyName); + this.versionPolicyName + ); } } return this._versionPolicy; diff --git a/apps/rush-lib/src/api/Variants.ts b/apps/rush-lib/src/api/Variants.ts index 3730cc2e894..2520ca566e3 100644 --- a/apps/rush-lib/src/api/Variants.ts +++ b/apps/rush-lib/src/api/Variants.ts @@ -1,7 +1,4 @@ - -import { - ICommandLineStringDefinition -} from '@rushstack/ts-command-line'; +import { ICommandLineStringDefinition } from '@rushstack/ts-command-line'; /** * Namespace for utilities relating to the Variants feature. @@ -14,6 +11,6 @@ export class Variants { parameterLongName: '--variant', argumentName: 'VARIANT', description: 'Run command using a variant installation configuration', - environmentVariable: 'RUSH_VARIANT' + environmentVariable: 'RUSH_VARIANT', }; } diff --git a/apps/rush-lib/src/api/VersionPolicy.ts b/apps/rush-lib/src/api/VersionPolicy.ts index 23e32c71b2d..4ebf006d175 100644 --- a/apps/rush-lib/src/api/VersionPolicy.ts +++ b/apps/rush-lib/src/api/VersionPolicy.ts @@ -11,7 +11,7 @@ import { IIndividualVersionJson, VersionFormatForCommit, VersionFormatForPublish, - IVersionPolicyDependencyJson + IVersionPolicyDependencyJson, } from './VersionPolicyConfiguration'; import { PackageJsonEditor } from './PackageJsonEditor'; import { RushConfiguration } from './RushConfiguration'; @@ -33,7 +33,7 @@ export enum BumpType { // Minor version bump 'minor', // Major version bump - 'major' + 'major', } /** @@ -42,7 +42,7 @@ export enum BumpType { */ export enum VersionPolicyDefinitionName { 'lockStepVersion', - 'individualVersion' + 'individualVersion', } /** @@ -64,9 +64,10 @@ export abstract class VersionPolicy { this._definitionName = VersionPolicyDefinitionName[versionPolicyJson.definitionName]; this._exemptFromRushChange = versionPolicyJson.exemptFromRushChange || false; - const jsonDependencies: IVersionPolicyDependencyJson = versionPolicyJson.dependencies || { }; + const jsonDependencies: IVersionPolicyDependencyJson = versionPolicyJson.dependencies || {}; this._versionFormatForCommit = jsonDependencies.versionFormatForCommit || VersionFormatForCommit.original; - this._versionFormatForPublish = jsonDependencies.versionFormatForPublish || VersionFormatForPublish.original; + this._versionFormatForPublish = + jsonDependencies.versionFormatForPublish || VersionFormatForPublish.original; } /** @@ -77,7 +78,8 @@ export abstract class VersionPolicy { * @internal */ public static load(versionPolicyJson: IVersionPolicyJson): VersionPolicy | undefined { - const definition: VersionPolicyDefinitionName = VersionPolicyDefinitionName[versionPolicyJson.definitionName]; + const definition: VersionPolicyDefinitionName = + VersionPolicyDefinitionName[versionPolicyJson.definitionName]; if (definition === VersionPolicyDefinitionName.lockStepVersion) { // eslint-disable-next-line @typescript-eslint/no-use-before-define return new LockStepVersionPolicy(versionPolicyJson as ILockStepVersionJson); @@ -158,8 +160,9 @@ export abstract class VersionPolicy { const packageJsonEditor: PackageJsonEditor = project.packageJsonEditor; for (const dependency of packageJsonEditor.dependencyList) { - const rushDependencyProject: RushConfigurationProject | undefined = - configuration.getProjectByName(dependency.name); + const rushDependencyProject: RushConfigurationProject | undefined = configuration.getProjectByName( + dependency.name + ); if (rushDependencyProject) { const dependencyVersion: string = rushDependencyProject.packageJson.version; @@ -183,8 +186,9 @@ export abstract class VersionPolicy { const packageJsonEditor: PackageJsonEditor = project.packageJsonEditor; for (const dependency of packageJsonEditor.dependencyList) { - const rushDependencyProject: RushConfigurationProject | undefined = - configuration.getProjectByName(dependency.name); + const rushDependencyProject: RushConfigurationProject | undefined = configuration.getProjectByName( + dependency.name + ); if (rushDependencyProject) { dependency.setVersion('*'); @@ -251,7 +255,7 @@ export class LockStepVersionPolicy extends VersionPolicy { policyName: this.policyName, definitionName: VersionPolicyDefinitionName[this.definitionName], version: this.version, - nextBump: BumpType[this.nextBump] + nextBump: BumpType[this.nextBump], }; if (this._mainProject) { json.mainProject = this._mainProject; @@ -271,8 +275,9 @@ export class LockStepVersionPolicy extends VersionPolicy { if (compareResult === 0) { return undefined; } else if (compareResult > 0 && !force) { - const errorMessage: string = `Version ${project.version} in package ${project.name}` - + ` is higher than locked version ${this._version.format()}.`; + const errorMessage: string = + `Version ${project.version} in package ${project.name}` + + ` is higher than locked version ${this._version.format()}.`; throw new Error(errorMessage); } return this._updatePackageVersion(project, this._version); @@ -356,7 +361,7 @@ export class IndividualVersionPolicy extends VersionPolicy { public get _json(): IIndividualVersionJson { const json: IIndividualVersionJson = { policyName: this.policyName, - definitionName: VersionPolicyDefinitionName[this.definitionName] + definitionName: VersionPolicyDefinitionName[this.definitionName], }; if (this.lockedMajor !== undefined) { json.lockedMajor = this.lockedMajor; @@ -378,8 +383,9 @@ export class IndividualVersionPolicy extends VersionPolicy { updatedProject.version = `${this._lockedMajor}.0.0`; return updatedProject; } else if (version.major > this.lockedMajor) { - const errorMessage: string = `Version ${project.version} in package ${project.name}` - + ` is higher than locked major version ${this._lockedMajor}.`; + const errorMessage: string = + `Version ${project.version} in package ${project.name}` + + ` is higher than locked major version ${this._lockedMajor}.`; throw new Error(errorMessage); } } @@ -411,4 +417,4 @@ export class IndividualVersionPolicy extends VersionPolicy { } } } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/api/VersionPolicyConfiguration.ts b/apps/rush-lib/src/api/VersionPolicyConfiguration.ts index 75801dc9ad9..1b15040c41f 100644 --- a/apps/rush-lib/src/api/VersionPolicyConfiguration.ts +++ b/apps/rush-lib/src/api/VersionPolicyConfiguration.ts @@ -38,7 +38,7 @@ export interface IIndividualVersionJson extends IVersionPolicyJson { */ export enum VersionFormatForPublish { original = 'original', - exact = 'exact' + exact = 'exact', } /** @@ -46,7 +46,7 @@ export enum VersionFormatForPublish { */ export enum VersionFormatForCommit { wildcard = 'wildcard', - original = 'original' + original = 'original', } /** @@ -65,7 +65,8 @@ export interface IVersionPolicyDependencyJson { */ export class VersionPolicyConfiguration { private static _jsonSchema: JsonSchema = JsonSchema.fromFile( - path.join(__dirname, '../schemas/version-policies.schema.json')); + path.join(__dirname, '../schemas/version-policies.schema.json') + ); private _versionPolicies: Map; private _jsonFileName: string; @@ -89,8 +90,10 @@ export class VersionPolicyConfiguration { this.versionPolicies.forEach((policy) => { const lockStepPolicy: LockStepVersionPolicy = policy as LockStepVersionPolicy; if (lockStepPolicy.mainProject && !projectsByName.get(lockStepPolicy.mainProject)) { - throw new Error(`Version policy \"${policy.policyName}\" has a non-existing mainProject:` + - ` ${lockStepPolicy.mainProject}.`); + throw new Error( + `Version policy \"${policy.policyName}\" has a non-existing mainProject:` + + ` ${lockStepPolicy.mainProject}.` + ); } }); } @@ -123,7 +126,8 @@ export class VersionPolicyConfiguration { * @param identifier - prerelease identifier to override what policy has defined. * @param shouldCommit - should save to disk */ - public bump(versionPolicyName?: string, + public bump( + versionPolicyName?: string, bumpType?: BumpType, identifier?: string, shouldCommit?: boolean @@ -148,9 +152,7 @@ export class VersionPolicyConfiguration { * @param versionPolicyName - version policy name * @param newVersion - new version */ - public update(versionPolicyName: string, - newVersion: string - ): void { + public update(versionPolicyName: string, newVersion: string): void { const policy: VersionPolicy | undefined = this.versionPolicies.get(versionPolicyName); if (!policy || !policy.isLockstepped) { throw new Error(`Lockstep Version policy with name "${versionPolicyName}" cannot be found`); @@ -165,10 +167,12 @@ export class VersionPolicyConfiguration { if (!FileSystem.exists(this._jsonFileName)) { return; } - const versionPolicyJson: IVersionPolicyJson[] = JsonFile.loadAndValidate(this._jsonFileName, - VersionPolicyConfiguration._jsonSchema); + const versionPolicyJson: IVersionPolicyJson[] = JsonFile.loadAndValidate( + this._jsonFileName, + VersionPolicyConfiguration._jsonSchema + ); - versionPolicyJson.forEach(policyJson => { + versionPolicyJson.forEach((policyJson) => { const policy: VersionPolicy | undefined = VersionPolicy.load(policyJson); if (policy) { this._versionPolicies.set(policy.policyName, policy); diff --git a/apps/rush-lib/src/api/test/ChangeFile.test.ts b/apps/rush-lib/src/api/test/ChangeFile.test.ts index ca4db41bf73..4dd7a1513e5 100644 --- a/apps/rush-lib/src/api/test/ChangeFile.test.ts +++ b/apps/rush-lib/src/api/test/ChangeFile.test.ts @@ -12,26 +12,29 @@ describe('ChangeFile', () => { const rushFilename: string = path.resolve(__dirname, 'repo', 'rush-npm.json'); const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile(rushFilename); - const changeFile: ChangeFile = new ChangeFile({ - packageName: 'a', - changes: [], - email: 'fake@microsoft.com' - }, rushConfiguration); + const changeFile: ChangeFile = new ChangeFile( + { + packageName: 'a', + changes: [], + email: 'fake@microsoft.com', + }, + rushConfiguration + ); changeFile.addChange({ packageName: 'a', changeType: ChangeType.minor, - comment: 'for minor' + comment: 'for minor', }); changeFile.addChange({ packageName: 'a', changeType: ChangeType.patch, - comment: 'for patch' + comment: 'for patch', }); expect(changeFile.getChanges('a')).toHaveLength(2); expect(changeFile.getChanges('a')[0].comment).toEqual('for minor'); expect(changeFile.getChanges('a')[1].comment).toEqual('for patch'); }); -}); \ No newline at end of file +}); diff --git a/apps/rush-lib/src/api/test/EnvironmentConfiguration.test.ts b/apps/rush-lib/src/api/test/EnvironmentConfiguration.test.ts index 3b6a9d0f901..3b217166de1 100644 --- a/apps/rush-lib/src/api/test/EnvironmentConfiguration.test.ts +++ b/apps/rush-lib/src/api/test/EnvironmentConfiguration.test.ts @@ -83,7 +83,7 @@ describe('EnvironmentConfiguration', () => { EnvironmentConfiguration.initialize({ doNotNormalizePaths: true }); expect(EnvironmentConfiguration.pnpmStorePathOverride).toEqual(expectedValue); - }) + }); it('returns expected path from environment variable with normalization', () => { const expectedValue: string = path.resolve(path.join(process.cwd(), 'temp')); @@ -93,6 +93,6 @@ describe('EnvironmentConfiguration', () => { EnvironmentConfiguration.initialize(); expect(EnvironmentConfiguration.pnpmStorePathOverride).toEqual(expectedValue); - }) - }) + }); + }); }); diff --git a/apps/rush-lib/src/api/test/EventHooks.test.ts b/apps/rush-lib/src/api/test/EventHooks.test.ts index 44e64b6abe3..c3b53c48a4b 100644 --- a/apps/rush-lib/src/api/test/EventHooks.test.ts +++ b/apps/rush-lib/src/api/test/EventHooks.test.ts @@ -18,15 +18,11 @@ describe('EventHooks', () => { }); it('loads two rush hooks', () => { - const expectedHooks: string[] = [ - 'do one', - 'do two' - ]; + const expectedHooks: string[] = ['do one', 'do two']; const eventHooks: EventHooks = new EventHooks({ - postRushBuild: expectedHooks + postRushBuild: expectedHooks, }); const resultHooks: string[] = eventHooks.get(Event.postRushBuild); expect(resultHooks).toEqual(expectedHooks); }); - -}); \ No newline at end of file +}); diff --git a/apps/rush-lib/src/api/test/LastInstallFlag.test.ts b/apps/rush-lib/src/api/test/LastInstallFlag.test.ts index 160e4827fa7..dfcbafba3f0 100644 --- a/apps/rush-lib/src/api/test/LastInstallFlag.test.ts +++ b/apps/rush-lib/src/api/test/LastInstallFlag.test.ts @@ -68,31 +68,35 @@ describe('LastInstallFlag', () => { FileSystem.deleteFile(flag.path); }); - it('throws an error if new storePath doesn\'t match the old one', () => { + it("throws an error if new storePath doesn't match the old one", () => { const flag1: LastInstallFlag = new LastInstallFlag(TEMP_DIR, { packageManager: 'pnpm', - storePath: path.join(TEMP_DIR, 'pnpm-store') + storePath: path.join(TEMP_DIR, 'pnpm-store'), }); const flag2: LastInstallFlag = new LastInstallFlag(TEMP_DIR, { packageManager: 'pnpm', - storePath: path.join(TEMP_DIR, 'temp-store') + storePath: path.join(TEMP_DIR, 'temp-store'), }); flag1.create(); - expect(() => { flag2.checkValidAndReportStoreIssues() }).toThrowError(/PNPM store path/); + expect(() => { + flag2.checkValidAndReportStoreIssues(); + }).toThrowError(/PNPM store path/); }); - it('doesn\'t throw an error if conditions for error aren\'t met', () => { + it("doesn't throw an error if conditions for error aren't met", () => { const flag1: LastInstallFlag = new LastInstallFlag(TEMP_DIR, { packageManager: 'pnpm', - storePath: path.join(TEMP_DIR, 'pnpm-store') + storePath: path.join(TEMP_DIR, 'pnpm-store'), }); const flag2: LastInstallFlag = new LastInstallFlag(TEMP_DIR, { packageManager: 'npm', }); flag1.create(); - expect(() => { flag2.checkValidAndReportStoreIssues() }).not.toThrow(); + expect(() => { + flag2.checkValidAndReportStoreIssues(); + }).not.toThrow(); expect(flag2.checkValidAndReportStoreIssues()).toEqual(false); - }) + }); }); diff --git a/apps/rush-lib/src/api/test/RushConfiguration.test.ts b/apps/rush-lib/src/api/test/RushConfiguration.test.ts index fdc7a1140af..92b5d7d3b4f 100644 --- a/apps/rush-lib/src/api/test/RushConfiguration.test.ts +++ b/apps/rush-lib/src/api/test/RushConfiguration.test.ts @@ -28,14 +28,13 @@ describe('RushConfiguration', () => { process.env['USERPROFILE'] = _oldEnv['USERPROFILE']; // eslint-disable-line dot-notation process.env['HOME'] = _oldEnv['HOME']; // eslint-disable-line dot-notation - }); afterEach(() => { process.env = _oldEnv; }); - it('can\'t load too new rush', (done: jest.DoneCallback) => { + it("can't load too new rush", (done: jest.DoneCallback) => { const rushFilename: string = path.resolve(__dirname, 'repo', 'rush-too-new.json'); expect(() => { @@ -50,27 +49,37 @@ describe('RushConfiguration', () => { const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile(rushFilename); expect(rushConfiguration.packageManager).toEqual('npm'); - assertPathProperty('committedShrinkwrapFilename', - rushConfiguration.committedShrinkwrapFilename, './repo/common/config/rush/npm-shrinkwrap.json'); - assertPathProperty('commonFolder', - rushConfiguration.commonFolder, './repo/common'); - assertPathProperty('commonRushConfigFolder', - rushConfiguration.commonRushConfigFolder, './repo/common/config/rush'); - assertPathProperty('commonTempFolder', - rushConfiguration.commonTempFolder, './repo/common/temp'); - assertPathProperty('npmCacheFolder', - rushConfiguration.npmCacheFolder, './repo/common/temp/npm-cache'); - assertPathProperty('npmTmpFolder', - rushConfiguration.npmTmpFolder, './repo/common/temp/npm-tmp'); + assertPathProperty( + 'committedShrinkwrapFilename', + rushConfiguration.committedShrinkwrapFilename, + './repo/common/config/rush/npm-shrinkwrap.json' + ); + assertPathProperty('commonFolder', rushConfiguration.commonFolder, './repo/common'); + assertPathProperty( + 'commonRushConfigFolder', + rushConfiguration.commonRushConfigFolder, + './repo/common/config/rush' + ); + assertPathProperty('commonTempFolder', rushConfiguration.commonTempFolder, './repo/common/temp'); + assertPathProperty('npmCacheFolder', rushConfiguration.npmCacheFolder, './repo/common/temp/npm-cache'); + assertPathProperty('npmTmpFolder', rushConfiguration.npmTmpFolder, './repo/common/temp/npm-tmp'); expect(rushConfiguration.pnpmOptions.pnpmStore).toEqual('local'); - assertPathProperty('pnpmStorePath', - rushConfiguration.pnpmOptions.pnpmStorePath, './repo/common/temp/pnpm-store'); - assertPathProperty('packageManagerToolFilename', - rushConfiguration.packageManagerToolFilename, './repo/common/temp/npm-local/node_modules/.bin/npm'); - assertPathProperty('rushJsonFolder', - rushConfiguration.rushJsonFolder, './repo'); - assertPathProperty('rushLinkJsonFilename', - rushConfiguration.rushLinkJsonFilename, './repo/common/temp/rush-link.json'); + assertPathProperty( + 'pnpmStorePath', + rushConfiguration.pnpmOptions.pnpmStorePath, + './repo/common/temp/pnpm-store' + ); + assertPathProperty( + 'packageManagerToolFilename', + rushConfiguration.packageManagerToolFilename, + './repo/common/temp/npm-local/node_modules/.bin/npm' + ); + assertPathProperty('rushJsonFolder', rushConfiguration.rushJsonFolder, './repo'); + assertPathProperty( + 'rushLinkJsonFilename', + rushConfiguration.rushLinkJsonFilename, + './repo/common/temp/rush-link.json' + ); expect(rushConfiguration.packageManagerToolVersion).toEqual('4.5.0'); @@ -84,11 +93,13 @@ describe('RushConfiguration', () => { // "approvedPackagesPolicy" feature const approvedPackagesPolicy: ApprovedPackagesPolicy = rushConfiguration.approvedPackagesPolicy; expect(approvedPackagesPolicy.enabled).toEqual(true); - expect(Utilities.getSetAsArray(approvedPackagesPolicy.reviewCategories)).toEqual( - ['first-party', 'third-party', 'prototype']); + expect(Utilities.getSetAsArray(approvedPackagesPolicy.reviewCategories)).toEqual([ + 'first-party', + 'third-party', + 'prototype', + ]); - expect(Utilities.getSetAsArray(approvedPackagesPolicy.ignoredNpmScopes)).toEqual( - ['@types', '@internal']); + expect(Utilities.getSetAsArray(approvedPackagesPolicy.ignoredNpmScopes)).toEqual(['@types', '@internal']); expect(approvedPackagesPolicy.browserApprovedPackages.items[0].packageName).toEqual('example'); expect(approvedPackagesPolicy.browserApprovedPackages.items[0].allowedCategories.size).toEqual(3); @@ -117,27 +128,37 @@ describe('RushConfiguration', () => { const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile(rushFilename); expect(rushConfiguration.packageManager).toEqual('pnpm'); - assertPathProperty('committedShrinkwrapFilename', - rushConfiguration.committedShrinkwrapFilename, './repo/common/config/rush/pnpm-lock.yaml'); - assertPathProperty('commonFolder', - rushConfiguration.commonFolder, './repo/common'); - assertPathProperty('commonRushConfigFolder', - rushConfiguration.commonRushConfigFolder, './repo/common/config/rush'); - assertPathProperty('commonTempFolder', - rushConfiguration.commonTempFolder, './repo/common/temp'); - assertPathProperty('npmCacheFolder', - rushConfiguration.npmCacheFolder, './repo/common/temp/npm-cache'); - assertPathProperty('npmTmpFolder', - rushConfiguration.npmTmpFolder, './repo/common/temp/npm-tmp'); + assertPathProperty( + 'committedShrinkwrapFilename', + rushConfiguration.committedShrinkwrapFilename, + './repo/common/config/rush/pnpm-lock.yaml' + ); + assertPathProperty('commonFolder', rushConfiguration.commonFolder, './repo/common'); + assertPathProperty( + 'commonRushConfigFolder', + rushConfiguration.commonRushConfigFolder, + './repo/common/config/rush' + ); + assertPathProperty('commonTempFolder', rushConfiguration.commonTempFolder, './repo/common/temp'); + assertPathProperty('npmCacheFolder', rushConfiguration.npmCacheFolder, './repo/common/temp/npm-cache'); + assertPathProperty('npmTmpFolder', rushConfiguration.npmTmpFolder, './repo/common/temp/npm-tmp'); expect(rushConfiguration.pnpmOptions.pnpmStore).toEqual('local'); - assertPathProperty('pnpmStorePath', - rushConfiguration.pnpmOptions.pnpmStorePath, './repo/common/temp/pnpm-store'); - assertPathProperty('packageManagerToolFilename', - rushConfiguration.packageManagerToolFilename, './repo/common/temp/pnpm-local/node_modules/.bin/pnpm'); - assertPathProperty('rushJsonFolder', - rushConfiguration.rushJsonFolder, './repo'); - assertPathProperty('rushLinkJsonFilename', - rushConfiguration.rushLinkJsonFilename, './repo/common/temp/rush-link.json'); + assertPathProperty( + 'pnpmStorePath', + rushConfiguration.pnpmOptions.pnpmStorePath, + './repo/common/temp/pnpm-store' + ); + assertPathProperty( + 'packageManagerToolFilename', + rushConfiguration.packageManagerToolFilename, + './repo/common/temp/pnpm-local/node_modules/.bin/pnpm' + ); + assertPathProperty('rushJsonFolder', rushConfiguration.rushJsonFolder, './repo'); + assertPathProperty( + 'rushLinkJsonFilename', + rushConfiguration.rushLinkJsonFilename, + './repo/common/temp/rush-link.json' + ); expect(rushConfiguration.packageManagerToolVersion).toEqual('4.5.0'); @@ -150,10 +171,12 @@ describe('RushConfiguration', () => { // "approvedPackagesPolicy" feature const approvedPackagesPolicy: ApprovedPackagesPolicy = rushConfiguration.approvedPackagesPolicy; expect(approvedPackagesPolicy.enabled).toBe(true); - expect(Utilities.getSetAsArray(approvedPackagesPolicy.reviewCategories)).toEqual( - ['first-party', 'third-party', 'prototype']); - expect(Utilities.getSetAsArray(approvedPackagesPolicy.ignoredNpmScopes)).toEqual( - ['@types', '@internal']); + expect(Utilities.getSetAsArray(approvedPackagesPolicy.reviewCategories)).toEqual([ + 'first-party', + 'third-party', + 'prototype', + ]); + expect(Utilities.getSetAsArray(approvedPackagesPolicy.ignoredNpmScopes)).toEqual(['@types', '@internal']); expect(approvedPackagesPolicy.browserApprovedPackages.items[0].packageName).toEqual('example'); expect(approvedPackagesPolicy.browserApprovedPackages.items[0].allowedCategories.size).toEqual(3); @@ -202,11 +225,19 @@ describe('RushConfiguration', () => { const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile(rushFilename); assertPathProperty('commonTempFolder', rushConfiguration.commonTempFolder, expectedValue); - assertPathProperty('npmCacheFolder', rushConfiguration.npmCacheFolder, path.join(expectedValue, 'npm-cache')); + assertPathProperty( + 'npmCacheFolder', + rushConfiguration.npmCacheFolder, + path.join(expectedValue, 'npm-cache') + ); assertPathProperty('npmTmpFolder', rushConfiguration.npmTmpFolder, path.join(expectedValue, 'npm-tmp')); expect(rushConfiguration.pnpmOptions.pnpmStore).toEqual('local'); - assertPathProperty('pnpmStorePath', rushConfiguration.pnpmOptions.pnpmStorePath, path.join(expectedValue, 'pnpm-store')); + assertPathProperty( + 'pnpmStorePath', + rushConfiguration.pnpmOptions.pnpmStorePath, + path.join(expectedValue, 'pnpm-store') + ); assertPathProperty( 'packageManagerToolFilename', rushConfiguration.packageManagerToolFilename, @@ -222,7 +253,7 @@ describe('RushConfiguration', () => { describe('PNPM Store Paths', () => { afterEach(() => { EnvironmentConfiguration['_pnpmStorePathOverride'] = undefined; - }) + }); const PNPM_STORE_PATH_ENV: string = 'RUSH_PNPM_STORE_PATH'; @@ -231,7 +262,9 @@ describe('RushConfiguration', () => { it(`loads the correct path when pnpmStore = "local"`, (done: jest.DoneCallback) => { const EXPECT_STORE_PATH: string = path.resolve(__dirname, 'repo', 'common', 'temp', 'pnpm-store'); - const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile(RUSH_JSON_FILENAME); + const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile( + RUSH_JSON_FILENAME + ); expect(rushConfiguration.packageManager).toEqual('pnpm'); expect(rushConfiguration.pnpmOptions.pnpmStore).toEqual('local'); @@ -245,7 +278,9 @@ describe('RushConfiguration', () => { const EXPECT_STORE_PATH: string = path.resolve('/var/temp'); process.env[PNPM_STORE_PATH_ENV] = EXPECT_STORE_PATH; - const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile(RUSH_JSON_FILENAME); + const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile( + RUSH_JSON_FILENAME + ); expect(rushConfiguration.packageManager).toEqual('pnpm'); expect(rushConfiguration.pnpmOptions.pnpmStore).toEqual('local'); @@ -254,14 +289,16 @@ describe('RushConfiguration', () => { done(); }); - }) + }); describe('Loading repo/rush-pnpm-global.json', () => { const RUSH_JSON_FILENAME: string = path.resolve(__dirname, 'repo', 'rush-pnpm-global.json'); it(`loads the correct path when pnpmStore = "global"`, (done: jest.DoneCallback) => { - const EXPECT_STORE_PATH: string = ""; - const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile(RUSH_JSON_FILENAME); + const EXPECT_STORE_PATH: string = ''; + const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile( + RUSH_JSON_FILENAME + ); expect(rushConfiguration.packageManager).toEqual('pnpm'); expect(rushConfiguration.pnpmOptions.pnpmStore).toEqual('global'); @@ -274,7 +311,9 @@ describe('RushConfiguration', () => { const EXPECT_STORE_PATH: string = path.resolve('/var/temp'); process.env[PNPM_STORE_PATH_ENV] = EXPECT_STORE_PATH; - const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile(RUSH_JSON_FILENAME); + const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile( + RUSH_JSON_FILENAME + ); expect(rushConfiguration.packageManager).toEqual('pnpm'); expect(rushConfiguration.pnpmOptions.pnpmStore).toEqual('global'); @@ -282,16 +321,18 @@ describe('RushConfiguration', () => { done(); }); - }) + }); it(`throws an error when invalid pnpmStore is defined`, (done: jest.DoneCallback) => { const RUSH_JSON_FILENAME: string = path.resolve(__dirname, 'repo', 'rush-pnpm-invalid-store.json'); expect(() => { //@ts-ignore - const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile(RUSH_JSON_FILENAME); // eslint-disable-line @typescript-eslint/no-unused-vars + const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile( + RUSH_JSON_FILENAME + ); // eslint-disable-line @typescript-eslint/no-unused-vars }).toThrow(); done(); }); - }) + }); }); diff --git a/apps/rush-lib/src/api/test/VersionMismatchFinder.test.ts b/apps/rush-lib/src/api/test/VersionMismatchFinder.test.ts index 24f29a2f82e..e46bee6b7e3 100644 --- a/apps/rush-lib/src/api/test/VersionMismatchFinder.test.ts +++ b/apps/rush-lib/src/api/test/VersionMismatchFinder.test.ts @@ -14,26 +14,32 @@ import { VersionMismatchFinderCommonVersions } from '../../logic/versionMismatch /* eslint-disable @typescript-eslint/no-explicit-any */ describe('VersionMismatchFinder', () => { it('finds no mismatches if there are none', (done: jest.DoneCallback) => { - const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'A', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '1.2.3', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); - const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '1.2.3', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); + const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'B', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '1.2.3', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '1.2.3', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); const mismatchFinder: VersionMismatchFinder = new VersionMismatchFinder([projectA, projectB]); expect(mismatchFinder.numberOfMismatches).toEqual(0); @@ -42,26 +48,32 @@ describe('VersionMismatchFinder', () => { }); it('finds a mismatch in two packages', (done: jest.DoneCallback) => { - const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'A', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '1.2.3', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); - const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '1.2.3', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); + const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'B', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '2.0.0', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '2.0.0', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); const mismatchFinder: VersionMismatchFinder = new VersionMismatchFinder([projectA, projectB]); expect(mismatchFinder.numberOfMismatches).toEqual(1); @@ -74,26 +86,32 @@ describe('VersionMismatchFinder', () => { }); it('ignores cyclic dependencies', (done: jest.DoneCallback) => { - const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'A', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '1.2.3', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set(['@types/foo']) - } as any as RushConfigurationProject); - const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '1.2.3', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(['@types/foo']), + } as any) as RushConfigurationProject); + const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'B', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '2.0.0', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '2.0.0', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); const mismatchFinder: VersionMismatchFinder = new VersionMismatchFinder([projectA, projectB]); expect(mismatchFinder.numberOfMismatches).toEqual(0); @@ -101,27 +119,33 @@ describe('VersionMismatchFinder', () => { done(); }); - it('won\'t let you access mismatches that don\t exist', (done: jest.DoneCallback) => { - const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + it("won't let you access mismatches that don\t exist", (done: jest.DoneCallback) => { + const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'A', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '1.2.3', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); - const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '1.2.3', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); + const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'B', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '2.0.0', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '2.0.0', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); const mismatchFinder: VersionMismatchFinder = new VersionMismatchFinder([projectA, projectB]); expect(mismatchFinder.getVersionsOfMismatch('@types/foobar')).toEqual(undefined); @@ -131,48 +155,65 @@ describe('VersionMismatchFinder', () => { }); it('finds two mismatches in two different pairs of projects', (done: jest.DoneCallback) => { - const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'A', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '1.2.3', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); - const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '1.2.3', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); + const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'B', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '2.0.0', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); - const projectC: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '2.0.0', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); + const projectC: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'C', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - 'mocha': '1.2.3', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); - const projectD: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + mocha: '1.2.3', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); + const projectD: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'D', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - 'mocha': '2.0.0', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + mocha: '2.0.0', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); - const mismatchFinder: VersionMismatchFinder = new VersionMismatchFinder([projectA, projectB, projectC, projectD]); + const mismatchFinder: VersionMismatchFinder = new VersionMismatchFinder([ + projectA, + projectB, + projectC, + projectD, + ]); expect(mismatchFinder.numberOfMismatches).toEqual(2); expect(mismatchFinder.getMismatches()).toHaveLength(2); expect(mismatchFinder.getMismatches()).toMatchObject(['@types/foo', 'mocha']); @@ -186,36 +227,45 @@ describe('VersionMismatchFinder', () => { }); it('finds three mismatches in three projects', (done: jest.DoneCallback) => { - const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'A', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '1.2.3', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); - const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '1.2.3', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); + const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'B', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '2.0.0', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); - const projectC: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '2.0.0', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); + const projectC: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'C', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '9.9.9', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '9.9.9', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); const mismatchFinder: VersionMismatchFinder = new VersionMismatchFinder([projectA, projectB, projectC]); expect(mismatchFinder.numberOfMismatches).toEqual(1); @@ -229,26 +279,32 @@ describe('VersionMismatchFinder', () => { }); it('checks dev dependencies', (done: jest.DoneCallback) => { - const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'A', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '1.2.3', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); - const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '1.2.3', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); + const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'B', - packageJsonEditor: PackageJsonEditor.fromObject({ - devDependencies: { - '@types/foo': '2.0.0', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); + packageJsonEditor: PackageJsonEditor.fromObject( + { + devDependencies: { + '@types/foo': '2.0.0', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); const mismatchFinder: VersionMismatchFinder = new VersionMismatchFinder([projectA, projectB]); @@ -262,26 +318,32 @@ describe('VersionMismatchFinder', () => { }); it('does not check peer dependencies', (done: jest.DoneCallback) => { - const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'A', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '1.2.3', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); - const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '1.2.3', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); + const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'B', - packageJsonEditor: PackageJsonEditor.fromObject({ - peerDependencies: { - '@types/foo': '2.0.0', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); + packageJsonEditor: PackageJsonEditor.fromObject( + { + peerDependencies: { + '@types/foo': '2.0.0', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); const mismatchFinder: VersionMismatchFinder = new VersionMismatchFinder([projectA, projectB]); expect(mismatchFinder.numberOfMismatches).toEqual(0); @@ -289,26 +351,32 @@ describe('VersionMismatchFinder', () => { }); it('checks optional dependencies', (done: jest.DoneCallback) => { - const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'A', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '1.2.3', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); - const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '1.2.3', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); + const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'B', - packageJsonEditor: PackageJsonEditor.fromObject({ - optionalDependencies: { - '@types/foo': '2.0.0', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); + packageJsonEditor: PackageJsonEditor.fromObject( + { + optionalDependencies: { + '@types/foo': '2.0.0', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); const mismatchFinder: VersionMismatchFinder = new VersionMismatchFinder([projectA, projectB]); expect(mismatchFinder.numberOfMismatches).toEqual(1); @@ -321,50 +389,60 @@ describe('VersionMismatchFinder', () => { }); it('allows alternative versions', (done: jest.DoneCallback) => { - const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'A', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '1.2.3', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); - const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '1.2.3', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); + const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'B', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@types/foo': '2.0.0', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@types/foo': '2.0.0', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); const alternatives: Map> = new Map>(); alternatives.set('@types/foo', ['2.0.0']); - const mismatchFinder: VersionMismatchFinder = new VersionMismatchFinder([projectA, projectB], alternatives); + const mismatchFinder: VersionMismatchFinder = new VersionMismatchFinder( + [projectA, projectB], + alternatives + ); expect(mismatchFinder.numberOfMismatches).toEqual(0); expect(mismatchFinder.getMismatches()).toHaveLength(0); done(); }); it('handles the common-versions.json file correctly', (done: jest.DoneCallback) => { - const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject({ + const projectA: VersionMismatchFinderEntity = new VersionMismatchFinderProject(({ packageName: 'A', - packageJsonEditor: PackageJsonEditor.fromObject({ - dependencies: { - '@scope/library-1': '1.2.3', - 'karma': '0.0.1' - } - } as any, 'foo.json'), - cyclicDependencyProjects: new Set() - } as any as RushConfigurationProject); + packageJsonEditor: PackageJsonEditor.fromObject( + { + dependencies: { + '@scope/library-1': '1.2.3', + karma: '0.0.1', + }, + } as any, + 'foo.json' + ), + cyclicDependencyProjects: new Set(), + } as any) as RushConfigurationProject); const projectB: VersionMismatchFinderEntity = new VersionMismatchFinderCommonVersions( - CommonVersionsConfiguration.loadFromFile( - path.resolve(__dirname, 'jsonFiles', 'common-versions.json') - ) + CommonVersionsConfiguration.loadFromFile(path.resolve(__dirname, 'jsonFiles', 'common-versions.json')) ); const mismatchFinder: VersionMismatchFinder = new VersionMismatchFinder([projectA, projectB]); diff --git a/apps/rush-lib/src/api/test/VersionPolicy.test.ts b/apps/rush-lib/src/api/test/VersionPolicy.test.ts index 04740f0f80a..346d537eb25 100644 --- a/apps/rush-lib/src/api/test/VersionPolicy.test.ts +++ b/apps/rush-lib/src/api/test/VersionPolicy.test.ts @@ -5,12 +5,7 @@ import * as path from 'path'; import { IPackageJson } from '@rushstack/node-core-library'; import { VersionPolicyConfiguration } from '../VersionPolicyConfiguration'; -import { - VersionPolicy, - LockStepVersionPolicy, - IndividualVersionPolicy, - BumpType -} from '../VersionPolicy'; +import { VersionPolicy, LockStepVersionPolicy, IndividualVersionPolicy, BumpType } from '../VersionPolicy'; describe('VersionPolicy', () => { describe('LockStepVersion', () => { @@ -31,21 +26,23 @@ describe('VersionPolicy', () => { it('skips packageJson if version is already the locked step version', () => { const lockStepVersionPolicy: LockStepVersionPolicy = versionPolicy as LockStepVersionPolicy; - expect(lockStepVersionPolicy.ensure({ - name: 'a', - version: '1.1.0' - })).not.toBeDefined(); + expect( + lockStepVersionPolicy.ensure({ + name: 'a', + version: '1.1.0', + }) + ).not.toBeDefined(); }); it('updates packageJson if version is lower than the locked step version', () => { const lockStepVersionPolicy: LockStepVersionPolicy = versionPolicy as LockStepVersionPolicy; const expectedPackageJson: IPackageJson = { name: 'a', - version: '1.1.0' + version: '1.1.0', }; const originalPackageJson: IPackageJson = { name: 'a', - version: '1.0.1' + version: '1.0.1', }; expect(lockStepVersionPolicy.ensure(originalPackageJson)).toEqual(expectedPackageJson); }); @@ -54,7 +51,7 @@ describe('VersionPolicy', () => { const lockStepVersionPolicy: LockStepVersionPolicy = versionPolicy as LockStepVersionPolicy; const originalPackageJson: IPackageJson = { name: 'a', - version: '2.1.0' + version: '2.1.0', }; expect(() => { lockStepVersionPolicy.ensure(originalPackageJson); @@ -65,11 +62,11 @@ describe('VersionPolicy', () => { const lockStepVersionPolicy: LockStepVersionPolicy = versionPolicy as LockStepVersionPolicy; const originalPackageJson: IPackageJson = { name: 'a', - version: '2.1.0' + version: '2.1.0', }; const expectedPackageJson: IPackageJson = { name: 'a', - version: '1.1.0' + version: '1.1.0', }; expect(lockStepVersionPolicy.ensure(originalPackageJson, true)).toEqual(expectedPackageJson); }); @@ -109,21 +106,23 @@ describe('VersionPolicy', () => { it('skips packageJson if no need to change', () => { const individualVersionPolicy: IndividualVersionPolicy = versionPolicy as IndividualVersionPolicy; - expect(individualVersionPolicy.ensure({ - name: 'a', - version: '2.1.0' - })).not.toBeDefined(); + expect( + individualVersionPolicy.ensure({ + name: 'a', + version: '2.1.0', + }) + ).not.toBeDefined(); }); it('updates packageJson if version is lower than the locked major', () => { const individualVersionPolicy: IndividualVersionPolicy = versionPolicy as IndividualVersionPolicy; const expectedPackageJson: IPackageJson = { name: 'a', - version: '2.0.0' + version: '2.0.0', }; const originalPackageJson: IPackageJson = { name: 'a', - version: '1.0.1' + version: '1.0.1', }; expect(individualVersionPolicy.ensure(originalPackageJson)).toEqual(expectedPackageJson); }); @@ -132,7 +131,7 @@ describe('VersionPolicy', () => { const individualVersionPolicy: IndividualVersionPolicy = versionPolicy as IndividualVersionPolicy; const originalPackageJson: IPackageJson = { name: 'a', - version: '3.1.0' + version: '3.1.0', }; expect(() => { individualVersionPolicy.ensure(originalPackageJson); diff --git a/apps/rush-lib/src/api/test/jsonFiles/common-versions.json b/apps/rush-lib/src/api/test/jsonFiles/common-versions.json index 8b9d9f581d4..f6cfa23662e 100644 --- a/apps/rush-lib/src/api/test/jsonFiles/common-versions.json +++ b/apps/rush-lib/src/api/test/jsonFiles/common-versions.json @@ -6,6 +6,6 @@ "library-2": "1.2.3" }, "allowedAlternativeVersions": { - "library-3": [ "^1.2.3" ] + "library-3": ["^1.2.3"] } } diff --git a/apps/rush-lib/src/api/test/jsonFiles/rushWithLockVersion.json b/apps/rush-lib/src/api/test/jsonFiles/rushWithLockVersion.json index 9e7c31fa9a2..d263410a9e2 100644 --- a/apps/rush-lib/src/api/test/jsonFiles/rushWithLockVersion.json +++ b/apps/rush-lib/src/api/test/jsonFiles/rushWithLockVersion.json @@ -5,4 +5,4 @@ "version": "1.1.0", "nextBump": "patch" } -] \ No newline at end of file +] diff --git a/apps/rush-lib/src/api/test/repo/common/config/rush/browser-approved-packages.json b/apps/rush-lib/src/api/test/repo/common/config/rush/browser-approved-packages.json index 2ad030df51e..a3bc61f4d35 100644 --- a/apps/rush-lib/src/api/test/repo/common/config/rush/browser-approved-packages.json +++ b/apps/rush-lib/src/api/test/repo/common/config/rush/browser-approved-packages.json @@ -3,7 +3,7 @@ "packages": [ { "name": "example", - "allowedCategories": [ "first-party", "prototype", "third-party" ] + "allowedCategories": ["first-party", "prototype", "third-party"] } ] } diff --git a/apps/rush-lib/src/api/test/repo/common/config/rush/nonbrowser-approved-packages.json b/apps/rush-lib/src/api/test/repo/common/config/rush/nonbrowser-approved-packages.json index 2ad030df51e..a3bc61f4d35 100644 --- a/apps/rush-lib/src/api/test/repo/common/config/rush/nonbrowser-approved-packages.json +++ b/apps/rush-lib/src/api/test/repo/common/config/rush/nonbrowser-approved-packages.json @@ -3,7 +3,7 @@ "packages": [ { "name": "example", - "allowedCategories": [ "first-party", "prototype", "third-party" ] + "allowedCategories": ["first-party", "prototype", "third-party"] } ] } diff --git a/apps/rush-lib/src/api/test/repo/rush-npm.json b/apps/rush-lib/src/api/test/repo/rush-npm.json index e2311e32130..a1bead19121 100644 --- a/apps/rush-lib/src/api/test/repo/rush-npm.json +++ b/apps/rush-lib/src/api/test/repo/rush-npm.json @@ -6,8 +6,8 @@ "hotfixChangeEnabled": true, "approvedPackagesPolicy": { - "reviewCategories": [ "first-party", "third-party", "prototype" ], - "ignoredNpmScopes": [ "@types", "@internal" ] + "reviewCategories": ["first-party", "third-party", "prototype"], + "ignoredNpmScopes": ["@types", "@internal"] }, "repository": { @@ -15,20 +15,15 @@ }, "gitPolicy": { - "allowedEmailRegExps": [ - "[^@]+@contoso\\.com" - ], + "allowedEmailRegExps": ["[^@]+@contoso\\.com"], "sampleEmail": "mrexample@contoso.com" }, "eventHooks": { - "postRushBuild": [ - "do something" - ] + "postRushBuild": ["do something"] }, "projects": [ - { "packageName": "project1", "projectFolder": "project1", diff --git a/apps/rush-lib/src/api/test/repo/rush-pnpm-2.json b/apps/rush-lib/src/api/test/repo/rush-pnpm-2.json index 1b3380c71d9..6078c6367f4 100644 --- a/apps/rush-lib/src/api/test/repo/rush-pnpm-2.json +++ b/apps/rush-lib/src/api/test/repo/rush-pnpm-2.json @@ -5,8 +5,8 @@ "projectFolderMaxDepth": 99, "approvedPackagesPolicy": { - "reviewCategories": [ "first-party", "third-party", "prototype" ], - "ignoredNpmScopes": [ "@types", "@internal" ] + "reviewCategories": ["first-party", "third-party", "prototype"], + "ignoredNpmScopes": ["@types", "@internal"] }, "repository": { @@ -14,20 +14,15 @@ }, "gitPolicy": { - "allowedEmailRegExps": [ - "[^@]+@contoso\\.com" - ], + "allowedEmailRegExps": ["[^@]+@contoso\\.com"], "sampleEmail": "mrexample@contoso.com" }, "eventHooks": { - "postRushBuild": [ - "do something" - ] + "postRushBuild": ["do something"] }, "projects": [ - { "packageName": "project1", "projectFolder": "project1", diff --git a/apps/rush-lib/src/api/test/repo/rush-pnpm-3.json b/apps/rush-lib/src/api/test/repo/rush-pnpm-3.json index 0216b188529..f8a6f037ecd 100644 --- a/apps/rush-lib/src/api/test/repo/rush-pnpm-3.json +++ b/apps/rush-lib/src/api/test/repo/rush-pnpm-3.json @@ -5,8 +5,8 @@ "projectFolderMaxDepth": 99, "approvedPackagesPolicy": { - "reviewCategories": [ "first-party", "third-party", "prototype" ], - "ignoredNpmScopes": [ "@types", "@internal" ] + "reviewCategories": ["first-party", "third-party", "prototype"], + "ignoredNpmScopes": ["@types", "@internal"] }, "repository": { @@ -14,20 +14,15 @@ }, "gitPolicy": { - "allowedEmailRegExps": [ - "[^@]+@contoso\\.com" - ], + "allowedEmailRegExps": ["[^@]+@contoso\\.com"], "sampleEmail": "mrexample@contoso.com" }, "eventHooks": { - "postRushBuild": [ - "do something" - ] + "postRushBuild": ["do something"] }, "projects": [ - { "packageName": "project1", "projectFolder": "project1", diff --git a/apps/rush-lib/src/api/test/repo/rush-pnpm-global.json b/apps/rush-lib/src/api/test/repo/rush-pnpm-global.json index d08ad1abf36..729d8ecfefd 100644 --- a/apps/rush-lib/src/api/test/repo/rush-pnpm-global.json +++ b/apps/rush-lib/src/api/test/repo/rush-pnpm-global.json @@ -9,8 +9,8 @@ }, "approvedPackagesPolicy": { - "reviewCategories": [ "first-party", "third-party", "prototype" ], - "ignoredNpmScopes": [ "@types", "@internal" ] + "reviewCategories": ["first-party", "third-party", "prototype"], + "ignoredNpmScopes": ["@types", "@internal"] }, "repository": { @@ -18,20 +18,15 @@ }, "gitPolicy": { - "allowedEmailRegExps": [ - "[^@]+@contoso\\.com" - ], + "allowedEmailRegExps": ["[^@]+@contoso\\.com"], "sampleEmail": "mrexample@contoso.com" }, "eventHooks": { - "postRushBuild": [ - "do something" - ] + "postRushBuild": ["do something"] }, "projects": [ - { "packageName": "project1", "projectFolder": "project1", diff --git a/apps/rush-lib/src/api/test/repo/rush-pnpm-invalid-store.json b/apps/rush-lib/src/api/test/repo/rush-pnpm-invalid-store.json index 57cf8b0c6d5..66b60b36fae 100644 --- a/apps/rush-lib/src/api/test/repo/rush-pnpm-invalid-store.json +++ b/apps/rush-lib/src/api/test/repo/rush-pnpm-invalid-store.json @@ -9,8 +9,8 @@ }, "approvedPackagesPolicy": { - "reviewCategories": [ "first-party", "third-party", "prototype" ], - "ignoredNpmScopes": [ "@types", "@internal" ] + "reviewCategories": ["first-party", "third-party", "prototype"], + "ignoredNpmScopes": ["@types", "@internal"] }, "repository": { @@ -18,20 +18,15 @@ }, "gitPolicy": { - "allowedEmailRegExps": [ - "[^@]+@contoso\\.com" - ], + "allowedEmailRegExps": ["[^@]+@contoso\\.com"], "sampleEmail": "mrexample@contoso.com" }, "eventHooks": { - "postRushBuild": [ - "do something" - ] + "postRushBuild": ["do something"] }, "projects": [ - { "packageName": "project1", "projectFolder": "project1", diff --git a/apps/rush-lib/src/api/test/repo/rush-pnpm-local.json b/apps/rush-lib/src/api/test/repo/rush-pnpm-local.json index 681fc20fd78..3e7039d235a 100644 --- a/apps/rush-lib/src/api/test/repo/rush-pnpm-local.json +++ b/apps/rush-lib/src/api/test/repo/rush-pnpm-local.json @@ -9,8 +9,8 @@ }, "approvedPackagesPolicy": { - "reviewCategories": [ "first-party", "third-party", "prototype" ], - "ignoredNpmScopes": [ "@types", "@internal" ] + "reviewCategories": ["first-party", "third-party", "prototype"], + "ignoredNpmScopes": ["@types", "@internal"] }, "repository": { @@ -18,20 +18,15 @@ }, "gitPolicy": { - "allowedEmailRegExps": [ - "[^@]+@contoso\\.com" - ], + "allowedEmailRegExps": ["[^@]+@contoso\\.com"], "sampleEmail": "mrexample@contoso.com" }, "eventHooks": { - "postRushBuild": [ - "do something" - ] + "postRushBuild": ["do something"] }, "projects": [ - { "packageName": "project1", "projectFolder": "project1", diff --git a/apps/rush-lib/src/api/test/repo/rush-pnpm.json b/apps/rush-lib/src/api/test/repo/rush-pnpm.json index af33bcd18f4..d722e18b427 100644 --- a/apps/rush-lib/src/api/test/repo/rush-pnpm.json +++ b/apps/rush-lib/src/api/test/repo/rush-pnpm.json @@ -5,8 +5,8 @@ "projectFolderMaxDepth": 99, "approvedPackagesPolicy": { - "reviewCategories": [ "first-party", "third-party", "prototype" ], - "ignoredNpmScopes": [ "@types", "@internal" ] + "reviewCategories": ["first-party", "third-party", "prototype"], + "ignoredNpmScopes": ["@types", "@internal"] }, "repository": { @@ -14,20 +14,15 @@ }, "gitPolicy": { - "allowedEmailRegExps": [ - "[^@]+@contoso\\.com" - ], + "allowedEmailRegExps": ["[^@]+@contoso\\.com"], "sampleEmail": "mrexample@contoso.com" }, "eventHooks": { - "postRushBuild": [ - "do something" - ] + "postRushBuild": ["do something"] }, "projects": [ - { "packageName": "project1", "projectFolder": "project1", diff --git a/apps/rush-lib/src/cli/CommandLineMigrationAdvisor.ts b/apps/rush-lib/src/cli/CommandLineMigrationAdvisor.ts index d58a3363cd0..158aa740d5b 100644 --- a/apps/rush-lib/src/cli/CommandLineMigrationAdvisor.ts +++ b/apps/rush-lib/src/cli/CommandLineMigrationAdvisor.ts @@ -7,7 +7,6 @@ import { RushConstants } from '../logic/RushConstants'; import { Utilities } from '../utilities/Utilities'; export class CommandLineMigrationAdvisor { - // NOTE: THIS RUNS BEFORE THE REAL COMMAND-LINE PARSING. // TAKE EXTREME CARE THAT THE HEURISTICS CANNOT FALSELY MATCH A VALID COMMAND LINE. public static checkArgv(argv: string[]): boolean { @@ -15,32 +14,36 @@ export class CommandLineMigrationAdvisor { const args: string[] = process.argv.slice(2); if (args.length > 0) { - if (args[0] === 'generate') { CommandLineMigrationAdvisor._reportDeprecated( - 'Instead of "rush generate", use "rush update" or "rush update --full".'); + 'Instead of "rush generate", use "rush update" or "rush update --full".' + ); return false; } if (args[0] === 'install') { if (args.indexOf('--full-clean') >= 0) { CommandLineMigrationAdvisor._reportDeprecated( - 'Instead of "rush install --full-clean", use "rush purge --unsafe".'); + 'Instead of "rush install --full-clean", use "rush purge --unsafe".' + ); return false; } if (args.indexOf('-C') >= 0) { CommandLineMigrationAdvisor._reportDeprecated( - 'Instead of "rush install -C", use "rush purge --unsafe".'); + 'Instead of "rush install -C", use "rush purge --unsafe".' + ); return false; } if (args.indexOf('--clean') >= 0) { CommandLineMigrationAdvisor._reportDeprecated( - 'Instead of "rush install --clean", use "rush install --purge".'); + 'Instead of "rush install --clean", use "rush install --purge".' + ); return false; } if (args.indexOf('-c') >= 0) { CommandLineMigrationAdvisor._reportDeprecated( - 'Instead of "rush install -c", use "rush install --purge".'); + 'Instead of "rush install -c", use "rush install --purge".' + ); return false; } } @@ -51,13 +54,20 @@ export class CommandLineMigrationAdvisor { } private static _reportDeprecated(message: string): void { - console.error(colors.red(Utilities.wrapWords( - 'ERROR: You specified an outdated command-line that is no longer supported by this version of Rush:' - ))); + console.error( + colors.red( + Utilities.wrapWords( + 'ERROR: You specified an outdated command-line that is no longer supported by this version of Rush:' + ) + ) + ); console.error(colors.yellow(Utilities.wrapWords(message))); console.error(); - console.error(Utilities.wrapWords(`For command-line help, type "rush -h". For migration instructions,` - + ` please visit ${RushConstants.rushWebSiteUrl}`)); + console.error( + Utilities.wrapWords( + `For command-line help, type "rush -h". For migration instructions,` + + ` please visit ${RushConstants.rushWebSiteUrl}` + ) + ); } - } diff --git a/apps/rush-lib/src/cli/RushCommandLineParser.ts b/apps/rush-lib/src/cli/RushCommandLineParser.ts index ad52faeb007..9989a37b20e 100644 --- a/apps/rush-lib/src/cli/RushCommandLineParser.ts +++ b/apps/rush-lib/src/cli/RushCommandLineParser.ts @@ -43,7 +43,7 @@ import { NodeJsCompatibility } from '../logic/NodeJsCompatibility'; * Options for `RushCommandLineParser`. */ export interface IRushCommandLineParserOptions { - cwd: string; // Defaults to `cwd` + cwd: string; // Defaults to `cwd` alreadyReportedNodeTooNewError: boolean; } @@ -58,14 +58,15 @@ export class RushCommandLineParser extends CommandLineParser { public constructor(options?: Partial) { super({ toolFilename: 'rush', - toolDescription: 'Rush makes life easier for JavaScript developers who develop, build, and publish' - + ' many packages from a central Git repo. It is designed to handle very large repositories' - + ' supporting many projects and people. Rush provides policies, protections, and customizations' - + ' that help coordinate teams and safely onboard new contributors. Rush also generates change logs' - + ' and automates package publishing. It can manage decoupled subsets of projects with different' - + ' release and versioning strategies. A full API is included to facilitate integration with other' - + ' automation tools. If you are looking for a proven turnkey solution for monorepo management,' - + ' Rush is for you.' + toolDescription: + 'Rush makes life easier for JavaScript developers who develop, build, and publish' + + ' many packages from a central Git repo. It is designed to handle very large repositories' + + ' supporting many projects and people. Rush provides policies, protections, and customizations' + + ' that help coordinate teams and safely onboard new contributors. Rush also generates change logs' + + ' and automates package publishing. It can manage decoupled subsets of projects with different' + + ' release and versioning strategies. A full API is included to facilitate integration with other' + + ' automation tools. If you are looking for a proven turnkey solution for monorepo management,' + + ' Rush is for you.', }); this._rushOptions = this._normalizeOptions(options || {}); @@ -73,7 +74,7 @@ export class RushCommandLineParser extends CommandLineParser { try { const rushJsonFilename: string | undefined = RushConfiguration.tryFindRushJsonLocation({ startingFolder: this._rushOptions.cwd, - showVerbose: true + showVerbose: true, }); if (rushJsonFilename) { this.rushConfiguration = RushConfiguration.loadFromConfigurationFile(rushJsonFilename); @@ -85,7 +86,7 @@ export class RushCommandLineParser extends CommandLineParser { NodeJsCompatibility.warnAboutCompatibilityIssues({ isRushLib: true, alreadyReportedNodeTooNewError: this._rushOptions.alreadyReportedNodeTooNewError, - rushConfiguration: this.rushConfiguration + rushConfiguration: this.rushConfiguration, }); this._populateActions(); @@ -105,7 +106,7 @@ export class RushCommandLineParser extends CommandLineParser { this._debugParameter = this.defineFlagParameter({ parameterLongName: '--debug', parameterShortName: '-d', - description: 'Show the full call stack if an error occurs while executing the tool' + description: 'Show the full call stack if an error occurs while executing the tool', }); } @@ -121,18 +122,20 @@ export class RushCommandLineParser extends CommandLineParser { InternalError.breakInDebugger = true; } - return this._wrapOnExecute().catch((error: Error) => { - this._reportErrorAndSetExitCode(error); - }).then(() => { - // If we make it here, everything went fine, so reset the exit code back to 0 - process.exitCode = 0; - }); + return this._wrapOnExecute() + .catch((error: Error) => { + this._reportErrorAndSetExitCode(error); + }) + .then(() => { + // If we make it here, everything went fine, so reset the exit code back to 0 + process.exitCode = 0; + }); } private _normalizeOptions(options: Partial): IRushCommandLineParserOptions { return { cwd: options.cwd || process.cwd(), - alreadyReportedNodeTooNewError: options.alreadyReportedNodeTooNewError || false + alreadyReportedNodeTooNewError: options.alreadyReportedNodeTooNewError || false, }; } @@ -172,7 +175,6 @@ export class RushCommandLineParser extends CommandLineParser { this.addAction(new VersionAction(this)); this._populateScriptActions(); - } catch (error) { this._reportErrorAndSetExitCode(error); } @@ -200,7 +202,10 @@ export class RushCommandLineParser extends CommandLineParser { private _addDefaultBuildActions(commandLineConfiguration?: CommandLineConfiguration): void { if (!this.tryGetAction(RushConstants.buildCommandName)) { - this._addCommandLineConfigAction(commandLineConfiguration, CommandLineConfiguration.defaultBuildCommandJson); + this._addCommandLineConfigAction( + commandLineConfiguration, + CommandLineConfiguration.defaultBuildCommandJson + ); } if (!this.tryGetAction(RushConstants.rebuildCommandName)) { @@ -229,56 +234,66 @@ export class RushCommandLineParser extends CommandLineParser { commandToRun?: string ): void { if (this.tryGetAction(command.name)) { - throw new Error(`${RushConstants.commandLineFilename} defines a command "${command.name}"` - + ` using a name that already exists`); + throw new Error( + `${RushConstants.commandLineFilename} defines a command "${command.name}"` + + ` using a name that already exists` + ); } this._validateCommandLineConfigCommand(command); switch (command.commandKind) { case RushConstants.bulkCommandKind: - this.addAction(new BulkScriptAction({ - actionName: command.name, - - // By default, the "rebuild" action runs the "build" script. However, if the command-line.json file - // overrides "rebuild," the "rebuild" script should be run. - commandToRun: commandToRun, - - summary: command.summary, - documentation: command.description || command.summary, - safeForSimultaneousRushProcesses: command.safeForSimultaneousRushProcesses, - - parser: this, - commandLineConfiguration: commandLineConfiguration, - - enableParallelism: command.enableParallelism, - ignoreMissingScript: command.ignoreMissingScript || false, - ignoreDependencyOrder: command.ignoreDependencyOrder || false, - incremental: command.incremental || false, - allowWarningsInSuccessfulBuild: !!command.allowWarningsInSuccessfulBuild - })); + this.addAction( + new BulkScriptAction({ + actionName: command.name, + + // By default, the "rebuild" action runs the "build" script. However, if the command-line.json file + // overrides "rebuild," the "rebuild" script should be run. + commandToRun: commandToRun, + + summary: command.summary, + documentation: command.description || command.summary, + safeForSimultaneousRushProcesses: command.safeForSimultaneousRushProcesses, + + parser: this, + commandLineConfiguration: commandLineConfiguration, + + enableParallelism: command.enableParallelism, + ignoreMissingScript: command.ignoreMissingScript || false, + ignoreDependencyOrder: command.ignoreDependencyOrder || false, + incremental: command.incremental || false, + allowWarningsInSuccessfulBuild: !!command.allowWarningsInSuccessfulBuild, + }) + ); break; case RushConstants.globalCommandKind: - this.addAction(new GlobalScriptAction({ - actionName: command.name, - summary: command.summary, - documentation: command.description || command.summary, - safeForSimultaneousRushProcesses: command.safeForSimultaneousRushProcesses, - - parser: this, - commandLineConfiguration: commandLineConfiguration, - - shellCommand: command.shellCommand - })); + this.addAction( + new GlobalScriptAction({ + actionName: command.name, + summary: command.summary, + documentation: command.description || command.summary, + safeForSimultaneousRushProcesses: command.safeForSimultaneousRushProcesses, + + parser: this, + commandLineConfiguration: commandLineConfiguration, + + shellCommand: command.shellCommand, + }) + ); break; default: - throw new Error(`${RushConstants.commandLineFilename} defines a command "${command!.name}"` - + ` using an unsupported command kind "${command!.commandKind}"`); + throw new Error( + `${RushConstants.commandLineFilename} defines a command "${command!.name}"` + + ` using an unsupported command kind "${command!.commandKind}"` + ); } } - private _validateCommandLineConfigParameterAssociations(commandLineConfiguration?: CommandLineConfiguration): void { + private _validateCommandLineConfigParameterAssociations( + commandLineConfiguration?: CommandLineConfiguration + ): void { if (!commandLineConfiguration) { return; } @@ -288,13 +303,17 @@ export class RushCommandLineParser extends CommandLineParser { for (const associatedCommand of parameter.associatedCommands) { const action: CommandLineAction | undefined = this.tryGetAction(associatedCommand); if (!action) { - throw new Error(`${RushConstants.commandLineFilename} defines a parameter "${parameter.longName}"` - + ` that is associated with a nonexistent command "${associatedCommand}"`); + throw new Error( + `${RushConstants.commandLineFilename} defines a parameter "${parameter.longName}"` + + ` that is associated with a nonexistent command "${associatedCommand}"` + ); } if (!(action instanceof BaseScriptAction)) { - throw new Error(`${RushConstants.commandLineFilename} defines a parameter "${parameter.longName}"` - + ` that is associated with a command "${associatedCommand}", but that command does not` - + ` support custom parameters`); + throw new Error( + `${RushConstants.commandLineFilename} defines a parameter "${parameter.longName}"` + + ` that is associated with a command "${associatedCommand}", but that command does not` + + ` support custom parameters` + ); } } } @@ -302,18 +321,25 @@ export class RushCommandLineParser extends CommandLineParser { private _validateCommandLineConfigCommand(command: CommandJson): void { // There are some restrictions on the 'build' and 'rebuild' commands. - if (command.name !== RushConstants.buildCommandName && command.name !== RushConstants.rebuildCommandName) { + if ( + command.name !== RushConstants.buildCommandName && + command.name !== RushConstants.rebuildCommandName + ) { return; } if (command.commandKind === RushConstants.globalCommandKind) { - throw new Error(`${RushConstants.commandLineFilename} defines a command "${command.name}" using ` + - `the command kind "${RushConstants.globalCommandKind}". This command can only be designated as a command ` + - `kind "${RushConstants.bulkCommandKind}".`); + throw new Error( + `${RushConstants.commandLineFilename} defines a command "${command.name}" using ` + + `the command kind "${RushConstants.globalCommandKind}". This command can only be designated as a command ` + + `kind "${RushConstants.bulkCommandKind}".` + ); } if (command.safeForSimultaneousRushProcesses) { - throw new Error(`${RushConstants.commandLineFilename} defines a command "${command.name}" using ` + - `"safeForSimultaneousRushProcesses=true". This configuration is not supported for "${command.name}".`); + throw new Error( + `${RushConstants.commandLineFilename} defines a command "${command.name}" using ` + + `"safeForSimultaneousRushProcesses=true". This configuration is not supported for "${command.name}".` + ); } } diff --git a/apps/rush-lib/src/cli/RushXCommandLine.ts b/apps/rush-lib/src/cli/RushXCommandLine.ts index 7f7bd449712..31f44432ab6 100644 --- a/apps/rush-lib/src/cli/RushXCommandLine.ts +++ b/apps/rush-lib/src/cli/RushXCommandLine.ts @@ -5,11 +5,7 @@ import * as colors from 'colors'; import * as os from 'os'; import * as path from 'path'; -import { - PackageJsonLookup, - IPackageJson, - Text - } from '@rushstack/node-core-library'; +import { PackageJsonLookup, IPackageJson, Text } from '@rushstack/node-core-library'; import { Utilities } from '../utilities/Utilities'; import { ProjectCommandSet } from '../logic/ProjectCommandSet'; import { RushConfiguration } from '../api/RushConfiguration'; @@ -47,16 +43,20 @@ export class RushXCommandLine { NodeJsCompatibility.warnAboutCompatibilityIssues({ isRushLib: true, alreadyReportedNodeTooNewError: !!options.alreadyReportedNodeTooNewError, - rushConfiguration + rushConfiguration, }); // Find the governing package.json for this folder: const packageJsonLookup: PackageJsonLookup = new PackageJsonLookup(); - const packageJsonFilePath: string | undefined = packageJsonLookup.tryGetPackageJsonFilePathFor(process.cwd()); + const packageJsonFilePath: string | undefined = packageJsonLookup.tryGetPackageJsonFilePathFor( + process.cwd() + ); if (!packageJsonFilePath) { console.log(colors.red('This command should be used inside a project folder.')); - console.log(`Unable to find a package.json file in the current working directory or any of its parents.`); + console.log( + `Unable to find a package.json file in the current working directory or any of its parents.` + ); return; } @@ -83,12 +83,19 @@ export class RushXCommandLine { const scriptBody: string | undefined = projectCommandSet.tryGetScriptBody(commandName); if (scriptBody === undefined) { - console.log(colors.red(`Error: The command "${commandName}" is not defined in the` - + ` package.json file for this project.`)); + console.log( + colors.red( + `Error: The command "${commandName}" is not defined in the` + + ` package.json file for this project.` + ) + ); if (projectCommandSet.commandNames.length > 0) { - console.log(os.EOL + 'Available commands for this project are: ' - + projectCommandSet.commandNames.map(x => `"${x}"`).join(', ')); + console.log( + os.EOL + + 'Available commands for this project are: ' + + projectCommandSet.commandNames.map((x) => `"${x}"`).join(', ') + ); } console.log(`Use ${colors.yellow('"rushx --help"')} for more information.`); @@ -99,27 +106,23 @@ export class RushXCommandLine { const packageFolder: string = path.dirname(packageJsonFilePath); - const exitCode: number = Utilities.executeLifecycleCommand( - scriptBody, - { - rushConfiguration, - workingDirectory: packageFolder, - // If there is a rush.json then use its .npmrc from the temp folder. - // Otherwise look for npmrc in the project folder. - initCwd: rushConfiguration ? rushConfiguration.commonTempFolder : packageFolder, - handleOutput: false, - environmentPathOptions: { - includeProjectBin: true - } - } - ); + const exitCode: number = Utilities.executeLifecycleCommand(scriptBody, { + rushConfiguration, + workingDirectory: packageFolder, + // If there is a rush.json then use its .npmrc from the temp folder. + // Otherwise look for npmrc in the project folder. + initCwd: rushConfiguration ? rushConfiguration.commonTempFolder : packageFolder, + handleOutput: false, + environmentPathOptions: { + includeProjectBin: true, + }, + }); if (exitCode > 0) { console.log(colors.red(`The script failed with exit code ${exitCode}`)); } process.exitCode = exitCode; - } catch (error) { console.log(colors.red('Error: ' + error.message)); } @@ -152,20 +155,28 @@ export class RushXCommandLine { console.log( // Example: " command: " - ' ' + colors.cyan(Text.padEnd(commandName + ':', maxLength + 2)) - // Example: "do some thin..." - + Text.truncateWithEllipsis(escapedScriptBody, truncateLength) + ' ' + + colors.cyan(Text.padEnd(commandName + ':', maxLength + 2)) + + // Example: "do some thin..." + Text.truncateWithEllipsis(escapedScriptBody, truncateLength) ); } if (projectCommandSet.malformedScriptNames.length > 0) { - console.log(os.EOL + colors.yellow('Warning: Some "scripts" entries in the package.json file' - + ' have malformed names: ' - + projectCommandSet.malformedScriptNames.map(x => `"${x}"`).join(', '))); + console.log( + os.EOL + + colors.yellow( + 'Warning: Some "scripts" entries in the package.json file' + + ' have malformed names: ' + + projectCommandSet.malformedScriptNames.map((x) => `"${x}"`).join(', ') + ) + ); } } else { console.log(colors.yellow('Warning: No commands are defined yet for this project.')); - console.log('You can define a command by adding a "scripts" table to the project\'s package.json file.'); + console.log( + 'You can define a command by adding a "scripts" table to the project\'s package.json file.' + ); } } } diff --git a/apps/rush-lib/src/cli/actions/AddAction.ts b/apps/rush-lib/src/cli/actions/AddAction.ts index 56128e58f8d..d6a275922c5 100644 --- a/apps/rush-lib/src/cli/actions/AddAction.ts +++ b/apps/rush-lib/src/cli/actions/AddAction.ts @@ -4,10 +4,7 @@ import * as os from 'os'; import * as semver from 'semver'; -import { - CommandLineFlagParameter, - CommandLineStringParameter -} from '@rushstack/ts-command-line'; +import { CommandLineFlagParameter, CommandLineStringParameter } from '@rushstack/ts-command-line'; import { RushConfigurationProject } from '../../api/RushConfigurationProject'; import { BaseRushAction } from './BaseRushAction'; @@ -25,19 +22,19 @@ export class AddAction extends BaseRushAction { public constructor(parser: RushCommandLineParser) { const documentation: string[] = [ - 'Adds a specified package as a dependency of the current project (as determined by the current working directory)' - + ' and then runs "rush update". If no version is specified, a version will be automatically detected (typically' - + ' either the latest version or a version that won\'t break the "ensureConsistentVersions" policy). If a version' - + ' range is specified, the latest version in the range will be used. The version will be automatically prepended' - + ' with a tilde, unless the "--exact" or "--caret" flags are used. The "--make-consistent" flag can be used to' - + ' update all packages with the dependency.' + 'Adds a specified package as a dependency of the current project (as determined by the current working directory)' + + ' and then runs "rush update". If no version is specified, a version will be automatically detected (typically' + + ' either the latest version or a version that won\'t break the "ensureConsistentVersions" policy). If a version' + + ' range is specified, the latest version in the range will be used. The version will be automatically prepended' + + ' with a tilde, unless the "--exact" or "--caret" flags are used. The "--make-consistent" flag can be used to' + + ' update all packages with the dependency.', ]; super({ actionName: 'add', summary: 'Adds a dependency to the package.json and runs rush upgrade.', documentation: documentation.join(os.EOL), safeForSimultaneousRushProcesses: false, - parser + parser, }); } @@ -47,41 +44,45 @@ export class AddAction extends BaseRushAction { parameterShortName: '-p', required: true, argumentName: 'PACKAGE', - description: '(Required) The name of the package which should be added as a dependency.' - + ' A SemVer version specifier can be appended after an "@" sign. WARNING: Symbol characters' - + ' are usually interpreted by your shell, so it\'s recommended to use quotes.' - + ' For example, write "rush add --package "example@^1.2.3"" instead of "rush add --package example@^1.2.3".' + description: + '(Required) The name of the package which should be added as a dependency.' + + ' A SemVer version specifier can be appended after an "@" sign. WARNING: Symbol characters' + + " are usually interpreted by your shell, so it's recommended to use quotes." + + ' For example, write "rush add --package "example@^1.2.3"" instead of "rush add --package example@^1.2.3".', }); this._exactFlag = this.defineFlagParameter({ parameterLongName: '--exact', - description: 'If specified, the SemVer specifier added to the' - + ' package.json will be an exact version (e.g. without tilde or caret).' + description: + 'If specified, the SemVer specifier added to the' + + ' package.json will be an exact version (e.g. without tilde or caret).', }); this._caretFlag = this.defineFlagParameter({ parameterLongName: '--caret', - description: 'If specified, the SemVer specifier added to the' - + ' package.json will be a prepended with a "caret" specifier ("^").' + description: + 'If specified, the SemVer specifier added to the' + + ' package.json will be a prepended with a "caret" specifier ("^").', }); this._devDependencyFlag = this.defineFlagParameter({ parameterLongName: '--dev', - description: 'If specified, the package will be added to the "devDependencies" section of' - + ' the package.json' + description: + 'If specified, the package will be added to the "devDependencies" section of' + ' the package.json', }); this._makeConsistentFlag = this.defineFlagParameter({ parameterLongName: '--make-consistent', parameterShortName: '-m', - description: 'If specified, other packages with this dependency will have their package.json' - + ' files updated to use the same version of the dependency.' + description: + 'If specified, other packages with this dependency will have their package.json' + + ' files updated to use the same version of the dependency.', }); this._skipUpdateFlag = this.defineFlagParameter({ parameterLongName: '--skip-update', parameterShortName: '-s', - description: 'If specified, the "rush update" command will not be run after updating the' - + ' package.json files.' + description: + 'If specified, the "rush update" command will not be run after updating the' + ' package.json files.', }); this._allFlag = this.defineFlagParameter({ parameterLongName: '--all', - description: 'If specified, the dependency will be added to all projects.' + description: 'If specified, the dependency will be added to all projects.', }); } @@ -90,13 +91,15 @@ export class AddAction extends BaseRushAction { if (this._allFlag.value) { projects = this.rushConfiguration.projects; } else { - const currentProject: RushConfigurationProject | undefined = this.rushConfiguration.tryGetProjectForPath( - process.cwd() - ); + const currentProject: + | RushConfigurationProject + | undefined = this.rushConfiguration.tryGetProjectForPath(process.cwd()); if (!currentProject) { - throw new Error('The "rush add" command must be invoked under a project' - + ` folder that is registered in rush.json unless the ${this._allFlag.longName} is used.`); + throw new Error( + 'The "rush add" command must be invoked under a project' + + ` folder that is registered in rush.json unless the ${this._allFlag.longName} is used.` + ); } projects = [currentProject]; @@ -136,7 +139,7 @@ export class AddAction extends BaseRushAction { if (this._exactFlag.value || this._caretFlag.value) { throw new Error( `The "${this._caretFlag.longName}" and "${this._exactFlag.longName}" flags may not be specified if a ` + - `version is provided in the ${this._packageName.longName} specifier. In this case "${version}" was provided.` + `version is provided in the ${this._packageName.longName} specifier. In this case "${version}" was provided.` ); } @@ -144,7 +147,9 @@ export class AddAction extends BaseRushAction { } else { rangeStyle = this._caretFlag.value ? SemVerStyle.Caret - : (this._exactFlag.value ? SemVerStyle.Exact : SemVerStyle.Tilde); + : this._exactFlag.value + ? SemVerStyle.Exact + : SemVerStyle.Tilde; } await updater.doRushAdd({ @@ -155,7 +160,7 @@ export class AddAction extends BaseRushAction { updateOtherPackages: this._makeConsistentFlag.value, skipUpdate: this._skipUpdateFlag.value, debugInstall: this.parser.isDebug, - rangeStyle: rangeStyle + rangeStyle: rangeStyle, }); } } diff --git a/apps/rush-lib/src/cli/actions/BaseInstallAction.ts b/apps/rush-lib/src/cli/actions/BaseInstallAction.ts index 577d8b5193c..674dca084cc 100644 --- a/apps/rush-lib/src/cli/actions/BaseInstallAction.ts +++ b/apps/rush-lib/src/cli/actions/BaseInstallAction.ts @@ -7,7 +7,7 @@ import * as os from 'os'; import { CommandLineFlagParameter, CommandLineIntegerParameter, - CommandLineStringParameter + CommandLineStringParameter, } from '@rushstack/ts-command-line'; import { BaseRushAction } from './BaseRushAction'; @@ -37,35 +37,38 @@ export abstract class BaseInstallAction extends BaseRushAction { this._purgeParameter = this.defineFlagParameter({ parameterLongName: '--purge', parameterShortName: '-p', - description: 'Perform "rush purge" before starting the installation' + description: 'Perform "rush purge" before starting the installation', }); this._bypassPolicyParameter = this.defineFlagParameter({ parameterLongName: '--bypass-policy', - description: 'Overrides enforcement of the "gitPolicy" rules from rush.json (use honorably!)' + description: 'Overrides enforcement of the "gitPolicy" rules from rush.json (use honorably!)', }); this._noLinkParameter = this.defineFlagParameter({ parameterLongName: '--no-link', - description: 'If "--no-link" is specified, then project symlinks will NOT be created' - + ' after the installation completes. You will need to run "rush link" manually.' - + ' This flag is useful for automated builds that want to report stages individually' - + ' or perform extra operations in between the two stages.' + description: + 'If "--no-link" is specified, then project symlinks will NOT be created' + + ' after the installation completes. You will need to run "rush link" manually.' + + ' This flag is useful for automated builds that want to report stages individually' + + ' or perform extra operations in between the two stages.', }); this._networkConcurrencyParameter = this.defineIntegerParameter({ parameterLongName: '--network-concurrency', argumentName: 'COUNT', - description: 'If specified, limits the maximum number of concurrent network requests.' - + ' This is useful when troubleshooting network failures.' + description: + 'If specified, limits the maximum number of concurrent network requests.' + + ' This is useful when troubleshooting network failures.', }); this._debugPackageManagerParameter = this.defineFlagParameter({ parameterLongName: '--debug-package-manager', - description: 'Activates verbose logging for the package manager. You will probably want to pipe' - + ' the output of Rush to a file when using this command.' + description: + 'Activates verbose logging for the package manager. You will probably want to pipe' + + ' the output of Rush to a file when using this command.', }); this._maxInstallAttempts = this.defineIntegerParameter({ parameterLongName: '--max-install-attempts', argumentName: 'NUMBER', description: `Overrides the default maximum number of install attempts.`, - defaultValue: RushConstants.defaultMaxInstallAttempts + defaultValue: RushConstants.defaultMaxInstallAttempts, }); this._variant = this.defineStringParameter(Variants.VARIANT_PARAMETER); } @@ -74,7 +77,7 @@ export abstract class BaseInstallAction extends BaseRushAction { protected run(): Promise { VersionMismatchFinder.ensureConsistentVersions(this.rushConfiguration, { - variant: this._variant.value + variant: this._variant.value, }); const stopwatch: Stopwatch = Stopwatch.start(); @@ -99,8 +102,10 @@ export abstract class BaseInstallAction extends BaseRushAction { if (this._networkConcurrencyParameter.value) { if (this.rushConfiguration.packageManager !== 'pnpm') { - throw new Error(`The "${this._networkConcurrencyParameter.longName}" parameter is` - + ` only supported when using the PNPM package manager.`); + throw new Error( + `The "${this._networkConcurrencyParameter.longName}" parameter is` + + ` only supported when using the PNPM package manager.` + ); } } @@ -119,7 +124,8 @@ export abstract class BaseInstallAction extends BaseRushAction { installManagerOptions ); - return installManager.doInstall() + return installManager + .doInstall() .then(() => { purgeManager.deleteAll(); stopwatch.stop(); @@ -128,12 +134,18 @@ export abstract class BaseInstallAction extends BaseRushAction { this.eventHooksManager.handle(Event.postRushInstall, this.parser.isDebug); if (warnAboutScriptUpdate) { - console.log(os.EOL + colors.yellow('Rush refreshed some files in the "common/scripts" folder.' - + ' Please commit this change to Git.')); + console.log( + os.EOL + + colors.yellow( + 'Rush refreshed some files in the "common/scripts" folder.' + + ' Please commit this change to Git.' + ) + ); } - console.log(os.EOL + colors.green( - `Rush ${this.actionName} finished successfully. (${stopwatch.toString()})`)); + console.log( + os.EOL + colors.green(`Rush ${this.actionName} finished successfully. (${stopwatch.toString()})`) + ); }) .catch((error) => { purgeManager.deleteAll(); @@ -144,9 +156,11 @@ export abstract class BaseInstallAction extends BaseRushAction { }); } - private _collectTelemetry(stopwatch: Stopwatch, installManagerOptions: IInstallManagerOptions, - success: boolean): void { - + private _collectTelemetry( + stopwatch: Stopwatch, + installManagerOptions: IInstallManagerOptions, + success: boolean + ): void { if (this.parser.telemetry) { this.parser.telemetry.log({ name: 'install', @@ -155,10 +169,9 @@ export abstract class BaseInstallAction extends BaseRushAction { extraData: { mode: this.actionName, clean: (!!this._purgeParameter.value).toString(), - full: installManagerOptions.fullUpgrade.toString() - } + full: installManagerOptions.fullUpgrade.toString(), + }, }); } } - } diff --git a/apps/rush-lib/src/cli/actions/BaseRushAction.ts b/apps/rush-lib/src/cli/actions/BaseRushAction.ts index 6618bd64469..e16bb830fa7 100644 --- a/apps/rush-lib/src/cli/actions/BaseRushAction.ts +++ b/apps/rush-lib/src/cli/actions/BaseRushAction.ts @@ -5,10 +5,7 @@ import * as colors from 'colors'; import * as os from 'os'; import * as path from 'path'; -import { - CommandLineAction, - ICommandLineActionOptions -} from '@rushstack/ts-command-line'; +import { CommandLineAction, ICommandLineActionOptions } from '@rushstack/ts-command-line'; import { LockFile } from '@rushstack/node-core-library'; @@ -87,8 +84,10 @@ export abstract class BaseConfiglessRushAction extends CommandLineAction { if (this.rushConfiguration) { // eslint-disable-next-line dot-notation let environmentPath: string | undefined = process.env['PATH']; - environmentPath = path.join(this.rushConfiguration.commonTempFolder, 'node_modules', '.bin') + - path.delimiter + environmentPath; + environmentPath = + path.join(this.rushConfiguration.commonTempFolder, 'node_modules', '.bin') + + path.delimiter + + environmentPath; // eslint-disable-next-line dot-notation process.env['PATH'] = environmentPath; } diff --git a/apps/rush-lib/src/cli/actions/ChangeAction.ts b/apps/rush-lib/src/cli/actions/ChangeAction.ts index 4d3222cf58c..86185ab6b61 100644 --- a/apps/rush-lib/src/cli/actions/ChangeAction.ts +++ b/apps/rush-lib/src/cli/actions/ChangeAction.ts @@ -10,19 +10,12 @@ import * as inquirer from 'inquirer'; import { CommandLineFlagParameter, CommandLineStringParameter, - CommandLineChoiceParameter + CommandLineChoiceParameter, } from '@rushstack/ts-command-line'; -import { - FileSystem, - Path -} from '@rushstack/node-core-library'; +import { FileSystem, Path } from '@rushstack/node-core-library'; import { RushConfigurationProject } from '../../api/RushConfigurationProject'; -import { - IChangeFile, - IChangeInfo, - ChangeType -} from '../../api/ChangeManagement'; +import { IChangeFile, IChangeInfo, ChangeType } from '../../api/ChangeManagement'; import { VersionControl } from '../../utilities/VersionControl'; import { ChangeFile } from '../../api/ChangeFile'; import { BaseRushAction } from './BaseRushAction'; @@ -32,7 +25,7 @@ import { VersionPolicy, IndividualVersionPolicy, LockStepVersionPolicy, - VersionPolicyDefinitionName + VersionPolicyDefinitionName, } from '../../api/VersionPolicy'; import { AlreadyReportedError } from '../../utilities/AlreadyReportedError'; @@ -52,37 +45,38 @@ export class ChangeAction extends BaseRushAction { public constructor(parser: RushCommandLineParser) { const documentation: string[] = [ 'Asks a series of questions and then generates a -.json file ' + - 'in the common folder. The `publish` command will consume these files and perform the proper ' + - 'version bumps. Note these changes will eventually be published in a changelog.md file in each package.', + 'in the common folder. The `publish` command will consume these files and perform the proper ' + + 'version bumps. Note these changes will eventually be published in a changelog.md file in each package.', '', 'The possible types of changes are: ', '', 'MAJOR - these are breaking changes that are not backwards compatible. ' + - 'Examples are: renaming a public class, adding/removing a non-optional ' + - 'parameter from a public API, or renaming an variable or function that ' + - 'is exported.', + 'Examples are: renaming a public class, adding/removing a non-optional ' + + 'parameter from a public API, or renaming an variable or function that ' + + 'is exported.', '', 'MINOR - these are changes that are backwards compatible (but not ' + - 'forwards compatible). Examples are: adding a new public API or adding an ' + - 'optional parameter to a public API', + 'forwards compatible). Examples are: adding a new public API or adding an ' + + 'optional parameter to a public API', '', 'PATCH - these are changes that are backwards and forwards compatible. ' + - 'Examples are: Modifying a private API or fixing a bug in the logic ' + - 'of how an existing API works.', + 'Examples are: Modifying a private API or fixing a bug in the logic ' + + 'of how an existing API works.', '', 'HOTFIX (EXPERIMENTAL) - these are changes that are hotfixes targeting a ' + - 'specific older version of the package. When a hotfix change is added, ' + - 'other changes will not be able to increment the version number. ' + - 'Enable this feature by setting \'hotfixChangeEnabled\' in your rush.json.', - '' + 'specific older version of the package. When a hotfix change is added, ' + + 'other changes will not be able to increment the version number. ' + + "Enable this feature by setting 'hotfixChangeEnabled' in your rush.json.", + '', ]; super({ actionName: 'change', - summary: 'Records changes made to projects, indicating how the package version number should be bumped ' + + summary: + 'Records changes made to projects, indicating how the package version number should be bumped ' + 'for the next publish.', documentation: documentation.join(os.EOL), safeForSimultaneousRushProcesses: true, - parser + parser, }); } @@ -94,53 +88,57 @@ export class ChangeAction extends BaseRushAction { this._verifyParameter = this.defineFlagParameter({ parameterLongName: '--verify', parameterShortName: '-v', - description: 'Verify the change file has been generated and that it is a valid JSON file' + description: 'Verify the change file has been generated and that it is a valid JSON file', }); this._noFetchParameter = this.defineFlagParameter({ parameterLongName: '--no-fetch', - description: 'Skips fetching the baseline branch before running "git diff" to detect changes.' + description: 'Skips fetching the baseline branch before running "git diff" to detect changes.', }); this._targetBranchParameter = this.defineStringParameter({ parameterLongName: '--target-branch', parameterShortName: '-b', argumentName: 'BRANCH', - description: 'If this parameter is specified, compare the checked out branch with the specified branch to ' + + description: + 'If this parameter is specified, compare the checked out branch with the specified branch to ' + 'determine which projects were changed. If this parameter is not specified, the checked out branch ' + - 'is compared against the "master" branch.' + 'is compared against the "master" branch.', }); this._overwriteFlagParameter = this.defineFlagParameter({ parameterLongName: '--overwrite', - description: `If a changefile already exists, overwrite without prompting ` + - `(or erroring in ${BULK_LONG_NAME} mode).` + description: + `If a changefile already exists, overwrite without prompting ` + + `(or erroring in ${BULK_LONG_NAME} mode).`, }); this._changeEmailParameter = this.defineStringParameter({ parameterLongName: '--email', argumentName: 'EMAIL', - description: 'The email address to use in changefiles. If this parameter is not provided, the email address ' + - 'will be detected or prompted for in interactive mode.' + description: + 'The email address to use in changefiles. If this parameter is not provided, the email address ' + + 'will be detected or prompted for in interactive mode.', }); this._bulkChangeParameter = this.defineFlagParameter({ parameterLongName: BULK_LONG_NAME, - description: 'If this flag is specified, apply the same change message and bump type to all changed projects. ' + + description: + 'If this flag is specified, apply the same change message and bump type to all changed projects. ' + `The ${BULK_MESSAGE_LONG_NAME} and the ${BULK_BUMP_TYPE_LONG_NAME} parameters must be specified if the ` + - `${BULK_LONG_NAME} parameter is specified` + `${BULK_LONG_NAME} parameter is specified`, }); this._bulkChangeMessageParameter = this.defineStringParameter({ parameterLongName: BULK_MESSAGE_LONG_NAME, argumentName: 'MESSAGE', - description: `The message to apply to all changed projects if the ${BULK_LONG_NAME} flag is provided.` + description: `The message to apply to all changed projects if the ${BULK_LONG_NAME} flag is provided.`, }); this._bulkChangeBumpTypeParameter = this.defineChoiceParameter({ parameterLongName: BULK_BUMP_TYPE_LONG_NAME, alternatives: [...Object.keys(this._getBumpOptions()), ChangeType[ChangeType.none]], - description: `The bump type to apply to all changed projects if the ${BULK_LONG_NAME} flag is provided.` + description: `The bump type to apply to all changed projects if the ${BULK_LONG_NAME} flag is provided.`, }); } @@ -149,19 +147,19 @@ export class ChangeAction extends BaseRushAction { this._projectHostMap = this._generateHostMap(); if (this._verifyParameter.value) { - const errors: string[] = ([ + const errors: string[] = [ this._bulkChangeParameter, this._bulkChangeMessageParameter, this._bulkChangeBumpTypeParameter, - this._overwriteFlagParameter - ]).map((parameter) => { - return parameter.value - ? ( - `The {${this._bulkChangeParameter.longName} parameter cannot be provided with the ` + - `${this._verifyParameter.longName} parameter` - ) - : ''; - }).filter((error) => error !== ''); + this._overwriteFlagParameter, + ] + .map((parameter) => { + return parameter.value + ? `The {${this._bulkChangeParameter.longName} parameter cannot be provided with the ` + + `${this._verifyParameter.longName} parameter` + : ''; + }) + .filter((error) => error !== ''); if (errors.length > 0) { errors.forEach((error) => console.error(error)); throw new AlreadyReportedError(); @@ -186,24 +184,24 @@ export class ChangeAction extends BaseRushAction { if (this._bulkChangeParameter.value) { if ( !this._bulkChangeBumpTypeParameter.value || - ( - !this._bulkChangeMessageParameter.value && - this._bulkChangeBumpTypeParameter.value !== ChangeType[ChangeType.none] - ) + (!this._bulkChangeMessageParameter.value && + this._bulkChangeBumpTypeParameter.value !== ChangeType[ChangeType.none]) ) { throw new Error( `The ${this._bulkChangeBumpTypeParameter.longName} and ${this._bulkChangeMessageParameter.longName} ` + - `parameters must provided if the ${this._bulkChangeParameter.longName} flag is provided. If the value ` + - `"${ChangeType[ChangeType.none]}" is provided to the ${this._bulkChangeBumpTypeParameter.longName} ` + - `parameter, the ${this._bulkChangeMessageParameter.longName} parameter may be omitted.` + `parameters must provided if the ${this._bulkChangeParameter.longName} flag is provided. If the value ` + + `"${ChangeType[ChangeType.none]}" is provided to the ${ + this._bulkChangeBumpTypeParameter.longName + } ` + + `parameter, the ${this._bulkChangeMessageParameter.longName} parameter may be omitted.` ); } const email: string | undefined = this._changeEmailParameter.value || this._detectEmail(); if (!email) { throw new Error( - 'Unable to detect Git email and an email address wasn\'t provided using the ' + - `${this._changeEmailParameter.longName} paramter.` + "Unable to detect Git email and an email address wasn't provided using the " + + `${this._changeEmailParameter.longName} paramter.` ); } @@ -223,20 +221,17 @@ export class ChangeAction extends BaseRushAction { errors.push(`The "${projectChangeType}" change type is not allowed for package "${packageName}".`); } - changeFileData.set( + changeFileData.set(packageName, { + changes: [ + { + comment, + type: projectChangeType, + packageName, + } as IChangeInfo, + ], packageName, - { - changes: [ - { - comment, - type: projectChangeType, - packageName - } as IChangeInfo - ], - packageName, - email - } - ); + email, + }); } if (errors.length > 0) { @@ -249,12 +244,14 @@ export class ChangeAction extends BaseRushAction { } else if (this._bulkChangeBumpTypeParameter.value || this._bulkChangeMessageParameter.value) { throw new Error( `The ${this._bulkChangeParameter.longName} flag must be provided with the ` + - `${this._bulkChangeBumpTypeParameter.longName} and ${this._bulkChangeMessageParameter.longName} parameters.` + `${this._bulkChangeBumpTypeParameter.longName} and ${this._bulkChangeMessageParameter.longName} parameters.` ); } else { interactiveMode = true; - const existingChangeComments: Map = ChangeFiles.getChangeComments(this._getChangeFiles()); + const existingChangeComments: Map = ChangeFiles.getChangeComments( + this._getChangeFiles() + ); changeFileData = await this._promptForChangeFileData( promptModule, sortedProjectList, @@ -283,7 +280,7 @@ export class ChangeAction extends BaseRushAction { private _generateHostMap(): Map { const hostMap: Map = new Map(); - this.rushConfiguration.projects.forEach(project => { + this.rushConfiguration.projects.forEach((project) => { let hostProjectName: string = project.packageName; if (project.versionPolicy && project.versionPolicy.isLockstepped) { const lockstepPolicy: LockStepVersionPolicy = project.versionPolicy as LockStepVersionPolicy; @@ -307,9 +304,8 @@ export class ChangeAction extends BaseRushAction { private get _targetBranch(): string { if (!this._targetBranchName) { - this._targetBranchName = ( - this._targetBranchParameter.value || VersionControl.getRemoteMasterBranch(this.rushConfiguration) - ); + this._targetBranchName = + this._targetBranchParameter.value || VersionControl.getRemoteMasterBranch(this.rushConfiguration); } return this._targetBranchName; @@ -327,20 +323,20 @@ export class ChangeAction extends BaseRushAction { const repoRootFolder: string | undefined = VersionControl.getRepositoryRootPath(); this.rushConfiguration.projects - .filter(project => project.shouldPublish) - .filter(project => !project.versionPolicy || !project.versionPolicy.exemptFromRushChange) - .filter(project => { - const projectFolder: string = repoRootFolder - ? path.relative(repoRootFolder, project.projectFolder) - : project.projectRelativeFolder; - return this._hasProjectChanged(changedFolders, projectFolder); - }) - .forEach(project => { - const hostName: string | undefined = this._projectHostMap.get(project.packageName); - if (hostName) { - changedPackageNames.add(hostName); - } - }); + .filter((project) => project.shouldPublish) + .filter((project) => !project.versionPolicy || !project.versionPolicy.exemptFromRushChange) + .filter((project) => { + const projectFolder: string = repoRootFolder + ? path.relative(repoRootFolder, project.projectFolder) + : project.projectRelativeFolder; + return this._hasProjectChanged(changedFolders, projectFolder); + }) + .forEach((project) => { + const hostName: string | undefined = this._projectHostMap.get(project.packageName); + if (hostName) { + changedPackageNames.add(hostName); + } + }); return [...changedPackageNames]; } @@ -351,15 +347,12 @@ export class ChangeAction extends BaseRushAction { } private _getChangeFiles(): string[] { - return VersionControl.getChangedFiles(this._targetBranch, true, `common/changes/`).map(relativePath => { + return VersionControl.getChangedFiles(this._targetBranch, true, `common/changes/`).map((relativePath) => { return path.join(this.rushConfiguration.rushJsonFolder, relativePath); }); } - private _hasProjectChanged( - changedFolders: (string | undefined)[], - projectFolder: string - ): boolean { + private _hasProjectChanged(changedFolders: (string | undefined)[], projectFolder: string): boolean { for (const folder of changedFolders) { if (folder && Path.isUnderOrEqual(folder, projectFolder)) { return true; @@ -392,7 +385,7 @@ export class ChangeAction extends BaseRushAction { changeFile = { changes: [], packageName: changeInfo.packageName, - email: undefined + email: undefined, }; changedFileData.set(changeInfo.packageName, changeFile!); } @@ -416,7 +409,7 @@ export class ChangeAction extends BaseRushAction { const comments: string[] | undefined = existingChangeComments.get(packageName); if (comments) { console.log(`Found existing comments:`); - comments.forEach(comment => { + comments.forEach((comment) => { console.log(` > ${comment}`); }); const { appendComment }: { appendComment: 'skip' | 'append' } = await promptModule({ @@ -426,14 +419,14 @@ export class ChangeAction extends BaseRushAction { message: 'Append to existing comments or skip?', choices: [ { - 'name': 'Skip', - 'value': 'skip' + name: 'Skip', + value: 'skip', }, { - 'name': 'Append', - 'value': 'append' - } - ] + name: 'Append', + value: 'append', + }, + ], }); if (appendComment === 'skip') { @@ -454,50 +447,56 @@ export class ChangeAction extends BaseRushAction { const { comment }: { comment: string } = await promptModule({ name: 'comment', type: 'input', - message: `Describe changes, or ENTER if no changes:` + message: `Describe changes, or ENTER if no changes:`, }); if (Object.keys(bumpOptions).length === 0 || !comment) { return { packageName: packageName, comment: comment || '', - type: ChangeType[ChangeType.none] + type: ChangeType[ChangeType.none], } as IChangeInfo; } else { const { bumpType }: { bumpType: string } = await promptModule({ - choices: Object.keys(bumpOptions).map(option => { + choices: Object.keys(bumpOptions).map((option) => { return { - 'value': option, - 'name': bumpOptions[option] + value: option, + name: bumpOptions[option], }; }), default: 'patch', message: 'Select the type of change:', name: 'bumpType', - type: 'list' + type: 'list', }); return { packageName: packageName, comment: comment, - type: bumpType + type: bumpType, } as IChangeInfo; } } private _getBumpOptions(packageName?: string): { [type: string]: string } { - let bumpOptions: { [type: string]: string } = (this.rushConfiguration && this.rushConfiguration.hotfixChangeEnabled) - ? { - [ChangeType[ChangeType.hotfix]]: 'hotfix - for changes that need to be published in a separate hotfix package' - } - : { - [ChangeType[ChangeType.major]]: 'major - for changes that break compatibility, e.g. removing an API', - [ChangeType[ChangeType.minor]]: 'minor - for backwards compatible changes, e.g. adding a new API', - [ChangeType[ChangeType.patch]]: 'patch - for changes that do not affect compatibility, e.g. fixing a bug' - }; + let bumpOptions: { [type: string]: string } = + this.rushConfiguration && this.rushConfiguration.hotfixChangeEnabled + ? { + [ChangeType[ChangeType.hotfix]]: + 'hotfix - for changes that need to be published in a separate hotfix package', + } + : { + [ChangeType[ChangeType.major]]: + 'major - for changes that break compatibility, e.g. removing an API', + [ChangeType[ChangeType.minor]]: 'minor - for backwards compatible changes, e.g. adding a new API', + [ChangeType[ChangeType.patch]]: + 'patch - for changes that do not affect compatibility, e.g. fixing a bug', + }; if (packageName) { - const project: RushConfigurationProject | undefined = this.rushConfiguration.getProjectByName(packageName); + const project: RushConfigurationProject | undefined = this.rushConfiguration.getProjectByName( + packageName + ); const versionPolicy: VersionPolicy | undefined = project!.versionPolicy; if (versionPolicy) { @@ -521,12 +520,13 @@ export class ChangeAction extends BaseRushAction { * or will ask for it if it is not found or the Git config is wrong. */ private async _detectOrAskForEmail(promptModule: inquirer.PromptModule): Promise { - return await this._detectAndConfirmEmail(promptModule) || await this._promptForEmail(promptModule); + return (await this._detectAndConfirmEmail(promptModule)) || (await this._promptForEmail(promptModule)); } private _detectEmail(): string | undefined { try { - return child_process.execSync('git config user.email') + return child_process + .execSync('git config user.email') .toString() .replace(/(\r\n|\n|\r)/gm, ''); } catch (err) { @@ -548,8 +548,8 @@ export class ChangeAction extends BaseRushAction { type: 'confirm', name: 'isCorrectEmail', default: 'Y', - message: `Is your email address ${email}?` - } + message: `Is your email address ${email}?`, + }, ]); return isCorrectEmail ? email : undefined; } else { @@ -568,8 +568,8 @@ export class ChangeAction extends BaseRushAction { message: 'What is your email address?', validate: (input: string) => { return true; // @todo should be an email - } - } + }, + }, ]); return email; } @@ -579,10 +579,10 @@ export class ChangeAction extends BaseRushAction { if (VersionControl.hasUncommittedChanges()) { console.log( os.EOL + - colors.yellow( - 'Warning: You have uncommitted changes, which do not trigger prompting for change ' + - 'descriptions.' - ) + colors.yellow( + 'Warning: You have uncommitted changes, which do not trigger prompting for change ' + + 'descriptions.' + ) ); } } catch (error) { @@ -615,11 +615,10 @@ export class ChangeAction extends BaseRushAction { const filePath: string = changeFile.generatePath(); const fileExists: boolean = FileSystem.exists(filePath); - const shouldWrite: boolean = ( + const shouldWrite: boolean = !fileExists || overwrite || - (interactiveMode ? await this._promptForOverwrite(promptModule, filePath) : false) - ); + (interactiveMode ? await this._promptForOverwrite(promptModule, filePath) : false); if (!interactiveMode && fileExists && !overwrite) { throw new Error(`Changefile ${filePath} already exists`); @@ -635,8 +634,8 @@ export class ChangeAction extends BaseRushAction { { name: 'overwrite', type: 'confirm', - message: `Overwrite ${filePath}?` - } + message: `Overwrite ${filePath}?`, + }, ]); if (overwrite) { diff --git a/apps/rush-lib/src/cli/actions/CheckAction.ts b/apps/rush-lib/src/cli/actions/CheckAction.ts index c89ba9bf706..74f14b3d56c 100644 --- a/apps/rush-lib/src/cli/actions/CheckAction.ts +++ b/apps/rush-lib/src/cli/actions/CheckAction.ts @@ -2,10 +2,7 @@ // See LICENSE in the project root for license information. import * as colors from 'colors'; -import { - CommandLineStringParameter, - CommandLineFlagParameter -} from '@rushstack/ts-command-line'; +import { CommandLineStringParameter, CommandLineFlagParameter } from '@rushstack/ts-command-line'; import { RushCommandLineParser } from '../RushCommandLineParser'; import { BaseRushAction } from './BaseRushAction'; @@ -19,12 +16,14 @@ export class CheckAction extends BaseRushAction { public constructor(parser: RushCommandLineParser) { super({ actionName: 'check', - summary: 'Checks each project\'s package.json files and ensures that all dependencies are of the same ' + + summary: + "Checks each project's package.json files and ensures that all dependencies are of the same " + 'version throughout the repository.', - documentation: 'Checks each project\'s package.json files and ensures that all dependencies are of the ' + + documentation: + "Checks each project's package.json files and ensures that all dependencies are of the " + 'same version throughout the repository.', safeForSimultaneousRushProcesses: true, - parser + parser, }); } @@ -32,7 +31,7 @@ export class CheckAction extends BaseRushAction { this._variant = this.defineStringParameter(Variants.VARIANT_PARAMETER); this._jsonFlag = this.defineFlagParameter({ parameterLongName: '--json', - description: 'If this flag is specified, output will be in JSON format.' + description: 'If this flag is specified, output will be in JSON format.', }); } @@ -40,15 +39,17 @@ export class CheckAction extends BaseRushAction { const variant: string | undefined = this.rushConfiguration.currentInstalledVariant; if (!this._variant.value && variant) { - console.log(colors.yellow( - `Variant '${variant}' has been installed, but 'rush check' is currently checking the default variant. ` + - `Use 'rush check --variant '${ variant }' to check the current installation.` - )); + console.log( + colors.yellow( + `Variant '${variant}' has been installed, but 'rush check' is currently checking the default variant. ` + + `Use 'rush check --variant '${variant}' to check the current installation.` + ) + ); } VersionMismatchFinder.rushCheck(this.rushConfiguration, { variant: this._variant.value, - printAsJson: this._jsonFlag.value + printAsJson: this._jsonFlag.value, }); return Promise.resolve(); } diff --git a/apps/rush-lib/src/cli/actions/DeployAction.ts b/apps/rush-lib/src/cli/actions/DeployAction.ts index d5029b5b654..c7e26f69c90 100644 --- a/apps/rush-lib/src/cli/actions/DeployAction.ts +++ b/apps/rush-lib/src/cli/actions/DeployAction.ts @@ -12,12 +12,13 @@ export class DeployAction extends BaseRushAction { super({ actionName: 'deploy', summary: '(EXPERIMENTAL) Copy a subset of Rush projects and their dependencies to a deployment folder', - documentation: '(EXPERIMENTAL) After building the repo, "rush deploy" can be used to copy a subset of' - + ' Rush projects and their dependencies to a deployment target folder, which can then be copied to' - + ' a production machine. The "rush deploy" behavior is specified by a scenario config file located under' - + ' the "common/config/deploy" folder. You can define multiple scenarios. Use the "rush init-deploy" command' - + ' to create a new config file.', - parser + documentation: + '(EXPERIMENTAL) After building the repo, "rush deploy" can be used to copy a subset of' + + ' Rush projects and their dependencies to a deployment target folder, which can then be copied to' + + ' a production machine. The "rush deploy" behavior is specified by a scenario config file located under' + + ' the "common/config/deploy" folder. You can define multiple scenarios. Use the "rush init-deploy" command' + + ' to create a new config file.', + parser, }); } @@ -29,14 +30,14 @@ export class DeployAction extends BaseRushAction { required: true, description: 'Specifies the name of a config file describing the deployment. ' + - 'For example if SCENARIO is "web", the input file is: common/config/deploy/web.json' + 'For example if SCENARIO is "web", the input file is: common/config/deploy/web.json', }); this._overwrite = this.defineFlagParameter({ parameterLongName: '--overwrite', description: 'By default, deployment will fail if the target folder is not empty. SPECIFYING THIS FLAG ' + - 'WILL RECURSIVELY DELETE EXISTING CONTENTS OF THE TARGET FOLDER.' + 'WILL RECURSIVELY DELETE EXISTING CONTENTS OF THE TARGET FOLDER.', }); this._targetFolder = this.defineStringParameter({ @@ -47,7 +48,7 @@ export class DeployAction extends BaseRushAction { description: 'By default, files are deployed to the common/deploy folder inside the Rush repo.' + ' Use this parameter to specify a different location. ' + - ' WARNING: USE CAUTION WHEN COMBINING WITH "--overwrite"' + ' WARNING: USE CAUTION WHEN COMBINING WITH "--overwrite"', }); } diff --git a/apps/rush-lib/src/cli/actions/InitAction.ts b/apps/rush-lib/src/cli/actions/InitAction.ts index 2265f5f5b50..86f4bcd8caf 100644 --- a/apps/rush-lib/src/cli/actions/InitAction.ts +++ b/apps/rush-lib/src/cli/actions/InitAction.ts @@ -55,24 +55,28 @@ export class InitAction extends BaseConfiglessRushAction { super({ actionName: 'init', summary: 'Initializes a new repository to be managed by Rush', - documentation: 'When invoked in an empty folder, this command provisions a standard' - + ' set of config file templates to start managing projects using Rush.', - parser + documentation: + 'When invoked in an empty folder, this command provisions a standard' + + ' set of config file templates to start managing projects using Rush.', + parser, }); } - protected onDefineParameters(): void { // abstract + protected onDefineParameters(): void { + // abstract this._overwriteParameter = this.defineFlagParameter({ parameterLongName: '--overwrite-existing', - description: 'By default "rush init" will not overwrite existing config files.' - + ' Specify this switch to override that. This can be useful when upgrading' - + ' your repo to a newer release of Rush. WARNING: USE WITH CARE!' + description: + 'By default "rush init" will not overwrite existing config files.' + + ' Specify this switch to override that. This can be useful when upgrading' + + ' your repo to a newer release of Rush. WARNING: USE WITH CARE!', }); this._rushExampleParameter = this.defineFlagParameter({ parameterLongName: '--rush-example-repo', - description: 'When copying the template config files, this uncomments fragments that are used' - + ' by the "rush-example" GitHub repo, which is a sample monorepo that illustrates many Rush' - + ' features. This option is primarily intended for maintaining that example.' + description: + 'When copying the template config files, this uncomments fragments that are used' + + ' by the "rush-example" GitHub repo, which is a sample monorepo that illustrates many Rush' + + ' features. This option is primarily intended for maintaining that example.', }); } @@ -106,10 +110,14 @@ export class InitAction extends BaseConfiglessRushAction { // Check whether it's safe to run "rush init" in the current working directory. private _validateFolderIsEmpty(initFolder: string): boolean { if (this.rushConfiguration !== undefined) { - console.error(colors.red('ERROR: Found an existing configuration in: ' - + this.rushConfiguration.rushJsonFile)); - console.log(os.EOL + 'The "rush init" command must be run in a new folder without ' - + 'an existing Rush configuration.'); + console.error( + colors.red('ERROR: Found an existing configuration in: ' + this.rushConfiguration.rushJsonFile) + ); + console.log( + os.EOL + + 'The "rush init" command must be run in a new folder without ' + + 'an existing Rush configuration.' + ); return false; } @@ -126,12 +134,16 @@ export class InitAction extends BaseConfiglessRushAction { // or "CONTRIBUTING.md" if (stats.isDirectory()) { console.error(colors.red(`ERROR: Found a subdirectory: "${itemName}"`)); - console.log(os.EOL + 'The "rush init" command must be run in a new folder with no projects added yet.'); + console.log( + os.EOL + 'The "rush init" command must be run in a new folder with no projects added yet.' + ); return false; } else { if (itemName.toLowerCase() === 'package.json') { console.error(colors.red(`ERROR: Found a package.json file in this folder`)); - console.log(os.EOL + 'The "rush init" command must be run in a new folder with no projects added yet.'); + console.log( + os.EOL + 'The "rush init" command must be run in a new folder with no projects added yet.' + ); return false; } } @@ -152,7 +164,7 @@ export class InitAction extends BaseConfiglessRushAction { 'common/config/rush/common-versions.json', 'common/config/rush/experiments.json', 'common/config/rush/pnpmfile.js', - 'common/config/rush/version-policies.json' + 'common/config/rush/version-policies.json', ]; const assetsSubfolder: string = path.resolve(__dirname, '../../../assets/rush-init'); @@ -165,8 +177,7 @@ export class InitAction extends BaseConfiglessRushAction { throw new InternalError('Unable to find template input file: ' + sourcePath); } - const destinationPath: string = path.join(initFolder, templateFilePath) - .replace('[dot]', '.'); + const destinationPath: string = path.join(initFolder, templateFilePath).replace('[dot]', '.'); this._copyTemplateFile(sourcePath, destinationPath); } @@ -220,8 +231,9 @@ export class InitAction extends BaseConfiglessRushAction { } const outputLines: string[] = []; - const lines: string[] = FileSystem.readFile(sourcePath, { convertLineEndings: NewlineKind.Lf }) - .split('\n'); + const lines: string[] = FileSystem.readFile(sourcePath, { convertLineEndings: NewlineKind.Lf }).split( + '\n' + ); let activeBlockSectionName: string | undefined = undefined; let activeBlockIndent: string = ''; @@ -235,7 +247,9 @@ export class InitAction extends BaseConfiglessRushAction { if (match) { if (activeBlockSectionName) { // If this happens, please report a Rush bug - throw new InternalError(`The template contains an unmatched BEGIN macro for "${activeBlockSectionName}"`); + throw new InternalError( + `The template contains an unmatched BEGIN macro for "${activeBlockSectionName}"` + ); } activeBlockSectionName = match[2]; @@ -250,18 +264,23 @@ export class InitAction extends BaseConfiglessRushAction { if (match) { if (activeBlockSectionName === undefined) { // If this happens, please report a Rush bug - throw new InternalError(`The template contains an unmatched END macro for "${activeBlockSectionName}"`); + throw new InternalError( + `The template contains an unmatched END macro for "${activeBlockSectionName}"` + ); } if (activeBlockSectionName !== match[2]) { // If this happens, please report a Rush bug - throw new InternalError(`The template contains an mismatched END macro for "${activeBlockSectionName}"`); + throw new InternalError( + `The template contains an mismatched END macro for "${activeBlockSectionName}"` + ); } if (activeBlockIndent !== match[1]) { // If this happens, please report a Rush bug - throw new InternalError(`The template contains an inconsistently indented section` - + ` "${activeBlockSectionName}"`); + throw new InternalError( + `The template contains an inconsistently indented section` + ` "${activeBlockSectionName}"` + ); } activeBlockSectionName = undefined; @@ -293,7 +312,9 @@ export class InitAction extends BaseConfiglessRushAction { match = transformedLine.match(InitAction._anyMacroRegExp); if (match) { // If this happens, please report a Rush bug - throw new InternalError('The template contains a malformed macro expression: ' + JSON.stringify(match[0])); + throw new InternalError( + 'The template contains a malformed macro expression: ' + JSON.stringify(match[0]) + ); } // If we are inside a block section that is commented out, then insert the "//" after indentation @@ -302,8 +323,10 @@ export class InitAction extends BaseConfiglessRushAction { // Is the line indented properly? if (transformedLine.substr(0, activeBlockIndent.length).trim().length > 0) { // If this happens, please report a Rush bug - throw new InternalError(`The template contains inconsistently indented lines inside` - + ` the "${activeBlockSectionName}" section`); + throw new InternalError( + `The template contains inconsistently indented lines inside` + + ` the "${activeBlockSectionName}" section` + ); } // Insert comment characters after the indentation @@ -317,7 +340,7 @@ export class InitAction extends BaseConfiglessRushAction { // Write the output FileSystem.writeFile(destinationPath, outputLines.join('\r\n'), { - ensureFolderExists: true + ensureFolderExists: true, }); } diff --git a/apps/rush-lib/src/cli/actions/InitDeployAction.ts b/apps/rush-lib/src/cli/actions/InitDeployAction.ts index db1133eea56..972d5463cc5 100644 --- a/apps/rush-lib/src/cli/actions/InitDeployAction.ts +++ b/apps/rush-lib/src/cli/actions/InitDeployAction.ts @@ -8,7 +8,10 @@ import { FileSystem, NewlineKind } from '@rushstack/node-core-library'; import { RushConfigurationProject } from '../../api/RushConfigurationProject'; export class InitDeployAction extends BaseRushAction { - private static _CONFIG_TEMPLATE_PATH: string = path.join(__dirname, '../../../assets/rush-deploy-init/scenario-template.json'); + private static _CONFIG_TEMPLATE_PATH: string = path.join( + __dirname, + '../../../assets/rush-deploy-init/scenario-template.json' + ); private _scenario: CommandLineStringParameter; private _project: CommandLineStringParameter; @@ -16,9 +19,10 @@ export class InitDeployAction extends BaseRushAction { super({ actionName: 'init-deploy', summary: 'Create the config file for a new deployment scenario.', - documentation: 'The deployment config files are stored under "common/config/deploy" and are used' - + ' to configure behavior of the "rush deploy" command.', - parser + documentation: + 'The deployment config files are stored under "common/config/deploy" and are used' + + ' to configure behavior of the "rush deploy" command.', + parser, }); } @@ -30,14 +34,14 @@ export class InitDeployAction extends BaseRushAction { required: true, description: 'Specifies the name of the config file describing the deployment. ' + - 'The name must be lower case and separated by dashes. Example: "production-web"' + 'The name must be lower case and separated by dashes. Example: "production-web"', }); this._project = this.defineStringParameter({ parameterLongName: '--project', parameterShortName: '-p', argumentName: 'PROJECT_NAME', required: true, - description: 'Specifies the name of the main Rush project to be deployed in this scenario.' + description: 'Specifies the name of the main Rush project to be deployed in this scenario.', }); } @@ -45,28 +49,38 @@ export class InitDeployAction extends BaseRushAction { const scenarioName: string = this._scenario.value!; DeployManager.validateScenarioName(scenarioName); - const scenarioFilePath: string = path.join(this.rushConfiguration.commonDeployConfigFolder,`${scenarioName}.json`); + const scenarioFilePath: string = path.join( + this.rushConfiguration.commonDeployConfigFolder, + `${scenarioName}.json` + ); if (FileSystem.exists(scenarioFilePath)) { - throw new Error('The target file already exists:\n' + scenarioFilePath + - '\nIf you intend to replace it, please delete the old file first.'); + throw new Error( + 'The target file already exists:\n' + + scenarioFilePath + + '\nIf you intend to replace it, please delete the old file first.' + ); } console.log(colors.green('Creating scenario file: ') + scenarioFilePath); const shortProjectName: string = this._project.value!; - const rushProject: RushConfigurationProject | undefined - = this.rushConfiguration.findProjectByShorthandName(shortProjectName); + const rushProject: + | RushConfigurationProject + | undefined = this.rushConfiguration.findProjectByShorthandName(shortProjectName); if (!rushProject) { throw new Error(`The specified project was not found in rush.json: "${shortProjectName}"`); } const templateContent: string = FileSystem.readFile(InitDeployAction._CONFIG_TEMPLATE_PATH); - const expandedContent: string = templateContent.replace('[%PROJECT_NAME_TO_DEPLOY%]', rushProject.packageName); + const expandedContent: string = templateContent.replace( + '[%PROJECT_NAME_TO_DEPLOY%]', + rushProject.packageName + ); FileSystem.writeFile(scenarioFilePath, expandedContent, { ensureFolderExists: true, - convertLineEndings: NewlineKind.OsDefault + convertLineEndings: NewlineKind.OsDefault, }); console.log('\nFile successfully written. Please review the file contents before committing.'); diff --git a/apps/rush-lib/src/cli/actions/InstallAction.ts b/apps/rush-lib/src/cli/actions/InstallAction.ts index 28ee9a9a3ab..2189e2a8c3b 100644 --- a/apps/rush-lib/src/cli/actions/InstallAction.ts +++ b/apps/rush-lib/src/cli/actions/InstallAction.ts @@ -10,17 +10,18 @@ export class InstallAction extends BaseInstallAction { super({ actionName: 'install', summary: 'Install package dependencies for all projects in the repo according to the shrinkwrap file', - documentation: 'The "rush install" command installs package dependencies for all your projects,' - + ' based on the shrinkwrap file that is created/updated using "rush update".' - + ' (This "shrinkwrap" file stores a central inventory of all dependencies and versions' - + ' for projects in your repo. It is found in the "common/config/rush" folder.)' - + ' If the shrinkwrap file is missing or outdated (e.g. because project package.json files have' - + ' changed), "rush install" will fail and tell you to run "rush update" instead.' - + ' This read-only nature is the main feature: Continuous integration builds should use' - + ' "rush install" instead of "rush update" to catch developers who forgot to commit their' - + ' shrinkwrap changes. Cautious people can also use "rush install" if they want to avoid' - + ' accidentally updating their shrinkwrap file.', - parser + documentation: + 'The "rush install" command installs package dependencies for all your projects,' + + ' based on the shrinkwrap file that is created/updated using "rush update".' + + ' (This "shrinkwrap" file stores a central inventory of all dependencies and versions' + + ' for projects in your repo. It is found in the "common/config/rush" folder.)' + + ' If the shrinkwrap file is missing or outdated (e.g. because project package.json files have' + + ' changed), "rush install" will fail and tell you to run "rush update" instead.' + + ' This read-only nature is the main feature: Continuous integration builds should use' + + ' "rush install" instead of "rush update" to catch developers who forgot to commit their' + + ' shrinkwrap changes. Cautious people can also use "rush install" if they want to avoid' + + ' accidentally updating their shrinkwrap file.', + parser, }); } @@ -37,7 +38,7 @@ export class InstallAction extends BaseInstallAction { variant: this._variant.value, // Because the 'defaultValue' option on the _maxInstallAttempts parameter is set, // it is safe to assume that the value is not null - maxInstallAttempts: this._maxInstallAttempts.value! + maxInstallAttempts: this._maxInstallAttempts.value!, }; } } diff --git a/apps/rush-lib/src/cli/actions/LinkAction.ts b/apps/rush-lib/src/cli/actions/LinkAction.ts index d910eeb8265..138ae5b4b31 100644 --- a/apps/rush-lib/src/cli/actions/LinkAction.ts +++ b/apps/rush-lib/src/cli/actions/LinkAction.ts @@ -15,11 +15,12 @@ export class LinkAction extends BaseRushAction { super({ actionName: 'link', summary: 'Create node_modules symlinks for all projects', - documentation: 'Create node_modules symlinks for all projects. This operation is normally performed' - + ' automatically as part of "rush install" or "rush update". You should only need to use "rush link"' - + ' if you performed "rush unlink" for some reason, or if you specified the "--no-link" option' - + ' for "rush install" or "rush update".', - parser + documentation: + 'Create node_modules symlinks for all projects. This operation is normally performed' + + ' automatically as part of "rush install" or "rush update". You should only need to use "rush link"' + + ' if you performed "rush unlink" for some reason, or if you specified the "--no-link" option' + + ' for "rush install" or "rush update".', + parser, }); } @@ -27,8 +28,9 @@ export class LinkAction extends BaseRushAction { this._force = this.defineFlagParameter({ parameterLongName: '--force', parameterShortName: '-f', - description: 'Deletes and recreates all links, even if the filesystem state seems to indicate that this is ' + - 'unnecessary.' + description: + 'Deletes and recreates all links, even if the filesystem state seems to indicate that this is ' + + 'unnecessary.', }); } diff --git a/apps/rush-lib/src/cli/actions/ListAction.ts b/apps/rush-lib/src/cli/actions/ListAction.ts index cdbb99c2dbf..cddd53d595b 100644 --- a/apps/rush-lib/src/cli/actions/ListAction.ts +++ b/apps/rush-lib/src/cli/actions/ListAction.ts @@ -4,7 +4,6 @@ import { CommandLineFlagParameter } from '@rushstack/ts-command-line'; import { RushConfigurationProject } from '../../api/RushConfigurationProject'; import * as Table from 'cli-table'; - export interface IJsonEntry { name: string; version: string; @@ -30,7 +29,7 @@ export class ListAction extends BaseRushAction { 'List package names, and optionally version (--version) and ' + 'path (--path) or full path (--full-path), for projects in the ' + 'current rush config.', - parser + parser, }); } @@ -40,7 +39,7 @@ export class ListAction extends BaseRushAction { parameterShortName: '-v', description: 'If this flag is specified, the project version will be ' + - 'displayed in a column along with the package name.' + 'displayed in a column along with the package name.', }); this._path = this.defineFlagParameter({ @@ -48,7 +47,7 @@ export class ListAction extends BaseRushAction { parameterShortName: '-p', description: 'If this flag is specified, the project path will be ' + - 'displayed in a column along with the package name.' + 'displayed in a column along with the package name.', }); this._fullPath = this.defineFlagParameter({ @@ -56,12 +55,12 @@ export class ListAction extends BaseRushAction { parameterShortName: '-f', description: 'If this flag is specified, the project full path will ' + - 'be displayed in a column along with the package name.' + 'be displayed in a column along with the package name.', }); this._jsonFlag = this.defineFlagParameter({ parameterLongName: '--json', - description: 'If this flag is specified, output will be in JSON format.' + description: 'If this flag is specified, output will be in JSON format.', }); } @@ -76,37 +75,31 @@ export class ListAction extends BaseRushAction { } } - private _printJson( - allPackages: Map - ): void { + private _printJson(allPackages: Map): void { const projects: IJsonEntry[] = []; allPackages.forEach((_config: RushConfigurationProject, name: string) => { const project: IJsonEntry = { name: name, version: _config.packageJson.version, path: _config.projectRelativeFolder, - fullPath: _config.projectFolder + fullPath: _config.projectFolder, }; projects.push(project); }); const output: IJsonOutput = { - projects + projects, }; console.log(JSON.stringify(output, undefined, 2)); } - private _printList( - allPackages: Map - ): void { + private _printList(allPackages: Map): void { allPackages.forEach((_config: RushConfigurationProject, name: string) => { console.log(name); }); } - private _printListTable( - allPackages: Map - ): void { + private _printListTable(allPackages: Map): void { const tableHeader: string[] = ['Project']; if (this._version.value) { tableHeader.push('Version'); @@ -118,7 +111,7 @@ export class ListAction extends BaseRushAction { tableHeader.push('Full Path'); } const table: Table = new Table({ - head: tableHeader + head: tableHeader, }); allPackages.forEach((config: RushConfigurationProject, name: string) => { diff --git a/apps/rush-lib/src/cli/actions/PublishAction.ts b/apps/rush-lib/src/cli/actions/PublishAction.ts index e130e6cf598..9f3dc286a31 100644 --- a/apps/rush-lib/src/cli/actions/PublishAction.ts +++ b/apps/rush-lib/src/cli/actions/PublishAction.ts @@ -7,14 +7,11 @@ import * as path from 'path'; import { CommandLineFlagParameter, CommandLineStringParameter, - CommandLineChoiceParameter + CommandLineChoiceParameter, } from '@rushstack/ts-command-line'; import { FileSystem } from '@rushstack/node-core-library'; -import { - IChangeInfo, - ChangeType -} from '../../api/ChangeManagement'; +import { IChangeInfo, ChangeType } from '../../api/ChangeManagement'; import { RushConfigurationProject } from '../../api/RushConfigurationProject'; import { Npm } from '../../utilities/Npm'; import { RushCommandLineParser } from '../RushCommandLineParser'; @@ -61,10 +58,10 @@ export class PublishAction extends BaseRushAction { actionName: 'publish', summary: 'Reads and processes package publishing change requests generated by "rush change".', documentation: - 'Reads and processes package publishing change requests generated by "rush change". This will perform a ' + - 'read-only operation by default, printing operations executed to the console. To commit ' + - 'changes and publish packages, you must use the --commit flag and/or the --publish flag.', - parser + 'Reads and processes package publishing change requests generated by "rush change". This will perform a ' + + 'read-only operation by default, printing operations executed to the console. To commit ' + + 'changes and publish packages, you must use the --commit flag and/or the --publish flag.', + parser, }); } @@ -72,30 +69,30 @@ export class PublishAction extends BaseRushAction { this._apply = this.defineFlagParameter({ parameterLongName: '--apply', parameterShortName: '-a', - description: 'If this flag is specified, the change requests will be applied to package.json files.' + description: 'If this flag is specified, the change requests will be applied to package.json files.', }); this._targetBranch = this.defineStringParameter({ parameterLongName: '--target-branch', parameterShortName: '-b', argumentName: 'BRANCH', description: - 'If this flag is specified, applied changes and deleted change requests will be ' + - 'committed and merged into the target branch.' + 'If this flag is specified, applied changes and deleted change requests will be ' + + 'committed and merged into the target branch.', }); this._publish = this.defineFlagParameter({ parameterLongName: '--publish', parameterShortName: '-p', - description: 'If this flag is specified, applied changes will be published to npm.' + description: 'If this flag is specified, applied changes will be published to npm.', }); this._addCommitDetails = this.defineFlagParameter({ parameterLongName: '--add-commit-details', parameterShortName: undefined, - description: 'Adds commit author and hash to the changelog.json files for each change.' + description: 'Adds commit author and hash to the changelog.json files for each change.', }); this._regenerateChangelogs = this.defineFlagParameter({ parameterLongName: '--regenerate-changelogs', parameterShortName: undefined, - description: 'Regenerates all changelog files based on the current JSON content.' + description: 'Regenerates all changelog files based on the current JSON content.', }); // NPM registry related parameters @@ -104,35 +101,35 @@ export class PublishAction extends BaseRushAction { parameterShortName: '-r', argumentName: 'REGISTRY', description: - `Publishes to a specified NPM registry. If this is specified, it will prevent the current commit will not be ` + - 'tagged.' + `Publishes to a specified NPM registry. If this is specified, it will prevent the current commit will not be ` + + 'tagged.', }); this._npmAuthToken = this.defineStringParameter({ parameterLongName: '--npm-auth-token', parameterShortName: '-n', argumentName: 'TOKEN', description: - 'Provide the default scope NPM auth token to be passed into npm publish for global package publishing.' + 'Provide the default scope NPM auth token to be passed into npm publish for global package publishing.', }); this._npmTag = this.defineStringParameter({ parameterLongName: '--tag', parameterShortName: '-t', argumentName: 'TAG', description: - `The tag option to pass to npm publish. By default NPM will publish using the 'latest' tag, even if ` + - `the package is older than the current latest, so in publishing workflows for older releases, providing ` + - `a tag is important. When hotfix changes are made, this parameter defaults to 'hotfix'.` + `The tag option to pass to npm publish. By default NPM will publish using the 'latest' tag, even if ` + + `the package is older than the current latest, so in publishing workflows for older releases, providing ` + + `a tag is important. When hotfix changes are made, this parameter defaults to 'hotfix'.`, }); this._npmAccessLevel = this.defineChoiceParameter({ alternatives: ['public', 'restricted'], parameterLongName: '--set-access-level', parameterShortName: undefined, description: - `By default, when Rush invokes "npm publish" it will publish scoped packages with an access level ` + - `of "restricted". Scoped packages can be published with an access level of "public" by specifying ` + - `that value for this flag with the initial publication. NPM always publishes unscoped packages with ` + - `an access level of "public". For more information, see the NPM documentation for the "--access" ` + - `option of "npm publish".` + `By default, when Rush invokes "npm publish" it will publish scoped packages with an access level ` + + `of "restricted". Scoped packages can be published with an access level of "public" by specifying ` + + `that value for this flag with the initial publication. NPM always publishes unscoped packages with ` + + `an access level of "public". For more information, see the NPM documentation for the "--access" ` + + `option of "npm publish".`, }); // NPM pack tarball related parameters @@ -140,61 +137,67 @@ export class PublishAction extends BaseRushAction { parameterLongName: '--pack', description: `Packs projects into tarballs instead of publishing to npm repository. It can only be used when ` + - `--include-all is specified. If this flag is specified, NPM registry related parameters will be ignored.` + `--include-all is specified. If this flag is specified, NPM registry related parameters will be ignored.`, }); this._releaseFolder = this.defineStringParameter({ parameterLongName: '--release-folder', argumentName: 'FOLDER', description: - `This parameter is used with --pack parameter to provide customized location for the tarballs instead of ` + - `the default value. ` + `This parameter is used with --pack parameter to provide customized location for the tarballs instead of ` + + `the default value. `, }); // End of NPM pack tarball related parameters this._includeAll = this.defineFlagParameter({ parameterLongName: '--include-all', parameterShortName: undefined, - description: 'If this flag is specified, all packages with shouldPublish=true in rush.json ' + - 'or with a specified version policy ' + - 'will be published if their version is newer than published version.' + description: + 'If this flag is specified, all packages with shouldPublish=true in rush.json ' + + 'or with a specified version policy ' + + 'will be published if their version is newer than published version.', }); this._versionPolicy = this.defineStringParameter({ parameterLongName: '--version-policy', argumentName: 'POLICY', - description: 'Version policy name. Only projects with this version policy will be published if used ' + - 'with --include-all.' + description: + 'Version policy name. Only projects with this version policy will be published if used ' + + 'with --include-all.', }); this._prereleaseName = this.defineStringParameter({ parameterLongName: '--prerelease-name', argumentName: 'NAME', - description: 'Bump up to a prerelease version with the provided prerelease name. Cannot be used with --suffix' + description: + 'Bump up to a prerelease version with the provided prerelease name. Cannot be used with --suffix', }); this._partialPrerelease = this.defineFlagParameter({ parameterLongName: '--partial-prerelease', parameterShortName: undefined, - description: 'Used with --prerelease-name. Only bump packages to a prerelease version if they have changes.' + description: + 'Used with --prerelease-name. Only bump packages to a prerelease version if they have changes.', }); this._suffix = this.defineStringParameter({ parameterLongName: '--suffix', argumentName: 'SUFFIX', - description: 'Append a suffix to all changed versions. Cannot be used with --prerelease-name.' + description: 'Append a suffix to all changed versions. Cannot be used with --prerelease-name.', }); this._force = this.defineFlagParameter({ parameterLongName: '--force', parameterShortName: undefined, - description: 'If this flag is specified with --publish, packages will be published with --force on npm' + description: 'If this flag is specified with --publish, packages will be published with --force on npm', }); this._applyGitTagsOnPack = this.defineFlagParameter({ parameterLongName: '--apply-git-tags-on-pack', - description: `If specified with --publish and --pack, git tags will be applied for packages` + - ` as if a publish was being run without --pack.` + description: + `If specified with --publish and --pack, git tags will be applied for packages` + + ` as if a publish was being run without --pack.`, }); this._commitId = this.defineStringParameter({ parameterLongName: '--commit', parameterShortName: '-c', argumentName: 'COMMIT_ID', - description: `Used in conjunction with git tagging -- apply git tags at the commit hash` + - ` specified. If not provided, the current HEAD will be tagged.` + description: + `Used in conjunction with git tagging -- apply git tags at the commit hash` + + ` specified. If not provided, the current HEAD will be tagged.`, }); } @@ -249,16 +252,17 @@ export class PublishAction extends BaseRushAction { throw new Error(`--release-folder can only be used with --pack`); } if (this._applyGitTagsOnPack.value && !this._pack.value) { - throw new Error(`${this._applyGitTagsOnPack.longName} must be used ` - + `with ${this._pack.longName}`); + throw new Error(`${this._applyGitTagsOnPack.longName} must be used ` + `with ${this._pack.longName}`); } } private _publishChanges(allPackages: Map): void { const changeManager: ChangeManager = new ChangeManager(this.rushConfiguration); - changeManager.load(this.rushConfiguration.changesFolder, + changeManager.load( + this.rushConfiguration.changesFolder, this._prereleaseToken, - this._addCommitDetails.value); + this._addCommitDetails.value + ); if (changeManager.hasChanges()) { const orderedChanges: IChangeInfo[] = changeManager.changes; @@ -334,7 +338,8 @@ export class PublishAction extends BaseRushAction { const git: PublishGit = new PublishGit(this._targetBranch.value); allPackages.forEach((packageConfig, packageName) => { - if (packageConfig.shouldPublish && + if ( + packageConfig.shouldPublish && (!this._versionPolicy.value || this._versionPolicy.value === packageConfig.versionPolicyName) ) { const applyTag: (apply: boolean) => void = (apply: boolean): void => { @@ -346,7 +351,9 @@ export class PublishAction extends BaseRushAction { // Do not create a new tag if one already exists, this will result in a fatal error if (git.hasTag(packageConfig)) { - console.log(`Not tagging ${packageName}@${packageVersion}. A tag already exists for this version.`); + console.log( + `Not tagging ${packageName}@${packageVersion}. A tag already exists for this version.` + ); return; } @@ -379,7 +386,12 @@ export class PublishAction extends BaseRushAction { change.changeType > ChangeType.dependency && this.rushConfiguration.projectsByName.get(change.packageName)!.shouldPublish ) { - git.addTag(!!this._publish.value && !this._registryUrl.value, change.packageName, change.newVersion!, this._commitId.value); + git.addTag( + !!this._publish.value && !this._registryUrl.value, + change.packageName, + change.newVersion!, + this._commitId.value + ); } } } @@ -408,8 +420,10 @@ export class PublishAction extends BaseRushAction { // TODO: Yarn's "publish" command line is fairly different from NPM and PNPM. The right thing to do here // would be to remap our options to the Yarn equivalents. But until we get around to that, we'll simply invoke // whatever NPM binary happens to be installed in the global path. - const packageManagerToolFilename: string = this.rushConfiguration.packageManager === 'yarn' - ? 'npm' : this.rushConfiguration.packageManagerToolFilename; + const packageManagerToolFilename: string = + this.rushConfiguration.packageManager === 'yarn' + ? 'npm' + : this.rushConfiguration.packageManagerToolFilename; // If the auth token was specified via the command line, avoid printing it on the console const secretSubstring: string | undefined = this._npmAuthToken.value; @@ -420,7 +434,8 @@ export class PublishAction extends BaseRushAction { args, packagePath, env, - secretSubstring); + secretSubstring + ); } } @@ -429,10 +444,12 @@ export class PublishAction extends BaseRushAction { const args: string[] = []; this._addSharedNpmConfig(env, args); - const publishedVersions: string[] = Npm.publishedVersions(packageConfig.packageName, + const publishedVersions: string[] = Npm.publishedVersions( + packageConfig.packageName, packageConfig.projectFolder, env, - args); + args + ); return publishedVersions.indexOf(packageConfig.packageJson.version) >= 0; } @@ -452,13 +469,14 @@ export class PublishAction extends BaseRushAction { // Copy the tarball the release folder const tarballName: string = this._calculateTarballName(project); const tarballPath: string = path.join(project.projectFolder, tarballName); - const destFolder: string = this._releaseFolder.value ? - this._releaseFolder.value : path.join(this.rushConfiguration.commonTempFolder, 'artifacts', 'packages'); + const destFolder: string = this._releaseFolder.value + ? this._releaseFolder.value + : path.join(this.rushConfiguration.commonTempFolder, 'artifacts', 'packages'); FileSystem.move({ sourcePath: tarballPath, destinationPath: path.join(destFolder, tarballName), - overwrite: true + overwrite: true, }); } } @@ -509,7 +527,7 @@ export class PublishAction extends BaseRushAction { } private _addSharedNpmConfig(env: { [key: string]: string | undefined }, args: string[]): void { - const userHomeEnvVariable: string = (process.platform === 'win32') ? 'USERPROFILE' : 'HOME'; + const userHomeEnvVariable: string = process.platform === 'win32' ? 'USERPROFILE' : 'HOME'; let registry: string = '//registry.npmjs.org/'; // Check if .npmrc file exists in "common\temp\publish-home" @@ -529,4 +547,4 @@ export class PublishAction extends BaseRushAction { args.push(`--${registry}:_authToken=${this._npmAuthToken.value}`); } } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/cli/actions/PurgeAction.ts b/apps/rush-lib/src/cli/actions/PurgeAction.ts index e18b0db4af0..effba82e2f4 100644 --- a/apps/rush-lib/src/cli/actions/PurgeAction.ts +++ b/apps/rush-lib/src/cli/actions/PurgeAction.ts @@ -18,19 +18,22 @@ export class PurgeAction extends BaseRushAction { public constructor(parser: RushCommandLineParser) { super({ actionName: 'purge', - summary: 'For diagnostic purposes, use this command to delete caches and other temporary files used by Rush', - documentation: 'The "rush purge" command is used to delete temporary files created by Rush. This is' - + ' useful if you are having problems and suspect that cache files may be corrupt.', - parser + summary: + 'For diagnostic purposes, use this command to delete caches and other temporary files used by Rush', + documentation: + 'The "rush purge" command is used to delete temporary files created by Rush. This is' + + ' useful if you are having problems and suspect that cache files may be corrupt.', + parser, }); } protected onDefineParameters(): void { this._unsafeParameter = this.defineFlagParameter({ parameterLongName: '--unsafe', - description: '(UNSAFE!) Also delete shared files such as the package manager instances stored in' - + ' the ".rush" folder in the user\'s home directory. This is a more aggressive fix that is' - + ' NOT SAFE to run in a live environment because it will cause other concurrent Rush processes to fail.' + description: + '(UNSAFE!) Also delete shared files such as the package manager instances stored in' + + ' the ".rush" folder in the user\'s home directory. This is a more aggressive fix that is' + + ' NOT SAFE to run in a live environment because it will cause other concurrent Rush processes to fail.', }); } @@ -51,8 +54,12 @@ export class PurgeAction extends BaseRushAction { purgeManager.deleteAll(); - console.log(os.EOL + colors.green(`Rush purge started successfully and will complete asynchronously.` - + ` (${stopwatch.toString()})`)); + console.log( + os.EOL + + colors.green( + `Rush purge started successfully and will complete asynchronously.` + ` (${stopwatch.toString()})` + ) + ); }); } } diff --git a/apps/rush-lib/src/cli/actions/ScanAction.ts b/apps/rush-lib/src/cli/actions/ScanAction.ts index 4f161fac922..8392c9b2957 100644 --- a/apps/rush-lib/src/cli/actions/ScanAction.ts +++ b/apps/rush-lib/src/cli/actions/ScanAction.ts @@ -15,16 +15,17 @@ export class ScanAction extends BaseConfiglessRushAction { super({ actionName: 'scan', summary: 'Scan the current project folder and display a report of imported packages.', - documentation: `The NPM system allows a project to import dependencies without explicitly` - + ` listing them in its package.json file. This is a dangerous practice, because` - + ` there is no guarantee you will get a compatible version. The "rush scan" command` - + ` reports a list of packages that are imported by your code, which you can` - + ` compare against your package.json file to find mistakes. It searches the "./src"` - + ` and "./lib" folders for typical import syntaxes such as "import __ from '__'",` - + ` "require('__')", "System.import('__'), etc. The results are only approximate,` - + ` but generally pretty accurate.`, + documentation: + `The NPM system allows a project to import dependencies without explicitly` + + ` listing them in its package.json file. This is a dangerous practice, because` + + ` there is no guarantee you will get a compatible version. The "rush scan" command` + + ` reports a list of packages that are imported by your code, which you can` + + ` compare against your package.json file to find mistakes. It searches the "./src"` + + ` and "./lib" folders for typical import syntaxes such as "import __ from '__'",` + + ` "require('__')", "System.import('__'), etc. The results are only approximate,` + + ` but generally pretty accurate.`, safeForSimultaneousRushProcesses: true, - parser + parser, }); } @@ -70,7 +71,7 @@ export class ScanAction extends BaseConfiglessRushAction { // Example: // /// - /\/\/\/\s*<\s*reference\s+types\s*=\s*["]([^"]+)["]\s*\/>/ + /\/\/\/\s*<\s*reference\s+types\s*=\s*["]([^"]+)["]\s*\/>/, ]; // Example: "my-package/lad/dee/dah" --> "my-package" diff --git a/apps/rush-lib/src/cli/actions/UnlinkAction.ts b/apps/rush-lib/src/cli/actions/UnlinkAction.ts index cf0b205815f..0538cd71316 100644 --- a/apps/rush-lib/src/cli/actions/UnlinkAction.ts +++ b/apps/rush-lib/src/cli/actions/UnlinkAction.ts @@ -12,10 +12,11 @@ export class UnlinkAction extends BaseRushAction { super({ actionName: 'unlink', summary: 'Delete node_modules symlinks for all projects in the repo', - documentation: 'This removes the symlinks created by the "rush link" command. This is useful for' - + ' cleaning a repo using "git clean" without accidentally deleting source files, or for using standard NPM' - + ' commands on a project.', - parser + documentation: + 'This removes the symlinks created by the "rush link" command. This is useful for' + + ' cleaning a repo using "git clean" without accidentally deleting source files, or for using standard NPM' + + ' commands on a project.', + parser, }); } diff --git a/apps/rush-lib/src/cli/actions/UpdateAction.ts b/apps/rush-lib/src/cli/actions/UpdateAction.ts index 957cd6b9fb5..657b7799ecb 100644 --- a/apps/rush-lib/src/cli/actions/UpdateAction.ts +++ b/apps/rush-lib/src/cli/actions/UpdateAction.ts @@ -14,19 +14,21 @@ export class UpdateAction extends BaseInstallAction { public constructor(parser: RushCommandLineParser) { super({ actionName: 'update', - summary: 'Install package dependencies for all projects in the repo,' - + ' and create or update the shrinkwrap file as needed', - documentation: 'The "rush update" command installs the dependencies described in your' - + ' package.json files, and updates the shrinkwrap file as needed.' - + ' (This "shrinkwrap" file stores a central inventory of all dependencies and versions' - + ' for projects in your repo. It is found in the "common/config/rush" folder.)' - + ' Note that Rush always performs a single install for all projects in your repo.' - + ' You should run "rush update" whenever you start working in a Rush repo,' - + ' after you pull from Git, and after you modify a package.json file.' - + ' If there is nothing to do, "rush update" is instantaneous.' - + ' NOTE: In certain cases "rush install" should be used instead of "rush update"' - + ' -- for details, see the command help for "rush install".', - parser + summary: + 'Install package dependencies for all projects in the repo,' + + ' and create or update the shrinkwrap file as needed', + documentation: + 'The "rush update" command installs the dependencies described in your' + + ' package.json files, and updates the shrinkwrap file as needed.' + + ' (This "shrinkwrap" file stores a central inventory of all dependencies and versions' + + ' for projects in your repo. It is found in the "common/config/rush" folder.)' + + ' Note that Rush always performs a single install for all projects in your repo.' + + ' You should run "rush update" whenever you start working in a Rush repo,' + + ' after you pull from Git, and after you modify a package.json file.' + + ' If there is nothing to do, "rush update" is instantaneous.' + + ' NOTE: In certain cases "rush install" should be used instead of "rush update"' + + ' -- for details, see the command help for "rush install".', + parser, }); } @@ -35,20 +37,22 @@ export class UpdateAction extends BaseInstallAction { this._fullParameter = this.defineFlagParameter({ parameterLongName: '--full', - description: 'Normally "rush update" tries to preserve your existing installed versions' - + ' and only makes the minimum updates needed to satisfy the package.json files.' - + ' This conservative approach prevents your PR from getting involved with package updates that' - + ' are unrelated to your work. Use "--full" when you really want to update all dependencies' - + ' to the latest SemVer-compatible version. This should be done periodically by a person' - + ' or robot whose role is to deal with potential upgrade regressions.' + description: + 'Normally "rush update" tries to preserve your existing installed versions' + + ' and only makes the minimum updates needed to satisfy the package.json files.' + + ' This conservative approach prevents your PR from getting involved with package updates that' + + ' are unrelated to your work. Use "--full" when you really want to update all dependencies' + + ' to the latest SemVer-compatible version. This should be done periodically by a person' + + ' or robot whose role is to deal with potential upgrade regressions.', }); this._recheckParameter = this.defineFlagParameter({ parameterLongName: '--recheck', - description: 'If the shrinkwrap file appears to already satisfy the package.json files,' - + ' then "rush update" will skip invoking the package manager at all. In certain situations' - + ' this heuristic may be inaccurate. Use the "--recheck" flag to force the package manager' - + ' to process the shrinkwrap file. This will also update your shrinkwrap file with Rush\'s fixups.' - + ' (To minimize shrinkwrap churn, these fixups are normally performed only in the temporary folder.)' + description: + 'If the shrinkwrap file appears to already satisfy the package.json files,' + + ' then "rush update" will skip invoking the package manager at all. In certain situations' + + ' this heuristic may be inaccurate. Use the "--recheck" flag to force the package manager' + + " to process the shrinkwrap file. This will also update your shrinkwrap file with Rush's fixups." + + ' (To minimize shrinkwrap churn, these fixups are normally performed only in the temporary folder.)', }); } @@ -65,7 +69,7 @@ export class UpdateAction extends BaseInstallAction { variant: this._variant.value, // Because the 'defaultValue' option on the _maxInstallAttempts parameter is set, // it is safe to assume that the value is not null - maxInstallAttempts: this._maxInstallAttempts.value! + maxInstallAttempts: this._maxInstallAttempts.value!, }; } } diff --git a/apps/rush-lib/src/cli/actions/VersionAction.ts b/apps/rush-lib/src/cli/actions/VersionAction.ts index e06fa0c0fec..c86978cb7ea 100644 --- a/apps/rush-lib/src/cli/actions/VersionAction.ts +++ b/apps/rush-lib/src/cli/actions/VersionAction.ts @@ -2,14 +2,8 @@ // See LICENSE in the project root for license information. import * as semver from 'semver'; -import { - IPackageJson, - FileConstants -} from '@rushstack/node-core-library'; -import { - CommandLineFlagParameter, - CommandLineStringParameter -} from '@rushstack/ts-command-line'; +import { IPackageJson, FileConstants } from '@rushstack/node-core-library'; +import { CommandLineFlagParameter, CommandLineStringParameter } from '@rushstack/ts-command-line'; import { BumpType, LockStepVersionPolicy } from '../../api/VersionPolicy'; import { VersionPolicyConfiguration } from '../../api/VersionPolicyConfiguration'; @@ -41,8 +35,9 @@ export class VersionAction extends BaseRushAction { super({ actionName: 'version', summary: '(EXPERIMENTAL) Manage package versions in the repo.', - documentation: '(EXPERIMENTAL) use this "rush version" command to ensure version policies and bump versions.', - parser + documentation: + '(EXPERIMENTAL) use this "rush version" command to ensure version policies and bump versions.', + parser, }); } @@ -51,47 +46,49 @@ export class VersionAction extends BaseRushAction { parameterLongName: '--target-branch', parameterShortName: '-b', argumentName: 'BRANCH', - description: - 'If this flag is specified, changes will be committed and merged into the target branch.' + description: 'If this flag is specified, changes will be committed and merged into the target branch.', }); this._ensureVersionPolicy = this.defineFlagParameter({ parameterLongName: '--ensure-version-policy', - description: 'Updates package versions if needed to satisfy version policies.' + description: 'Updates package versions if needed to satisfy version policies.', }); this._overrideVersion = this.defineStringParameter({ parameterLongName: '--override-version', argumentName: 'NEW_VERSION', - description: 'Override the version in the specified --version-policy. ' + - 'This setting only works for lock-step version policy and when --ensure-version-policy is specified.' + description: + 'Override the version in the specified --version-policy. ' + + 'This setting only works for lock-step version policy and when --ensure-version-policy is specified.', }); this._bumpVersion = this.defineFlagParameter({ parameterLongName: '--bump', - description: 'Bumps package version based on version policies.' + description: 'Bumps package version based on version policies.', }); this._bypassPolicy = this.defineFlagParameter({ parameterLongName: '--bypass-policy', - description: 'Overrides "gitPolicy" enforcement (use honorably!)' + description: 'Overrides "gitPolicy" enforcement (use honorably!)', }); this._versionPolicy = this.defineStringParameter({ parameterLongName: '--version-policy', argumentName: 'POLICY', - description: 'The name of the version policy' + description: 'The name of the version policy', }); this._overwriteBump = this.defineStringParameter({ parameterLongName: '--override-bump', argumentName: 'BUMPTYPE', - description: 'Overrides the bump type in the version-policy.json for the specified version policy. ' + + description: + 'Overrides the bump type in the version-policy.json for the specified version policy. ' + 'Valid BUMPTYPE values include: prerelease, patch, preminor, minor, major. ' + - 'This setting only works for lock-step version policy in bump action.' + 'This setting only works for lock-step version policy in bump action.', }); this._prereleaseIdentifier = this.defineStringParameter({ parameterLongName: '--override-prerelease-id', argumentName: 'ID', - description: 'Overrides the prerelease identifier in the version value of version-policy.json ' + + description: + 'Overrides the prerelease identifier in the version value of version-policy.json ' + 'for the specified version policy. ' + 'This setting only works for lock-step version policy. ' + 'This setting increases to new prerelease id when "--bump" is provided but only replaces the ' + - 'prerelease name when "--ensure-version-policy" is provided.' + 'prerelease name when "--ensure-version-policy" is provided.', }); } @@ -107,8 +104,11 @@ export class VersionAction extends BaseRushAction { if (this._ensureVersionPolicy.value) { this._overwritePolicyVersionIfNeeded(); const tempBranch: string = 'version/ensure-' + new Date().getTime(); - this._versionManager.ensure(this._versionPolicy.value, true, - !!this._overrideVersion.value || !!this._prereleaseIdentifier.value); + this._versionManager.ensure( + this._versionPolicy.value, + true, + !!this._overrideVersion.value || !!this._prereleaseIdentifier.value + ); const updatedPackages: Map = this._versionManager.updatedProjects; if (updatedPackages.size > 0) { @@ -117,10 +117,12 @@ export class VersionAction extends BaseRushAction { } } else if (this._bumpVersion.value) { const tempBranch: string = 'version/bump-' + new Date().getTime(); - this._versionManager.bump(this._versionPolicy.value, + this._versionManager.bump( + this._versionPolicy.value, this._overwriteBump.value ? BumpType[this._overwriteBump.value] : undefined, this._prereleaseIdentifier.value, - true); + true + ); this._gitProcess(tempBranch); } }); @@ -132,14 +134,16 @@ export class VersionAction extends BaseRushAction { return; } if (this._overrideVersion.value && this._prereleaseIdentifier.value) { - throw new Error(`The parameters "--override-version" and` + - ` "--override-prerelease-id" cannot be used together.`); + throw new Error( + `The parameters "--override-version" and` + ` "--override-prerelease-id" cannot be used together.` + ); } if (this._versionPolicy.value) { const versionConfig: VersionPolicyConfiguration = this.rushConfiguration.versionPolicyConfiguration; - const policy: LockStepVersionPolicy = versionConfig.getVersionPolicy(this._versionPolicy.value) as - LockStepVersionPolicy; + const policy: LockStepVersionPolicy = versionConfig.getVersionPolicy( + this._versionPolicy.value + ) as LockStepVersionPolicy; if (!policy || !policy.isLockstepped) { throw new Error(`The lockstep version policy "${policy.policyName}" is not found.`); } @@ -163,7 +167,9 @@ export class VersionAction extends BaseRushAction { versionConfig.update(this._versionPolicy.value, newVersion); } } else { - throw new Error('Missing --version-policy parameter to specify which version policy should be overwritten.'); + throw new Error( + 'Missing --version-policy parameter to specify which version policy should be overwritten.' + ); } } @@ -173,8 +179,10 @@ export class VersionAction extends BaseRushAction { } if (this._overwriteBump.value && !BumpType[this._overwriteBump.value]) { - throw new Error('The value of override-bump is not valid. ' + - 'Valid values include prerelease, patch, preminor, minor, and major'); + throw new Error( + 'The value of override-bump is not valid. ' + + 'Valid values include prerelease, patch, preminor, minor, and major' + ); } } @@ -186,8 +194,10 @@ export class VersionAction extends BaseRushAction { const mismatchFinder: VersionMismatchFinder = VersionMismatchFinder.getMismatches(rushConfig); if (mismatchFinder.numberOfMismatches) { - throw new Error('Unable to finish version bump because inconsistencies were encountered. ' + - 'Run \"rush check\" to find more details.'); + throw new Error( + 'Unable to finish version bump because inconsistencies were encountered. ' + + 'Run "rush check" to find more details.' + ); } } diff --git a/apps/rush-lib/src/cli/actions/test/AddAction.test.ts b/apps/rush-lib/src/cli/actions/test/AddAction.test.ts index c54fbfe3bfd..3e5f5786ff3 100644 --- a/apps/rush-lib/src/cli/actions/test/AddAction.test.ts +++ b/apps/rush-lib/src/cli/actions/test/AddAction.test.ts @@ -15,10 +15,9 @@ describe('AddAction', () => { let oldArgs: string[]; beforeEach(() => { - doRushAddMock = jest.spyOn( - PackageJsonUpdater.prototype, - 'doRushAdd' - ).mockImplementation(() => Promise.resolve()); + doRushAddMock = jest + .spyOn(PackageJsonUpdater.prototype, 'doRushAdd') + .mockImplementation(() => Promise.resolve()); jest.spyOn(process, 'exit').mockImplementation(); oldExitCode = process.exitCode; oldArgs = process.argv; @@ -47,7 +46,8 @@ describe('AddAction', () => { // Mock the command process.argv = ['pretend-this-is-node.exe', 'pretend-this-is-rush', 'add', '-p', 'assert']; - return expect(parser.execute()).resolves.toEqual(true) + return expect(parser.execute()) + .resolves.toEqual(true) .then(() => { expect(doRushAddMock).toHaveBeenCalledTimes(1); expect(doRushAddMock.mock.calls[0][0].projects).toHaveLength(1); @@ -74,7 +74,8 @@ describe('AddAction', () => { // Mock the command process.argv = ['pretend-this-is-node.exe', 'pretend-this-is-rush', 'add', '-p', 'assert', '--all']; - return expect(parser.execute()).resolves.toEqual(true) + return expect(parser.execute()) + .resolves.toEqual(true) .then(() => { expect(doRushAddMock).toHaveBeenCalledTimes(1); expect(doRushAddMock.mock.calls[0][0].projects).toHaveLength(2); @@ -85,4 +86,4 @@ describe('AddAction', () => { }); }); }); -}); \ No newline at end of file +}); diff --git a/apps/rush-lib/src/cli/scriptActions/BaseScriptAction.ts b/apps/rush-lib/src/cli/scriptActions/BaseScriptAction.ts index 0f398a12be2..3e00d26b13c 100644 --- a/apps/rush-lib/src/cli/scriptActions/BaseScriptAction.ts +++ b/apps/rush-lib/src/cli/scriptActions/BaseScriptAction.ts @@ -27,9 +27,7 @@ export abstract class BaseScriptAction extends BaseRushAction { protected readonly _commandLineConfiguration: CommandLineConfiguration | undefined; protected readonly customParameters: CommandLineParameter[] = []; - public constructor( - options: IBaseScriptActionOptions - ) { + public constructor(options: IBaseScriptActionOptions) { super(options); this._commandLineConfiguration = options.commandLineConfiguration; } @@ -57,17 +55,17 @@ export abstract class BaseScriptAction extends BaseRushAction { parameterShortName: parameterJson.shortName, parameterLongName: parameterJson.longName, description: parameterJson.description, - required: parameterJson.required + required: parameterJson.required, }); break; case 'choice': - customParameter = this.defineChoiceParameter({ + customParameter = this.defineChoiceParameter({ parameterShortName: parameterJson.shortName, parameterLongName: parameterJson.longName, description: parameterJson.description, required: parameterJson.required, - alternatives: parameterJson.alternatives.map(x => x.name), - defaultValue: parameterJson.defaultValue + alternatives: parameterJson.alternatives.map((x) => x.name), + defaultValue: parameterJson.defaultValue, }); break; case 'string': @@ -76,12 +74,14 @@ export abstract class BaseScriptAction extends BaseRushAction { parameterShortName: parameterJson.shortName, description: parameterJson.description, required: parameterJson.required, - argumentName: parameterJson.argumentName + argumentName: parameterJson.argumentName, }); break; default: - throw new Error(`${RushConstants.commandLineFilename} defines a parameter "${parameterJson!.longName}"` - + ` using an unsupported parameter kind "${parameterJson!.parameterKind}"`); + throw new Error( + `${RushConstants.commandLineFilename} defines a parameter "${parameterJson!.longName}"` + + ` using an unsupported parameter kind "${parameterJson!.parameterKind}"` + ); } if (customParameter) { diff --git a/apps/rush-lib/src/cli/scriptActions/BulkScriptAction.ts b/apps/rush-lib/src/cli/scriptActions/BulkScriptAction.ts index b58faf595da..3497957daa6 100644 --- a/apps/rush-lib/src/cli/scriptActions/BulkScriptAction.ts +++ b/apps/rush-lib/src/cli/scriptActions/BulkScriptAction.ts @@ -8,13 +8,9 @@ import { CommandLineFlagParameter, CommandLineStringParameter, CommandLineStringListParameter, - CommandLineParameterKind + CommandLineParameterKind, } from '@rushstack/ts-command-line'; -import { - FileSystem, - PackageJsonLookup, - IPackageJson -} from '@rushstack/node-core-library'; +import { FileSystem, PackageJsonLookup, IPackageJson } from '@rushstack/node-core-library'; import { Event } from '../../index'; import { SetupChecks } from '../../logic/SetupChecks'; @@ -81,20 +77,19 @@ export class BulkScriptAction extends BaseScriptAction { public run(): Promise { if (!FileSystem.exists(this.rushConfiguration.rushLinkJsonFilename)) { - throw new Error(`File not found: ${this.rushConfiguration.rushLinkJsonFilename}` + - `${os.EOL}Did you run "rush link"?`); + throw new Error( + `File not found: ${this.rushConfiguration.rushLinkJsonFilename}` + `${os.EOL}Did you run "rush link"?` + ); } this._doBeforeTask(); const stopwatch: Stopwatch = Stopwatch.start(); - const isQuietMode: boolean = !(this._verboseParameter.value); + const isQuietMode: boolean = !this._verboseParameter.value; // if this is parallelizable, then use the value from the flag (undefined or a number), // if parallelism is not enabled, then restrict to 1 core - const parallelism: string | undefined = this._enableParallelism - ? this._parallelismParameter!.value - : '1'; + const parallelism: string | undefined = this._enableParallelism ? this._parallelismParameter!.value : '1'; // Collect all custom parameter values const customParameterValues: string[] = []; @@ -114,41 +109,41 @@ export class BulkScriptAction extends BaseScriptAction { isIncrementalBuildAllowed: this._isIncrementalBuildAllowed, ignoreMissingScript: this._ignoreMissingScript, ignoreDependencyOrder: this._ignoreDependencyOrder, - packageDepsFilename: Utilities.getPackageDepsFilenameForCommand(this._commandToRun) + packageDepsFilename: Utilities.getPackageDepsFilenameForCommand(this._commandToRun), }); // Register all tasks with the task collection const taskCollection: TaskCollection = taskSelector.registerTasks(); - const taskRunner: TaskRunner = new TaskRunner( - taskCollection.getOrderedTasks(), - { - quietMode: isQuietMode, - parallelism: parallelism, - changedProjectsOnly: changedProjectsOnly, - allowWarningsInSuccessfulBuild: this._allowWarningsInSuccessfulBuild - } - ); - - return taskRunner.execute().then(() => { - stopwatch.stop(); - console.log(colors.green(`rush ${this.actionName} (${stopwatch.toString()})`)); - this._doAfterTask(stopwatch, true); - }).catch((error: Error) => { - stopwatch.stop(); - if (error instanceof AlreadyReportedError) { + const taskRunner: TaskRunner = new TaskRunner(taskCollection.getOrderedTasks(), { + quietMode: isQuietMode, + parallelism: parallelism, + changedProjectsOnly: changedProjectsOnly, + allowWarningsInSuccessfulBuild: this._allowWarningsInSuccessfulBuild, + }); + + return taskRunner + .execute() + .then(() => { + stopwatch.stop(); console.log(colors.green(`rush ${this.actionName} (${stopwatch.toString()})`)); - } else { - if (error && error.message) { - console.log('Error: ' + error.message); - } + this._doAfterTask(stopwatch, true); + }) + .catch((error: Error) => { + stopwatch.stop(); + if (error instanceof AlreadyReportedError) { + console.log(colors.green(`rush ${this.actionName} (${stopwatch.toString()})`)); + } else { + if (error && error.message) { + console.log('Error: ' + error.message); + } - console.log(colors.red(`rush ${this.actionName} - Errors! (${stopwatch.toString()})`)); - } + console.log(colors.red(`rush ${this.actionName} - Errors! (${stopwatch.toString()})`)); + } - this._doAfterTask(stopwatch, false); - throw new AlreadyReportedError(); - }); + this._doAfterTask(stopwatch, false); + throw new AlreadyReportedError(); + }); } protected onDefineParameters(): void { @@ -158,48 +153,54 @@ export class BulkScriptAction extends BaseScriptAction { parameterShortName: '-p', argumentName: 'COUNT', environmentVariable: EnvironmentVariableNames.RUSH_PARALLELISM, - description: 'Specifies the maximum number of concurrent processes to launch during a build.' - + ' The COUNT should be a positive integer or else the word "max" to specify a count that is equal to' - + ' the number of CPU cores. If this parameter is omitted, then the default value depends on the' - + ' operating system and number of CPU cores.' + description: + 'Specifies the maximum number of concurrent processes to launch during a build.' + + ' The COUNT should be a positive integer or else the word "max" to specify a count that is equal to' + + ' the number of CPU cores. If this parameter is omitted, then the default value depends on the' + + ' operating system and number of CPU cores.', }); } this._toFlag = this.defineStringListParameter({ parameterLongName: '--to', parameterShortName: '-t', argumentName: 'PROJECT1', - description: 'Run command in the specified project and all of its dependencies. "." can be used as shorthand ' + - 'to specify the project in the current working directory.' + description: + 'Run command in the specified project and all of its dependencies. "." can be used as shorthand ' + + 'to specify the project in the current working directory.', }); - this._fromVersionPolicy = this.defineStringListParameter({ + this._fromVersionPolicy = this.defineStringListParameter({ parameterLongName: '--from-version-policy', argumentName: 'VERSION_POLICY_NAME', - description: 'Run command in all projects with the specified version policy ' - + 'and all projects that directly or indirectly depend on projects with the specified version policy' + description: + 'Run command in all projects with the specified version policy ' + + 'and all projects that directly or indirectly depend on projects with the specified version policy', }); - this._toVersionPolicy = this.defineStringListParameter({ + this._toVersionPolicy = this.defineStringListParameter({ parameterLongName: '--to-version-policy', argumentName: 'VERSION_POLICY_NAME', - description: 'Run command in all projects with the specified version policy and all of their dependencies' + description: + 'Run command in all projects with the specified version policy and all of their dependencies', }); this._fromFlag = this.defineStringListParameter({ parameterLongName: '--from', parameterShortName: '-f', argumentName: 'PROJECT2', - description: 'Run command in all projects that directly or indirectly depend on the specified project. ' + - '"." can be used as shorthand to specify the project in the current working directory.' + description: + 'Run command in all projects that directly or indirectly depend on the specified project. ' + + '"." can be used as shorthand to specify the project in the current working directory.', }); this._verboseParameter = this.defineFlagParameter({ parameterLongName: '--verbose', parameterShortName: '-v', - description: 'Display the logs during the build, rather than just displaying the build status summary' + description: 'Display the logs during the build, rather than just displaying the build status summary', }); if (this._isIncrementalBuildAllowed) { this._changedProjectsOnly = this.defineFlagParameter({ parameterLongName: '--changed-projects-only', parameterShortName: '-o', - description: 'If specified, the incremental build will only rebuild projects that have changed, ' - + 'but not any projects that directly or indirectly depend on the changed package.' + description: + 'If specified, the incremental build will only rebuild projects that have changed, ' + + 'but not any projects that directly or indirectly depend on the changed package.', }); } @@ -221,19 +222,23 @@ export class BulkScriptAction extends BaseScriptAction { if (this.rushConfiguration.projectsByName.has(projectName)) { projects.push(projectName); } else { - console.log(colors.red( - 'Rush is not currently running in a project directory specified in rush.json. ' + - `The "." value for the ${this._toFlag.longName} parameter or the ${this._fromFlag.longName} parameter ` + - 'is not allowed.' - )); + console.log( + colors.red( + 'Rush is not currently running in a project directory specified in rush.json. ' + + `The "." value for the ${this._toFlag.longName} parameter or the ${this._fromFlag.longName} parameter ` + + 'is not allowed.' + ) + ); throw new AlreadyReportedError(); } } else { - console.log(colors.red( - 'Rush is not currently running in a project directory. ' + - `The "." value for the ${this._toFlag.longName} parameter or the ${this._fromFlag.longName} parameter ` + - 'is not allowed.' - )); + console.log( + colors.red( + 'Rush is not currently running in a project directory. ' + + `The "." value for the ${this._toFlag.longName} parameter or the ${this._fromFlag.longName} parameter ` + + 'is not allowed.' + ) + ); throw new AlreadyReportedError(); } } else { @@ -242,8 +247,8 @@ export class BulkScriptAction extends BaseScriptAction { } if (versionPoliciesParameters.values && versionPoliciesParameters.values.length > 0) { - this.rushConfiguration.projects.forEach(project => { - const matches: boolean = versionPoliciesParameters.values.some(policyName => { + this.rushConfiguration.projects.forEach((project) => { + const matches: boolean = versionPoliciesParameters.values.some((policyName) => { return project.versionPolicyName === policyName; }); if (matches) { @@ -256,7 +261,10 @@ export class BulkScriptAction extends BaseScriptAction { } private _doBeforeTask(): void { - if (this.actionName !== RushConstants.buildCommandName && this.actionName !== RushConstants.rebuildCommandName) { + if ( + this.actionName !== RushConstants.buildCommandName && + this.actionName !== RushConstants.rebuildCommandName + ) { // Only collects information for built-in tasks like build or rebuild. return; } @@ -267,7 +275,10 @@ export class BulkScriptAction extends BaseScriptAction { } private _doAfterTask(stopwatch: Stopwatch, success: boolean): void { - if (this.actionName !== RushConstants.buildCommandName && this.actionName !== RushConstants.rebuildCommandName) { + if ( + this.actionName !== RushConstants.buildCommandName && + this.actionName !== RushConstants.rebuildCommandName + ) { // Only collects information for built-in tasks like build or rebuild. return; } @@ -279,7 +290,7 @@ export class BulkScriptAction extends BaseScriptAction { private _collectTelemetry(stopwatch: Stopwatch, success: boolean): void { const extraData: { [key: string]: string } = { command_to: (this._toFlag.values.length > 0).toString(), - command_from: (this._fromFlag.values.length > 0).toString() + command_from: (this._fromFlag.values.length > 0).toString(), }; for (const customParameter of this.customParameters) { @@ -301,7 +312,7 @@ export class BulkScriptAction extends BaseScriptAction { name: this.actionName, duration: stopwatch.duration, result: success ? 'Succeeded' : 'Failed', - extraData + extraData, }); } } diff --git a/apps/rush-lib/src/cli/scriptActions/GlobalScriptAction.ts b/apps/rush-lib/src/cli/scriptActions/GlobalScriptAction.ts index 8cd63520c8c..2ce8afda4e5 100644 --- a/apps/rush-lib/src/cli/scriptActions/GlobalScriptAction.ts +++ b/apps/rush-lib/src/cli/scriptActions/GlobalScriptAction.ts @@ -28,9 +28,7 @@ export interface IGlobalScriptActionOptions extends IBaseScriptActionOptions { export class GlobalScriptAction extends BaseScriptAction { private _shellCommand: string; - public constructor( - options: IGlobalScriptActionOptions - ) { + public constructor(options: IGlobalScriptActionOptions) { super(options); this._shellCommand = options.shellCommand; } @@ -49,18 +47,15 @@ export class GlobalScriptAction extends BaseScriptAction { shellCommand += ' ' + customParameterValues.join(' '); } - const exitCode: number = Utilities.executeLifecycleCommand( - shellCommand, - { - rushConfiguration: this.rushConfiguration, - workingDirectory: this.rushConfiguration.rushJsonFolder, - initCwd: this.rushConfiguration.commonTempFolder, - handleOutput: false, - environmentPathOptions: { - includeRepoBin: true - } - } - ); + const exitCode: number = Utilities.executeLifecycleCommand(shellCommand, { + rushConfiguration: this.rushConfiguration, + workingDirectory: this.rushConfiguration.rushJsonFolder, + initCwd: this.rushConfiguration.commonTempFolder, + handleOutput: false, + environmentPathOptions: { + includeRepoBin: true, + }, + }); process.exitCode = exitCode; diff --git a/apps/rush-lib/src/cli/test/Cli.test.ts b/apps/rush-lib/src/cli/test/Cli.test.ts index 965100340cb..b9577fc8440 100644 --- a/apps/rush-lib/src/cli/test/Cli.test.ts +++ b/apps/rush-lib/src/cli/test/Cli.test.ts @@ -11,7 +11,7 @@ describe('CLI', () => { const startPath: string = path.resolve(path.join(__dirname, '../../start.js')); expect(() => { - Utilities.executeCommand('node', [ startPath ], workingDir, undefined, true); + Utilities.executeCommand('node', [startPath], workingDir, undefined, true); }).not.toThrow(); }); }); diff --git a/apps/rush-lib/src/cli/test/CommandLineHelp.test.ts b/apps/rush-lib/src/cli/test/CommandLineHelp.test.ts index d482b1174b1..ff05b7b4c77 100644 --- a/apps/rush-lib/src/cli/test/CommandLineHelp.test.ts +++ b/apps/rush-lib/src/cli/test/CommandLineHelp.test.ts @@ -12,9 +12,9 @@ describe('CommandLineHelp', () => { beforeEach(() => { // ts-command-line calls process.exit() which interferes with Jest - jest.spyOn(process, 'exit').mockImplementation(((code?: number) => { + jest.spyOn(process, 'exit').mockImplementation((code?: number) => { throw new Error('Test code called process.exit(${code})'); - })); + }); oldCwd = process.cwd(); const localCwd: string = path.join(__dirname, 'repo'); diff --git a/apps/rush-lib/src/cli/test/RushCommandLineParser.test.ts b/apps/rush-lib/src/cli/test/RushCommandLineParser.test.ts index 9a5cd21bb47..cee1865dd47 100644 --- a/apps/rush-lib/src/cli/test/RushCommandLineParser.test.ts +++ b/apps/rush-lib/src/cli/test/RushCommandLineParser.test.ts @@ -71,7 +71,7 @@ function getCommandLineParserInstance(repoName: string, taskName: string): IPars return { parser, - spawnMock + spawnMock, }; } @@ -100,7 +100,8 @@ describe('RushCommandLineParser', () => { const instance: IParserTestInstance = getCommandLineParserInstance(repoName, 'build'); expect.assertions(8); - return expect(instance.parser.execute()).resolves.toEqual(true) + return expect(instance.parser.execute()) + .resolves.toEqual(true) .then(() => { // There should be 1 build per package const packageCount: number = instance.spawnMock.mock.calls.length; @@ -111,17 +112,17 @@ describe('RushCommandLineParser', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const firstSpawn: any[] = instance.spawnMock.mock.calls[0]; - expect(firstSpawn[SPAWN_ARG_ARGS]).toEqual(expect.arrayContaining([ - expect.stringMatching(expectedBuildTaskRegexp) - ])); + expect(firstSpawn[SPAWN_ARG_ARGS]).toEqual( + expect.arrayContaining([expect.stringMatching(expectedBuildTaskRegexp)]) + ); expect(firstSpawn[SPAWN_ARG_OPTIONS]).toEqual(expect.any(Object)); expect(firstSpawn[SPAWN_ARG_OPTIONS].cwd).toEqual(path.resolve(__dirname, `${repoName}/a`)); // eslint-disable-next-line @typescript-eslint/no-explicit-any const secondSpawn: any[] = instance.spawnMock.mock.calls[1]; - expect(secondSpawn[SPAWN_ARG_ARGS]).toEqual(expect.arrayContaining([ - expect.stringMatching(expectedBuildTaskRegexp) - ])); + expect(secondSpawn[SPAWN_ARG_ARGS]).toEqual( + expect.arrayContaining([expect.stringMatching(expectedBuildTaskRegexp)]) + ); expect(secondSpawn[SPAWN_ARG_OPTIONS]).toEqual(expect.any(Object)); expect(secondSpawn[SPAWN_ARG_OPTIONS].cwd).toEqual(path.resolve(__dirname, `${repoName}/b`)); }); @@ -134,7 +135,8 @@ describe('RushCommandLineParser', () => { const instance: IParserTestInstance = getCommandLineParserInstance(repoName, 'rebuild'); expect.assertions(8); - return expect(instance.parser.execute()).resolves.toEqual(true) + return expect(instance.parser.execute()) + .resolves.toEqual(true) .then(() => { // There should be 1 build per package const packageCount: number = instance.spawnMock.mock.calls.length; @@ -145,17 +147,17 @@ describe('RushCommandLineParser', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const firstSpawn: any[] = instance.spawnMock.mock.calls[0]; - expect(firstSpawn[SPAWN_ARG_ARGS]).toEqual(expect.arrayContaining([ - expect.stringMatching(expectedBuildTaskRegexp) - ])); + expect(firstSpawn[SPAWN_ARG_ARGS]).toEqual( + expect.arrayContaining([expect.stringMatching(expectedBuildTaskRegexp)]) + ); expect(firstSpawn[SPAWN_ARG_OPTIONS]).toEqual(expect.any(Object)); expect(firstSpawn[SPAWN_ARG_OPTIONS].cwd).toEqual(path.resolve(__dirname, `${repoName}/a`)); // eslint-disable-next-line @typescript-eslint/no-explicit-any const secondSpawn: any[] = instance.spawnMock.mock.calls[1]; - expect(secondSpawn[SPAWN_ARG_ARGS]).toEqual(expect.arrayContaining([ - expect.stringMatching(expectedBuildTaskRegexp) - ])); + expect(secondSpawn[SPAWN_ARG_ARGS]).toEqual( + expect.arrayContaining([expect.stringMatching(expectedBuildTaskRegexp)]) + ); expect(secondSpawn[SPAWN_ARG_OPTIONS]).toEqual(expect.any(Object)); expect(secondSpawn[SPAWN_ARG_OPTIONS].cwd).toEqual(path.resolve(__dirname, `${repoName}/b`)); }); @@ -170,7 +172,8 @@ describe('RushCommandLineParser', () => { const instance: IParserTestInstance = getCommandLineParserInstance(repoName, 'build'); expect.assertions(8); - return expect(instance.parser.execute()).resolves.toEqual(true) + return expect(instance.parser.execute()) + .resolves.toEqual(true) .then(() => { // There should be 1 build per package const packageCount: number = instance.spawnMock.mock.calls.length; @@ -181,17 +184,17 @@ describe('RushCommandLineParser', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const firstSpawn: any[] = instance.spawnMock.mock.calls[0]; - expect(firstSpawn[SPAWN_ARG_ARGS]).toEqual(expect.arrayContaining([ - expect.stringMatching(expectedBuildTaskRegexp) - ])); + expect(firstSpawn[SPAWN_ARG_ARGS]).toEqual( + expect.arrayContaining([expect.stringMatching(expectedBuildTaskRegexp)]) + ); expect(firstSpawn[SPAWN_ARG_OPTIONS]).toEqual(expect.any(Object)); expect(firstSpawn[SPAWN_ARG_OPTIONS].cwd).toEqual(path.resolve(__dirname, `${repoName}/a`)); // eslint-disable-next-line @typescript-eslint/no-explicit-any const secondSpawn: any[] = instance.spawnMock.mock.calls[1]; - expect(secondSpawn[SPAWN_ARG_ARGS]).toEqual(expect.arrayContaining([ - expect.stringMatching(expectedBuildTaskRegexp) - ])); + expect(secondSpawn[SPAWN_ARG_ARGS]).toEqual( + expect.arrayContaining([expect.stringMatching(expectedBuildTaskRegexp)]) + ); expect(secondSpawn[SPAWN_ARG_OPTIONS]).toEqual(expect.any(Object)); expect(secondSpawn[SPAWN_ARG_OPTIONS].cwd).toEqual(path.resolve(__dirname, `${repoName}/b`)); }); @@ -204,7 +207,8 @@ describe('RushCommandLineParser', () => { const instance: IParserTestInstance = getCommandLineParserInstance(repoName, 'rebuild'); expect.assertions(8); - return expect(instance.parser.execute()).resolves.toEqual(true) + return expect(instance.parser.execute()) + .resolves.toEqual(true) .then(() => { // There should be 1 build per package const packageCount: number = instance.spawnMock.mock.calls.length; @@ -215,17 +219,17 @@ describe('RushCommandLineParser', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const firstSpawn: any[] = instance.spawnMock.mock.calls[0]; - expect(firstSpawn[SPAWN_ARG_ARGS]).toEqual(expect.arrayContaining([ - expect.stringMatching(expectedBuildTaskRegexp) - ])); + expect(firstSpawn[SPAWN_ARG_ARGS]).toEqual( + expect.arrayContaining([expect.stringMatching(expectedBuildTaskRegexp)]) + ); expect(firstSpawn[SPAWN_ARG_OPTIONS]).toEqual(expect.any(Object)); expect(firstSpawn[SPAWN_ARG_OPTIONS].cwd).toEqual(path.resolve(__dirname, `${repoName}/a`)); // eslint-disable-next-line @typescript-eslint/no-explicit-any const secondSpawn: any[] = instance.spawnMock.mock.calls[1]; - expect(secondSpawn[SPAWN_ARG_ARGS]).toEqual(expect.arrayContaining([ - expect.stringMatching(expectedBuildTaskRegexp) - ])); + expect(secondSpawn[SPAWN_ARG_ARGS]).toEqual( + expect.arrayContaining([expect.stringMatching(expectedBuildTaskRegexp)]) + ); expect(secondSpawn[SPAWN_ARG_OPTIONS]).toEqual(expect.any(Object)); expect(secondSpawn[SPAWN_ARG_OPTIONS].cwd).toEqual(path.resolve(__dirname, `${repoName}/b`)); }); @@ -239,7 +243,8 @@ describe('RushCommandLineParser', () => { const repoName: string = 'overrideAndDefaultBuildActionRepo'; const instance: IParserTestInstance = getCommandLineParserInstance(repoName, 'build'); expect.assertions(8); - return expect(instance.parser.execute()).resolves.toEqual(true) + return expect(instance.parser.execute()) + .resolves.toEqual(true) .then(() => { // There should be 1 build per package const packageCount: number = instance.spawnMock.mock.calls.length; @@ -250,17 +255,17 @@ describe('RushCommandLineParser', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const firstSpawn: any[] = instance.spawnMock.mock.calls[0]; - expect(firstSpawn[SPAWN_ARG_ARGS]).toEqual(expect.arrayContaining([ - expect.stringMatching(expectedBuildTaskRegexp) - ])); + expect(firstSpawn[SPAWN_ARG_ARGS]).toEqual( + expect.arrayContaining([expect.stringMatching(expectedBuildTaskRegexp)]) + ); expect(firstSpawn[SPAWN_ARG_OPTIONS]).toEqual(expect.any(Object)); expect(firstSpawn[SPAWN_ARG_OPTIONS].cwd).toEqual(path.resolve(__dirname, `${repoName}/a`)); // eslint-disable-next-line @typescript-eslint/no-explicit-any const secondSpawn: any[] = instance.spawnMock.mock.calls[1]; - expect(secondSpawn[SPAWN_ARG_ARGS]).toEqual(expect.arrayContaining([ - expect.stringMatching(expectedBuildTaskRegexp) - ])); + expect(secondSpawn[SPAWN_ARG_ARGS]).toEqual( + expect.arrayContaining([expect.stringMatching(expectedBuildTaskRegexp)]) + ); expect(secondSpawn[SPAWN_ARG_OPTIONS]).toEqual(expect.any(Object)); expect(secondSpawn[SPAWN_ARG_OPTIONS].cwd).toEqual(path.resolve(__dirname, `${repoName}/b`)); }); @@ -272,7 +277,8 @@ describe('RushCommandLineParser', () => { const repoName: string = 'overrideAndDefaultRebuildActionRepo'; const instance: IParserTestInstance = getCommandLineParserInstance(repoName, 'rebuild'); expect.assertions(8); - return expect(instance.parser.execute()).resolves.toEqual(true) + return expect(instance.parser.execute()) + .resolves.toEqual(true) .then(() => { // There should be 1 build per package const packageCount: number = instance.spawnMock.mock.calls.length; @@ -283,17 +289,17 @@ describe('RushCommandLineParser', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const firstSpawn: any[] = instance.spawnMock.mock.calls[0]; - expect(firstSpawn[SPAWN_ARG_ARGS]).toEqual(expect.arrayContaining([ - expect.stringMatching(expectedBuildTaskRegexp) - ])); + expect(firstSpawn[SPAWN_ARG_ARGS]).toEqual( + expect.arrayContaining([expect.stringMatching(expectedBuildTaskRegexp)]) + ); expect(firstSpawn[SPAWN_ARG_OPTIONS]).toEqual(expect.any(Object)); expect(firstSpawn[SPAWN_ARG_OPTIONS].cwd).toEqual(path.resolve(__dirname, `${repoName}/a`)); // eslint-disable-next-line @typescript-eslint/no-explicit-any const secondSpawn: any[] = instance.spawnMock.mock.calls[1]; - expect(secondSpawn[SPAWN_ARG_ARGS]).toEqual(expect.arrayContaining([ - expect.stringMatching(expectedBuildTaskRegexp) - ])); + expect(secondSpawn[SPAWN_ARG_ARGS]).toEqual( + expect.arrayContaining([expect.stringMatching(expectedBuildTaskRegexp)]) + ); expect(secondSpawn[SPAWN_ARG_OPTIONS]).toEqual(expect.any(Object)); expect(secondSpawn[SPAWN_ARG_OPTIONS].cwd).toEqual(path.resolve(__dirname, `${repoName}/b`)); }); diff --git a/apps/rush-lib/src/cli/test/overrideAndDefaultBuildActionRepo/common/config/rush/command-line.json b/apps/rush-lib/src/cli/test/overrideAndDefaultBuildActionRepo/common/config/rush/command-line.json index 0880b6c8e68..5dc8db3d775 100644 --- a/apps/rush-lib/src/cli/test/overrideAndDefaultBuildActionRepo/common/config/rush/command-line.json +++ b/apps/rush-lib/src/cli/test/overrideAndDefaultBuildActionRepo/common/config/rush/command-line.json @@ -9,7 +9,6 @@ "allowWarningsInSuccessfulBuild": true }, { - "commandKind": "bulk", "name": "my-bulk-command", "summary": "Example bulk custom command", @@ -34,13 +33,13 @@ "longName": "--no-color", "parameterKind": "flag", "description": "disable colors in the build log, defaults to 'true'", - "associatedCommands": [ "build", "rebuild" ] + "associatedCommands": ["build", "rebuild"] }, { "longName": "--production", "parameterKind": "flag", "description": "Perform a production build, including minification and localization steps", - "associatedCommands": [ "build", "rebuild" ] + "associatedCommands": ["build", "rebuild"] } ] -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/cli/test/overrideAndDefaultRebuildActionRepo/common/config/rush/command-line.json b/apps/rush-lib/src/cli/test/overrideAndDefaultRebuildActionRepo/common/config/rush/command-line.json index 0880b6c8e68..5dc8db3d775 100644 --- a/apps/rush-lib/src/cli/test/overrideAndDefaultRebuildActionRepo/common/config/rush/command-line.json +++ b/apps/rush-lib/src/cli/test/overrideAndDefaultRebuildActionRepo/common/config/rush/command-line.json @@ -9,7 +9,6 @@ "allowWarningsInSuccessfulBuild": true }, { - "commandKind": "bulk", "name": "my-bulk-command", "summary": "Example bulk custom command", @@ -34,13 +33,13 @@ "longName": "--no-color", "parameterKind": "flag", "description": "disable colors in the build log, defaults to 'true'", - "associatedCommands": [ "build", "rebuild" ] + "associatedCommands": ["build", "rebuild"] }, { "longName": "--production", "parameterKind": "flag", "description": "Perform a production build, including minification and localization steps", - "associatedCommands": [ "build", "rebuild" ] + "associatedCommands": ["build", "rebuild"] } ] -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/cli/test/overrideBuildAsGlobalCommandRepo/common/config/rush/command-line.json b/apps/rush-lib/src/cli/test/overrideBuildAsGlobalCommandRepo/common/config/rush/command-line.json index 4d4b12d2919..6d3d4ebb50c 100644 --- a/apps/rush-lib/src/cli/test/overrideBuildAsGlobalCommandRepo/common/config/rush/command-line.json +++ b/apps/rush-lib/src/cli/test/overrideBuildAsGlobalCommandRepo/common/config/rush/command-line.json @@ -9,4 +9,4 @@ "shellCommand": "node fake-build" } ] -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/cli/test/overrideBuildWithSimultaneousProcessesRepo/common/config/rush/command-line.json b/apps/rush-lib/src/cli/test/overrideBuildWithSimultaneousProcessesRepo/common/config/rush/command-line.json index 482b5cf5c07..b337bb04bb2 100644 --- a/apps/rush-lib/src/cli/test/overrideBuildWithSimultaneousProcessesRepo/common/config/rush/command-line.json +++ b/apps/rush-lib/src/cli/test/overrideBuildWithSimultaneousProcessesRepo/common/config/rush/command-line.json @@ -10,4 +10,4 @@ "safeForSimultaneousRushProcesses": true } ] -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/cli/test/overrideRebuildAndRunBuildActionRepo/common/config/rush/command-line.json b/apps/rush-lib/src/cli/test/overrideRebuildAndRunBuildActionRepo/common/config/rush/command-line.json index cabdccc3e93..8cccb52fb9e 100644 --- a/apps/rush-lib/src/cli/test/overrideRebuildAndRunBuildActionRepo/common/config/rush/command-line.json +++ b/apps/rush-lib/src/cli/test/overrideRebuildAndRunBuildActionRepo/common/config/rush/command-line.json @@ -14,7 +14,7 @@ "longName": "--flag-for-build-and-rebuild", "description": "This flag should be usable for build and rebuild commands.", "parameterKind": "flag", - "associatedCommands": [ "build", "rebuild" ] + "associatedCommands": ["build", "rebuild"] } ] -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/cli/test/overrideRebuildAndRunRebuildActionRepo/common/config/rush/command-line.json b/apps/rush-lib/src/cli/test/overrideRebuildAndRunRebuildActionRepo/common/config/rush/command-line.json index cabdccc3e93..8cccb52fb9e 100644 --- a/apps/rush-lib/src/cli/test/overrideRebuildAndRunRebuildActionRepo/common/config/rush/command-line.json +++ b/apps/rush-lib/src/cli/test/overrideRebuildAndRunRebuildActionRepo/common/config/rush/command-line.json @@ -14,7 +14,7 @@ "longName": "--flag-for-build-and-rebuild", "description": "This flag should be usable for build and rebuild commands.", "parameterKind": "flag", - "associatedCommands": [ "build", "rebuild" ] + "associatedCommands": ["build", "rebuild"] } ] -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/cli/test/overrideRebuildAsGlobalCommandRepo/common/config/rush/command-line.json b/apps/rush-lib/src/cli/test/overrideRebuildAsGlobalCommandRepo/common/config/rush/command-line.json index 688c1a7cc4a..a1e5db80eb5 100644 --- a/apps/rush-lib/src/cli/test/overrideRebuildAsGlobalCommandRepo/common/config/rush/command-line.json +++ b/apps/rush-lib/src/cli/test/overrideRebuildAsGlobalCommandRepo/common/config/rush/command-line.json @@ -9,4 +9,4 @@ "shellCommand": "node fake-rebuild" } ] -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/cli/test/overrideRebuildWithSimultaneousProcessesRepo/common/config/rush/command-line.json b/apps/rush-lib/src/cli/test/overrideRebuildWithSimultaneousProcessesRepo/common/config/rush/command-line.json index ea2fc24ac41..208dc9a375d 100644 --- a/apps/rush-lib/src/cli/test/overrideRebuildWithSimultaneousProcessesRepo/common/config/rush/command-line.json +++ b/apps/rush-lib/src/cli/test/overrideRebuildWithSimultaneousProcessesRepo/common/config/rush/command-line.json @@ -10,4 +10,4 @@ "safeForSimultaneousRushProcesses": true } ] -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/cli/test/repo/common/config/rush/command-line.json b/apps/rush-lib/src/cli/test/repo/common/config/rush/command-line.json index 7a729f0e5ab..d082f493cce 100644 --- a/apps/rush-lib/src/cli/test/repo/common/config/rush/command-line.json +++ b/apps/rush-lib/src/cli/test/repo/common/config/rush/command-line.json @@ -21,7 +21,7 @@ "longName": "--locale", "parameterKind": "choice", "description": "Selects a single instead of the default locale (en-us) for non-ship builds or all locales for ship builds.", - "associatedCommands": [ "import-strings", "upload" ], + "associatedCommands": ["import-strings", "upload"], "alternatives": [ { "name": "en-us", @@ -47,7 +47,7 @@ "shortName": "-s", "parameterKind": "flag", "description": "Perform a production build, including minification and localization steps", - "associatedCommands": [ "build", "rebuild" ] + "associatedCommands": ["build", "rebuild"] }, { @@ -55,7 +55,7 @@ "shortName": "-m", "parameterKind": "flag", "description": "Perform a fast build, which disables certain tasks such as unit tests and linting", - "associatedCommands": [ "build", "rebuild" ] + "associatedCommands": ["build", "rebuild"] } ] } diff --git a/apps/rush-lib/src/cli/test/repo/common/scripts/deploy.js b/apps/rush-lib/src/cli/test/repo/common/scripts/deploy.js index 1521954473d..1832b07dc4d 100644 --- a/apps/rush-lib/src/cli/test/repo/common/scripts/deploy.js +++ b/apps/rush-lib/src/cli/test/repo/common/scripts/deploy.js @@ -3,4 +3,4 @@ console.log('ARGV: ' + JSON.stringify(process.argv)); console.log('CWD: ' + process.cwd()); console.log('INITCWD: ' + process.env['INIT_CWD']); -process.exit(123) +process.exit(123); diff --git a/apps/rush-lib/src/cli/test/repo/rush.json b/apps/rush-lib/src/cli/test/repo/rush.json index fa1af090d5d..13fa46cb260 100644 --- a/apps/rush-lib/src/cli/test/repo/rush.json +++ b/apps/rush-lib/src/cli/test/repo/rush.json @@ -1,6 +1,5 @@ { "pnpmVersion": "4.5.0", "rushVersion": "5.0.0", - "projects": [ - ] + "projects": [] } diff --git a/apps/rush-lib/src/index.ts b/apps/rush-lib/src/index.ts index 487b027a9d6..fab7941797d 100644 --- a/apps/rush-lib/src/index.ts +++ b/apps/rush-lib/src/index.ts @@ -6,9 +6,7 @@ * @packageDocumentation */ -export { - ApprovedPackagesPolicy -} from './api/ApprovedPackagesPolicy'; +export { ApprovedPackagesPolicy } from './api/ApprovedPackagesPolicy'; export { RushConfiguration, @@ -24,72 +22,39 @@ export { PackageManagerOptionsConfigurationBase, PnpmOptionsConfiguration, NpmOptionsConfiguration, - YarnOptionsConfiguration + YarnOptionsConfiguration, } from './api/RushConfiguration'; -export { - PackageManagerName, - PackageManager -} from './api/packageManager/PackageManager'; +export { PackageManagerName, PackageManager } from './api/packageManager/PackageManager'; -export { - EnvironmentVariableNames -} from './api/EnvironmentConfiguration'; +export { EnvironmentVariableNames } from './api/EnvironmentConfiguration'; -export { - RushConfigurationProject -} from './api/RushConfigurationProject'; +export { RushConfigurationProject } from './api/RushConfigurationProject'; -export { - RushGlobalFolder as _RushGlobalFolder -} from './api/RushGlobalFolder'; +export { RushGlobalFolder as _RushGlobalFolder } from './api/RushGlobalFolder'; -export { - ApprovedPackagesItem, - ApprovedPackagesConfiguration -} from './api/ApprovedPackagesConfiguration'; +export { ApprovedPackagesItem, ApprovedPackagesConfiguration } from './api/ApprovedPackagesConfiguration'; -export { - CommonVersionsConfiguration -} from './api/CommonVersionsConfiguration'; +export { CommonVersionsConfiguration } from './api/CommonVersionsConfiguration'; -export { - PackageJsonEditor, - PackageJsonDependency, - DependencyType -} from './api/PackageJsonEditor'; +export { PackageJsonEditor, PackageJsonDependency, DependencyType } from './api/PackageJsonEditor'; -export { - EventHooks, - Event -} from './api/EventHooks'; +export { EventHooks, Event } from './api/EventHooks'; -export { - ChangeManager -} from './api/ChangeManager'; +export { ChangeManager } from './api/ChangeManager'; -export { - LastInstallFlag as _LastInstallFlag -} from './api/LastInstallFlag'; +export { LastInstallFlag as _LastInstallFlag } from './api/LastInstallFlag'; export { VersionPolicyDefinitionName, BumpType, LockStepVersionPolicy, IndividualVersionPolicy, - VersionPolicy + VersionPolicy, } from './api/VersionPolicy'; -export { - VersionPolicyConfiguration -} from './api/VersionPolicyConfiguration'; +export { VersionPolicyConfiguration } from './api/VersionPolicyConfiguration'; -export { - ILaunchOptions, - Rush -} from './api/Rush'; +export { ILaunchOptions, Rush } from './api/Rush'; -export { - ExperimentsConfiguration, - IExperimentsJson -} from './api/ExperimentsConfiguration'; +export { ExperimentsConfiguration, IExperimentsJson } from './api/ExperimentsConfiguration'; diff --git a/apps/rush-lib/src/logic/ApprovedPackagesChecker.ts b/apps/rush-lib/src/logic/ApprovedPackagesChecker.ts index 5063b5451fe..d3410b3136b 100644 --- a/apps/rush-lib/src/logic/ApprovedPackagesChecker.ts +++ b/apps/rush-lib/src/logic/ApprovedPackagesChecker.ts @@ -49,26 +49,10 @@ export class ApprovedPackagesChecker { for (const rushProject of this._rushConfiguration.projects) { const packageJson: IPackageJson = rushProject.packageJson; - this._collectDependencies( - packageJson.dependencies, - this._approvedPackagesPolicy, - rushProject - ); - this._collectDependencies( - packageJson.devDependencies, - this._approvedPackagesPolicy, - rushProject - ); - this._collectDependencies( - packageJson.peerDependencies, - this._approvedPackagesPolicy, - rushProject - ); - this._collectDependencies( - packageJson.optionalDependencies, - this._approvedPackagesPolicy, - rushProject - ); + this._collectDependencies(packageJson.dependencies, this._approvedPackagesPolicy, rushProject); + this._collectDependencies(packageJson.devDependencies, this._approvedPackagesPolicy, rushProject); + this._collectDependencies(packageJson.peerDependencies, this._approvedPackagesPolicy, rushProject); + this._collectDependencies(packageJson.optionalDependencies, this._approvedPackagesPolicy, rushProject); } } @@ -79,7 +63,6 @@ export class ApprovedPackagesChecker { ): void { if (dependencies) { for (const packageName of Object.keys(dependencies)) { - let referencedPackageName: string = packageName; // Special handling for NPM package aliases such as this: diff --git a/apps/rush-lib/src/logic/ChangeFiles.ts b/apps/rush-lib/src/logic/ChangeFiles.ts index 7fc1dbf94c8..5ec9423cfb3 100644 --- a/apps/rush-lib/src/logic/ChangeFiles.ts +++ b/apps/rush-lib/src/logic/ChangeFiles.ts @@ -15,7 +15,6 @@ import { RushConfiguration } from '../api/RushConfiguration'; * for those change files. */ export class ChangeFiles { - /** * Change file path relative to changes folder. */ @@ -46,14 +45,15 @@ export class ChangeFiles { if (change.type !== 'none' && change.type !== 'hotfix') { throw new Error( `Change file ${filePath} specifies a type of '${change.type}' ` + - `but only 'hotfix' and 'none' change types may be used in a branch with 'hotfixChangeEnabled'.`); + `but only 'hotfix' and 'none' change types may be used in a branch with 'hotfixChangeEnabled'.` + ); } } } } if (changeFile && changeFile.changes) { - changeFile.changes.forEach(change => projectsWithChangeDescriptions.add(change.packageName)); + changeFile.changes.forEach((change) => projectsWithChangeDescriptions.add(change.packageName)); } else { throw new Error(`Invalid change file: ${filePath}`); } @@ -63,27 +63,27 @@ export class ChangeFiles { projectsWithChangeDescriptions.forEach((name) => projectsMissingChangeDescriptions.delete(name)); if (projectsMissingChangeDescriptions.size > 0) { const projectsMissingChangeDescriptionsArray: string[] = []; - projectsMissingChangeDescriptions.forEach(name => projectsMissingChangeDescriptionsArray.push(name)); - throw new Error([ - 'The following projects have been changed and require change descriptions, but change descriptions were not ' + - 'detected for them:', - ...projectsMissingChangeDescriptionsArray.map((projectName) => `- ${projectName}`), - 'To resolve this error, run "rush change." This will generate change description files that must be ' + - 'committed to source control.' - ].join(EOL)); + projectsMissingChangeDescriptions.forEach((name) => projectsMissingChangeDescriptionsArray.push(name)); + throw new Error( + [ + 'The following projects have been changed and require change descriptions, but change descriptions were not ' + + 'detected for them:', + ...projectsMissingChangeDescriptionsArray.map((projectName) => `- ${projectName}`), + 'To resolve this error, run "rush change." This will generate change description files that must be ' + + 'committed to source control.', + ].join(EOL) + ); } } - public static getChangeComments( - newChangeFilePaths: string[] - ): Map { + public static getChangeComments(newChangeFilePaths: string[]): Map { const changes: Map = new Map(); newChangeFilePaths.forEach((filePath) => { console.log(`Found change file: ${filePath}`); const changeRequest: IChangeInfo = JsonFile.load(filePath); if (changeRequest && changeRequest.changes) { - changeRequest.changes!.forEach(change => { + changeRequest.changes!.forEach((change) => { if (!changes.get(change.packageName)) { changes.set(change.packageName, []); } @@ -147,9 +147,7 @@ export class ChangeFiles { private _deleteFiles(files: string[], shouldDelete: boolean): number { if (files.length) { console.log( - `${EOL}* ` + - `${shouldDelete ? 'DELETING:' : 'DRYRUN: Deleting'} ` + - `${files.length} change file(s).` + `${EOL}* ` + `${shouldDelete ? 'DELETING:' : 'DRYRUN: Deleting'} ` + `${files.length} change file(s).` ); for (const filePath of files) { diff --git a/apps/rush-lib/src/logic/ChangeManager.ts b/apps/rush-lib/src/logic/ChangeManager.ts index cdd8db8a8cc..fce07684dbf 100644 --- a/apps/rush-lib/src/logic/ChangeManager.ts +++ b/apps/rush-lib/src/logic/ChangeManager.ts @@ -57,7 +57,7 @@ export class ChangeManager { includeCommitDetails, this._prereleaseToken, this._lockStepProjectsToExclude - ); + ); this._orderedChanges = PublishUtilities.sortChangeRequests(this._allChanges); } @@ -74,17 +74,15 @@ export class ChangeManager { } public validateChanges(versionConfig: VersionPolicyConfiguration): void { - Object - .keys(this._allChanges) - .filter((key) => { - const projectInfo: RushConfigurationProject | undefined = this._rushConfiguration.getProjectByName(key); - if (projectInfo) { - if (projectInfo.versionPolicy) { - const changeInfo: IChangeInfo = this._allChanges[key]; - projectInfo.versionPolicy.validate(changeInfo.newVersion!, key); - } + Object.keys(this._allChanges).filter((key) => { + const projectInfo: RushConfigurationProject | undefined = this._rushConfiguration.getProjectByName(key); + if (projectInfo) { + if (projectInfo.versionPolicy) { + const changeInfo: IChangeInfo = this._allChanges[key]; + projectInfo.versionPolicy.validate(changeInfo.newVersion!, key); } - }); + } + }); } /** @@ -104,7 +102,8 @@ export class ChangeManager { this._rushConfiguration, shouldCommit, this._prereleaseToken, - this._lockStepProjectsToExclude); + this._lockStepProjectsToExclude + ); return updatedPackages; } @@ -125,4 +124,4 @@ export class ChangeManager { this._changeFiles.deleteAll(shouldCommit, updatedChangelogs); } } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/logic/ChangelogGenerator.ts b/apps/rush-lib/src/logic/ChangelogGenerator.ts index 0b3b2c6cdfe..80f6f5db5a4 100644 --- a/apps/rush-lib/src/logic/ChangelogGenerator.ts +++ b/apps/rush-lib/src/logic/ChangelogGenerator.ts @@ -4,24 +4,11 @@ import * as path from 'path'; import * as semver from 'semver'; -import { - FileSystem, - JsonFile -} from '@rushstack/node-core-library'; - -import { - PublishUtilities, - IChangeInfoHash -} from './PublishUtilities'; -import { - IChangeInfo, - ChangeType -} from '../api/ChangeManagement'; -import { - IChangelog, - IChangeLogEntry, - IChangeLogComment -} from '../api/Changelog'; +import { FileSystem, JsonFile } from '@rushstack/node-core-library'; + +import { PublishUtilities, IChangeInfoHash } from './PublishUtilities'; +import { IChangeInfo, ChangeType } from '../api/ChangeManagement'; +import { IChangelog, IChangeLogEntry, IChangeLogComment } from '../api/Changelog'; import { RushConfigurationProject } from '../api/RushConfigurationProject'; import { RushConfiguration } from '../api/RushConfiguration'; @@ -71,7 +58,7 @@ export class ChangelogGenerator { allProjects: Map, rushConfiguration: RushConfiguration ): void { - allProjects.forEach(project => { + allProjects.forEach((project) => { const markdownPath: string = path.resolve(project.projectFolder, CHANGELOG_MD); const markdownJSONPath: string = path.resolve(project.projectFolder, CHANGELOG_JSON); @@ -81,7 +68,10 @@ export class ChangelogGenerator { throw new Error('A CHANGELOG.md without json: ' + markdownPath); } - const changelog: IChangelog = ChangelogGenerator._getChangelog(project.packageName, project.projectFolder); + const changelog: IChangelog = ChangelogGenerator._getChangelog( + project.packageName, + project.projectFolder + ); const isLockstepped: boolean = !!project.versionPolicy && project.versionPolicy.isLockstepped; FileSystem.writeFile( @@ -89,7 +79,6 @@ export class ChangelogGenerator { ChangelogGenerator._translateToMarkdown(changelog, rushConfiguration, isLockstepped) ); } - }); } @@ -110,27 +99,23 @@ export class ChangelogGenerator { } const changelog: IChangelog = ChangelogGenerator._getChangelog(change.packageName, projectFolder); - if ( - !changelog.entries.some(entry => entry.version === change.newVersion)) { - + if (!changelog.entries.some((entry) => entry.version === change.newVersion)) { const changelogEntry: IChangeLogEntry = { version: change.newVersion!, tag: PublishUtilities.createTagname(change.packageName, change.newVersion!), date: new Date().toUTCString(), - comments: {} + comments: {}, }; - change.changes!.forEach(individualChange => { + change.changes!.forEach((individualChange) => { if (individualChange.comment) { - // Initialize the comments array only as necessary. const changeTypeString: string = ChangeType[individualChange.changeType!]; - const comments: IChangeLogComment[] = - changelogEntry.comments[changeTypeString] = - changelogEntry.comments[changeTypeString] || []; + const comments: IChangeLogComment[] = (changelogEntry.comments[changeTypeString] = + changelogEntry.comments[changeTypeString] || []); const changeLogComment: IChangeLogComment = { - comment: individualChange.comment + comment: individualChange.comment, }; if (individualChange.author) { changeLogComment.author = individualChange.author; @@ -149,7 +134,7 @@ export class ChangelogGenerator { console.log( `${EOL}* ${shouldCommit ? 'APPLYING' : 'DRYRUN'}: ` + - `Changelog update for "${change.packageName}@${change.newVersion}".` + `Changelog update for "${change.packageName}@${change.newVersion}".` ); if (shouldCommit) { @@ -182,7 +167,7 @@ export class ChangelogGenerator { if (!changelog) { changelog = { name: packageName, - entries: [] + entries: [], }; } else { // Force the changelog name to be same as package name. @@ -206,7 +191,7 @@ export class ChangelogGenerator { '', `This log was last generated on ${new Date().toUTCString()} and should not be manually modified.`, '', - '' + '', ].join(EOL); changelog.entries.forEach((entry, index) => { @@ -222,38 +207,42 @@ export class ChangelogGenerator { comments += ChangelogGenerator._getChangeComments( 'Breaking changes', - entry.comments[ChangeType[ChangeType.major]]); + entry.comments[ChangeType[ChangeType.major]] + ); comments += ChangelogGenerator._getChangeComments( 'Minor changes', - entry.comments[ChangeType[ChangeType.minor]]); + entry.comments[ChangeType[ChangeType.minor]] + ); comments += ChangelogGenerator._getChangeComments( 'Patches', - entry.comments[ChangeType[ChangeType.patch]]); + entry.comments[ChangeType[ChangeType.patch]] + ); if (isLockstepped) { // In lockstepped projects, all changes are of type ChangeType.none. comments += ChangelogGenerator._getChangeComments( 'Updates', - entry.comments[ChangeType[ChangeType.none]]); + entry.comments[ChangeType[ChangeType.none]] + ); } if (rushConfiguration.hotfixChangeEnabled) { comments += ChangelogGenerator._getChangeComments( 'Hotfixes', - entry.comments[ChangeType[ChangeType.hotfix]]); + entry.comments[ChangeType[ChangeType.hotfix]] + ); } if (!comments) { - markdown += ((changelog.entries.length === index + 1) ? - '*Initial release*' : - '*Version update only*') + - EOL + EOL; + markdown += + (changelog.entries.length === index + 1 ? '*Initial release*' : '*Version update only*') + + EOL + + EOL; } else { markdown += comments; } - }); return markdown; @@ -267,7 +256,7 @@ export class ChangelogGenerator { if (commentsArray) { comments = `### ${title}${EOL + EOL}`; - commentsArray.forEach(comment => { + commentsArray.forEach((comment) => { comments += `- ${comment.comment}${EOL}`; }); comments += EOL; @@ -288,9 +277,10 @@ export class ChangelogGenerator { project: RushConfigurationProject, allChanges: IChangeInfoHash ): boolean { - - return project.shouldPublish && + return ( + project.shouldPublish && (!semver.prerelease(project.packageJson.version) || - allChanges[project.packageName].changeType === ChangeType.hotfix); + allChanges[project.packageName].changeType === ChangeType.hotfix) + ); } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/logic/EventHooksManager.ts b/apps/rush-lib/src/logic/EventHooksManager.ts index dc3570c131d..fe860912d11 100644 --- a/apps/rush-lib/src/logic/EventHooksManager.ts +++ b/apps/rush-lib/src/logic/EventHooksManager.ts @@ -32,22 +32,22 @@ export class EventHooksManager { console.log(os.EOL + colors.green(`Executing event hooks for ${Event[event]}`)); scripts.forEach((script) => { try { - Utilities.executeLifecycleCommand( - script, - { - rushConfiguration: this._rushConfiguration, - workingDirectory: this._rushConfiguration.rushJsonFolder, - initCwd: this._commonTempFolder, - handleOutput: true, - environmentPathOptions: { - includeRepoBin: true - } - } - ); + Utilities.executeLifecycleCommand(script, { + rushConfiguration: this._rushConfiguration, + workingDirectory: this._rushConfiguration.rushJsonFolder, + initCwd: this._commonTempFolder, + handleOutput: true, + environmentPathOptions: { + includeRepoBin: true, + }, + }); } catch (error) { console.error( - os.EOL + colors.yellow(`Event hook "${script}" failed. Run "rush" with --debug` + - ` to see detailed error information.`) + os.EOL + + colors.yellow( + `Event hook "${script}" failed. Run "rush" with --debug` + + ` to see detailed error information.` + ) ); if (isDebug) { console.error(os.EOL + error.message); diff --git a/apps/rush-lib/src/logic/Git.ts b/apps/rush-lib/src/logic/Git.ts index 534d4e7dacd..d1e074d7122 100644 --- a/apps/rush-lib/src/logic/Git.ts +++ b/apps/rush-lib/src/logic/Git.ts @@ -49,7 +49,8 @@ export class Git { * the result of `Git.getGitInfo()` is used. */ public static isPathUnderGitWorkingTree(repoInfo?: gitInfo.GitRepoInfo): boolean { - if (Git.isGitPresent()) { // Do we even have a Git binary? + if (Git.isGitPresent()) { + // Do we even have a Git binary? if (!repoInfo) { repoInfo = Git.getGitInfo(); } @@ -87,21 +88,23 @@ export class Git { 'Unable to determine your Git configuration using this command:', '', ' git config user.email', - '' + '', ].join(os.EOL) ); throw new AlreadyReportedError(); } if (emailResult.result === undefined || emailResult.result.length === 0) { - console.log([ - 'This operation requires that a Git email be specified.', - '', - `If you didn't configure your email yet, try something like this:`, - '', - ...GitEmailPolicy.getEmailExampleLines(rushConfiguration), - '' - ].join(os.EOL)); + console.log( + [ + 'This operation requires that a Git email be specified.', + '', + `If you didn't configure your email yet, try something like this:`, + '', + ...GitEmailPolicy.getEmailExampleLines(rushConfiguration), + '', + ].join(os.EOL) + ); throw new AlreadyReportedError(); } @@ -146,20 +149,16 @@ export class Git { if (Git._gitEmailResult === undefined) { if (!Git.isGitPresent()) { Git._gitEmailResult = { - error: new Error('Git isn\'t present on the path') + error: new Error("Git isn't present on the path"), }; } else { try { Git._gitEmailResult = { - result: Utilities.executeCommandAndCaptureOutput( - 'git', - ['config', 'user.email'], - '.' - ).trim() + result: Utilities.executeCommandAndCaptureOutput('git', ['config', 'user.email'], '.').trim(), }; } catch (e) { Git._gitEmailResult = { - error: e + error: e, }; } } diff --git a/apps/rush-lib/src/logic/InstallManager.ts b/apps/rush-lib/src/logic/InstallManager.ts index 9df30a4908d..da8da051ba4 100644 --- a/apps/rush-lib/src/logic/InstallManager.ts +++ b/apps/rush-lib/src/logic/InstallManager.ts @@ -23,7 +23,7 @@ import { FileConstants, Sort, PosixModeBits, - JsonObject + JsonObject, } from '@rushstack/node-core-library'; import { ApprovedPackagesChecker } from '../logic/ApprovedPackagesChecker'; @@ -123,7 +123,7 @@ export interface IInstallManagerOptions { /** * Retry the install the specified number of times */ - maxInstallAttempts: number + maxInstallAttempts: number; } /** @@ -151,14 +151,17 @@ export class InstallManager { const lastInstallState: JsonObject = { node: process.versions.node, packageManager: rushConfiguration.packageManager, - packageManagerVersion: rushConfiguration.packageManagerToolVersion - } + packageManagerVersion: rushConfiguration.packageManagerToolVersion, + }; if (lastInstallState.packageManager === 'pnpm') { lastInstallState.storePath = rushConfiguration.pnpmOptions.pnpmStorePath; } - this._commonNodeModulesMarker = new LastInstallFlag(this._rushConfiguration.commonTempFolder, lastInstallState); + this._commonNodeModulesMarker = new LastInstallFlag( + this._rushConfiguration.commonTempFolder, + lastInstallState + ); } /** @@ -168,7 +171,7 @@ export class InstallManager { public static collectImplicitlyPreferredVersions( rushConfiguration: RushConfiguration, options: { - variant?: string | undefined + variant?: string | undefined; } = {} ): Map { // First, collect all the direct dependencies of all local projects, and their versions: @@ -176,23 +179,19 @@ export class InstallManager { const versionsForDependencies: Map> = new Map>(); rushConfiguration.projects.forEach((project: RushConfigurationProject) => { - InstallManager._collectVersionsForDependencies( - rushConfiguration, - { - versionsForDependencies, - dependencies: project.packageJsonEditor.dependencyList, - cyclicDependencies: project.cyclicDependencyProjects, - variant: options.variant - }); + InstallManager._collectVersionsForDependencies(rushConfiguration, { + versionsForDependencies, + dependencies: project.packageJsonEditor.dependencyList, + cyclicDependencies: project.cyclicDependencyProjects, + variant: options.variant, + }); - InstallManager._collectVersionsForDependencies( - rushConfiguration, - { - versionsForDependencies, - dependencies: project.packageJsonEditor.devDependencyList, - cyclicDependencies: project.cyclicDependencyProjects, - variant: options.variant - }); + InstallManager._collectVersionsForDependencies(rushConfiguration, { + versionsForDependencies, + dependencies: project.packageJsonEditor.devDependencyList, + cyclicDependencies: project.cyclicDependencyProjects, + variant: options.variant, + }); }); // If any dependency has more than one version, then filter it out (since we don't know which version @@ -209,8 +208,11 @@ export class InstallManager { } // Helper for collectImplicitlyPreferredVersions() - private static _updateVersionsForDependencies(versionsForDependencies: Map>, - dependency: string, version: string): void { + private static _updateVersionsForDependencies( + versionsForDependencies: Map>, + dependency: string, + version: string + ): void { if (!versionsForDependencies.has(dependency)) { versionsForDependencies.set(dependency, new Set()); } @@ -225,22 +227,18 @@ export class InstallManager { dependencies: ReadonlyArray; cyclicDependencies: Set; variant: string | undefined; - }): void { - const { - variant, - dependencies, - versionsForDependencies, - cyclicDependencies - } = options; + } + ): void { + const { variant, dependencies, versionsForDependencies, cyclicDependencies } = options; const commonVersions: CommonVersionsConfiguration = rushConfiguration.getCommonVersions(variant); - const allowedAlternativeVersions: Map> - = commonVersions.allowedAlternativeVersions; + const allowedAlternativeVersions: Map> = + commonVersions.allowedAlternativeVersions; for (const dependency of dependencies) { - const alternativesForThisDependency: ReadonlyArray - = allowedAlternativeVersions.get(dependency.name) || []; + const alternativesForThisDependency: ReadonlyArray = + allowedAlternativeVersions.get(dependency.name) || []; // For each dependency, collectImplicitlyPreferredVersions() is collecting the set of all version specifiers // that appear across the repo. If there is only one version specifier, then that's the "preferred" one. @@ -254,21 +252,29 @@ export class InstallManager { ignoreVersion = true; } else { // Is it a local project? - const localProject: RushConfigurationProject | undefined = rushConfiguration.getProjectByName(dependency.name); + const localProject: RushConfigurationProject | undefined = rushConfiguration.getProjectByName( + dependency.name + ); if (localProject) { // 2. If it's a symlinked local project, then it's not a candidate, because the package manager will // never even see it. // However there are two ways that a local project can NOT be symlinked: // - if the local project doesn't satisfy the referenced semver specifier; OR // - if the local project was specified in "cyclicDependencyProjects" in rush.json - if (semver.satisfies(localProject.packageJsonEditor.version, dependency.version) - && !cyclicDependencies.has(dependency.name)) { + if ( + semver.satisfies(localProject.packageJsonEditor.version, dependency.version) && + !cyclicDependencies.has(dependency.name) + ) { ignoreVersion = true; } } if (!ignoreVersion) { - InstallManager._updateVersionsForDependencies(versionsForDependencies, dependency.name, dependency.version); + InstallManager._updateVersionsForDependencies( + versionsForDependencies, + dependency.name, + dependency.version + ); } } } @@ -297,27 +303,35 @@ export class InstallManager { FileSystem.ensureEmptyFolder(hookDestination); // Only copy files that look like Git hook names - const filteredHookFilenames: string[] = hookFilenames.filter(x => /^[a-z\-]+/.test(x)); + const filteredHookFilenames: string[] = hookFilenames.filter((x) => /^[a-z\-]+/.test(x)); for (const filename of filteredHookFilenames) { FileSystem.copyFile({ sourcePath: path.join(hookSource, filename), - destinationPath: path.join(hookDestination, filename) + destinationPath: path.join(hookDestination, filename), }); - FileSystem.changePosixModeBits(path.join(hookDestination, filename), - PosixModeBits.UserRead | PosixModeBits.UserExecute); + FileSystem.changePosixModeBits( + path.join(hookDestination, filename), + PosixModeBits.UserRead | PosixModeBits.UserExecute + ); } - console.log('Successfully installed these Git hook scripts: ' + filteredHookFilenames.join(', ') + os.EOL); + console.log( + 'Successfully installed these Git hook scripts: ' + filteredHookFilenames.join(', ') + os.EOL + ); } } - const approvedPackagesChecker: ApprovedPackagesChecker = new ApprovedPackagesChecker(this._rushConfiguration); + const approvedPackagesChecker: ApprovedPackagesChecker = new ApprovedPackagesChecker( + this._rushConfiguration + ); if (approvedPackagesChecker.approvedPackagesFilesAreOutOfDate) { if (this._options.allowShrinkwrapUpdates) { approvedPackagesChecker.rewriteConfigFiles(); - console.log(colors.yellow( - 'Approved package files have been updated. These updates should be committed to source control' - )); + console.log( + colors.yellow( + 'Approved package files have been updated. These updates should be committed to source control' + ) + ); } else { throw new Error(`Approved packages files are out-of date. Run "rush update" to update them.`); } @@ -353,13 +367,13 @@ export class InstallManager { // This will be used by bulk scripts to determine the correct Shrinkwrap file to track. const currentVariantJsonFilename: string = this._rushConfiguration.currentVariantJsonFilename; const currentVariantJson: ICurrentVariantJson = { - variant: options.variant || null // eslint-disable-line @rushstack/no-null + variant: options.variant || null, // eslint-disable-line @rushstack/no-null }; // Determine if the variant is already current by updating current-variant.json. // If nothing is written, the variant has not changed. const variantIsUpToDate: boolean = !JsonFile.save(currentVariantJson, currentVariantJsonFilename, { - onlyIfChanged: true + onlyIfChanged: true, }); if (options.variant) { @@ -370,17 +384,18 @@ export class InstallManager { console.log(colors.bold('Using the default variant for installation.')); } - const shrinkwrapIsUpToDate: boolean = this._createTempModulesAndCheckShrinkwrap({ - shrinkwrapFile, - variant: options.variant - }) && !options.recheckShrinkwrap; + const shrinkwrapIsUpToDate: boolean = + this._createTempModulesAndCheckShrinkwrap({ + shrinkwrapFile, + variant: options.variant, + }) && !options.recheckShrinkwrap; if (!shrinkwrapIsUpToDate) { if (!options.allowShrinkwrapUpdates) { console.log(); - console.log(colors.red( - `The ${this._shrinkwrapFilePhrase} is out of date. You need to run "rush update".` - )); + console.log( + colors.red(`The ${this._shrinkwrapFilePhrase} is out of date. You need to run "rush update".`) + ); throw new AlreadyReportedError(); } } @@ -388,7 +403,7 @@ export class InstallManager { await this._installCommonModules({ shrinkwrapIsUpToDate, variantIsUpToDate, - ...options + ...options, }); if (!options.noLink) { @@ -422,7 +437,7 @@ export class InstallManager { const packageManagerToolFolder: string = path.join(rushUserFolder, packageManagerAndVersion); const packageManagerMarker: LastInstallFlag = new LastInstallFlag(packageManagerToolFolder, { - node: process.versions.node + node: process.versions.node, }); console.log(`Trying to acquire lock for ${packageManagerAndVersion}`); @@ -445,12 +460,14 @@ export class InstallManager { // In particular, we'll assume that two different NPM registries cannot have two // different implementations of the same version of the same package. // This was needed for: https://github.com/microsoft/rushstack/issues/691 - commonRushConfigFolder: this._rushConfiguration.commonRushConfigFolder + commonRushConfigFolder: this._rushConfiguration.commonRushConfigFolder, }); console.log(`Successfully installed ${packageManager} version ${packageManagerVersion}`); } else { - console.log(`Found ${packageManager} version ${packageManagerVersion} in ${packageManagerToolFolder}`); + console.log( + `Found ${packageManager} version ${packageManagerVersion} in ${packageManagerToolFolder}` + ); } packageManagerMarker.create(); @@ -459,8 +476,10 @@ export class InstallManager { FileSystem.ensureFolder(this._rushConfiguration.commonTempFolder); // Example: "C:\MyRepo\common\temp\pnpm-local" - const localPackageManagerToolFolder: string = - path.join(this._rushConfiguration.commonTempFolder, `${packageManager}-local`); + const localPackageManagerToolFolder: string = path.join( + this._rushConfiguration.commonTempFolder, + `${packageManager}-local` + ); console.log(os.EOL + 'Symlinking "' + localPackageManagerToolFolder + '"'); console.log(' --> "' + packageManagerToolFolder + '"'); @@ -477,7 +496,7 @@ export class InstallManager { FileSystem.createSymbolicLinkJunction({ linkTargetPath: packageManagerToolFolder, - newLinkPath: localPackageManagerToolFolder + newLinkPath: localPackageManagerToolFolder, }); lock.release(); @@ -494,16 +513,15 @@ export class InstallManager { shrinkwrapFile: BaseShrinkwrapFile | undefined; variant: string | undefined; }): boolean { - const { - shrinkwrapFile, - variant - } = options; + const { shrinkwrapFile, variant } = options; const stopwatch: Stopwatch = Stopwatch.start(); // Example: "C:\MyRepo\common\temp\projects" - const tempProjectsFolder: string = path.join(this._rushConfiguration.commonTempFolder, - RushConstants.rushTempProjectsFolderName); + const tempProjectsFolder: string = path.join( + this._rushConfiguration.commonTempFolder, + RushConstants.rushTempProjectsFolderName + ); console.log(os.EOL + colors.bold('Updating temp projects in ' + tempProjectsFolder)); @@ -520,7 +538,8 @@ export class InstallManager { } // dependency name --> version specifier - const allExplicitPreferredVersions: Map = this._rushConfiguration.getCommonVersions(variant) + const allExplicitPreferredVersions: Map = this._rushConfiguration + .getCommonVersions(variant) .getAllPreferredVersions(); if (shrinkwrapFile) { @@ -529,8 +548,10 @@ export class InstallManager { const dependencySpecifier: DependencySpecifier = new DependencySpecifier(dependency, version); if (!shrinkwrapFile.hasCompatibleTopLevelDependency(dependencySpecifier)) { - shrinkwrapWarnings.push(`"${dependency}" (${version}) required by the preferred versions from ` - + RushConstants.commonVersionsFilename); + shrinkwrapWarnings.push( + `"${dependency}" (${version}) required by the preferred versions from ` + + RushConstants.commonVersionsFilename + ); shrinkwrapIsUpToDate = false; } }); @@ -546,14 +567,18 @@ export class InstallManager { // Also copy down the committed .npmrc file, if there is one // "common\config\rush\.npmrc" --> "common\temp\.npmrc" // Also ensure that we remove any old one that may be hanging around - Utilities.syncNpmrc(this._rushConfiguration.commonRushConfigFolder, this._rushConfiguration.commonTempFolder); + Utilities.syncNpmrc( + this._rushConfiguration.commonRushConfigFolder, + this._rushConfiguration.commonTempFolder + ); // also, copy the pnpmfile.js if it exists if (this._rushConfiguration.packageManager === 'pnpm') { - const committedPnpmFilePath: string = - this._rushConfiguration.getPnpmfilePath(this._options.variant); - const tempPnpmFilePath: string - = path.join(this._rushConfiguration.commonTempFolder, RushConstants.pnpmfileFilename); + const committedPnpmFilePath: string = this._rushConfiguration.getPnpmfilePath(this._options.variant); + const tempPnpmFilePath: string = path.join( + this._rushConfiguration.commonTempFolder, + RushConstants.pnpmfileFilename + ); // ensure that we remove any old one that may be hanging around this._syncFile(committedPnpmFilePath, tempPnpmFilePath); @@ -564,7 +589,7 @@ export class InstallManager { description: 'Temporary file generated by the Rush tool', name: 'rush-common', private: true, - version: '0.0.0' + version: '0.0.0', }; // dependency name --> version specifier @@ -584,8 +609,10 @@ export class InstallManager { // Add in the implicitly preferred versions. // These are any first-level dependencies for which we only consume a single version range // (e.g. every package that depends on react uses an identical specifier) - const implicitlyPreferredVersions: Map = - InstallManager.collectImplicitlyPreferredVersions(this._rushConfiguration, { variant }); + const implicitlyPreferredVersions: Map< + string, + string + > = InstallManager.collectImplicitlyPreferredVersions(this._rushConfiguration, { variant }); MapExtensions.mergeFromMap(allPreferredVersions, implicitlyPreferredVersions); } @@ -602,7 +629,7 @@ export class InstallManager { // To make the common/package.json file more readable, sort alphabetically // according to rushProject.tempProjectName instead of packageName. const sortedRushProjects: RushConfigurationProject[] = this._rushConfiguration.projects.slice(0); - Sort.sortBy(sortedRushProjects, x => x.tempProjectName); + Sort.sortBy(sortedRushProjects, (x) => x.tempProjectName); for (const rushProject of sortedRushProjects) { const packageJson: PackageJsonEditor = rushProject.packageJsonEditor; @@ -611,14 +638,15 @@ export class InstallManager { const tarballFile: string = this._getTarballFilePath(rushProject); // Example: dependencies["@rush-temp/my-project-2"] = "file:./projects/my-project-2.tgz" - commonPackageJson.dependencies![rushProject.tempProjectName] - = `file:./${RushConstants.rushTempProjectsFolderName}/${rushProject.unscopedTempProjectName}.tgz`; + commonPackageJson.dependencies![ + rushProject.tempProjectName + ] = `file:./${RushConstants.rushTempProjectsFolderName}/${rushProject.unscopedTempProjectName}.tgz`; const tempPackageJson: IRushTempPackageJson = { name: rushProject.tempProjectName, version: '0.0.0', private: true, - dependencies: {} + dependencies: {}, }; // Collect pairs of (packageName, packageVersion) to be added as dependencies of the @rush-temp package.json @@ -627,7 +655,6 @@ export class InstallManager { // These can be regular, optional, or peer dependencies (but NOT dev dependencies). // (A given packageName will never appear more than once in this list.) for (const dependency of packageJson.dependencyList) { - // If there are any optional dependencies, copy directly into the optionalDependencies field. if (dependency.dependencyType === DependencyType.Optional) { if (!tempPackageJson.optionalDependencies) { @@ -654,17 +681,16 @@ export class InstallManager { // If so, then we will symlink to the project folder rather than to common/temp/node_modules. // In this case, we don't want "npm install" to process this package, but we do need // to record this decision for "rush link" later, so we add it to a special 'rushDependencies' field. - const localProject: RushConfigurationProject | undefined = - this._rushConfiguration.getProjectByName(packageName); + const localProject: RushConfigurationProject | undefined = this._rushConfiguration.getProjectByName( + packageName + ); if (localProject) { // Don't locally link if it's listed in the cyclicDependencyProjects if (!rushProject.cyclicDependencyProjects.has(packageName)) { - // Also, don't locally link if the SemVer doesn't match const localProjectVersion: string = localProject.packageJsonEditor.version; if (semver.satisfies(localProjectVersion, packageVersion)) { - // We will locally link this package, so instead add it to our special "rushDependencies" // field in the package.json file. if (!tempPackageJson.rushDependencies) { @@ -683,15 +709,21 @@ export class InstallManager { if (this._rushConfiguration.packageManager === 'pnpm') { // Shrinkwrap churn optimization doesn't make sense when --frozen-lockfile is true - tryReusingPackageVersionsFromShrinkwrap = - !this._rushConfiguration.experimentsConfiguration.configuration.usePnpmFrozenLockfileForRushInstall; + tryReusingPackageVersionsFromShrinkwrap = !this._rushConfiguration.experimentsConfiguration + .configuration.usePnpmFrozenLockfileForRushInstall; } if (shrinkwrapFile) { - if (!shrinkwrapFile.tryEnsureCompatibleDependency(dependencySpecifier, rushProject.tempProjectName, - tryReusingPackageVersionsFromShrinkwrap)) { - shrinkwrapWarnings.push(`"${packageName}" (${packageVersion}) required by` - + ` "${rushProject.packageName}"`); + if ( + !shrinkwrapFile.tryEnsureCompatibleDependency( + dependencySpecifier, + rushProject.tempProjectName, + tryReusingPackageVersionsFromShrinkwrap + ) + ) { + shrinkwrapWarnings.push( + `"${packageName}" (${packageVersion}) required by` + ` "${rushProject.packageName}"` + ); shrinkwrapIsUpToDate = false; } } @@ -708,7 +740,6 @@ export class InstallManager { try { // if the tarball and the temp file still exist, then compare the contents if (FileSystem.exists(tarballFile) && FileSystem.exists(tempPackageJsonFilename)) { - // compare the extracted package.json with the one we are about to write const oldBuffer: Buffer = FileSystem.readFileToBuffer(tempPackageJsonFilename); const newBuffer: Buffer = Buffer.from(JsonFile.stringify(tempPackageJson)); @@ -749,8 +780,10 @@ export class InstallManager { } // Example: "C:\MyRepo\common\temp\package.json" - const commonPackageJsonFilename: string = path.join(this._rushConfiguration.commonTempFolder, - FileConstants.PackageJson); + const commonPackageJsonFilename: string = path.join( + this._rushConfiguration.commonTempFolder, + FileConstants.PackageJson + ); if (shrinkwrapFile) { // If we have a (possibly incomplete) shrinkwrap file, check to see if any shrinkwrap-specific @@ -774,11 +807,15 @@ export class InstallManager { // new lockfile. Deleting this file in addition to deleting common/temp/pnpm-lock.yaml // ensures that a new lockfile will be generated with "rush update --full". - const pnpmPackageManager: PnpmPackageManager = - (this._rushConfiguration.packageManagerWrapper as PnpmPackageManager); + const pnpmPackageManager: PnpmPackageManager = this._rushConfiguration + .packageManagerWrapper as PnpmPackageManager; - FileSystem.deleteFile(path.join(this._rushConfiguration.commonTempFolder, - pnpmPackageManager.internalShrinkwrapRelativePath)); + FileSystem.deleteFile( + path.join( + this._rushConfiguration.commonTempFolder, + pnpmPackageManager.internalShrinkwrapRelativePath + ) + ); } } @@ -791,8 +828,11 @@ export class InstallManager { if (shrinkwrapWarnings.length > 0) { console.log(); - console.log(colors.yellow(Utilities.wrapWords( - `The ${this._shrinkwrapFilePhrase} is missing the following dependencies:`))); + console.log( + colors.yellow( + Utilities.wrapWords(`The ${this._shrinkwrapFilePhrase} is missing the following dependencies:`) + ) + ); for (const shrinkwrapWarning of shrinkwrapWarnings) { console.log(colors.yellow(' ' + shrinkwrapWarning)); @@ -805,7 +845,11 @@ export class InstallManager { private _getTempProjectFolder(rushProject: RushConfigurationProject): string { const unscopedTempProjectName: string = rushProject.unscopedTempProjectName; - return path.join(this._rushConfiguration.commonTempFolder, RushConstants.rushTempProjectsFolderName, unscopedTempProjectName); + return path.join( + this._rushConfiguration.commonTempFolder, + RushConstants.rushTempProjectsFolderName, + unscopedTempProjectName + ); } /** @@ -820,7 +864,7 @@ export class InstallManager { // NPM expects the root of the tarball to have a directory called 'package' const npmPackageFolder: string = 'package'; - const tarOptions: tar.CreateOptions = ({ + const tarOptions: tar.CreateOptions = { gzip: true, file: tarballFile, cwd: tempProjectFolder, @@ -830,14 +874,15 @@ export class InstallManager { sync: true, prefix: npmPackageFolder, filter: (path: string, stat: tar.FileStat): boolean => { - if (!this._rushConfiguration.experimentsConfiguration.configuration - .noChmodFieldInTarHeaderNormalization) { - stat.mode = (stat.mode & ~0x1FF) | PosixModeBits.AllRead | PosixModeBits.UserWrite - | PosixModeBits.AllExecute; + if ( + !this._rushConfiguration.experimentsConfiguration.configuration.noChmodFieldInTarHeaderNormalization + ) { + stat.mode = + (stat.mode & ~0x1ff) | PosixModeBits.AllRead | PosixModeBits.UserWrite | PosixModeBits.AllExecute; } return true; - } - } as tar.CreateOptions); + }, + } as tar.CreateOptions; // create the new tarball tar.create(tarOptions, [FileConstants.PackageJson]); } @@ -845,23 +890,27 @@ export class InstallManager { /** * Runs "npm/pnpm/yarn install" in the "common/temp" folder. */ - private _installCommonModules(options: { - shrinkwrapIsUpToDate: boolean; - variantIsUpToDate: boolean; - } & IInstallManagerOptions): Promise { - const { - shrinkwrapIsUpToDate, - variantIsUpToDate - } = options; - - const usePnpmFrozenLockfile: boolean = this._rushConfiguration.packageManager === 'pnpm' && - this._rushConfiguration.experimentsConfiguration.configuration.usePnpmFrozenLockfileForRushInstall === true; + private _installCommonModules( + options: { + shrinkwrapIsUpToDate: boolean; + variantIsUpToDate: boolean; + } & IInstallManagerOptions + ): Promise { + const { shrinkwrapIsUpToDate, variantIsUpToDate } = options; + + const usePnpmFrozenLockfile: boolean = + this._rushConfiguration.packageManager === 'pnpm' && + this._rushConfiguration.experimentsConfiguration.configuration.usePnpmFrozenLockfileForRushInstall === + true; return Promise.resolve().then(() => { - console.log(os.EOL + colors.bold('Checking node_modules in ' + this._rushConfiguration.commonTempFolder) - + os.EOL); + console.log( + os.EOL + colors.bold('Checking node_modules in ' + this._rushConfiguration.commonTempFolder) + os.EOL + ); - const commonNodeModulesFolder: string = path.join(this._rushConfiguration.commonTempFolder, - 'node_modules'); + const commonNodeModulesFolder: string = path.join( + this._rushConfiguration.commonTempFolder, + 'node_modules' + ); // This marker file indicates that the last "rush install" completed successfully const markerFileExistedAndWasValidAtStart: boolean = this._commonNodeModulesMarker.checkValidAndReportStoreIssues(); @@ -898,9 +947,11 @@ export class InstallManager { // Also consider timestamps for all the temp tarballs. (createTempModulesAndCheckShrinkwrap() will // carefully preserve these timestamps unless something has changed.) // Example: "C:\MyRepo\common\temp\projects\my-project-2.tgz" - potentiallyChangedFiles.push(...this._rushConfiguration.projects.map(x => { - return this._getTarballFilePath(x); - })); + potentiallyChangedFiles.push( + ...this._rushConfiguration.projects.map((x) => { + return this._getTarballFilePath(x); + }) + ); // NOTE: If commonNodeModulesMarkerFilename (or any of the potentiallyChangedFiles) does not // exist, then isFileTimestampCurrent() returns false. @@ -922,10 +973,12 @@ export class InstallManager { // If the user is working in an environment that can't reach the registry, // don't bother them with errors. return undefined; - }).then((publishedRelease: boolean | undefined) => { - + }) + .then((publishedRelease: boolean | undefined) => { if (publishedRelease === false) { - console.log(colors.yellow('Warning: This release of the Rush tool was unpublished; it may be unstable.')); + console.log( + colors.yellow('Warning: This release of the Rush tool was unpublished; it may be unstable.') + ); } // Since we're going to be tampering with common/node_modules, delete the "rush link" flag file if it exists; @@ -978,10 +1031,7 @@ export class InstallManager { } } - packageManagerEnv = this._mergeEnvironmentVariables( - process.env, - configurationEnvironment - ); + packageManagerEnv = this._mergeEnvironmentVariables(process.env, configurationEnvironment); // Is there an existing "node_modules" folder to consider? if (FileSystem.exists(commonNodeModulesFolder)) { @@ -1000,27 +1050,42 @@ export class InstallManager { // note: it is not necessary to run "prune" with pnpm if (this._rushConfiguration.packageManager === 'npm') { - console.log(`Running "${this._rushConfiguration.packageManager} prune"` - + ` in ${this._rushConfiguration.commonTempFolder}`); + console.log( + `Running "${this._rushConfiguration.packageManager} prune"` + + ` in ${this._rushConfiguration.commonTempFolder}` + ); const args: string[] = ['prune']; this._pushConfigurationArgs(args, options); - Utilities.executeCommandWithRetry(this._options.maxInstallAttempts, packageManagerFilename, args, - this._rushConfiguration.commonTempFolder, packageManagerEnv); + Utilities.executeCommandWithRetry( + this._options.maxInstallAttempts, + packageManagerFilename, + args, + this._rushConfiguration.commonTempFolder, + packageManagerEnv + ); // Delete the (installed image of) the temp projects, since "npm install" does not // detect changes for "file:./" references. // We recognize the temp projects by their names, which always start with "rush-". // Example: "C:\MyRepo\common\temp\node_modules\@rush-temp" - const pathToDeleteWithoutStar: string = path.join(commonNodeModulesFolder, - RushConstants.rushTempNpmScope); + const pathToDeleteWithoutStar: string = path.join( + commonNodeModulesFolder, + RushConstants.rushTempNpmScope + ); console.log(`Deleting ${pathToDeleteWithoutStar}\\*`); // Glob can't handle Windows paths - const normalizedpathToDeleteWithoutStar: string = Text.replaceAll(pathToDeleteWithoutStar, '\\', '/'); + const normalizedpathToDeleteWithoutStar: string = Text.replaceAll( + pathToDeleteWithoutStar, + '\\', + '/' + ); // Example: "C:/MyRepo/common/temp/node_modules/@rush-temp/*" - for (const tempModulePath of glob.sync(globEscape(normalizedpathToDeleteWithoutStar) + '/*')) { + for (const tempModulePath of glob.sync( + globEscape(normalizedpathToDeleteWithoutStar) + '/*' + )) { // We could potentially use AsyncRecycler here, but in practice these folders tend // to be very small Utilities.dangerouslyDeletePath(tempModulePath); @@ -1032,7 +1097,9 @@ export class InstallManager { if (this._rushConfiguration.packageManager === 'yarn') { // Yarn does not correctly detect changes to a tarball, so we need to forcibly clear its cache const yarnRushTempCacheFolder: string = path.join( - this._rushConfiguration.yarnCacheFolder, 'v2', 'npm-@rush-temp' + this._rushConfiguration.yarnCacheFolder, + 'v2', + 'npm-@rush-temp' ); if (FileSystem.exists(yarnRushTempCacheFolder)) { console.log('Deleting ' + yarnRushTempCacheFolder); @@ -1044,21 +1111,36 @@ export class InstallManager { const installArgs: string[] = ['install']; this._pushConfigurationArgs(installArgs, options); - console.log(os.EOL + colors.bold(`Running "${this._rushConfiguration.packageManager} install" in` - + ` ${this._rushConfiguration.commonTempFolder}`) + os.EOL); + console.log( + os.EOL + + colors.bold( + `Running "${this._rushConfiguration.packageManager} install" in` + + ` ${this._rushConfiguration.commonTempFolder}` + ) + + os.EOL + ); // If any diagnostic options were specified, then show the full command-line if (options.debug || options.collectLogFile || options.networkConcurrency) { - console.log(os.EOL + colors.green('Invoking package manager: ') - + FileSystem.getRealPath(packageManagerFilename) + ' ' + installArgs.join(' ') + os.EOL); + console.log( + os.EOL + + colors.green('Invoking package manager: ') + + FileSystem.getRealPath(packageManagerFilename) + + ' ' + + installArgs.join(' ') + + os.EOL + ); } try { - Utilities.executeCommandWithRetry(this._options.maxInstallAttempts, packageManagerFilename, + Utilities.executeCommandWithRetry( + this._options.maxInstallAttempts, + packageManagerFilename, installArgs, this._rushConfiguration.commonTempFolder, packageManagerEnv, - false, () => { + false, + () => { if (this._rushConfiguration.packageManager === 'pnpm') { console.log(colors.yellow(`Deleting the "node_modules" folder`)); this._commonTempFolderRecycler.moveFolder(commonNodeModulesFolder); @@ -1069,7 +1151,8 @@ export class InstallManager { Utilities.createFolderWithRetry(commonNodeModulesFolder); } - }); + } + ); } catch (error) { // All the install attempts failed. @@ -1088,12 +1171,14 @@ export class InstallManager { } if (this._rushConfiguration.packageManager === 'npm') { - console.log(os.EOL + colors.bold('Running "npm shrinkwrap"...')); const npmArgs: string[] = ['shrinkwrap']; this._pushConfigurationArgs(npmArgs, options); - Utilities.executeCommand(this._rushConfiguration.packageManagerToolFilename, - npmArgs, this._rushConfiguration.commonTempFolder); + Utilities.executeCommand( + this._rushConfiguration.packageManagerToolFilename, + npmArgs, + this._rushConfiguration.commonTempFolder + ); console.log('"npm shrinkwrap" completed' + os.EOL); this._fixupNpm5Regression(); @@ -1101,17 +1186,22 @@ export class InstallManager { if (options.allowShrinkwrapUpdates && (usePnpmFrozenLockfile || !shrinkwrapIsUpToDate)) { // Shrinkwrap files may need to be post processed after install, so load and save it - const tempShrinkwrapFile: BaseShrinkwrapFile | undefined = ShrinkwrapFileFactory.getShrinkwrapFile( + const tempShrinkwrapFile: + | BaseShrinkwrapFile + | undefined = ShrinkwrapFileFactory.getShrinkwrapFile( this._rushConfiguration.packageManager, this._rushConfiguration.packageManagerOptions, - this._rushConfiguration.tempShrinkwrapFilename); + this._rushConfiguration.tempShrinkwrapFilename + ); if (tempShrinkwrapFile) { tempShrinkwrapFile.save(this._rushConfiguration.tempShrinkwrapFilename); } // Copy (or delete) common\temp\pnpm-lock.yaml --> common\config\rush\pnpm-lock.yaml - this._syncFile(this._rushConfiguration.tempShrinkwrapFilename, - this._rushConfiguration.getCommittedShrinkwrapFilename(options.variant)); + this._syncFile( + this._rushConfiguration.tempShrinkwrapFilename, + this._rushConfiguration.getCommittedShrinkwrapFilename(options.variant) + ); } else { // TODO: Validate whether the package manager updated it in a nontrivial way } @@ -1146,8 +1236,7 @@ export class InstallManager { if (environmentVariables[envVar].override) { setEnvironmentVariable = true; console.log(`Overriding the environment variable with the value set in rush.json.`); - } - else { + } else { console.log(colors.yellow(`WARNING: Not overriding the value of the environment variable.`)); } } @@ -1168,8 +1257,11 @@ export class InstallManager { private _checkIfReleaseIsPublished(): Promise { return Promise.resolve().then(() => { - const lastCheckFile: string = path.join(this._rushGlobalFolder.nodeSpecificPath, - 'rush-' + Rush.version, 'last-check.flag'); + const lastCheckFile: string = path.join( + this._rushGlobalFolder.nodeSpecificPath, + 'rush-' + Rush.version, + 'last-check.flag' + ); if (FileSystem.exists(lastCheckFile)) { let cachedResult: boolean | 'error' | undefined = undefined; @@ -1233,48 +1325,48 @@ export class InstallManager { agent = new HttpsProxyAgent(process.env.HTTP_PROXY); } - return fetch.default(queryUrl, { - headers: headers, - agent: agent - }) + return fetch + .default(queryUrl, { + headers: headers, + agent: agent, + }) .then((response: fetch.Response) => { if (!response.ok) { return Promise.reject(new Error('Failed to query')); } - return response - .json() - .then((data) => { - let url: string; - try { - if (!data.versions[Rush.version]) { - // Version was not published - return false; - } - url = data.versions[Rush.version].dist.tarball; - if (!url) { - return Promise.reject(new Error(`URL not found`)); - } - } catch (e) { - return Promise.reject(new Error('Error parsing response')); + return response.json().then((data) => { + let url: string; + try { + if (!data.versions[Rush.version]) { + // Version was not published + return false; } + url = data.versions[Rush.version].dist.tarball; + if (!url) { + return Promise.reject(new Error(`URL not found`)); + } + } catch (e) { + return Promise.reject(new Error('Error parsing response')); + } - // Make sure the tarball wasn't deleted from the CDN - headers.set('accept', '*/*'); - return fetch.default(url, { + // Make sure the tarball wasn't deleted from the CDN + headers.set('accept', '*/*'); + return fetch + .default(url, { headers: headers, - agent: agent + agent: agent, }) - .then((response2: fetch.Response) => { - if (!response2.ok) { - if (response2.status === 404) { - return false; - } else { - return Promise.reject(new Error('Failed to fetch')); - } + .then((response2: fetch.Response) => { + if (!response2.ok) { + if (response2.status === 404) { + return false; + } else { + return Promise.reject(new Error('Failed to fetch')); } - return true; - }); - }); + } + return true; + }); + }); }); } @@ -1329,8 +1421,10 @@ export class InstallManager { // last install flag, which encapsulates the entire installation args.push('--no-lock'); - if (this._rushConfiguration.experimentsConfiguration.configuration.usePnpmFrozenLockfileForRushInstall && - !this._options.allowShrinkwrapUpdates) { + if ( + this._rushConfiguration.experimentsConfiguration.configuration.usePnpmFrozenLockfileForRushInstall && + !this._options.allowShrinkwrapUpdates + ) { if (semver.gte(this._rushConfiguration.packageManagerToolVersion, '3.0.0')) { args.push('--frozen-lockfile'); } else { @@ -1403,7 +1497,8 @@ export class InstallManager { return path.join( this._rushConfiguration.commonTempFolder, RushConstants.rushTempProjectsFolderName, - `${project.unscopedTempProjectName}.tgz`); + `${project.unscopedTempProjectName}.tgz` + ); } /** @@ -1421,15 +1516,20 @@ export class InstallManager { * in the node_modules folder, after "npm install" completes. */ private _fixupNpm5Regression(): void { - const pathToDeleteWithoutStar: string = path.join(this._rushConfiguration.commonTempFolder, - 'node_modules', RushConstants.rushTempNpmScope); + const pathToDeleteWithoutStar: string = path.join( + this._rushConfiguration.commonTempFolder, + 'node_modules', + RushConstants.rushTempNpmScope + ); // Glob can't handle Windows paths const normalizedPathToDeleteWithoutStar: string = Text.replaceAll(pathToDeleteWithoutStar, '\\', '/'); let anyChanges: boolean = false; // Example: "C:/MyRepo/common/temp/node_modules/@rush-temp/*/package.json" - for (const packageJsonPath of glob.sync(globEscape(normalizedPathToDeleteWithoutStar) + '/*/package.json')) { + for (const packageJsonPath of glob.sync( + globEscape(normalizedPathToDeleteWithoutStar) + '/*/package.json' + )) { // Example: "C:/MyRepo/common/temp/node_modules/@rush-temp/example/package.json" const packageJsonObject: IRushTempPackageJson = JsonFile.load(packageJsonPath); @@ -1453,18 +1553,23 @@ export class InstallManager { * @returns true if orphans were found, or false if everything is okay */ private _findOrphanedTempProjects(shrinkwrapFile: BaseShrinkwrapFile): boolean { - // We can recognize temp projects because they are under the "@rush-temp" NPM scope. for (const tempProjectName of shrinkwrapFile.getTempProjectNames()) { if (!this._rushConfiguration.findProjectByTempName(tempProjectName)) { - console.log(os.EOL + colors.yellow(Utilities.wrapWords( - `Your ${this._shrinkwrapFilePhrase} references a project "${tempProjectName}" which no longer exists.`)) - + os.EOL); - return true; // found one + console.log( + os.EOL + + colors.yellow( + Utilities.wrapWords( + `Your ${this._shrinkwrapFilePhrase} references a project "${tempProjectName}" which no longer exists.` + ) + ) + + os.EOL + ); + return true; // found one } } - return false; // none found + return false; // none found } private get _shrinkwrapFilePhrase(): string { diff --git a/apps/rush-lib/src/logic/JsonSchemaUrls.ts b/apps/rush-lib/src/logic/JsonSchemaUrls.ts index 7912aaf74cb..26be91f22ad 100644 --- a/apps/rush-lib/src/logic/JsonSchemaUrls.ts +++ b/apps/rush-lib/src/logic/JsonSchemaUrls.ts @@ -5,9 +5,9 @@ * JSON schema URLs that Rush writes into config files. */ export class JsonSchemaUrls { - public static readonly approvedPackages: string - = 'https://developer.microsoft.com/json-schemas/rush/v5/approved-packages.schema.json'; + public static readonly approvedPackages: string = + 'https://developer.microsoft.com/json-schemas/rush/v5/approved-packages.schema.json'; - public static readonly commonVersions: string - = 'https://developer.microsoft.com/json-schemas/rush/v5/common-versions.schema.json'; + public static readonly commonVersions: string = + 'https://developer.microsoft.com/json-schemas/rush/v5/common-versions.schema.json'; } diff --git a/apps/rush-lib/src/logic/LinkManagerFactory.ts b/apps/rush-lib/src/logic/LinkManagerFactory.ts index 3118653d9b0..c6f36989a94 100644 --- a/apps/rush-lib/src/logic/LinkManagerFactory.ts +++ b/apps/rush-lib/src/logic/LinkManagerFactory.ts @@ -7,10 +7,7 @@ import { NpmLinkManager } from './npm/NpmLinkManager'; import { PnpmLinkManager } from './pnpm/PnpmLinkManager'; export class LinkManagerFactory { - public static getLinkManager( - rushConfiguration: RushConfiguration - ): BaseLinkManager { - + public static getLinkManager(rushConfiguration: RushConfiguration): BaseLinkManager { switch (rushConfiguration.packageManager) { case 'npm': return new NpmLinkManager(rushConfiguration); diff --git a/apps/rush-lib/src/logic/NodeJsCompatibility.ts b/apps/rush-lib/src/logic/NodeJsCompatibility.ts index f3b1765d4dd..9e6703a70ba 100644 --- a/apps/rush-lib/src/logic/NodeJsCompatibility.ts +++ b/apps/rush-lib/src/logic/NodeJsCompatibility.ts @@ -42,10 +42,12 @@ export class NodeJsCompatibility { public static warnAboutVersionTooOld(): boolean { if (semver.satisfies(nodeVersion, '< 8.9.0')) { // We are on an ancient version of Node.js that is known not to work with Rush - console.error(colors.red( - `Your version of Node.js (${nodeVersion}) is very old and incompatible with Rush. ` + - `Please upgrade to the latest Long-Term Support (LTS) version.` - )); + console.error( + colors.red( + `Your version of Node.js (${nodeVersion}) is very old and incompatible with Rush. ` + + `Please upgrade to the latest Long-Term Support (LTS) version.` + ) + ); return true; } else { @@ -54,20 +56,24 @@ export class NodeJsCompatibility { } public static warnAboutVersionTooNew(options: IWarnAboutVersionTooNewOptions): boolean { - if (!options.alreadyReportedNodeTooNewError && nodeMajorVersion >= (UPCOMING_NODE_LTS_VERSION + 1)) { + if (!options.alreadyReportedNodeTooNewError && nodeMajorVersion >= UPCOMING_NODE_LTS_VERSION + 1) { // We are on a much newer release than we have tested and support if (options.isRushLib) { - console.warn(colors.yellow( - `Your version of Node.js (${nodeVersion}) has not been tested with this release ` + - `of the Rush engine. Please consider upgrading the "rushVersion" setting in rush.json, ` + - `or downgrading Node.js.` - )); + console.warn( + colors.yellow( + `Your version of Node.js (${nodeVersion}) has not been tested with this release ` + + `of the Rush engine. Please consider upgrading the "rushVersion" setting in rush.json, ` + + `or downgrading Node.js.` + ) + ); } else { - console.warn(colors.yellow( - `Your version of Node.js (${nodeVersion}) has not been tested with this release ` + - `of Rush. Please consider installing a newer version of the "@microsoft/rush" ` + - `package, or downgrading Node.js.` - )); + console.warn( + colors.yellow( + `Your version of Node.js (${nodeVersion}) has not been tested with this release ` + + `of Rush. Please consider installing a newer version of the "@microsoft/rush" ` + + `package, or downgrading Node.js.` + ) + ); } return true; @@ -77,15 +83,13 @@ export class NodeJsCompatibility { } public static warnAboutNonLtsVersion(rushConfiguration: RushConfiguration | undefined): boolean { - if ( - rushConfiguration && - !rushConfiguration.suppressNodeLtsWarning && - !NodeJsCompatibility.isLtsVersion - ) { - console.warn(colors.yellow( - `Your version of Node.js (${nodeVersion}) is not a Long-Term Support (LTS) release. ` + - 'These versions frequently have bugs. Please consider installing a stable release.' - )); + if (rushConfiguration && !rushConfiguration.suppressNodeLtsWarning && !NodeJsCompatibility.isLtsVersion) { + console.warn( + colors.yellow( + `Your version of Node.js (${nodeVersion}) is not a Long-Term Support (LTS) release. ` + + 'These versions frequently have bugs. Please consider installing a stable release.' + ) + ); return true; } else { @@ -95,11 +99,13 @@ export class NodeJsCompatibility { public static warnAboutOddNumberedVersion(): boolean { if (NodeJsCompatibility.isOddNumberedVersion) { - console.warn(colors.yellow( - `Your version of Node.js (${nodeVersion}) is an odd-numbered release. ` + - `These releases frequently have bugs. Please consider installing a Long Term Support (LTS) ` + - `version instead.` - )); + console.warn( + colors.yellow( + `Your version of Node.js (${nodeVersion}) is an odd-numbered release. ` + + `These releases frequently have bugs. Please consider installing a Long Term Support (LTS) ` + + `version instead.` + ) + ); return true; } else { @@ -108,10 +114,10 @@ export class NodeJsCompatibility { } public static get isLtsVersion(): boolean { - return !!process.release.lts; + return !!process.release.lts; } public static get isOddNumberedVersion(): boolean { - return (nodeMajorVersion % 2) !== 0; + return nodeMajorVersion % 2 !== 0; } } diff --git a/apps/rush-lib/src/logic/PackageChangeAnalyzer.ts b/apps/rush-lib/src/logic/PackageChangeAnalyzer.ts index 377038c1e1c..c8d60d7f96b 100644 --- a/apps/rush-lib/src/logic/PackageChangeAnalyzer.ts +++ b/apps/rush-lib/src/logic/PackageChangeAnalyzer.ts @@ -4,16 +4,8 @@ import * as path from 'path'; import * as colors from 'colors'; -import { - getPackageDeps, - getGitHashForFiles, - IPackageDeps -} from '@rushstack/package-deps-hash'; -import { - Path, - InternalError, - FileSystem -} from '@rushstack/node-core-library'; +import { getPackageDeps, getGitHashForFiles, IPackageDeps } from '@rushstack/package-deps-hash'; +import { Path, InternalError, FileSystem } from '@rushstack/node-core-library'; import { RushConfiguration } from '../api/RushConfiguration'; import { Git } from './Git'; @@ -53,7 +45,7 @@ export class PackageChangeAnalyzer { // pre-populate the map with the projects from the config for (const project of this._rushConfiguration.projects) { projectHashDeps.set(project.packageName, { - files: {} + files: {}, }); } @@ -70,9 +62,11 @@ export class PackageChangeAnalyzer { } catch (e) { // If getPackageDeps fails, don't fail the whole build. Treat this case as if we don't know anything about // the state of the files in the repo. This can happen if the environment doesn't have Git. - console.log(colors.yellow( - `Error calculating the state of the repo. (inner error: ${e}). Continuing without diffing files.` - )); + console.log( + colors.yellow( + `Error calculating the state of the repo. (inner error: ${e}). Continuing without diffing files.` + ) + ); return projectHashDeps; } @@ -136,22 +130,24 @@ export class PackageChangeAnalyzer { if ( this._rushConfiguration.packageManager === 'pnpm' && - !this._rushConfiguration.experimentsConfiguration.configuration.legacyIncrementalBuildDependencyDetection + !this._rushConfiguration.experimentsConfiguration.configuration + .legacyIncrementalBuildDependencyDetection ) { const projects: RushConfigurationProject[] = []; const projectDependencyManifestPaths: string[] = []; for (const project of this._rushConfiguration.projects) { - const dependencyManifestFilePath: string = PnpmProjectDependencyManifest.getFilePathForProject(project); - const relativeDependencyManifestFilePath: string = path.relative( - this._rushConfiguration.rushJsonFolder, - dependencyManifestFilePath - ).replace(/\\/g, '/'); + const dependencyManifestFilePath: string = PnpmProjectDependencyManifest.getFilePathForProject( + project + ); + const relativeDependencyManifestFilePath: string = path + .relative(this._rushConfiguration.rushJsonFolder, dependencyManifestFilePath) + .replace(/\\/g, '/'); if (!FileSystem.exists(dependencyManifestFilePath)) { throw new Error( `A project dependency file (${relativeDependencyManifestFilePath}) is missing. You may need to run ` + - '"rush unlink" and "rush link".' + '"rush unlink" and "rush link".' ); } @@ -177,10 +173,12 @@ export class PackageChangeAnalyzer { const variant: string | undefined = this._rushConfiguration.currentInstalledVariant; // Add the shrinkwrap file to every project's dependencies - const shrinkwrapFile: string = path.relative( - this._rushConfiguration.rushJsonFolder, - this._rushConfiguration.getCommittedShrinkwrapFilename(variant) - ).replace(/\\/g, '/'); + const shrinkwrapFile: string = path + .relative( + this._rushConfiguration.rushJsonFolder, + this._rushConfiguration.getCommittedShrinkwrapFilename(variant) + ) + .replace(/\\/g, '/'); for (const project of this._rushConfiguration.projects) { const shrinkwrapHash: string | undefined = noProjectHashes[shrinkwrapFile]; diff --git a/apps/rush-lib/src/logic/PackageJsonUpdater.ts b/apps/rush-lib/src/logic/PackageJsonUpdater.ts index 61a8dba3ac3..580ce4d4048 100644 --- a/apps/rush-lib/src/logic/PackageJsonUpdater.ts +++ b/apps/rush-lib/src/logic/PackageJsonUpdater.ts @@ -9,10 +9,7 @@ import { InstallManager, IInstallManagerOptions } from './InstallManager'; import { VersionMismatchFinder } from './versionMismatch/VersionMismatchFinder'; import { PurgeManager } from './PurgeManager'; import { Utilities } from '../utilities/Utilities'; -import { - DependencyType, - PackageJsonDependency -} from '../api/PackageJsonEditor'; +import { DependencyType, PackageJsonDependency } from '../api/PackageJsonEditor'; import { RushGlobalFolder } from '../api/RushGlobalFolder'; import { RushConfigurationProject } from '../api/RushConfigurationProject'; import { VersionMismatchFinderEntity } from './versionMismatch/VersionMismatchFinderEntity'; @@ -26,7 +23,7 @@ export const enum SemVerStyle { Exact = 'exact', Caret = 'caret', Tilde = 'tilde', - Passthrough = 'passthrough' + Passthrough = 'passthrough', } /** @@ -122,13 +119,13 @@ export class PackageJsonUpdater { skipUpdate, debugInstall, rangeStyle, - variant + variant, } = options; const implicitlyPinned: Map = InstallManager.collectImplicitlyPreferredVersions( this._rushConfiguration, { - variant + variant, } ); @@ -143,7 +140,7 @@ export class PackageJsonUpdater { networkConcurrency: undefined, collectLogFile: false, variant: variant, - maxInstallAttempts: RushConstants.defaultMaxInstallAttempts + maxInstallAttempts: RushConstants.defaultMaxInstallAttempts, }; const installManager: InstallManager = new InstallManager( this._rushConfiguration, @@ -172,7 +169,7 @@ export class PackageJsonUpdater { project: new VersionMismatchFinderProject(project), packageName, newVersion: version, - dependencyType: devDependency ? DependencyType.Dev : undefined + dependencyType: devDependency ? DependencyType.Dev : undefined, }; this.updateProject(currentProjectUpdate); @@ -180,18 +177,23 @@ export class PackageJsonUpdater { if (this._rushConfiguration.ensureConsistentVersions || updateOtherPackages) { // we need to do a mismatch check - const mismatchFinder: VersionMismatchFinder = VersionMismatchFinder.getMismatches(this._rushConfiguration, { - variant: variant - }); + const mismatchFinder: VersionMismatchFinder = VersionMismatchFinder.getMismatches( + this._rushConfiguration, + { + variant: variant, + } + ); const mismatches: string[] = mismatchFinder.getMismatches().filter((mismatch) => { return !projects.find((proj) => proj.packageName === mismatch); }); if (mismatches.length) { if (!updateOtherPackages) { - throw new Error(`Adding '${packageName}@${version}' to ${project.packageName}` - + ` causes mismatched dependencies. Use the "--make-consistent" flag to update other packages to use` - + ` this version, or do not specify a SemVer range.`); + throw new Error( + `Adding '${packageName}@${version}' to ${project.packageName}` + + ` causes mismatched dependencies. Use the "--make-consistent" flag to update other packages to use` + + ` this version, or do not specify a SemVer range.` + ); } // otherwise we need to go update a bunch of other projects @@ -203,7 +205,7 @@ export class PackageJsonUpdater { otherPackageUpdates.push({ project: consumer, packageName: packageName, - newVersion: version + newVersion: version, }); } } @@ -249,18 +251,16 @@ export class PackageJsonUpdater { */ public updateProject(options: IUpdateProjectOptions): void { let { dependencyType } = options; - const { - project, - packageName, - newVersion - } = options; + const { project, packageName, newVersion } = options; const oldDependency: PackageJsonDependency | undefined = project.tryGetDependency(packageName); const oldDevDependency: PackageJsonDependency | undefined = project.tryGetDevDependency(packageName); const oldDependencyType: DependencyType | undefined = oldDevDependency ? oldDevDependency.dependencyType - : (oldDependency ? oldDependency.dependencyType : undefined); + : oldDependency + ? oldDependency.dependencyType + : undefined; dependencyType = dependencyType || oldDependencyType || DependencyType.Regular; @@ -295,20 +295,29 @@ export class PackageJsonUpdater { console.log(); // determine if the package is a project in the local repository and if the version exists - const localProject: RushConfigurationProject | undefined = this._tryGetLocalProject(packageName, projects); + const localProject: RushConfigurationProject | undefined = this._tryGetLocalProject( + packageName, + projects + ); // if ensureConsistentVersions => reuse the pinned version // else, query the registry and use the latest that satisfies semver spec if (initialSpec && implicitlyPinnedVersion && initialSpec === implicitlyPinnedVersion) { - console.log(colors.green('Assigning "') - + colors.cyan(initialSpec) - + colors.green(`" for "${packageName}" because it matches what other projects are using in this repo.`)); + console.log( + colors.green('Assigning "') + + colors.cyan(initialSpec) + + colors.green( + `" for "${packageName}" because it matches what other projects are using in this repo.` + ) + ); return initialSpec; } if (this._rushConfiguration.ensureConsistentVersions && !initialSpec && implicitlyPinnedVersion) { - console.log(`Assigning the version range "${colors.cyan(implicitlyPinnedVersion)}" for "${packageName}" because` - + ` it is already used by other projects in this repo.`); + console.log( + `Assigning the version range "${colors.cyan(implicitlyPinnedVersion)}" for "${packageName}" because` + + ` it is already used by other projects in this repo.` + ); return implicitlyPinnedVersion; } @@ -326,10 +335,10 @@ export class PackageJsonUpdater { } else { throw new Error( `The dependency being added ("${packageName}") is a project in the local Rush repository, ` + - `but the version specifier provided (${initialSpec}) does not match the local project's version ` + - `(${version}). Correct the version specifier, omit a version specifier, or include "${packageName}" as a ` + - `cyclicDependencyProject if it is intended for "${packageName}" to come from an external feed and not ` + - 'from the local Rush repository.' + `but the version specifier provided (${initialSpec}) does not match the local project's version ` + + `(${version}). Correct the version specifier, omit a version specifier, or include "${packageName}" as a ` + + `cyclicDependencyProject if it is intended for "${packageName}" to come from an external feed and not ` + + 'from the local Rush repository.' ); } } else { @@ -342,12 +351,11 @@ export class PackageJsonUpdater { commandArgs = ['view', packageName, 'versions', '--json']; } - const allVersions: string = - Utilities.executeCommandAndCaptureOutput( - this._rushConfiguration.packageManagerToolFilename, - commandArgs, - this._rushConfiguration.commonTempFolder - ); + const allVersions: string = Utilities.executeCommandAndCaptureOutput( + this._rushConfiguration.packageManagerToolFilename, + commandArgs, + this._rushConfiguration.commonTempFolder + ); let versionList: string[]; if (this._rushConfiguration.packageManager === 'yarn') { @@ -367,14 +375,19 @@ export class PackageJsonUpdater { } if (!selectedVersion) { - throw new Error(`Unable to find a version of "${packageName}" that satisfies` - + ` the version specifier "${initialSpec}"`); + throw new Error( + `Unable to find a version of "${packageName}" that satisfies` + + ` the version specifier "${initialSpec}"` + ); } } } else { if (!this._rushConfiguration.ensureConsistentVersions) { - console.log(colors.gray(`The "ensureConsistentVersions" policy is NOT active,` - + ` so we will assign the latest version.`)); + console.log( + colors.gray( + `The "ensureConsistentVersions" policy is NOT active,` + ` so we will assign the latest version.` + ) + ); console.log(); } @@ -406,14 +419,22 @@ export class PackageJsonUpdater { switch (rangeStyle) { case SemVerStyle.Caret: { - console.log(colors.grey(`Assigning version "^${selectedVersion}" for "${packageName}" because the "--caret"` - + ` flag was specified.`)); + console.log( + colors.grey( + `Assigning version "^${selectedVersion}" for "${packageName}" because the "--caret"` + + ` flag was specified.` + ) + ); return `^${selectedVersion}`; } case SemVerStyle.Exact: { - console.log(colors.grey(`Assigning version "${selectedVersion}" for "${packageName}" because the "--exact"` - + ` flag was specified.`)); + console.log( + colors.grey( + `Assigning version "${selectedVersion}" for "${packageName}" because the "--exact"` + + ` flag was specified.` + ) + ); return selectedVersion; } @@ -433,8 +454,12 @@ export class PackageJsonUpdater { } } - private _collectAllDownstreamDependencies(project: RushConfigurationProject): Set { - const allProjectDownstreamDependencies: Set = new Set(); + private _collectAllDownstreamDependencies( + project: RushConfigurationProject + ): Set { + const allProjectDownstreamDependencies: Set = new Set< + RushConfigurationProject + >(); const collectDependencies: (rushProject: RushConfigurationProject) => void = ( rushProject: RushConfigurationProject @@ -453,11 +478,11 @@ export class PackageJsonUpdater { } if (!allProjectDownstreamDependencies.has(foundProject)) { - allProjectDownstreamDependencies.add(foundProject) + allProjectDownstreamDependencies.add(foundProject); collectDependencies(foundProject); } } - } + }; collectDependencies(project); return allProjectDownstreamDependencies; @@ -499,16 +524,18 @@ export class PackageJsonUpdater { if (project === foundProject) { throw new Error( 'Unable to add a project as a dependency of itself unless the dependency is listed as a cyclic dependency ' + - `in rush.json. This command attempted to add "${foundProject.packageName}" as a dependency of itself.` + `in rush.json. This command attempted to add "${foundProject.packageName}" as a dependency of itself.` ); } // Are we attempting to create a cycle? - const downstreamDependencies: Set = this._collectAllDownstreamDependencies(project); + const downstreamDependencies: Set = this._collectAllDownstreamDependencies( + project + ); if (downstreamDependencies.has(foundProject)) { throw new Error( `Adding "${foundProject.packageName}" as a direct or indirect dependency of ` + - `"${project.packageName}" would create a dependency cycle.` + `"${project.packageName}" would create a dependency cycle.` ); } diff --git a/apps/rush-lib/src/logic/ProjectCommandSet.ts b/apps/rush-lib/src/logic/ProjectCommandSet.ts index 36045b9eb8d..b02ff60762e 100644 --- a/apps/rush-lib/src/logic/ProjectCommandSet.ts +++ b/apps/rush-lib/src/logic/ProjectCommandSet.ts @@ -1,10 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - IPackageJson, - IPackageJsonScriptTable - } from '@rushstack/node-core-library'; +import { IPackageJson, IPackageJsonScriptTable } from '@rushstack/node-core-library'; /** * Parses the "scripts" section from package.json and provides support for executing scripts. @@ -15,7 +12,7 @@ export class ProjectCommandSet { private readonly _scriptsByName: Map = new Map(); public constructor(packageJson: IPackageJson) { - const scripts: IPackageJsonScriptTable = packageJson.scripts || { }; + const scripts: IPackageJsonScriptTable = packageJson.scripts || {}; for (const scriptName of Object.keys(scripts)) { if (scriptName[0] === '-' || scriptName.length === 0) { diff --git a/apps/rush-lib/src/logic/PublishGit.ts b/apps/rush-lib/src/logic/PublishGit.ts index efef2ff4c0f..52293418080 100644 --- a/apps/rush-lib/src/logic/PublishGit.ts +++ b/apps/rush-lib/src/logic/PublishGit.ts @@ -9,7 +9,6 @@ export class PublishGit { private _targetBranch: string | undefined; public constructor(targetBranch: string | undefined) { - this._targetBranch = targetBranch; } @@ -26,7 +25,11 @@ export class PublishGit { public deleteBranch(branchName: string, hasRemote: boolean = true): void { PublishUtilities.execCommand(!!this._targetBranch, 'git', `branch -d ${branchName}`.split(' ')); if (hasRemote) { - PublishUtilities.execCommand(!!this._targetBranch, 'git', `push origin --delete ${branchName}`.split(' ')); + PublishUtilities.execCommand( + !!this._targetBranch, + 'git', + `push origin --delete ${branchName}`.split(' ') + ); } } @@ -40,17 +43,30 @@ export class PublishGit { public addChanges(pathspec?: string, workingDirectory?: string): void { const files: string = pathspec ? pathspec : '.'; - PublishUtilities.execCommand(!!this._targetBranch, 'git', ['add', files], - workingDirectory ? workingDirectory : process.cwd()); + PublishUtilities.execCommand( + !!this._targetBranch, + 'git', + ['add', files], + workingDirectory ? workingDirectory : process.cwd() + ); } - public addTag(shouldExecute: boolean, packageName: string, packageVersion: string, commitId: string | undefined): void { + public addTag( + shouldExecute: boolean, + packageName: string, + packageVersion: string, + commitId: string | undefined + ): void { // Tagging only happens if we're publishing to real NPM and committing to git. const tagName: string = PublishUtilities.createTagname(packageName, packageVersion); - PublishUtilities.execCommand( - !!this._targetBranch && shouldExecute, - 'git', - ['tag', '-a', tagName, '-m', `${packageName} v${packageVersion}`, ...(commitId ? [commitId] : [])]); + PublishUtilities.execCommand(!!this._targetBranch && shouldExecute, 'git', [ + 'tag', + '-a', + tagName, + '-m', + `${packageName} v${packageVersion}`, + ...(commitId ? [commitId] : []), + ]); } public hasTag(packageConfig: RushConfigurationProject): boolean { @@ -79,6 +95,7 @@ export class PublishGit { 'git', // We append "--no-verify" to prevent Git hooks from running. For example, people may // want to invoke "rush change -v" as a pre-push hook. - ['push', 'origin', 'HEAD:' + branchName, '--follow-tags', '--verbose', '--no-verify']); + ['push', 'origin', 'HEAD:' + branchName, '--follow-tags', '--verbose', '--no-verify'] + ); } } diff --git a/apps/rush-lib/src/logic/PublishUtilities.ts b/apps/rush-lib/src/logic/PublishUtilities.ts index 583c1fe1150..1281107a301 100644 --- a/apps/rush-lib/src/logic/PublishUtilities.ts +++ b/apps/rush-lib/src/logic/PublishUtilities.ts @@ -10,17 +10,9 @@ import { EOL } from 'os'; import * as path from 'path'; import * as semver from 'semver'; -import { - IPackageJson, - JsonFile, - FileConstants, - Text -} from '@rushstack/node-core-library'; - -import { - IChangeInfo, - ChangeType -} from '../api/ChangeManagement'; +import { IPackageJson, JsonFile, FileConstants, Text } from '@rushstack/node-core-library'; + +import { IChangeInfo, ChangeType } from '../api/ChangeManagement'; import { RushConfigurationProject } from '../api/RushConfigurationProject'; import { Utilities, IEnvironment } from '../utilities/Utilities'; import { execSync } from 'child_process'; @@ -46,7 +38,6 @@ export class PublishUtilities { prereleaseToken?: PrereleaseToken, projectsToExclude?: Set ): IChangeInfoHash { - const allChanges: IChangeInfoHash = {}; console.log(`Finding changes in: ${changeFiles.getChangesPath()}`); @@ -95,15 +86,21 @@ export class PublishUtilities { const deps: string[] = project.downstreamDependencyProjects; // Write the new version expected for the change. - const skipVersionBump: boolean = PublishUtilities._shouldSkipVersionBump(project, - prereleaseToken, projectsToExclude); + const skipVersionBump: boolean = PublishUtilities._shouldSkipVersionBump( + project, + prereleaseToken, + projectsToExclude + ); if (skipVersionBump) { change.newVersion = pkg.version; } else { // For hotfix changes, do not re-write new version - change.newVersion = (change.changeType! >= ChangeType.patch) ? - semver.inc(pkg.version, PublishUtilities._getReleaseType(change.changeType!)) : - (change.changeType === ChangeType.hotfix ? change.newVersion : pkg.version); + change.newVersion = + change.changeType! >= ChangeType.patch + ? semver.inc(pkg.version, PublishUtilities._getReleaseType(change.changeType!)) + : change.changeType === ChangeType.hotfix + ? change.newVersion + : pkg.version; } if (deps) { @@ -127,10 +124,9 @@ export class PublishUtilities { * @returns Sorted array of change requests. */ public static sortChangeRequests(allChanges: IChangeInfoHash): IChangeInfo[] { - return Object - .keys(allChanges) - .map(key => allChanges[key]) - .sort((a, b) => a.order! < b.order! ? -1 : 1); + return Object.keys(allChanges) + .map((key) => allChanges[key]) + .sort((a, b) => (a.order! < b.order! ? -1 : 1)); } /** @@ -146,7 +142,7 @@ export class PublishUtilities { ): Map { const updatedPackages: Map = new Map(); - Object.keys(allChanges).forEach(packageName => { + Object.keys(allChanges).forEach((packageName) => { const updatedPackage: IPackageJson = PublishUtilities._writePackageChanges( allChanges[packageName], allChanges, @@ -154,7 +150,8 @@ export class PublishUtilities { rushConfiguration, shouldCommit, prereleaseToken, - projectsToExclude); + projectsToExclude + ); updatedPackages.set(updatedPackage.name, updatedPackage); }); @@ -196,7 +193,6 @@ export class PublishUtilities { environment?: IEnvironment, secretSubstring?: string ): void { - let relativeDirectory: string = path.relative(process.cwd(), workingDirectory); if (relativeDirectory) { @@ -215,17 +211,12 @@ export class PublishUtilities { ); if (shouldExecute) { - Utilities.executeCommand( - command, - args, - workingDirectory, - environment, - false, - true); + Utilities.executeCommand(command, args, workingDirectory, environment, false, true); } } - public static getNewDependencyVersion(dependencies: { [key: string]: string; }, + public static getNewDependencyVersion( + dependencies: { [key: string]: string }, dependencyName: string, newProjectVersion: string ): string { @@ -269,28 +260,35 @@ export class PublishUtilities { return `>=${newVersion} <${upperLimit}`; } - private static _shouldSkipVersionBump(project: RushConfigurationProject, + private static _shouldSkipVersionBump( + project: RushConfigurationProject, prereleaseToken?: PrereleaseToken, projectsToExclude?: Set ): boolean { // Suffix does not bump up the version. // Excluded projects do not bump up version. - return prereleaseToken && prereleaseToken.isSuffix || - projectsToExclude && projectsToExclude.has(project.packageName) || - !project.shouldPublish; + return ( + (prereleaseToken && prereleaseToken.isSuffix) || + (projectsToExclude && projectsToExclude.has(project.packageName)) || + !project.shouldPublish + ); } private static _updateCommitDetails(filename: string, changes: IChangeInfo[] | undefined): void { try { - const fileLog: string = execSync('git log -n 1 ' + filename, { cwd: path.dirname(filename) }).toString(); + const fileLog: string = execSync('git log -n 1 ' + filename, { + cwd: path.dirname(filename), + }).toString(); const author: string = fileLog.match(/Author: (.*)/)![1]; const commit: string = fileLog.match(/commit (.*)/)![1]; - changes!.forEach(change => { + changes!.forEach((change) => { change.author = author; change.commit = commit; }); - } catch (e) { /* no-op, best effort. */ } + } catch (e) { + /* no-op, best effort. */ + } } private static _writePackageChanges( @@ -302,20 +300,20 @@ export class PublishUtilities { prereleaseToken?: PrereleaseToken, projectsToExclude?: Set ): IPackageJson { - const project: RushConfigurationProject = allPackages.get(change.packageName)!; const pkg: IPackageJson = project.packageJson; - const shouldSkipVersionBump: boolean = !project.shouldPublish || - !!projectsToExclude && projectsToExclude.has(change.packageName); + const shouldSkipVersionBump: boolean = + !project.shouldPublish || (!!projectsToExclude && projectsToExclude.has(change.packageName)); - const newVersion: string = shouldSkipVersionBump ? pkg.version : - PublishUtilities._getChangeInfoNewVersion(change, prereleaseToken); + const newVersion: string = shouldSkipVersionBump + ? pkg.version + : PublishUtilities._getChangeInfoNewVersion(change, prereleaseToken); if (!shouldSkipVersionBump) { console.log( `${EOL}* ${shouldCommit ? 'APPLYING' : 'DRYRUN'}: ${ChangeType[change.changeType!]} update ` + - `for ${change.packageName} to ${newVersion}` + `for ${change.packageName} to ${newVersion}` ); } else { console.log( @@ -358,7 +356,7 @@ export class PublishUtilities { projectsToExclude ); - change.changes!.forEach(subChange => { + change.changes!.forEach((subChange) => { if (subChange.comment) { console.log(` - [${ChangeType[subChange.changeType!]}] ${subChange.comment}`); } @@ -381,16 +379,15 @@ export class PublishUtilities { private static _updateDependencies( packageName: string, - dependencies: { [key: string]: string; } | undefined, + dependencies: { [key: string]: string } | undefined, allChanges: IChangeInfoHash, allPackages: Map, rushConfiguration: RushConfiguration, prereleaseToken: PrereleaseToken | undefined, projectsToExclude?: Set ): void { - if (dependencies) { - Object.keys(dependencies).forEach(depName => { + Object.keys(dependencies).forEach((depName) => { if (!PublishUtilities._isCyclicDependency(allPackages, packageName, depName)) { const depChange: IChangeInfo = allChanges[depName]; if (!depChange) { @@ -398,7 +395,7 @@ export class PublishUtilities { } const depProject: RushConfigurationProject = allPackages.get(depName)!; - if (!depProject.shouldPublish || projectsToExclude && projectsToExclude.has(depName)) { + if (!depProject.shouldPublish || (projectsToExclude && projectsToExclude.has(depName))) { // No version change. return; } else if ( @@ -474,8 +471,9 @@ export class PublishUtilities { const project: RushConfigurationProject | undefined = allPackages.get(packageName); if (!project) { - console.log(`The package ${packageName} was requested for publishing but ` + - `does not exist. Skip this change.`); + console.log( + `The package ${packageName} was requested for publishing but ` + `does not exist. Skip this change.` + ); return false; } @@ -493,7 +491,7 @@ export class PublishUtilities { packageName, changeType: change.changeType, order: 0, - changes: [change] + changes: [change], }; } else { currentChange = allChanges[packageName]; @@ -501,19 +499,26 @@ export class PublishUtilities { const oldChangeType: ChangeType = currentChange.changeType!; if (oldChangeType === ChangeType.hotfix && change.changeType! > oldChangeType) { - throw new Error(`Cannot apply ${this._getReleaseType(change.changeType!)} change after hotfix on same package`); + throw new Error( + `Cannot apply ${this._getReleaseType(change.changeType!)} change after hotfix on same package` + ); } if (change.changeType! === ChangeType.hotfix && oldChangeType > change.changeType!) { - throw new Error(`Cannot apply hotfix alongside ${this._getReleaseType(oldChangeType!)} change on same package`); + throw new Error( + `Cannot apply hotfix alongside ${this._getReleaseType(oldChangeType!)} change on same package` + ); } currentChange.changeType = Math.max(currentChange.changeType!, change.changeType!); currentChange.changes!.push(change); - hasChanged = hasChanged || (oldChangeType !== currentChange.changeType); + hasChanged = hasChanged || oldChangeType !== currentChange.changeType; } - const skipVersionBump: boolean = PublishUtilities._shouldSkipVersionBump(project, - prereleaseToken, projectsToExclude); + const skipVersionBump: boolean = PublishUtilities._shouldSkipVersionBump( + project, + prereleaseToken, + projectsToExclude + ); if (skipVersionBump) { currentChange.newVersion = pkg.version; @@ -538,15 +543,17 @@ export class PublishUtilities { if (currentChange.newVersion && semver.gt(currentChange.newVersion, pkg.version)) { packageVersion = currentChange.newVersion; } - currentChange.newVersion = change.changeType! >= ChangeType.patch ? - semver.inc(pkg.version, PublishUtilities._getReleaseType(currentChange.changeType!)) : - packageVersion; + currentChange.newVersion = + change.changeType! >= ChangeType.patch + ? semver.inc(pkg.version, PublishUtilities._getReleaseType(currentChange.changeType!)) + : packageVersion; } // If hotfix change, force new range dependency to be the exact new version - currentChange.newRangeDependency = change.changeType === ChangeType.hotfix ? - currentChange.newVersion : - PublishUtilities._getNewRangeDependency(currentChange.newVersion!); + currentChange.newRangeDependency = + change.changeType === ChangeType.hotfix + ? currentChange.newVersion + : PublishUtilities._getNewRangeDependency(currentChange.newVersion!); } return hasChanged; } @@ -559,14 +566,12 @@ export class PublishUtilities { prereleaseToken: PrereleaseToken | undefined, projectsToExclude?: Set ): void { - const packageName: string = change.packageName; const downstreamNames: string[] = allPackages.get(packageName)!.downstreamDependencyProjects; // Iterate through all downstream dependencies for the package. if (downstreamNames) { - if ((change.changeType! >= ChangeType.hotfix) || - (prereleaseToken && prereleaseToken.hasValue)) { + if (change.changeType! >= ChangeType.hotfix || (prereleaseToken && prereleaseToken.hasValue)) { for (const depName of downstreamNames) { const pkg: IPackageJson = allPackages.get(depName)!.packageJson; @@ -605,16 +610,17 @@ export class PublishUtilities { prereleaseToken: PrereleaseToken | undefined, projectsToExclude?: Set ): void { - - if (dependencies && dependencies[change.packageName] && - !PublishUtilities._isCyclicDependency(allPackages, parentPackageName, change.packageName)) { + if ( + dependencies && + dependencies[change.packageName] && + !PublishUtilities._isCyclicDependency(allPackages, parentPackageName, change.packageName) + ) { const requiredVersion: string = dependencies[change.packageName]; - const alwaysUpdate: boolean = !!prereleaseToken && prereleaseToken.hasValue && - !allChanges.hasOwnProperty(parentPackageName); + const alwaysUpdate: boolean = + !!prereleaseToken && prereleaseToken.hasValue && !allChanges.hasOwnProperty(parentPackageName); // If the version range exists and has not yet been updated to this version, update it. if (requiredVersion !== change.newRangeDependency || alwaysUpdate) { - let changeType: ChangeType; // Propagate hotfix changes to dependencies if (change.changeType === ChangeType.hotfix) { @@ -622,15 +628,22 @@ export class PublishUtilities { } else { // Either it already satisfies the new version, or doesn't. // If not, the downstream dep needs to be republished. - changeType = semver.satisfies(change.newVersion!, requiredVersion) ? - ChangeType.dependency : - ChangeType.patch; + changeType = semver.satisfies(change.newVersion!, requiredVersion) + ? ChangeType.dependency + : ChangeType.patch; } - const hasChanged: boolean = PublishUtilities._addChange({ - packageName: parentPackageName, - changeType - }, allChanges, allPackages, rushConfiguration, prereleaseToken, projectsToExclude); + const hasChanged: boolean = PublishUtilities._addChange( + { + packageName: parentPackageName, + changeType, + }, + allChanges, + allPackages, + rushConfiguration, + prereleaseToken, + projectsToExclude + ); if (hasChanged || alwaysUpdate) { // Only re-evaluate downstream dependencies if updating the parent package's dependency @@ -650,7 +663,7 @@ export class PublishUtilities { private static _updateDependencyVersion( packageName: string, - dependencies: { [key: string]: string; }, + dependencies: { [key: string]: string }, dependencyName: string, dependencyChange: IChangeInfo, allChanges: IChangeInfoHash, @@ -672,7 +685,7 @@ export class PublishUtilities { changeType: ChangeType.dependency, comment: `Updating dependency "${dependencyName}" from \`${currentDependencyVersion}\`` + - ` to \`${dependencies[dependencyName]}\`` + ` to \`${dependencies[dependencyName]}\``, }, allChanges, allPackages, diff --git a/apps/rush-lib/src/logic/PurgeManager.ts b/apps/rush-lib/src/logic/PurgeManager.ts index 6d4a2a88a5b..57029d749b2 100644 --- a/apps/rush-lib/src/logic/PurgeManager.ts +++ b/apps/rush-lib/src/logic/PurgeManager.ts @@ -55,8 +55,10 @@ export class PurgeManager { // Delete everything under common\temp except for the recycler folder itself console.log('Purging ' + this._rushConfiguration.commonTempFolder); - this._commonTempFolderRecycler.moveAllItemsInFolder(this._rushConfiguration.commonTempFolder, - this._getMembersToExclude(this._rushConfiguration.commonTempFolder, true)); + this._commonTempFolderRecycler.moveAllItemsInFolder( + this._rushConfiguration.commonTempFolder, + this._getMembersToExclude(this._rushConfiguration.commonTempFolder, true) + ); } /** @@ -73,22 +75,25 @@ export class PurgeManager { // we cannot delete that folder. // First purge the node-specific folder, e.g. ~/.rush/node-v4.5.6/* except for rush-1.2.3: - this._rushUserFolderRecycler.moveAllItemsInFolder(this._rushGlobalFolder.nodeSpecificPath, - this._getMembersToExclude(this._rushGlobalFolder.nodeSpecificPath, true)); + this._rushUserFolderRecycler.moveAllItemsInFolder( + this._rushGlobalFolder.nodeSpecificPath, + this._getMembersToExclude(this._rushGlobalFolder.nodeSpecificPath, true) + ); // Then purge the the global folder, e.g. ~/.rush/* except for node-v4.5.6 - this._rushUserFolderRecycler.moveAllItemsInFolder(this._rushGlobalFolder.path, - this._getMembersToExclude(this._rushGlobalFolder.path, false)); + this._rushUserFolderRecycler.moveAllItemsInFolder( + this._rushGlobalFolder.path, + this._getMembersToExclude(this._rushGlobalFolder.path, false) + ); if ( this._rushConfiguration.packageManager === 'pnpm' && this._rushConfiguration.pnpmOptions.pnpmStore === 'global' && this._rushConfiguration.pnpmOptions.pnpmStorePath ) { - console.warn(colors.yellow(`Purging the global pnpm-store`)) + console.warn(colors.yellow(`Purging the global pnpm-store`)); this._rushUserFolderRecycler.moveAllItemsInFolder(this._rushConfiguration.pnpmOptions.pnpmStorePath); } - } private _getMembersToExclude(folderToRecycle: string, showWarning: boolean): string[] { @@ -113,8 +118,11 @@ export class PurgeManager { if (showWarning) { // Warn that we won't dispose this folder - console.log(colors.yellow('The active process\'s folder will not be deleted: ' - + path.join(folderToRecycle, firstPart))); + console.log( + colors.yellow( + "The active process's folder will not be deleted: " + path.join(folderToRecycle, firstPart) + ) + ); } } } diff --git a/apps/rush-lib/src/logic/SetupChecks.ts b/apps/rush-lib/src/logic/SetupChecks.ts index 4ab4101a50f..70593986c92 100644 --- a/apps/rush-lib/src/logic/SetupChecks.ts +++ b/apps/rush-lib/src/logic/SetupChecks.ts @@ -42,15 +42,19 @@ export class SetupChecks { // Check for outdated tools if (rushConfiguration.packageManager === 'pnpm') { if (semver.lt(rushConfiguration.packageManagerToolVersion, MINIMUM_SUPPORTED_PNPM_VERSION)) { - return `The rush.json file requests PNPM version ` - + rushConfiguration.packageManagerToolVersion - + `, but PNPM ${MINIMUM_SUPPORTED_PNPM_VERSION} is the minimum supported by Rush.`; + return ( + `The rush.json file requests PNPM version ` + + rushConfiguration.packageManagerToolVersion + + `, but PNPM ${MINIMUM_SUPPORTED_PNPM_VERSION} is the minimum supported by Rush.` + ); } } else if (rushConfiguration.packageManager === 'npm') { if (semver.lt(rushConfiguration.packageManagerToolVersion, MINIMUM_SUPPORTED_NPM_VERSION)) { - return `The rush.json file requests NPM version ` - + rushConfiguration.packageManagerToolVersion - + `, but NPM ${MINIMUM_SUPPORTED_NPM_VERSION} is the minimum supported by Rush.`; + return ( + `The rush.json file requests NPM version ` + + rushConfiguration.packageManagerToolVersion + + `, but NPM ${MINIMUM_SUPPORTED_NPM_VERSION} is the minimum supported by Rush.` + ); } } @@ -71,17 +75,25 @@ export class SetupChecks { if (phantomFolders.length > 0) { if (phantomFolders.length === 1) { - console.log(colors.yellow(Utilities.wrapWords( - 'Warning: A phantom "node_modules" folder was found. This defeats Rush\'s protection against' - + ' NPM phantom dependencies and may cause confusing build errors. It is recommended to' - + ' delete this folder:' - ))); + console.log( + colors.yellow( + Utilities.wrapWords( + 'Warning: A phantom "node_modules" folder was found. This defeats Rush\'s protection against' + + ' NPM phantom dependencies and may cause confusing build errors. It is recommended to' + + ' delete this folder:' + ) + ) + ); } else { - console.log(colors.yellow(Utilities.wrapWords( - 'Warning: Phantom "node_modules" folders were found. This defeats Rush\'s protection against' - + ' NPM phantom dependencies and may cause confusing build errors. It is recommended to' - + ' delete these folders:' - ))); + console.log( + colors.yellow( + Utilities.wrapWords( + 'Warning: Phantom "node_modules" folders were found. This defeats Rush\'s protection against' + + ' NPM phantom dependencies and may cause confusing build errors. It is recommended to' + + ' delete these folders:' + ) + ) + ); } for (const folder of phantomFolders) { console.log(colors.yellow(`"${folder}"`)); @@ -95,9 +107,11 @@ export class SetupChecks { * The bad folders will be added to phantomFolders. * The seenFolders set is used to avoid duplicates. */ - private static _collectPhantomFoldersUpwards(folder: string, phantomFolders: string[], - seenFolders: Set): void { - + private static _collectPhantomFoldersUpwards( + folder: string, + phantomFolders: string[], + seenFolders: Set + ): void { // Stop if we reached a folder that we already analyzed while (!seenFolders.has(folder)) { seenFolders.add(folder); diff --git a/apps/rush-lib/src/logic/ShrinkwrapFileFactory.ts b/apps/rush-lib/src/logic/ShrinkwrapFileFactory.ts index fe0a7ac9460..1766c63229f 100644 --- a/apps/rush-lib/src/logic/ShrinkwrapFileFactory.ts +++ b/apps/rush-lib/src/logic/ShrinkwrapFileFactory.ts @@ -24,4 +24,4 @@ export class ShrinkwrapFileFactory { } throw new Error(`Invalid package manager: ${packageManager}`); } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/logic/StandardScriptUpdater.ts b/apps/rush-lib/src/logic/StandardScriptUpdater.ts index c9c2f83045a..9be2a868e03 100644 --- a/apps/rush-lib/src/logic/StandardScriptUpdater.ts +++ b/apps/rush-lib/src/logic/StandardScriptUpdater.ts @@ -14,7 +14,7 @@ export class StandardScriptUpdater { private static readonly _scriptNames: string[] = [ 'install-run.js', 'install-run-rush.js', - 'install-run-rushx.js' + 'install-run-rushx.js', ]; /** @@ -50,8 +50,11 @@ export class StandardScriptUpdater { * If throwInsteadOfCopy=false, then an outdated or missing script will be recopied; * otherwise, an exception is thrown. */ - private static _updateScriptOrThrow(scriptName: string, rushConfiguration: RushConfiguration, - throwInsteadOfCopy: boolean): boolean { + private static _updateScriptOrThrow( + scriptName: string, + rushConfiguration: RushConfiguration, + throwInsteadOfCopy: boolean + ): boolean { const targetFilePath: string = path.join(rushConfiguration.commonScriptsFolder, scriptName); const sourceFilePath: string = path.resolve(__dirname, '../scripts', scriptName); @@ -74,13 +77,15 @@ export class StandardScriptUpdater { if (!filesAreSame) { if (throwInsteadOfCopy) { - throw new Error('The standard files in the "common/scripts" folders need to be updated' - + ' for this Rush version. Please run "rush update" and commit the changes.'); + throw new Error( + 'The standard files in the "common/scripts" folders need to be updated' + + ' for this Rush version. Please run "rush update" and commit the changes.' + ); } else { console.log(`Script is out of date; updating "${targetFilePath}"`); FileSystem.copyFile({ sourcePath: sourceFilePath, - destinationPath: targetFilePath + destinationPath: targetFilePath, }); } } @@ -90,8 +95,12 @@ export class StandardScriptUpdater { private static _normalize(content: string): string { // Ignore newline differences from .gitattributes - return Text.convertToLf(content) - // Ignore trailing whitespace - .split('\n').map(x => x.trimRight()).join('\n'); + return ( + Text.convertToLf(content) + // Ignore trailing whitespace + .split('\n') + .map((x) => x.trimRight()) + .join('\n') + ); } } diff --git a/apps/rush-lib/src/logic/TaskSelector.ts b/apps/rush-lib/src/logic/TaskSelector.ts index f5a7c2fc02a..80145161cab 100644 --- a/apps/rush-lib/src/logic/TaskSelector.ts +++ b/apps/rush-lib/src/logic/TaskSelector.ts @@ -1,7 +1,4 @@ -import { - RushConfiguration, - IRushLinkJson -} from '../api/RushConfiguration'; +import { RushConfiguration, IRushLinkJson } from '../api/RushConfiguration'; import { RushConfigurationProject } from '../api/RushConfigurationProject'; import { JsonFile } from '@rushstack/node-core-library'; @@ -40,14 +37,16 @@ export class TaskSelector { this._packageChangeAnalyzer = new PackageChangeAnalyzer(options.rushConfiguration); this._taskCollection = new TaskCollection({ - quietMode: options.isQuietMode + quietMode: options.isQuietMode, }); try { this._rushLinkJson = JsonFile.load(this._options.rushConfiguration.rushLinkJsonFilename); } catch (error) { - throw new Error(`Could not read "${this._options.rushConfiguration.rushLinkJsonFilename}".` - + ` Did you run "rush install" or "rush update"?`); + throw new Error( + `Could not read "${this._options.rushConfiguration.rushLinkJsonFilename}".` + + ` Did you run "rush install" or "rush update"?` + ); } } @@ -69,8 +68,9 @@ export class TaskSelector { const dependencies: Set = new Set(); for (const toFlag of toFlags) { - const toProject: RushConfigurationProject | undefined = - this._options.rushConfiguration.findProjectByShorthandName(toFlag); + const toProject: + | RushConfigurationProject + | undefined = this._options.rushConfiguration.findProjectByShorthandName(toFlag); if (!toProject) { throw new Error(`The project '${toFlag}' does not exist in rush.json`); } @@ -86,10 +86,7 @@ export class TaskSelector { if (!this._options.ignoreDependencyOrder) { // Add ordering relationships for each dependency for (const dependency of dependencies) { - this._taskCollection.addDependencies( - dependency, - this._rushLinkJson.localLinks[dependency] || [] - ); + this._taskCollection.addDependencies(dependency, this._rushLinkJson.localLinks[dependency] || []); } } } @@ -99,8 +96,9 @@ export class TaskSelector { const dependents: Set = new Set(); for (const fromFlag of fromFlags) { - const fromProject: RushConfigurationProject | undefined - = this._options.rushConfiguration.findProjectByShorthandName(fromFlag); + const fromProject: + | RushConfigurationProject + | undefined = this._options.rushConfiguration.findProjectByShorthandName(fromFlag); if (!fromProject) { throw new Error(`The project '${fromFlag}' does not exist in rush.json`); } @@ -119,7 +117,7 @@ export class TaskSelector { for (const dependent of dependents) { this._taskCollection.addDependencies( dependent, - (this._rushLinkJson.localLinks[dependent] || []).filter(dep => dependents.has(dep)) + (this._rushLinkJson.localLinks[dependent] || []).filter((dep) => dependents.has(dep)) ); } } @@ -159,7 +157,7 @@ export class TaskSelector { if (!result.has(project)) { result.add(project); - for (const dependent of (this._dependentList.get(project) || new Set())) { + for (const dependent of this._dependentList.get(project) || new Set()) { this._collectAllDependents(dependent, result); } } @@ -190,7 +188,7 @@ export class TaskSelector { commandToRun: this._getScriptToRun(project), isIncrementalBuildAllowed: this._options.isIncrementalBuildAllowed, packageChangeAnalyzer: this._packageChangeAnalyzer, - packageDepsFilename: this._options.packageDepsFilename + packageDepsFilename: this._options.packageDepsFilename, }); if (!this._taskCollection.hasTask(projectTask.name)) { @@ -203,7 +201,9 @@ export class TaskSelector { const script: string | undefined = this._getScriptCommand(rushProject, this._options.commandToRun); if (script === undefined && !this._options.ignoreMissingScript) { - throw new Error(`The project [${rushProject.packageName}] does not define a '${this._options.commandToRun}' command in the 'scripts' section of its package.json`); + throw new Error( + `The project [${rushProject.packageName}] does not define a '${this._options.commandToRun}' command in the 'scripts' section of its package.json` + ); } if (!script) { @@ -211,9 +211,7 @@ export class TaskSelector { } const taskCommand: string = `${script} ${this._options.customParameterValues.join(' ')}`; - return process.platform === 'win32' - ? convertSlashesForWindows(taskCommand) - : taskCommand; + return process.platform === 'win32' ? convertSlashesForWindows(taskCommand) : taskCommand; } private _getScriptCommand(rushProject: RushConfigurationProject, script: string): string | undefined { diff --git a/apps/rush-lib/src/logic/Telemetry.ts b/apps/rush-lib/src/logic/Telemetry.ts index 8fe2f31ded3..a951f34a261 100644 --- a/apps/rush-lib/src/logic/Telemetry.ts +++ b/apps/rush-lib/src/logic/Telemetry.ts @@ -70,25 +70,26 @@ export class Telemetry { if (FileSystem.exists(this._dataFolder)) { const files: string[] = FileSystem.readFolder(this._dataFolder); if (files.length > MAX_FILE_COUNT) { - const sortedFiles: string[] = files.map(fileName => { - const filePath: string = path.join(this._dataFolder, fileName); - const stats: fs.Stats = FileSystem.getStatistics(filePath); - return { - filePath: filePath, - modifiedTime: stats.mtime.getTime(), - isFile: stats.isFile() - }; - }) - .filter(value => { - // Only delete files - return value.isFile; - }) - .sort((a, b) => { - return a.modifiedTime - b.modifiedTime; - }) - .map(s => { - return s.filePath; - }); + const sortedFiles: string[] = files + .map((fileName) => { + const filePath: string = path.join(this._dataFolder, fileName); + const stats: fs.Stats = FileSystem.getStatistics(filePath); + return { + filePath: filePath, + modifiedTime: stats.mtime.getTime(), + isFile: stats.isFile(), + }; + }) + .filter((value) => { + // Only delete files + return value.isFile; + }) + .sort((a, b) => { + return a.modifiedTime - b.modifiedTime; + }) + .map((s) => { + return s.filePath; + }); const filesToDelete: number = sortedFiles.length - MAX_FILE_COUNT; for (let i: number = 0; i < filesToDelete; i++) { FileSystem.deleteFile(sortedFiles[i]); @@ -102,4 +103,4 @@ export class Telemetry { fileName = fileName.replace(/[\-\:\.]/g, '_') + '.json'; return path.join(this._dataFolder, fileName); } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/logic/UnlinkManager.ts b/apps/rush-lib/src/logic/UnlinkManager.ts index b8a47624f85..3ea3cfb5b20 100644 --- a/apps/rush-lib/src/logic/UnlinkManager.ts +++ b/apps/rush-lib/src/logic/UnlinkManager.ts @@ -67,4 +67,4 @@ export class UnlinkManager { private _deleteFlagFile(): void { Utilities.deleteFile(this._rushConfiguration.rushLinkJsonFilename); } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/logic/VersionManager.ts b/apps/rush-lib/src/logic/VersionManager.ts index df818d4c572..80f25eae463 100644 --- a/apps/rush-lib/src/logic/VersionManager.ts +++ b/apps/rush-lib/src/logic/VersionManager.ts @@ -4,17 +4,9 @@ import * as path from 'path'; import * as semver from 'semver'; import { cloneDeep } from 'lodash'; -import { - IPackageJson, - JsonFile, - FileConstants -} from '@rushstack/node-core-library'; - -import { - VersionPolicy, - BumpType, - LockStepVersionPolicy -} from '../api/VersionPolicy'; +import { IPackageJson, JsonFile, FileConstants } from '@rushstack/node-core-library'; + +import { VersionPolicy, BumpType, LockStepVersionPolicy } from '../api/VersionPolicy'; import { ChangeFile } from '../api/ChangeFile'; import { ChangeType, IChangeInfo } from '../api/ChangeManagement'; import { RushConfiguration } from '../api/RushConfiguration'; @@ -68,7 +60,8 @@ export class VersionManager { * @param identifier - overrides the prerelease identifier and only works for lock step policy * @param shouldCommit - whether the changes will be written to disk */ - public bump(lockStepVersionPolicyName?: string, + public bump( + lockStepVersionPolicyName?: string, bumpType?: BumpType, identifier?: string, shouldCommit?: boolean @@ -80,15 +73,19 @@ export class VersionManager { this._ensure(lockStepVersionPolicyName, shouldCommit); // Refresh rush configuration - this._rushConfiguration = RushConfiguration.loadFromConfigurationFile(this._rushConfiguration.rushJsonFile); + this._rushConfiguration = RushConfiguration.loadFromConfigurationFile( + this._rushConfiguration.rushJsonFile + ); // Update projects based on individual policies - const changeManager: ChangeManager = new ChangeManager(this._rushConfiguration, - this._getLockStepProjects()); + const changeManager: ChangeManager = new ChangeManager( + this._rushConfiguration, + this._getLockStepProjects() + ); changeManager.load(this._rushConfiguration.changesFolder); if (changeManager.hasChanges()) { changeManager.validateChanges(this._versionPolicyConfiguration); - changeManager.apply(!!shouldCommit)!.forEach(packageJson => { + changeManager.apply(!!shouldCommit)!.forEach((packageJson) => { this._updatedProjects.set(packageJson.name, packageJson); }); changeManager.updateChangelog(!!shouldCommit); @@ -136,19 +133,21 @@ export class VersionManager { private _updateVersionsByPolicy(versionPolicyName?: string, force?: boolean): void { // Update versions based on version policy - this._rushConfiguration.projects.forEach(rushProject => { + this._rushConfiguration.projects.forEach((rushProject) => { const projectVersionPolicyName: string | undefined = rushProject.versionPolicyName; - if (projectVersionPolicyName && - (!versionPolicyName || projectVersionPolicyName === versionPolicyName)) { + if ( + projectVersionPolicyName && + (!versionPolicyName || projectVersionPolicyName === versionPolicyName) + ) { const versionPolicy: VersionPolicy = this._versionPolicyConfiguration.getVersionPolicy( - projectVersionPolicyName); + projectVersionPolicyName + ); const updatedProject: IPackageJson | undefined = versionPolicy.ensure(rushProject.packageJson, force); if (updatedProject) { this._updatedProjects.set(updatedProject.name, updatedProject); // No need to create an entry for prerelease version bump. if (!this._isPrerelease(updatedProject.version) && rushProject.isMainProject) { - this._addChangeInfo(updatedProject.name, - [this._createChangeInfo(updatedProject, rushProject)]); + this._addChangeInfo(updatedProject.name, [this._createChangeInfo(updatedProject, rushProject)]); } } } @@ -159,19 +158,20 @@ export class VersionManager { return !!semver.prerelease(version); } - private _addChangeInfo(packageName: string, - changeInfos: IChangeInfo[] - ): void { + private _addChangeInfo(packageName: string, changeInfos: IChangeInfo[]): void { if (!changeInfos.length) { return; } let changeFile: ChangeFile | undefined = this._changeFiles.get(packageName); if (!changeFile) { - changeFile = new ChangeFile({ - changes: [], - packageName: packageName, - email: this._userEmail - }, this._rushConfiguration); + changeFile = new ChangeFile( + { + changes: [], + packageName: packageName, + email: this._userEmail, + }, + this._rushConfiguration + ); this._changeFiles.set(packageName, changeFile); } changeInfos.forEach((changeInfo) => { @@ -180,7 +180,7 @@ export class VersionManager { } private _updateDependencies(): void { - this._rushConfiguration.projects.forEach(rushProject => { + this._rushConfiguration.projects.forEach((rushProject) => { let clonedProject: IPackageJson | undefined = this._updatedProjects.get(rushProject.packageName); let projectVersionChanged: boolean = true; if (!clonedProject) { @@ -201,18 +201,36 @@ export class VersionManager { } const changes: IChangeInfo[] = []; let updated: boolean = false; - if (this._updateProjectDependencies(clonedProject.dependencies, changes, - clonedProject, rushProject, projectVersionChanged) + if ( + this._updateProjectDependencies( + clonedProject.dependencies, + changes, + clonedProject, + rushProject, + projectVersionChanged + ) ) { updated = true; } - if (this._updateProjectDependencies(clonedProject.devDependencies, changes, - clonedProject, rushProject, projectVersionChanged) + if ( + this._updateProjectDependencies( + clonedProject.devDependencies, + changes, + clonedProject, + rushProject, + projectVersionChanged + ) ) { updated = true; } - if (this._updateProjectDependencies(clonedProject.peerDependencies, changes, - clonedProject, rushProject, projectVersionChanged) + if ( + this._updateProjectDependencies( + clonedProject.peerDependencies, + changes, + clonedProject, + rushProject, + projectVersionChanged + ) ) { updated = true; } @@ -224,7 +242,8 @@ export class VersionManager { } } - private _updateProjectDependencies(dependencies: { [key: string]: string; } | undefined, + private _updateProjectDependencies( + dependencies: { [key: string]: string } | undefined, changes: IChangeInfo[], clonedProject: IPackageJson, rushProject: RushConfigurationProject, @@ -252,7 +271,10 @@ export class VersionManager { if (newDependencyVersion !== oldDependencyVersion) { updated = true; if (this._shouldTrackDependencyChange(rushProject, updatedDependentProjectName)) { - this._trackDependencyChange(changes, clonedProject, projectVersionChanged, + this._trackDependencyChange( + changes, + clonedProject, + projectVersionChanged, updatedDependentProject, oldDependencyVersion, newDependencyVersion @@ -269,13 +291,18 @@ export class VersionManager { rushProject: RushConfigurationProject, dependencyName: string ): boolean { - const dependencyRushProject: RushConfigurationProject | undefined = - this._rushConfiguration.projectsByName.get(dependencyName); + const dependencyRushProject: + | RushConfigurationProject + | undefined = this._rushConfiguration.projectsByName.get(dependencyName); - return !!dependencyRushProject && rushProject.shouldPublish && + return ( + !!dependencyRushProject && + rushProject.shouldPublish && (!rushProject.versionPolicy || !rushProject.versionPolicy.isLockstepped || - rushProject.isMainProject && (dependencyRushProject.versionPolicyName !== rushProject.versionPolicyName)); + (rushProject.isMainProject && + dependencyRushProject.versionPolicyName !== rushProject.versionPolicyName)) + ); } private _trackDependencyChange( @@ -287,31 +314,29 @@ export class VersionManager { newDependencyVersion: string ): void { if (!semver.satisfies(updatedDependentProject.version, oldDependencyVersion) && !projectVersionChanged) { - this._addChange(changes, - { - changeType: ChangeType.patch, - packageName: clonedProject.name - } - ); + this._addChange(changes, { + changeType: ChangeType.patch, + packageName: clonedProject.name, + }); } // If current version is not a prerelease version and new dependency is also not a prerelease version, // add change entry. Otherwise, too many changes will be created for frequent releases. if (!this._isPrerelease(updatedDependentProject.version) && !this._isPrerelease(clonedProject.version)) { - this._addChange(changes, - { - changeType: ChangeType.dependency, - comment: `Dependency ${updatedDependentProject.name} version bump from ${oldDependencyVersion}` + - ` to ${newDependencyVersion}.`, - packageName: clonedProject.name - } - ); + this._addChange(changes, { + changeType: ChangeType.dependency, + comment: + `Dependency ${updatedDependentProject.name} version bump from ${oldDependencyVersion}` + + ` to ${newDependencyVersion}.`, + packageName: clonedProject.name, + }); } } private _addChange(changes: IChangeInfo[], newChange: IChangeInfo): void { const exists: boolean = changes.some((changeInfo) => { - return (changeInfo.author === newChange.author && + return ( + changeInfo.author === newChange.author && changeInfo.changeType === newChange.changeType && changeInfo.comment === newChange.comment && changeInfo.commit === newChange.commit && @@ -326,7 +351,9 @@ export class VersionManager { private _updatePackageJsonFiles(): void { this._updatedProjects.forEach((newPackageJson, packageName) => { - const rushProject: RushConfigurationProject | undefined = this._rushConfiguration.getProjectByName(packageName); + const rushProject: RushConfigurationProject | undefined = this._rushConfiguration.getProjectByName( + packageName + ); // Update package.json if (rushProject) { const packagePath: string = path.join(rushProject.projectFolder, FileConstants.PackageJson); @@ -335,14 +362,15 @@ export class VersionManager { }); } - private _createChangeInfo(newPackageJson: IPackageJson, + private _createChangeInfo( + newPackageJson: IPackageJson, rushProject: RushConfigurationProject ): IChangeInfo { return { changeType: ChangeType.none, newVersion: newPackageJson.version, packageName: newPackageJson.name, - comment: '' + comment: '', }; } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/logic/base/BaseLinkManager.ts b/apps/rush-lib/src/logic/base/BaseLinkManager.ts index 406a196b0ba..912b6104724 100644 --- a/apps/rush-lib/src/logic/base/BaseLinkManager.ts +++ b/apps/rush-lib/src/logic/base/BaseLinkManager.ts @@ -16,7 +16,7 @@ import { EnvironmentConfiguration } from '../../api/EnvironmentConfiguration'; export enum SymlinkKind { File, - Directory + Directory, } export interface IBaseLinkManagerCreateSymlinkOptions extends IFileSystemCreateLinkOptions { @@ -36,13 +36,10 @@ export abstract class BaseLinkManager { let targetPath: string; if (EnvironmentConfiguration.absoluteSymlinks) { - targetPath = options.linkTargetPath; + targetPath = options.linkTargetPath; } else { // Link to the relative path, to avoid going outside containers such as a Docker image - targetPath = path.relative( - fs.realpathSync(newLinkFolder), - options.linkTargetPath - ); + targetPath = path.relative(fs.realpathSync(newLinkFolder), options.linkTargetPath); } if (process.platform === 'win32') { @@ -50,7 +47,7 @@ export abstract class BaseLinkManager { // For directories, we use a Windows "junction". On Unix, this produces a regular symlink. FileSystem.createSymbolicLinkJunction({ linkTargetPath: targetPath, - newLinkPath: options.newLinkPath + newLinkPath: options.newLinkPath, }); } else { // For files, we use a Windows "hard link", because creating a symbolic link requires @@ -59,7 +56,7 @@ export abstract class BaseLinkManager { // NOTE: We cannot use the relative path for hard links FileSystem.createHardLink({ linkTargetPath: options.linkTargetPath, - newLinkPath: options.newLinkPath + newLinkPath: options.newLinkPath, }); } } else { @@ -68,12 +65,12 @@ export abstract class BaseLinkManager { if (options.symlinkKind === SymlinkKind.Directory) { FileSystem.createSymbolicLinkFolder({ linkTargetPath: targetPath, - newLinkPath: options.newLinkPath + newLinkPath: options.newLinkPath, }); } else { FileSystem.createSymbolicLinkFile({ linkTargetPath: targetPath, - newLinkPath: options.newLinkPath + newLinkPath: options.newLinkPath, }); } } @@ -132,7 +129,7 @@ export abstract class BaseLinkManager { BaseLinkManager._createSymlink({ linkTargetPath: localPackage.symlinkTargetFolderPath, newLinkPath: localPackage.folderPath, - symlinkKind: SymlinkKind.Directory + symlinkKind: SymlinkKind.Directory, }); } else { // If there are children, then we need to symlink each item in the folder individually @@ -149,7 +146,6 @@ export abstract class BaseLinkManager { const linkStats: fs.Stats = FileSystem.getLinkStatistics(linkTarget); if (linkStats.isSymbolicLink()) { - const targetStats: fs.Stats = FileSystem.getStatistics(FileSystem.getRealPath(linkTarget)); if (targetStats.isDirectory()) { // Neither a junction nor a directory-symlink can have a directory-symlink @@ -168,7 +164,7 @@ export abstract class BaseLinkManager { BaseLinkManager._createSymlink({ linkTargetPath: linkTarget, newLinkPath: linkSource, - symlinkKind + symlinkKind, }); } } @@ -203,7 +199,7 @@ export abstract class BaseLinkManager { // a full "rush link" is required next time Utilities.deleteFile(this._rushConfiguration.rushLinkJsonFilename); - await this._linkProjects() + await this._linkProjects(); stopwatch.stop(); console.log(os.EOL + colors.green(`Linking finished successfully. (${stopwatch.toString()})`)); diff --git a/apps/rush-lib/src/logic/base/BasePackage.ts b/apps/rush-lib/src/logic/base/BasePackage.ts index 81586d3ba44..0e0a97db0f0 100644 --- a/apps/rush-lib/src/logic/base/BasePackage.ts +++ b/apps/rush-lib/src/logic/base/BasePackage.ts @@ -1,10 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - JsonFile, - IPackageJson -} from '@rushstack/node-core-library'; +import { JsonFile, IPackageJson } from '@rushstack/node-core-library'; /** * The type of dependency; used by IPackageDependency. @@ -19,7 +16,7 @@ export enum PackageDependencyKind { /** * The dependency should be a symlink to a project that is locally built by Rush.. */ - LocalLink + LocalLink, } export interface IPackageDependency { @@ -108,11 +105,12 @@ export class BasePackage { public children: BasePackage[]; private _childrenByName: Map; - protected constructor(name: string, + protected constructor( + name: string, version: string | undefined, folderPath: string, - packageJson: IRushTempPackageJson | undefined) { - + packageJson: IRushTempPackageJson | undefined + ) { this.name = name; this.packageJson = packageJson; this.version = version; @@ -137,10 +135,12 @@ export class BasePackage { * Used by link managers, creates a virtual Package object that represents symbolic links * which will be created later */ - public static createLinkedPackage(name: string, + public static createLinkedPackage( + name: string, version: string | undefined, folderPath: string, - packageJson?: IRushTempPackageJson): BasePackage { + packageJson?: IRushTempPackageJson + ): BasePackage { return new BasePackage(name, version, folderPath, packageJson); } @@ -152,9 +152,17 @@ export class BasePackage { * @param targetFolderName - Filename where it should have been installed * Example: `C:\MyRepo\common\temp\node_modules\@rush-temp\project1` */ - public static createVirtualTempPackage(packageJsonFilename: string, installFolderName: string): BasePackage { + public static createVirtualTempPackage( + packageJsonFilename: string, + installFolderName: string + ): BasePackage { const packageJson: IRushTempPackageJson = JsonFile.load(packageJsonFilename); - return BasePackage.createLinkedPackage(packageJson.name, packageJson.version, installFolderName, packageJson); + return BasePackage.createLinkedPackage( + packageJson.name, + packageJson.version, + installFolderName, + packageJson + ); } public get nameAndVersion(): string { @@ -199,4 +207,4 @@ export class BasePackage { child.printTree(indent + ' '); } } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/logic/base/BaseShrinkwrapFile.ts b/apps/rush-lib/src/logic/base/BaseShrinkwrapFile.ts index bf8083ea5be..3be7726de09 100644 --- a/apps/rush-lib/src/logic/base/BaseShrinkwrapFile.ts +++ b/apps/rush-lib/src/logic/base/BaseShrinkwrapFile.ts @@ -48,8 +48,7 @@ export abstract class BaseShrinkwrapFile { public validate( packageManagerOptionsConfig: PackageManagerOptionsConfigurationBase, policyOptions: IPolicyValidatorOptions - ): void { - } + ): void {} /** * Returns true if the shrinkwrap file includes a top-level package that would satisfy the specified @@ -58,8 +57,9 @@ export abstract class BaseShrinkwrapFile { * @virtual */ public hasCompatibleTopLevelDependency(dependencySpecifier: DependencySpecifier): boolean { - const shrinkwrapDependency: DependencySpecifier | undefined - = this.getTopLevelDependencyVersion(dependencySpecifier.packageName); + const shrinkwrapDependency: DependencySpecifier | undefined = this.getTopLevelDependencyVersion( + dependencySpecifier.packageName + ); if (!shrinkwrapDependency) { return false; } @@ -86,10 +86,16 @@ export abstract class BaseShrinkwrapFile { * * @virtual */ - public tryEnsureCompatibleDependency(dependencySpecifier: DependencySpecifier, - tempProjectName: string, tryReusingPackageVersionsFromShrinkwrap: boolean = true): boolean { - const shrinkwrapDependency: DependencySpecifier | undefined = - this.tryEnsureDependencyVersion(dependencySpecifier, tempProjectName, tryReusingPackageVersionsFromShrinkwrap); + public tryEnsureCompatibleDependency( + dependencySpecifier: DependencySpecifier, + tempProjectName: string, + tryReusingPackageVersionsFromShrinkwrap: boolean = true + ): boolean { + const shrinkwrapDependency: DependencySpecifier | undefined = this.tryEnsureDependencyVersion( + dependencySpecifier, + tempProjectName, + tryReusingPackageVersionsFromShrinkwrap + ); if (!shrinkwrapDependency) { return false; } @@ -106,8 +112,11 @@ export abstract class BaseShrinkwrapFile { public abstract getTempProjectNames(): ReadonlyArray; /** @virtual */ - protected abstract tryEnsureDependencyVersion(dependencySpecifier: DependencySpecifier, - tempProjectName: string, tryReusingPackageVersionsFromShrinkwrap: boolean): DependencySpecifier | undefined; + protected abstract tryEnsureDependencyVersion( + dependencySpecifier: DependencySpecifier, + tempProjectName: string, + tryReusingPackageVersionsFromShrinkwrap: boolean + ): DependencySpecifier | undefined; /** @virtual */ protected abstract getTopLevelDependencyVersion(dependencyName: string): DependencySpecifier | undefined; @@ -123,13 +132,14 @@ export abstract class BaseShrinkwrapFile { result.push(key); } } - result.sort(); // make the result deterministic + result.sort(); // make the result deterministic return result; } - private _checkDependencyVersion(projectDependency: DependencySpecifier, - shrinkwrapDependency: DependencySpecifier): boolean { - + private _checkDependencyVersion( + projectDependency: DependencySpecifier, + shrinkwrapDependency: DependencySpecifier + ): boolean { let normalizedProjectDependency: DependencySpecifier = projectDependency; let normalizedShrinkwrapDependency: DependencySpecifier = shrinkwrapDependency; @@ -162,8 +172,10 @@ export abstract class BaseShrinkwrapFile { switch (normalizedProjectDependency.specifierType) { case 'version': case 'range': - return semver.satisfies(normalizedShrinkwrapDependency.versionSpecifier, - normalizedProjectDependency.versionSpecifier); + return semver.satisfies( + normalizedShrinkwrapDependency.versionSpecifier, + normalizedProjectDependency.versionSpecifier + ); default: // For other version specifier types like "file:./blah.tgz" or "git://github.com/npm/cli.git#v1.0.27" // we allow the installation to continue but issue a warning. The "rush install" checks will not work @@ -172,8 +184,12 @@ export abstract class BaseShrinkwrapFile { // Only warn once for each versionSpecifier if (!this._alreadyWarnedSpecs.has(projectDependency.versionSpecifier)) { this._alreadyWarnedSpecs.add(projectDependency.versionSpecifier); - console.log(colors.yellow(`WARNING: Not validating ${projectDependency.specifierType}-based` - + ` specifier: "${projectDependency.versionSpecifier}"`)); + console.log( + colors.yellow( + `WARNING: Not validating ${projectDependency.specifierType}-based` + + ` specifier: "${projectDependency.versionSpecifier}"` + ) + ); } return true; } diff --git a/apps/rush-lib/src/logic/deploy/DeployManager.ts b/apps/rush-lib/src/logic/deploy/DeployManager.ts index 0448a29572a..fd9f6f3c585 100644 --- a/apps/rush-lib/src/logic/deploy/DeployManager.ts +++ b/apps/rush-lib/src/logic/deploy/DeployManager.ts @@ -2,8 +2,8 @@ // See LICENSE in the project root for license information. import * as colors from 'colors'; -import * as path from "path"; -import * as resolve from "resolve"; +import * as path from 'path'; +import * as resolve from 'resolve'; import * as npmPacklist from 'npm-packlist'; import ignore, { Ignore } from 'ignore'; import { @@ -18,14 +18,14 @@ import { AlreadyExistsBehavior, InternalError, NewlineKind, - Text + Text, } from '@rushstack/node-core-library'; import { RushConfiguration } from '../../api/RushConfiguration'; import { SymlinkAnalyzer, ILinkInfo } from './SymlinkAnalyzer'; -import { RushConfigurationProject } from "../../api/RushConfigurationProject"; +import { RushConfigurationProject } from '../../api/RushConfigurationProject'; // (@types/npm-packlist is missing this API) -declare module "npm-packlist" { +declare module 'npm-packlist' { export class WalkerSync { public readonly result: string[]; public constructor(opts: { path: string }); @@ -42,11 +42,11 @@ interface IDeployScenarioProjectJson { // The parsed JSON file structure, as defined by the "deploy-scenario.schema.json" JSON schema interface IDeployScenarioJson { - deploymentProjectNames: string[], + deploymentProjectNames: string[]; enableSubdeployments?: boolean; includeDevDependencies?: boolean; includeNpmIgnoreFiles?: boolean; - linkCreation?: "default" | "script" | "none"; + linkCreation?: 'default' | 'script' | 'none'; projectSettings?: IDeployScenarioProjectJson[]; } @@ -125,7 +125,7 @@ export class DeployManager { */ private _targetRootFolder: string; - /** + /** * The source folder that copying originates from. Generally it is the repo root folder with rush.json. */ private _sourceRootFolder: string; @@ -154,8 +154,10 @@ export class DeployManager { throw new Error('The scenario name cannot be an empty string'); } if (!this._scenarioNameRegExp.test(scenarioName)) { - throw new Error(`"${scenarioName}" is not a valid scenario name. The name must be comprised of` - + ' lowercase letters and numbers, separated by single hyphens. Example: "my-scenario"'); + throw new Error( + `"${scenarioName}" is not a valid scenario name. The name must be comprised of` + + ' lowercase letters and numbers, separated by single hyphens. Example: "my-scenario"' + ); } } @@ -163,14 +165,16 @@ export class DeployManager { * Load and validate the scenario config file. The result is stored in this._deployScenarioJson. */ private _loadConfigFile(scenarioName: string): void { - const scenarioFilePath: string = path.join(this._rushConfiguration.commonDeployConfigFolder, - `${scenarioName}.json`); + const scenarioFilePath: string = path.join( + this._rushConfiguration.commonDeployConfigFolder, + `${scenarioName}.json` + ); if (!FileSystem.exists(scenarioFilePath)) { throw new Error('The scenario config file was not found: ' + scenarioFilePath); } - console.log(colors.cyan('Loading deployment scenario: ') + scenarioFilePath) + console.log(colors.cyan('Loading deployment scenario: ') + scenarioFilePath); this._deployScenarioJson = JsonFile.loadAndValidate(scenarioFilePath, DeployManager._jsonSchema); @@ -182,13 +186,17 @@ export class DeployManager { for (const projectSetting of this._deployScenarioJson.projectSettings || []) { // Validate projectSetting.projectName if (!this._rushConfiguration.getProjectByName(projectSetting.projectName)) { - throw new Error(`The "projectSettings" section refers to the project name "${projectSetting.projectName}"` + - ` which was not found in rush.json`); + throw new Error( + `The "projectSettings" section refers to the project name "${projectSetting.projectName}"` + + ` which was not found in rush.json` + ); } for (const additionalProjectsToInclude of projectSetting.additionalProjectsToInclude || []) { if (!this._rushConfiguration.getProjectByName(projectSetting.projectName)) { - throw new Error(`The "additionalProjectsToInclude" setting refers to the` + - ` project name "${additionalProjectsToInclude}" which was not found in rush.json`); + throw new Error( + `The "additionalProjectsToInclude" setting refers to the` + + ` project name "${additionalProjectsToInclude}" which was not found in rush.json` + ); } } this._deployScenarioProjectJsonsByName.set(projectSetting.projectName, projectSetting); @@ -198,7 +206,10 @@ export class DeployManager { /** * Recursively crawl the node_modules dependencies and collect the result in ISubdeploymentState.foldersToCopy. */ - private _collectFoldersRecursive(packageJsonFolderPath: string, subdemploymentState: ISubdeploymentState): void { + private _collectFoldersRecursive( + packageJsonFolderPath: string, + subdemploymentState: ISubdeploymentState + ): void { const packageJsonRealFolderPath: string = FileSystem.getRealPath(packageJsonFolderPath); if (!subdemploymentState.foldersToCopy.has(packageJsonRealFolderPath)) { @@ -230,13 +241,14 @@ export class DeployManager { // (Used only by the legacy code fragment in the resolve.sync() hook below) // eslint-disable-next-line @typescript-eslint/no-var-requires - const fs: typeof import("fs") = require("fs"); + const fs: typeof import('fs') = require('fs'); for (const dependencyPackageName of allDependencyNames) { // The "resolve" library models the Node.js require() API, which gives precedence to "core" system modules // over an NPM package with the same name. But we are traversing package.json dependencies, which refer // to system modules. Appending a "/" forces require() to load the NPM package. - const resolveSuffix: string = dependencyPackageName + resolve.isCore(dependencyPackageName) ? '/' : ''; + const resolveSuffix: string = + dependencyPackageName + resolve.isCore(dependencyPackageName) ? '/' : ''; try { const resolvedDependency: string = resolve.sync(dependencyPackageName + resolveSuffix, { @@ -245,7 +257,7 @@ export class DeployManager { packageFilter: (pkg, dir) => { // point "main" at a file that is guaranteed to exist // This helps resolve packages such as @types/node that have no entry point - pkg.main = "./package.json"; + pkg.main = './package.json'; return pkg; }, realpathSync: (filePath) => { @@ -256,7 +268,7 @@ export class DeployManager { subdemploymentState.symlinkAnalyzer.analyzePath(filePath); return resolvedPath; } catch (realpathErr) { - if (realpathErr.code !== "ENOENT") { + if (realpathErr.code !== 'ENOENT') { throw realpathErr; } } @@ -272,8 +284,9 @@ export class DeployManager { throw new Error(`Error resolving ${dependencyPackageName} from ${packageJsonRealFolderPath}`); } - const dependencyPackageFolderPath: string | undefined - = this._packageJsonLookup.tryGetPackageFolderFor(resolvedDependency); + const dependencyPackageFolderPath: + | string + | undefined = this._packageJsonLookup.tryGetPackageFolderFor(resolvedDependency); if (!dependencyPackageFolderPath) { throw new Error(`Error finding package.json folder for ${resolvedDependency}`); } @@ -296,14 +309,20 @@ export class DeployManager { * Example input: "C:\MyRepo\libraries\my-lib" * Example output: "C:\MyRepo\common\deploy\my-scenario\libraries\my-lib" */ - private _remapPathForDeployFolder(absolutePathInSourceFolder: string, - subdemploymentState: ISubdeploymentState): string { - + private _remapPathForDeployFolder( + absolutePathInSourceFolder: string, + subdemploymentState: ISubdeploymentState + ): string { if (!Path.isUnderOrEqual(absolutePathInSourceFolder, this._sourceRootFolder)) { - throw new Error("Source path is not under " + this._sourceRootFolder + "\n" + absolutePathInSourceFolder); + throw new Error( + 'Source path is not under ' + this._sourceRootFolder + '\n' + absolutePathInSourceFolder + ); } const relativePath: string = path.relative(this._sourceRootFolder, absolutePathInSourceFolder); - const absolutePathInTargetFolder: string = path.join(subdemploymentState.targetSubdeploymentFolder, relativePath); + const absolutePathInTargetFolder: string = path.join( + subdemploymentState.targetSubdeploymentFolder, + relativePath + ); return absolutePathInTargetFolder; } @@ -313,9 +332,10 @@ export class DeployManager { * Example input: "C:\MyRepo\libraries\my-lib" * Example output: "libraries/my-lib" */ - private _remapPathForDeployMetadata(absolutePathInSourceFolder: string, - subdemploymentState: ISubdeploymentState): string { - + private _remapPathForDeployMetadata( + absolutePathInSourceFolder: string, + subdemploymentState: ISubdeploymentState + ): string { if (!Path.isUnderOrEqual(absolutePathInSourceFolder, this._sourceRootFolder)) { throw new Error(`Source path is not under ${this._sourceRootFolder}\n${absolutePathInSourceFolder}`); } @@ -323,17 +343,16 @@ export class DeployManager { return Text.replaceAll(relativePath, '\\', '/'); } - /** * Copy one package folder to the deployment target folder. */ private _deployFolder(sourceFolderPath: string, subdemploymentState: ISubdeploymentState): void { - let useNpmIgnoreFilter: boolean = false; if (!this._deployScenarioJson.includeNpmIgnoreFiles) { - const sourceFolderInfo: IFolderInfo | undefined - = subdemploymentState.folderInfosByPath.get(FileSystem.getRealPath(sourceFolderPath)); + const sourceFolderInfo: IFolderInfo | undefined = subdemploymentState.folderInfosByPath.get( + FileSystem.getRealPath(sourceFolderPath) + ); if (sourceFolderInfo) { if (sourceFolderInfo.isRushProject) { useNpmIgnoreFilter = true; @@ -347,7 +366,7 @@ export class DeployManager { // Use npm-packlist to filter the files. Using the WalkerSync class (instead of the sync() API) ensures // that "bundledDependencies" are not included. const walker: npmPacklist.WalkerSync = new npmPacklist.WalkerSync({ - path: sourceFolderPath + path: sourceFolderPath, }); walker.start(); const npmPackFiles: string[] = walker.result; @@ -356,13 +375,13 @@ export class DeployManager { const copySourcePath: string = path.join(sourceFolderPath, npmPackFile); const copyDestinationPath: string = path.join(targetFolderPath, npmPackFile); - if (subdemploymentState.symlinkAnalyzer.analyzePath(copySourcePath).kind !== "link") { + if (subdemploymentState.symlinkAnalyzer.analyzePath(copySourcePath).kind !== 'link') { FileSystem.ensureFolder(path.dirname(copyDestinationPath)); FileSystem.copyFile({ sourcePath: copySourcePath, destinationPath: copyDestinationPath, - alreadyExistsBehavior: AlreadyExistsBehavior.Error + alreadyExistsBehavior: AlreadyExistsBehavior.Error, }); } } @@ -376,7 +395,7 @@ export class DeployManager { '**/.git', '**/.svn', '**/.hg', - '**/.DS_Store' + '**/.DS_Store', ]); FileSystem.copyFiles({ @@ -386,7 +405,7 @@ export class DeployManager { filter: (src: string, dest: string) => { const relativeSrc: string = path.relative(sourceFolderPath, src); if (!relativeSrc) { - return true; // don't filter sourceFolderPath itself + return true; // don't filter sourceFolderPath itself } if (ignoreFilter.ignores(relativeSrc)) { @@ -400,7 +419,7 @@ export class DeployManager { } else { return true; } - } + }, }); } } @@ -466,14 +485,18 @@ export class DeployManager { /** * Recursively apply the "additionalProjectToInclude" setting. */ - private _collectAdditionalProjectsToInclude(includedProjectNamesSet: Set, projectName: string): void { + private _collectAdditionalProjectsToInclude( + includedProjectNamesSet: Set, + projectName: string + ): void { if (includedProjectNamesSet.has(projectName)) { return; } includedProjectNamesSet.add(projectName); - const projectSettings: IDeployScenarioProjectJson | undefined - = this._deployScenarioProjectJsonsByName.get(projectName); + const projectSettings: + | IDeployScenarioProjectJson + | undefined = this._deployScenarioProjectJsonsByName.get(projectName); if (projectSettings && projectSettings.additionalProjectsToInclude) { for (const additionalProjectToInclude of projectSettings.additionalProjectsToInclude) { this._collectAdditionalProjectsToInclude(includedProjectNamesSet, additionalProjectToInclude); @@ -482,13 +505,15 @@ export class DeployManager { } private _writeDeployMetadata(subdemploymentState: ISubdeploymentState): void { - const deployMetadataFilePath: string = path.join(subdemploymentState.targetSubdeploymentFolder, - 'deploy-metadata.json'); + const deployMetadataFilePath: string = path.join( + subdemploymentState.targetSubdeploymentFolder, + 'deploy-metadata.json' + ); const deployMetadataJson: IDeployMetadataJson = { scenarioName: subdemploymentState.scenarioName, mainProjectName: subdemploymentState.mainProjectName, - links: [ ] + links: [], }; // Remap the links to be relative to the subdeployment folder @@ -502,7 +527,7 @@ export class DeployManager { } JsonFile.save(deployMetadataJson, deployMetadataFilePath, { - newlineConversion: NewlineKind.OsDefault + newlineConversion: NewlineKind.OsDefault, }); } @@ -519,13 +544,15 @@ export class DeployManager { const projectFolder: string = FileSystem.getRealPath(rushProject.projectFolder); subdemploymentState.folderInfosByPath.set(projectFolder, { folderPath: projectFolder, - isRushProject: true + isRushProject: true, }); } for (const projectName of includedProjectNamesSet) { console.log(`Analyzing project "${projectName}"`); - const project: RushConfigurationProject | undefined = this._rushConfiguration.getProjectByName(projectName); + const project: RushConfigurationProject | undefined = this._rushConfiguration.getProjectByName( + projectName + ); if (!project) { throw new Error(`The project ${projectName} is not defined in rush.json`); @@ -536,7 +563,7 @@ export class DeployManager { Sort.sortSet(subdemploymentState.foldersToCopy); - console.log("Copying folders..."); + console.log('Copying folders...'); for (const folderToCopy of subdemploymentState.foldersToCopy) { this._deployFolder(folderToCopy, subdemploymentState); } @@ -549,7 +576,7 @@ export class DeployManager { FileSystem.copyFile({ sourcePath: path.join(__dirname, '../../scripts/create-links.js'), destinationPath: path.join(subdemploymentState.targetSubdeploymentFolder, 'create-links.js'), - alreadyExistsBehavior: AlreadyExistsBehavior.Error + alreadyExistsBehavior: AlreadyExistsBehavior.Error, }); } @@ -571,9 +598,11 @@ export class DeployManager { /** * The main entry point for performing a deployment. */ - public deployScenario(scenarioName: string, overwriteExisting: boolean, - targetFolderParameter: string | undefined): void { - + public deployScenario( + scenarioName: string, + overwriteExisting: boolean, + targetFolderParameter: string | undefined + ): void { DeployManager.validateScenarioName(scenarioName); if (this._targetRootFolder !== undefined) { @@ -586,14 +615,16 @@ export class DeployManager { if (targetFolderParameter) { this._targetRootFolder = path.resolve(targetFolderParameter); if (!FileSystem.exists(this._targetRootFolder)) { - throw new Error('The specified target folder does not exist: ' + JSON.stringify(targetFolderParameter)); + throw new Error( + 'The specified target folder does not exist: ' + JSON.stringify(targetFolderParameter) + ); } } else { this._targetRootFolder = path.join(this._rushConfiguration.commonFolder, 'deploy'); } this._sourceRootFolder = this._rushConfiguration.rushJsonFolder; - console.log(colors.cyan("Deploying to target folder: ") + this._targetRootFolder + '\n'); + console.log(colors.cyan('Deploying to target folder: ') + this._targetRootFolder + '\n'); FileSystem.ensureFolder(this._targetRootFolder); @@ -603,8 +634,10 @@ export class DeployManager { console.log('Deleting target folder contents because "--overwrite" was specified...'); FileSystem.ensureEmptyFolder(this._targetRootFolder); } else { - throw new Error('The deploy target folder is not empty. You can specify "--overwrite"' - + ' to recursively delete all folder contents.'); + throw new Error( + 'The deploy target folder is not empty. You can specify "--overwrite"' + + ' to recursively delete all folder contents.' + ); } } @@ -615,25 +648,33 @@ export class DeployManager { const usedSubdeploymentFolderNames: Set = new Set(); for (const subdeploymentProjectName of deploymentProjectNames) { - const rushProject: RushConfigurationProject | undefined = - this._rushConfiguration.getProjectByName(subdeploymentProjectName); + const rushProject: RushConfigurationProject | undefined = this._rushConfiguration.getProjectByName( + subdeploymentProjectName + ); if (!rushProject) { - throw new Error(`The "deploymentProjectNames" setting specified the name "${subdeploymentProjectName}"` + - ` which was not found in rush.json`); + throw new Error( + `The "deploymentProjectNames" setting specified the name "${subdeploymentProjectName}"` + + ` which was not found in rush.json` + ); } let subdeploymentFolderName: string; - const projectSettings: IDeployScenarioProjectJson | undefined - = this._deployScenarioProjectJsonsByName.get(subdeploymentProjectName); + const projectSettings: + | IDeployScenarioProjectJson + | undefined = this._deployScenarioProjectJsonsByName.get(subdeploymentProjectName); if (projectSettings && projectSettings.subdeploymentFolderName) { subdeploymentFolderName = projectSettings.subdeploymentFolderName; } else { - subdeploymentFolderName = this._rushConfiguration.packageNameParser.getUnscopedName(subdeploymentProjectName); + subdeploymentFolderName = this._rushConfiguration.packageNameParser.getUnscopedName( + subdeploymentProjectName + ); } if (usedSubdeploymentFolderNames.has(subdeploymentFolderName)) { - throw new Error(`The subdeployment folder name "${subdeploymentFolderName}" is not unique.` - + ` Use the "subdeploymentFolderName" setting to specify a different name.`); + throw new Error( + `The subdeployment folder name "${subdeploymentFolderName}" is not unique.` + + ` Use the "subdeploymentFolderName" setting to specify a different name.` + ); } usedSubdeploymentFolderNames.add(subdeploymentFolderName); @@ -645,15 +686,17 @@ export class DeployManager { targetSubdeploymentFolder: path.join(this._targetRootFolder, subdeploymentFolderName), foldersToCopy: new Set(), folderInfosByPath: new Map(), - symlinkAnalyzer: new SymlinkAnalyzer() + symlinkAnalyzer: new SymlinkAnalyzer(), }; this._deploySubdeployment(subdemploymentState); } } else { if (deploymentProjectNames.length !== 1) { - throw new Error(`The "deploymentProjectNames" setting specifies specifies more than one project;` - + ' this is not supported unless the "enableSubdeployments" setting is true.'); + throw new Error( + `The "deploymentProjectNames" setting specifies specifies more than one project;` + + ' this is not supported unless the "enableSubdeployments" setting is true.' + ); } const subdemploymentState: ISubdeploymentState = { @@ -662,12 +705,12 @@ export class DeployManager { targetSubdeploymentFolder: this._targetRootFolder, foldersToCopy: new Set(), folderInfosByPath: new Map(), - symlinkAnalyzer: new SymlinkAnalyzer() + symlinkAnalyzer: new SymlinkAnalyzer(), }; this._deploySubdeployment(subdemploymentState); } - console.log("\nThe operation completed successfully."); + console.log('\nThe operation completed successfully.'); } } diff --git a/apps/rush-lib/src/logic/deploy/SymlinkAnalyzer.ts b/apps/rush-lib/src/logic/deploy/SymlinkAnalyzer.ts index 0a55ee74f0b..ece200c80a2 100644 --- a/apps/rush-lib/src/logic/deploy/SymlinkAnalyzer.ts +++ b/apps/rush-lib/src/logic/deploy/SymlinkAnalyzer.ts @@ -1,14 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - FileSystem, - FileSystemStats, - Sort, - InternalError, -} from "@rushstack/node-core-library"; +import { FileSystem, FileSystemStats, Sort, InternalError } from '@rushstack/node-core-library'; -import * as path from "path"; +import * as path from 'path'; /** * Represents a file object analyzed by {@link SymlinkAnalyzer}. @@ -69,7 +64,7 @@ export class SymlinkAnalyzer { let pathSegments: string[] = path.resolve(inputPath).split(path.sep); let pathSegmentsIndex: number = 0; - for (; ;) { + for (;;) { const currentPath: string = pathSegments.slice(0, pathSegmentsIndex + 1).join(path.sep); if (currentPath === '') { @@ -89,17 +84,17 @@ export class SymlinkAnalyzer { currentNode = { kind: 'link', nodePath: currentPath, - linkTarget: resolvedLinkTargetPath + linkTarget: resolvedLinkTargetPath, }; } else if (linkStats.isDirectory()) { currentNode = { kind: 'folder', - nodePath: currentPath + nodePath: currentPath, }; } else if (linkStats.isFile()) { currentNode = { kind: 'file', - nodePath: currentPath + nodePath: currentPath, }; } else { throw new Error('Unknown object type: ' + currentPath); @@ -121,7 +116,7 @@ export class SymlinkAnalyzer { const linkInfo: ILinkInfo = { kind: targetIsDirectory ? 'folderLink' : 'fileLink', linkPath: currentNode.nodePath, - targetPath: targetNode.nodePath + targetPath: targetNode.nodePath, }; this._linkInfosByPath.set(currentNode.nodePath, linkInfo); } @@ -152,7 +147,7 @@ export class SymlinkAnalyzer { */ public reportSymlinks(): ILinkInfo[] { const list: ILinkInfo[] = [...this._linkInfosByPath.values()]; - Sort.sortBy(list, x => x.linkPath); + Sort.sortBy(list, (x) => x.linkPath); return list; } } diff --git a/apps/rush-lib/src/logic/npm/NpmLinkManager.ts b/apps/rush-lib/src/logic/npm/NpmLinkManager.ts index ca5ef53f8a8..95e4ec16408 100644 --- a/apps/rush-lib/src/logic/npm/NpmLinkManager.ts +++ b/apps/rush-lib/src/logic/npm/NpmLinkManager.ts @@ -8,27 +8,15 @@ import * as semver from 'semver'; import * as tar from 'tar'; import readPackageTree = require('read-package-tree'); -import { - JsonFile, - FileSystem, - FileConstants, - LegacyAdapters -} from '@rushstack/node-core-library'; +import { JsonFile, FileSystem, FileConstants, LegacyAdapters } from '@rushstack/node-core-library'; import { RushConstants } from '../../logic/RushConstants'; import { IRushLinkJson } from '../../api/RushConfiguration'; import { RushConfigurationProject } from '../../api/RushConfigurationProject'; import { Utilities } from '../../utilities/Utilities'; -import { - NpmPackage, - IResolveOrCreateResult, - PackageDependencyKind -} from './NpmPackage'; +import { NpmPackage, IResolveOrCreateResult, PackageDependencyKind } from './NpmPackage'; import { PackageLookup } from '../PackageLookup'; -import { - BaseLinkManager, - SymlinkKind -} from '../base/BaseLinkManager'; +import { BaseLinkManager, SymlinkKind } from '../base/BaseLinkManager'; interface IQueueItem { // A project from somewhere under "common/temp/node_modules" @@ -44,12 +32,11 @@ interface IQueueItem { export class NpmLinkManager extends BaseLinkManager { protected async _linkProjects(): Promise { - const npmPackage: readPackageTree.Node = ( - await LegacyAdapters.convertCallbackToPromise( - readPackageTree, - this._rushConfiguration.commonTempFolder - ) - ); + const npmPackage: readPackageTree.Node = await LegacyAdapters.convertCallbackToPromise< + readPackageTree.Node, + Error, + string + >(readPackageTree, this._rushConfiguration.commonTempFolder); const commonRootPackage: NpmPackage = NpmPackage.createFromNpm(npmPackage); @@ -57,7 +44,7 @@ export class NpmLinkManager extends BaseLinkManager { commonPackageLookup.loadTree(commonRootPackage); const rushLinkJson: IRushLinkJson = { - localLinks: {} + localLinks: {}, }; for (const rushProject of this._rushConfiguration.projects) { @@ -82,10 +69,11 @@ export class NpmLinkManager extends BaseLinkManager { project: RushConfigurationProject, commonRootPackage: NpmPackage, commonPackageLookup: PackageLookup, - rushLinkJson: IRushLinkJson): void { - - let commonProjectPackage: NpmPackage | undefined = - commonRootPackage.getChildByName(project.tempProjectName) as NpmPackage; + rushLinkJson: IRushLinkJson + ): void { + let commonProjectPackage: NpmPackage | undefined = commonRootPackage.getChildByName( + project.tempProjectName + ) as NpmPackage; if (!commonProjectPackage) { // Normally we would expect the temp project to have been installed into the common\node_modules // folder. However, if it was recently added, "rush install" doesn't technically require @@ -93,16 +81,23 @@ export class NpmLinkManager extends BaseLinkManager { // This avoids the need to run "rush generate" unnecessarily. // Example: "project1" - const unscopedTempProjectName: string = this._rushConfiguration.packageNameParser - .getUnscopedName(project.tempProjectName); + const unscopedTempProjectName: string = this._rushConfiguration.packageNameParser.getUnscopedName( + project.tempProjectName + ); // Example: "C:\MyRepo\common\temp\projects\project1 - const extractedFolder: string = path.join(this._rushConfiguration.commonTempFolder, - RushConstants.rushTempProjectsFolderName, unscopedTempProjectName); + const extractedFolder: string = path.join( + this._rushConfiguration.commonTempFolder, + RushConstants.rushTempProjectsFolderName, + unscopedTempProjectName + ); // Example: "C:\MyRepo\common\temp\projects\project1.tgz" - const tarballFile: string = path.join(this._rushConfiguration.commonTempFolder, - RushConstants.rushTempProjectsFolderName, unscopedTempProjectName + '.tgz'); + const tarballFile: string = path.join( + this._rushConfiguration.commonTempFolder, + RushConstants.rushTempProjectsFolderName, + unscopedTempProjectName + '.tgz' + ); // Example: "C:\MyRepo\common\temp\projects\project1\package.json" const packageJsonFilename: string = path.join(extractedFolder, 'package', FileConstants.PackageJson); @@ -111,12 +106,16 @@ export class NpmLinkManager extends BaseLinkManager { tar.extract({ cwd: extractedFolder, file: tarballFile, - sync: true + sync: true, }); // Example: "C:\MyRepo\common\temp\node_modules\@rush-temp\project1" - const installFolderName: string = path.join(this._rushConfiguration.commonTempFolder, - RushConstants.nodeModulesFolderName, RushConstants.rushTempNpmScope, unscopedTempProjectName); + const installFolderName: string = path.join( + this._rushConfiguration.commonTempFolder, + RushConstants.nodeModulesFolderName, + RushConstants.rushTempNpmScope, + unscopedTempProjectName + ); commonProjectPackage = NpmPackage.createVirtualTempPackage(packageJsonFilename, installFolderName); @@ -139,7 +138,7 @@ export class NpmLinkManager extends BaseLinkManager { queue.push({ commonPackage: commonProjectPackage, localPackage: localProjectPackage, - cyclicSubtreeRoot: undefined + cyclicSubtreeRoot: undefined, }); for (;;) { @@ -167,8 +166,9 @@ export class NpmLinkManager extends BaseLinkManager { // Should this be a "local link" to a top-level Rush project (i.e. versus a regular link // into the Common folder)? - const matchedRushPackage: RushConfigurationProject | undefined = - this._rushConfiguration.getProjectByName(dependency.name); + const matchedRushPackage: + | RushConfigurationProject + | undefined = this._rushConfiguration.getProjectByName(dependency.name); if (matchedRushPackage) { const matchedVersion: string = matchedRushPackage.packageJsonEditor.version; @@ -182,17 +182,23 @@ export class NpmLinkManager extends BaseLinkManager { // DO NOT create a local link, because we are starting a new // cyclicDependencyProjects subtree startingCyclicSubtree = true; - } else if (dependency.kind !== PackageDependencyKind.LocalLink - && !semver.satisfies(matchedVersion, dependency.versionRange)) { + } else if ( + dependency.kind !== PackageDependencyKind.LocalLink && + !semver.satisfies(matchedVersion, dependency.versionRange) + ) { // DO NOT create a local link, because the local project's version isn't SemVer compatible. // (Note that in order to make version bumping work as expected, we ignore SemVer for // immediate dependencies of top-level projects, indicated by PackageDependencyKind.LocalLink. // Is this wise?) - console.log(colors.yellow(`Rush will not locally link ${dependency.name} for ${localPackage.name}` - + ` because the requested version "${dependency.versionRange}" is incompatible` - + ` with the local version ${matchedVersion}`)); + console.log( + colors.yellow( + `Rush will not locally link ${dependency.name} for ${localPackage.name}` + + ` because the requested version "${dependency.versionRange}" is incompatible` + + ` with the local version ${matchedVersion}` + ) + ); } else { // Yes, it is compatible, so create a symlink to the Rush project. @@ -214,7 +220,10 @@ export class NpmLinkManager extends BaseLinkManager { // We did not find a suitable match, so place a new local package that // symlinks to the Rush project const newLocalFolderPath: string = path.join( - resolution.parentForCreate!.folderPath, 'node_modules', dependency.name); + resolution.parentForCreate!.folderPath, + 'node_modules', + dependency.name + ); const newLocalPackage: NpmPackage = NpmPackage.createLinkedNpmPackage( dependency.name, @@ -260,7 +269,10 @@ export class NpmLinkManager extends BaseLinkManager { // We did not find a suitable match, so place a new local package const newLocalFolderPath: string = path.join( - resolution.parentForCreate!.folderPath, 'node_modules', commonDependencyPackage.name); + resolution.parentForCreate!.folderPath, + 'node_modules', + commonDependencyPackage.name + ); const newLocalPackage: NpmPackage = NpmPackage.createLinkedNpmPackage( commonDependencyPackage.name, @@ -269,11 +281,14 @@ export class NpmLinkManager extends BaseLinkManager { newLocalFolderPath ); - const commonPackageFromLookup: NpmPackage | undefined = - commonPackageLookup.getPackage(newLocalPackage.nameAndVersion) as NpmPackage; + const commonPackageFromLookup: NpmPackage | undefined = commonPackageLookup.getPackage( + newLocalPackage.nameAndVersion + ) as NpmPackage; if (!commonPackageFromLookup) { - throw new Error(`The ${localPackage.name}@${localPackage.version} package was not found` - + ` in the common folder`); + throw new Error( + `The ${localPackage.name}@${localPackage.version} package was not found` + + ` in the common folder` + ); } newLocalPackage.symlinkTargetFolderPath = commonPackageFromLookup.folderPath; @@ -289,13 +304,15 @@ export class NpmLinkManager extends BaseLinkManager { queue.push({ commonPackage: commonDependencyPackage, localPackage: newLocalPackage, - cyclicSubtreeRoot: newCyclicSubtreeRoot + cyclicSubtreeRoot: newCyclicSubtreeRoot, }); } } else { if (dependency.kind !== PackageDependencyKind.Optional) { - throw new Error(`The dependency "${dependency.name}" needed by "${localPackage.name}"` - + ` was not found in the common folder -- do you need to run "rush install"?`); + throw new Error( + `The dependency "${dependency.name}" needed by "${localPackage.name}"` + + ` was not found in the common folder -- do you need to run "rush install"?` + ); } else { console.log('Skipping optional dependency: ' + dependency.name); } @@ -311,14 +328,18 @@ export class NpmLinkManager extends BaseLinkManager { // Also symlink the ".bin" folder if (localProjectPackage.children.length > 0) { - const commonBinFolder: string = path.join(this._rushConfiguration.commonTempFolder, 'node_modules', '.bin'); + const commonBinFolder: string = path.join( + this._rushConfiguration.commonTempFolder, + 'node_modules', + '.bin' + ); const projectBinFolder: string = path.join(localProjectPackage.folderPath, 'node_modules', '.bin'); if (FileSystem.exists(commonBinFolder)) { NpmLinkManager._createSymlink({ linkTargetPath: commonBinFolder, newLinkPath: projectBinFolder, - symlinkKind: SymlinkKind.Directory + symlinkKind: SymlinkKind.Directory, }); } } diff --git a/apps/rush-lib/src/logic/npm/NpmPackage.ts b/apps/rush-lib/src/logic/npm/NpmPackage.ts index e5f37ea6fe9..83ca5466642 100644 --- a/apps/rush-lib/src/logic/npm/NpmPackage.ts +++ b/apps/rush-lib/src/logic/npm/NpmPackage.ts @@ -1,14 +1,8 @@ import * as path from 'path'; import readPackageTree = require('read-package-tree'); -import { - JsonFile, - IPackageJson -} from '@rushstack/node-core-library'; +import { JsonFile, IPackageJson } from '@rushstack/node-core-library'; -import { - BasePackage, - IRushTempPackageJson -} from '../base/BasePackage'; +import { BasePackage, IRushTempPackageJson } from '../base/BasePackage'; /** * Used by the "rush link" algorithm when doing NPM package resolution. @@ -31,7 +25,7 @@ export enum PackageDependencyKind { /** * The dependency should be a symlink to a project that is locally built by Rush.. */ - LocalLink + LocalLink, } export interface IPackageDependency { @@ -61,11 +55,12 @@ export class NpmPackage extends BasePackage { */ public dependencies: IPackageDependency[]; - private constructor(name: string, + private constructor( + name: string, version: string | undefined, dependencies: IPackageDependency[], - folderPath: string) { - + folderPath: string + ) { super(name, version, folderPath, undefined); this.dependencies = dependencies.slice(0); // clone the array this.parent = undefined; @@ -74,8 +69,12 @@ export class NpmPackage extends BasePackage { /** * Used by "npm link" when creating a Package object that represents symbolic links to be created. */ - public static createLinkedNpmPackage(name: string, version: string | undefined, dependencies: IPackageDependency[], - folderPath: string): NpmPackage { + public static createLinkedNpmPackage( + name: string, + version: string | undefined, + dependencies: IPackageDependency[], + folderPath: string + ): NpmPackage { return new NpmPackage(name, version, dependencies, folderPath); } @@ -97,7 +96,7 @@ export class NpmPackage extends BasePackage { package: packageJson, parent: null, // eslint-disable-line @rushstack/no-null path: installFolderName, - realpath: installFolderName + realpath: installFolderName, }; return NpmPackage.createFromNpm(npmPackage); } @@ -108,8 +107,9 @@ export class NpmPackage extends BasePackage { */ public static createFromNpm(npmPackage: readPackageTree.Node): NpmPackage { if (npmPackage.error) { - throw new Error(`Failed to parse package.json for ${path.basename(npmPackage.path)}:` - + ` ${npmPackage.error.message}`); + throw new Error( + `Failed to parse package.json for ${path.basename(npmPackage.path)}:` + ` ${npmPackage.error.message}` + ); } let dependencies: IPackageDependency[] = []; @@ -123,7 +123,7 @@ export class NpmPackage extends BasePackage { dependencies.push({ name: dependencyName, versionRange: packageJson.optionalDependencies[dependencyName], - kind: PackageDependencyKind.Optional + kind: PackageDependencyKind.Optional, }); } } @@ -135,7 +135,7 @@ export class NpmPackage extends BasePackage { dependencies.push({ name: dependencyName, versionRange: packageJson.dependencies[dependencyName], - kind: PackageDependencyKind.Normal + kind: PackageDependencyKind.Normal, }); } } @@ -147,7 +147,7 @@ export class NpmPackage extends BasePackage { dependencies.push({ name: dependencyName, versionRange: packageJson.dependencies![dependencyName], - kind: PackageDependencyKind.LocalLink + kind: PackageDependencyKind.LocalLink, }); } } @@ -211,8 +211,7 @@ export class NpmPackage extends BasePackage { // could add a missing dependency. parentForCreate = currentParent; - if (!currentParent.parent - || (cyclicSubtreeRoot && currentParent === cyclicSubtreeRoot)) { + if (!currentParent.parent || (cyclicSubtreeRoot && currentParent === cyclicSubtreeRoot)) { // We reached the root without finding a match // parentForCreate will be the root. return { found: undefined, parentForCreate }; @@ -230,5 +229,4 @@ export class NpmPackage extends BasePackage { public resolve(dependencyName: string): NpmPackage | undefined { return this.resolveOrCreate(dependencyName).found as NpmPackage; } - -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/logic/npm/NpmShrinkwrapFile.ts b/apps/rush-lib/src/logic/npm/NpmShrinkwrapFile.ts index 8ac80a66539..a2267d4a49e 100644 --- a/apps/rush-lib/src/logic/npm/NpmShrinkwrapFile.ts +++ b/apps/rush-lib/src/logic/npm/NpmShrinkwrapFile.ts @@ -1,13 +1,8 @@ import * as os from 'os'; -import { - JsonFile, - FileSystem -} from '@rushstack/node-core-library'; - -import { - BaseShrinkwrapFile -} from '../base/BaseShrinkwrapFile'; +import { JsonFile, FileSystem } from '@rushstack/node-core-library'; + +import { BaseShrinkwrapFile } from '../base/BaseShrinkwrapFile'; import { DependencySpecifier } from '../DependencySpecifier'; interface INpmShrinkwrapDependencyJson { @@ -38,7 +33,7 @@ export class NpmShrinkwrapFile extends BaseShrinkwrapFile { this._shrinkwrapJson.name = ''; } if (!this._shrinkwrapJson.dependencies) { - this._shrinkwrapJson.dependencies = { }; + this._shrinkwrapJson.dependencies = {}; } } @@ -52,7 +47,8 @@ export class NpmShrinkwrapFile extends BaseShrinkwrapFile { // We don't use JsonFile/jju here because shrinkwrap.json is a special NPM file format // and typically very large, so we want to load it the same way that NPM does. data = FileSystem.readFile(shrinkwrapJsonFilename); - if (data.charCodeAt(0) === 0xFEFF) { // strip BOM + if (data.charCodeAt(0) === 0xfeff) { + // strip BOM data = data.slice(1); } @@ -74,15 +70,17 @@ export class NpmShrinkwrapFile extends BaseShrinkwrapFile { /** @override */ protected getTopLevelDependencyVersion(dependencyName: string): DependencySpecifier | undefined { - // First, check under tempProjectName, as this is the first place "rush link" looks. - const dependencyJson: INpmShrinkwrapDependencyJson | undefined = - NpmShrinkwrapFile.tryGetValue(this._shrinkwrapJson.dependencies, dependencyName); + // First, check under tempProjectName, as this is the first place "rush link" looks. + const dependencyJson: INpmShrinkwrapDependencyJson | undefined = NpmShrinkwrapFile.tryGetValue( + this._shrinkwrapJson.dependencies, + dependencyName + ); - if (!dependencyJson) { - return undefined; - } + if (!dependencyJson) { + return undefined; + } - return new DependencySpecifier(dependencyName, dependencyJson.version); + return new DependencySpecifier(dependencyName, dependencyJson.version); } /** @@ -91,16 +89,22 @@ export class NpmShrinkwrapFile extends BaseShrinkwrapFile { * @param versionRange Not used, just exists to satisfy abstract API contract * @override */ - protected tryEnsureDependencyVersion(dependencySpecifier: DependencySpecifier, - tempProjectName: string): DependencySpecifier | undefined { - + protected tryEnsureDependencyVersion( + dependencySpecifier: DependencySpecifier, + tempProjectName: string + ): DependencySpecifier | undefined { // First, check under tempProjectName, as this is the first place "rush link" looks. let dependencyJson: INpmShrinkwrapDependencyJson | undefined = undefined; const tempDependency: INpmShrinkwrapDependencyJson | undefined = NpmShrinkwrapFile.tryGetValue( - this._shrinkwrapJson.dependencies, tempProjectName); + this._shrinkwrapJson.dependencies, + tempProjectName + ); if (tempDependency && tempDependency.dependencies) { - dependencyJson = NpmShrinkwrapFile.tryGetValue(tempDependency.dependencies, dependencySpecifier.packageName); + dependencyJson = NpmShrinkwrapFile.tryGetValue( + tempDependency.dependencies, + dependencySpecifier.packageName + ); } // Otherwise look at the root of the shrinkwrap file @@ -110,5 +114,4 @@ export class NpmShrinkwrapFile extends BaseShrinkwrapFile { return new DependencySpecifier(dependencySpecifier.packageName, dependencyJson.version); } - -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/logic/pnpm/PnpmLinkManager.ts b/apps/rush-lib/src/logic/pnpm/PnpmLinkManager.ts index cd1a9baa4db..d930f3a5199 100644 --- a/apps/rush-lib/src/logic/pnpm/PnpmLinkManager.ts +++ b/apps/rush-lib/src/logic/pnpm/PnpmLinkManager.ts @@ -8,17 +8,9 @@ import pnpmLinkBins from '@pnpm/link-bins'; import * as semver from 'semver'; import * as colors from 'colors'; -import { - JsonFile, - Text, - FileSystem, - FileConstants, - InternalError -} from '@rushstack/node-core-library'; - -import { - BaseLinkManager -} from '../base/BaseLinkManager'; +import { JsonFile, Text, FileSystem, FileConstants, InternalError } from '@rushstack/node-core-library'; + +import { BaseLinkManager } from '../base/BaseLinkManager'; import { BasePackage } from '../base/BasePackage'; import { RushConstants } from '../../logic/RushConstants'; import { IRushLinkJson } from '../../api/RushConfiguration'; @@ -31,12 +23,13 @@ import { PnpmProjectDependencyManifest } from './PnpmProjectDependencyManifest'; const DEBUG: boolean = false; export class PnpmLinkManager extends BaseLinkManager { - - private readonly _pnpmVersion: semver.SemVer = new semver.SemVer(this._rushConfiguration.packageManagerToolVersion); + private readonly _pnpmVersion: semver.SemVer = new semver.SemVer( + this._rushConfiguration.packageManagerToolVersion + ); protected async _linkProjects(): Promise { const rushLinkJson: IRushLinkJson = { - localLinks: {} + localLinks: {}, }; // Use shrinkwrap from temp as the committed shrinkwrap may not always be up to date @@ -47,7 +40,9 @@ export class PnpmLinkManager extends BaseLinkManager { ); if (!pnpmShrinkwrapFile) { - throw new InternalError(`Cannot load shrinkwrap at "${this._rushConfiguration.tempShrinkwrapFilename}"`); + throw new InternalError( + `Cannot load shrinkwrap at "${this._rushConfiguration.tempShrinkwrapFilename}"` + ); } for (const rushProject of this._rushConfiguration.projects) { @@ -69,16 +64,19 @@ export class PnpmLinkManager extends BaseLinkManager { rushLinkJson: IRushLinkJson, pnpmShrinkwrapFile: PnpmShrinkwrapFile ): Promise { - // first, read the temp package.json information // Example: "project1" - const unscopedTempProjectName: string = this._rushConfiguration.packageNameParser - .getUnscopedName(project.tempProjectName); + const unscopedTempProjectName: string = this._rushConfiguration.packageNameParser.getUnscopedName( + project.tempProjectName + ); // Example: "C:\MyRepo\common\temp\projects\project1 - const extractedFolder: string = path.join(this._rushConfiguration.commonTempFolder, - RushConstants.rushTempProjectsFolderName, unscopedTempProjectName); + const extractedFolder: string = path.join( + this._rushConfiguration.commonTempFolder, + RushConstants.rushTempProjectsFolderName, + unscopedTempProjectName + ); // Example: "C:\MyRepo\common\temp\projects\project1\package.json" const packageJsonFilename: string = path.join(extractedFolder, FileConstants.PackageJson); @@ -91,7 +89,10 @@ export class PnpmLinkManager extends BaseLinkManager { unscopedTempProjectName ); - const commonPackage: BasePackage = BasePackage.createVirtualTempPackage(packageJsonFilename, installFolderName); + const commonPackage: BasePackage = BasePackage.createVirtualTempPackage( + packageJsonFilename, + installFolderName + ); const localPackage: BasePackage = BasePackage.createLinkedPackage( project.packageJsonEditor.name, @@ -103,8 +104,9 @@ export class PnpmLinkManager extends BaseLinkManager { // first, start with the rush dependencies, we just need to link to the project folder for (const dependencyName of Object.keys(commonPackage.packageJson!.rushDependencies || {})) { - const matchedRushPackage: RushConfigurationProject | undefined = - this._rushConfiguration.getProjectByName(dependencyName); + const matchedRushPackage: + | RushConfigurationProject + | undefined = this._rushConfiguration.getProjectByName(dependencyName); if (matchedRushPackage) { // We found a suitable match, so place a new local package that @@ -174,7 +176,10 @@ export class PnpmLinkManager extends BaseLinkManager { const relativePathToTgzFile: string | undefined = tarballEntry.slice(`file:`.length); // e.g.: C:\wbt\common\temp\projects\api-documenter.tgz - const absolutePathToTgzFile: string = path.resolve(this._rushConfiguration.commonTempFolder, relativePathToTgzFile); + const absolutePathToTgzFile: string = path.resolve( + this._rushConfiguration.commonTempFolder, + relativePathToTgzFile + ); // The folder name in `.local` is constructed as: // UriEncode(absolutePathToTgzFile) + _suffix @@ -190,32 +195,38 @@ export class PnpmLinkManager extends BaseLinkManager { // '' [empty string] // _jsdom@11.12.0 // _2a665c89609864b4e75bc5365d7f8f56 - const folderNameSuffix: string = tarballEntry && tarballEntry.length < tempProjectDependencyKey.length - ? tempProjectDependencyKey.slice(tarballEntry.length) - : ''; + const folderNameSuffix: string = + tarballEntry && tarballEntry.length < tempProjectDependencyKey.length + ? tempProjectDependencyKey.slice(tarballEntry.length) + : ''; // e.g.: // C%3A%2Fwbt%2Fcommon%2Ftemp%2Fprojects%2Fapi-documenter.tgz // C%3A%2Fdev%2Fimodeljs%2Fimodeljs%2Fcommon%2Ftemp%2Fprojects%2Fpresentation-integration-tests.tgz_jsdom@11.12.0 // C%3A%2Fdev%2Fimodeljs%2Fimodeljs%2Fcommon%2Ftemp%2Fprojects%2Fbuild-tools.tgz_2a665c89609864b4e75bc5365d7f8f56 - const folderNameInLocalInstallationRoot: string = uriEncode(Text.replaceAll(absolutePathToTgzFile, path.sep, '/')) + - folderNameSuffix; + const folderNameInLocalInstallationRoot: string = + uriEncode(Text.replaceAll(absolutePathToTgzFile, path.sep, '/')) + folderNameSuffix; // e.g.: C:\wbt\common\temp\node_modules\.local\C%3A%2Fwbt%2Fcommon%2Ftemp%2Fprojects%2Fapi-documenter.tgz\node_modules - const pathToLocalInstallation: string = this._getPathToLocalInstallation(folderNameInLocalInstallationRoot); + const pathToLocalInstallation: string = this._getPathToLocalInstallation( + folderNameInLocalInstallationRoot + ); - const parentShrinkwrapEntry: IPnpmShrinkwrapDependencyYaml | undefined = - pnpmShrinkwrapFile.getShrinkwrapEntryFromTempProjectDependencyKey(tempProjectDependencyKey); + const parentShrinkwrapEntry: + | IPnpmShrinkwrapDependencyYaml + | undefined = pnpmShrinkwrapFile.getShrinkwrapEntryFromTempProjectDependencyKey( + tempProjectDependencyKey + ); if (!parentShrinkwrapEntry) { throw new InternalError( - 'Cannot find shrinkwrap entry using dependency key for temp project: ' + - `${project.tempProjectName}`); + 'Cannot find shrinkwrap entry using dependency key for temp project: ' + `${project.tempProjectName}` + ); } const pnpmProjectDependencyManifest: PnpmProjectDependencyManifest = new PnpmProjectDependencyManifest({ pnpmShrinkwrapFile, - project + project, }); for (const dependencyName of Object.keys(commonPackage.packageJson!.dependencies || {})) { @@ -225,7 +236,8 @@ export class PnpmLinkManager extends BaseLinkManager { parentShrinkwrapEntry, localPackage, pathToLocalInstallation, - dependencyName)!; + dependencyName + )!; localPackage.addChild(newLocalPackage); } @@ -251,7 +263,10 @@ export class PnpmLinkManager extends BaseLinkManager { PnpmLinkManager._createSymlinksForTopLevelProject(localPackage); - if (!this._rushConfiguration.experimentsConfiguration.configuration.legacyIncrementalBuildDependencyDetection) { + if ( + !this._rushConfiguration.experimentsConfiguration.configuration + .legacyIncrementalBuildDependencyDetection + ) { pnpmProjectDependencyManifest.save(); } else { pnpmProjectDependencyManifest.deleteIfExists(); @@ -261,30 +276,30 @@ export class PnpmLinkManager extends BaseLinkManager { const projectFolder: string = path.join(localPackage.folderPath, 'node_modules'); const projectBinFolder: string = path.join(localPackage.folderPath, 'node_modules', '.bin'); - await pnpmLinkBins( - projectFolder, - projectBinFolder, - { - warn: (msg: string) => console.warn(colors.yellow(msg)) - } - ); + await pnpmLinkBins(projectFolder, projectBinFolder, { + warn: (msg: string) => console.warn(colors.yellow(msg)), + }); } private _getPathToLocalInstallation(folderNameInLocalInstallationRoot: string): string { // See https://github.com/pnpm/pnpm/releases/tag/v4.0.0 if (this._pnpmVersion.major >= 4) { - return path.join(this._rushConfiguration.commonTempFolder, + return path.join( + this._rushConfiguration.commonTempFolder, RushConstants.nodeModulesFolderName, '.pnpm', 'local', folderNameInLocalInstallationRoot, - RushConstants.nodeModulesFolderName); + RushConstants.nodeModulesFolderName + ); } else { - return path.join(this._rushConfiguration.commonTempFolder, + return path.join( + this._rushConfiguration.commonTempFolder, RushConstants.nodeModulesFolderName, '.local', folderNameInLocalInstallationRoot, - RushConstants.nodeModulesFolderName); + RushConstants.nodeModulesFolderName + ); } } private _createLocalPackageForDependency( @@ -301,18 +316,20 @@ export class PnpmLinkManager extends BaseLinkManager { // FYI dependencyName might contain an NPM scope, here it gets converted into a filesystem folder name // e.g. if the dependency is supi: // "C:\wbt\common\temp\node_modules\.local\C%3A%2Fwbt%2Fcommon%2Ftemp%2Fprojects%2Fapi-documenter.tgz\node_modules\supi" - const dependencyLocalInstallationSymlink: string = path.join( - pathToLocalInstallation, - dependencyName); + const dependencyLocalInstallationSymlink: string = path.join(pathToLocalInstallation, dependencyName); if (!FileSystem.exists(dependencyLocalInstallationSymlink)) { // if this occurs, it is a bug in Rush algorithm or unexpected PNPM behavior - throw new InternalError(`Cannot find installed dependency "${dependencyName}" in "${pathToLocalInstallation}"`); + throw new InternalError( + `Cannot find installed dependency "${dependencyName}" in "${pathToLocalInstallation}"` + ); } if (!FileSystem.getLinkStatistics(dependencyLocalInstallationSymlink).isSymbolicLink()) { // if this occurs, it is a bug in Rush algorithm or unexpected PNPM behavior - throw new InternalError(`Dependency "${dependencyName}" is not a symlink in "${pathToLocalInstallation}`); + throw new InternalError( + `Dependency "${dependencyName}" is not a symlink in "${pathToLocalInstallation}` + ); } // read the version number from the shrinkwrap entry @@ -323,7 +340,8 @@ export class PnpmLinkManager extends BaseLinkManager { if (!isOptional) { throw new InternalError( `Cannot find shrinkwrap entry dependency "${dependencyName}" for temp project: ` + - `${project.tempProjectName}`); + `${project.tempProjectName}` + ); } return; } @@ -339,7 +357,10 @@ export class PnpmLinkManager extends BaseLinkManager { // reads that are needed, we will link to where that symlink pointed, rather than linking to a link. newLocalPackage.symlinkTargetFolderPath = FileSystem.getRealPath(dependencyLocalInstallationSymlink); - if (!this._rushConfiguration.experimentsConfiguration.configuration.legacyIncrementalBuildDependencyDetection) { + if ( + !this._rushConfiguration.experimentsConfiguration.configuration + .legacyIncrementalBuildDependencyDetection + ) { pnpmProjectDependencyManifest.addDependency(newLocalPackage, parentShrinkwrapEntry); } diff --git a/apps/rush-lib/src/logic/pnpm/PnpmProjectDependencyManifest.ts b/apps/rush-lib/src/logic/pnpm/PnpmProjectDependencyManifest.ts index f3c8d644d89..812a2a018dc 100644 --- a/apps/rush-lib/src/logic/pnpm/PnpmProjectDependencyManifest.ts +++ b/apps/rush-lib/src/logic/pnpm/PnpmProjectDependencyManifest.ts @@ -3,16 +3,12 @@ import * as path from 'path'; import * as semver from 'semver'; -import { - JsonFile, - InternalError, - FileSystem -} from '@rushstack/node-core-library'; +import { JsonFile, InternalError, FileSystem } from '@rushstack/node-core-library'; import { PnpmShrinkwrapFile, IPnpmShrinkwrapDependencyYaml, - parsePnpmDependencyKey + parsePnpmDependencyKey, } from './PnpmShrinkwrapFile'; import { RushConfigurationProject } from '../../api/RushConfigurationProject'; import { RushConstants } from '../RushConstants'; @@ -47,7 +43,9 @@ export class PnpmProjectDependencyManifest { public constructor(options: IPnpmProjectDependencyManifestOptions) { this._pnpmShrinkwrapFile = options.pnpmShrinkwrapFile; this._project = options.project; - this._projectDependencyManifestFilename = PnpmProjectDependencyManifest.getFilePathForProject(this._project); + this._projectDependencyManifestFilename = PnpmProjectDependencyManifest.getFilePathForProject( + this._project + ); this._projectDependencyManifestFile = new Map(); } @@ -57,10 +55,7 @@ export class PnpmProjectDependencyManifest { * for the specified project. */ public static getFilePathForProject(project: RushConfigurationProject): string { - return path.join( - project.projectRushTempFolder, - RushConstants.projectDependencyManifestFilename - ); + return path.join(project.projectRushTempFolder, RushConstants.projectDependencyManifestFilename); } public addDependency(pkg: BasePackage, parentShrinkwrapEntry: IPnpmShrinkwrapDependencyYaml): void { @@ -81,11 +76,7 @@ export class PnpmProjectDependencyManifest { file[key] = this._projectDependencyManifestFile.get(key)!; } - JsonFile.save( - file, - this._projectDependencyManifestFilename, - { ensureFolderExists: true } - ); + JsonFile.save(file, this._projectDependencyManifestFilename, { ensureFolderExists: true }); } /** @@ -101,10 +92,9 @@ export class PnpmProjectDependencyManifest { parentShrinkwrapEntry: IPnpmShrinkwrapDependencyYaml, throwIfShrinkwrapEntryMissing: boolean = true ): void { - const shrinkwrapEntry: IPnpmShrinkwrapDependencyYaml | undefined = this._pnpmShrinkwrapFile.getShrinkwrapEntry( - name, - version - ); + const shrinkwrapEntry: + | IPnpmShrinkwrapDependencyYaml + | undefined = this._pnpmShrinkwrapFile.getShrinkwrapEntry(name, version); if (!shrinkwrapEntry) { if (throwIfShrinkwrapEntryMissing) { @@ -142,7 +132,8 @@ export class PnpmProjectDependencyManifest { optionalDependencyName, dependencyVersion, shrinkwrapEntry, - throwIfShrinkwrapEntryMissing = false); + (throwIfShrinkwrapEntryMissing = false) + ); } } @@ -152,10 +143,7 @@ export class PnpmProjectDependencyManifest { const dependencySemVer: string = shrinkwrapEntry.peerDependencies[peerDependencyName]; // Check the current package to see if the dependency is already satisfied - if ( - shrinkwrapEntry.dependencies && - shrinkwrapEntry.dependencies.hasOwnProperty(peerDependencyName) - ) { + if (shrinkwrapEntry.dependencies && shrinkwrapEntry.dependencies.hasOwnProperty(peerDependencyName)) { const dependencySpecifier: DependencySpecifier | undefined = parsePnpmDependencyKey( peerDependencyName, shrinkwrapEntry.dependencies[peerDependencyName] @@ -191,15 +179,17 @@ export class PnpmProjectDependencyManifest { // The parent doesn't have a version that satisfies the range. As a last attempt, check // if it's been hoisted up as a top-level dependency - const topLevelDependencySpecifier: DependencySpecifier | undefined = - this._pnpmShrinkwrapFile.getTopLevelDependencyVersion(peerDependencyName); + const topLevelDependencySpecifier: + | DependencySpecifier + | undefined = this._pnpmShrinkwrapFile.getTopLevelDependencyVersion(peerDependencyName); // Sometimes peer dependencies are hoisted but are not represented in the shrinkwrap file // (such as when implicitlyPreferredVersions is false) so we need to find the correct key // and add it ourselves if (!topLevelDependencySpecifier) { - const peerDependencyKeys: { [peerDependencyName: string]: string } = - this._parsePeerDependencyKeysFromSpecifier(specifier); + const peerDependencyKeys: { + [peerDependencyName: string]: string; + } = this._parsePeerDependencyKeysFromSpecifier(specifier); if (peerDependencyKeys.hasOwnProperty(peerDependencyName)) { this._addDependencyInternal( peerDependencyName, @@ -214,11 +204,9 @@ export class PnpmProjectDependencyManifest { if ( !this._project.rushConfiguration.pnpmOptions || !this._project.rushConfiguration.pnpmOptions.strictPeerDependencies || - ( - shrinkwrapEntry.peerDependenciesMeta && + (shrinkwrapEntry.peerDependenciesMeta && shrinkwrapEntry.peerDependenciesMeta.hasOwnProperty(peerDependencyName) && - shrinkwrapEntry.peerDependenciesMeta[peerDependencyName].optional - ) + shrinkwrapEntry.peerDependenciesMeta[peerDependencyName].optional) ) { // We couldn't find the peer dependency, but we determined it's by design, skip this dependency... continue; @@ -249,7 +237,7 @@ export class PnpmProjectDependencyManifest { if (specifierMatches) { const combinedPeerDependencies: string = specifierMatches[1]; // Parse "eslint@6.6.0+typescript@3.6.4" --> ["eslint@6.6.0", "typescript@3.6.4"] - const peerDependencies: string[] = combinedPeerDependencies.split("+"); + const peerDependencies: string[] = combinedPeerDependencies.split('+'); for (const peerDependencySpecifier of peerDependencies) { // Parse "eslint@6.6.0" --> "eslint", "6.6.0" const peerMatches: RegExpExecArray | null = /^([^+@]+)@(.+)$/.exec(peerDependencySpecifier); diff --git a/apps/rush-lib/src/logic/pnpm/PnpmShrinkwrapFile.ts b/apps/rush-lib/src/logic/pnpm/PnpmShrinkwrapFile.ts index d34f8683ae7..32a4d92435a 100644 --- a/apps/rush-lib/src/logic/pnpm/PnpmShrinkwrapFile.ts +++ b/apps/rush-lib/src/logic/pnpm/PnpmShrinkwrapFile.ts @@ -7,7 +7,10 @@ import { FileSystem } from '@rushstack/node-core-library'; import { BaseShrinkwrapFile } from '../base/BaseShrinkwrapFile'; import { DependencySpecifier } from '../DependencySpecifier'; -import { PackageManagerOptionsConfigurationBase, PnpmOptionsConfiguration } from '../../api/RushConfiguration'; +import { + PackageManagerOptionsConfigurationBase, + PnpmOptionsConfiguration, +} from '../../api/RushConfiguration'; import { IPolicyValidatorOptions } from '../policy/PolicyValidator'; import { AlreadyReportedError } from '../../utilities/AlreadyReportedError'; @@ -17,7 +20,7 @@ const SHRINKWRAP_YAML_FORMAT: yaml.DumpOptions = { lineWidth: 1000, noCompatMode: true, noRefs: true, - sortKeys: true + sortKeys: true, }; export interface IPeerDependenciesMetaYaml { @@ -93,7 +96,10 @@ interface IPnpmShrinkwrapYaml { * * @returns a SemVer string, or undefined if the version specifier cannot be parsed */ -export function parsePnpmDependencyKey(dependencyName: string, dependencyKey: string): DependencySpecifier | undefined { +export function parsePnpmDependencyKey( + dependencyName: string, + dependencyKey: string +): DependencySpecifier | undefined { if (!dependencyKey) { return undefined; } @@ -114,7 +120,9 @@ export function parsePnpmDependencyKey(dependencyName: string, dependencyKey: st // Example: "path.pkgs.visualstudio.com/@scope/depame/1.4.0" --> 0="@scope/depame" 1="1.4.0" // Example: "/isarray/2.0.1" --> 0="isarray" 1="2.0.1" // Example: "/sinon-chai/2.8.0/chai@3.5.0+sinon@1.17.7" --> 0="sinon-chai" 1="2.8.0/chai@3.5.0+sinon@1.17.7" - const packageNameMatch: RegExpMatchArray | null = /^[^\/]*\/((?:@[^\/]+\/)?[^\/]+)\/(.*)$/.exec(dependencyKey); + const packageNameMatch: RegExpMatchArray | null = /^[^\/]*\/((?:@[^\/]+\/)?[^\/]+)\/(.*)$/.exec( + dependencyKey + ); if (packageNameMatch) { parsedPackageName = packageNameMatch[1]; parsedInstallPath = packageNameMatch[2]; @@ -174,7 +182,8 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { shrinkwrapJson: IPnpmShrinkwrapYaml, shrinkwrapFilename: string, shrinkwrapHash?: string, - shrinkwrapHashEnabled?: boolean) { + shrinkwrapHashEnabled?: boolean + ) { super(); this._shrinkwrapJson = shrinkwrapJson; this.shrinkwrapFilename = shrinkwrapFilename; @@ -186,13 +195,13 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { this._shrinkwrapJson.registry = ''; } if (!this._shrinkwrapJson.dependencies) { - this._shrinkwrapJson.dependencies = { }; + this._shrinkwrapJson.dependencies = {}; } if (!this._shrinkwrapJson.specifiers) { - this._shrinkwrapJson.specifiers = { }; + this._shrinkwrapJson.specifiers = {}; } if (!this._shrinkwrapJson.packages) { - this._shrinkwrapJson.packages = { }; + this._shrinkwrapJson.packages = {}; } } @@ -239,7 +248,7 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { public validate( packageManagerOptionsConfig: PackageManagerOptionsConfigurationBase, policyOptions: IPolicyValidatorOptions - ) : void { + ): void { super.validate(packageManagerOptionsConfig, policyOptions); if (!(packageManagerOptionsConfig instanceof PnpmOptionsConfiguration)) { throw new Error('The provided package manager options are not valid for PNPM shrinkwrap files.'); @@ -252,7 +261,7 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { console.log( colors.red( 'The shrinkwrap file does not contain the generated hash. You may need to run "rush update" to ' + - 'populate the hash. See the "preventManualShrinkwrapChanges" setting documentation for details.' + 'populate the hash. See the "preventManualShrinkwrapChanges" setting documentation for details.' ) + os.EOL ); throw new AlreadyReportedError(); @@ -264,8 +273,8 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { console.log( colors.red( 'The shrinkwrap file hash does not match the expected hash. Please run "rush update" to ensure the ' + - 'shrinkwrap file is up to date. See the "preventManualShrinkwrapChanges" setting documentation for ' + - 'details.' + 'shrinkwrap file is up to date. See the "preventManualShrinkwrapChanges" setting documentation for ' + + 'details.' ) + os.EOL ); throw new AlreadyReportedError(); @@ -308,9 +317,11 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { * @override */ public getTopLevelDependencyVersion(dependencyName: string): DependencySpecifier | undefined { - let value: string | undefined = BaseShrinkwrapFile.tryGetValue(this._shrinkwrapJson.dependencies, dependencyName); + let value: string | undefined = BaseShrinkwrapFile.tryGetValue( + this._shrinkwrapJson.dependencies, + dependencyName + ); if (value) { - // Getting the top level dependency version from a PNPM lockfile version 5.1 // -------------------------------------------------------------------------- // @@ -340,8 +351,12 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { const dependency: IPnpmShrinkwrapDependencyYaml = this._shrinkwrapJson.packages[value]; - if (dependency && dependency.resolution && dependency.resolution.tarball && - value.startsWith(dependency.resolution.tarball)) { + if ( + dependency && + dependency.resolution && + dependency.resolution.tarball && + value.startsWith(dependency.resolution.tarball) + ) { return new DependencySpecifier(dependencyName, dependency.resolution.tarball); } else { const underscoreIndex: number = value.indexOf('_'); @@ -374,8 +389,10 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { * of the temp project '@rush-temp/my-app'. */ public getTempProjectDependencyKey(tempProjectName: string): string | undefined { - const tempProjectDependencyKey: string | undefined = - BaseShrinkwrapFile.tryGetValue(this._shrinkwrapJson.dependencies, tempProjectName); + const tempProjectDependencyKey: string | undefined = BaseShrinkwrapFile.tryGetValue( + this._shrinkwrapJson.dependencies, + tempProjectName + ); if (tempProjectDependencyKey) { return tempProjectDependencyKey; @@ -392,9 +409,7 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { public getShrinkwrapEntry(name: string, version: string): IPnpmShrinkwrapDependencyYaml | undefined { // Version can sometimes be in the form of a path that's already in the /name/version format. - const packageId: string = version.indexOf('/') !== -1 - ? version - : `/${name}/${version}`; + const packageId: string = version.indexOf('/') !== -1 ? version : `/${name}/${version}`; return this._shrinkwrapJson.packages[packageId]; } @@ -407,8 +422,9 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { let shrinkwrapContent: string = yaml.safeDump(this._shrinkwrapJson, SHRINKWRAP_YAML_FORMAT); if (this._shrinkwrapHashEnabled) { this._shrinkwrapHash = crypto.createHash('sha1').update(shrinkwrapContent).digest('hex'); - shrinkwrapContent = - `${shrinkwrapContent.trimRight()}\n${PnpmShrinkwrapFile._shrinkwrapHashPrefix} ${this._shrinkwrapHash}\n`; + shrinkwrapContent = `${shrinkwrapContent.trimRight()}\n${PnpmShrinkwrapFile._shrinkwrapHashPrefix} ${ + this._shrinkwrapHash + }\n`; } return shrinkwrapContent; @@ -421,9 +437,11 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { * * @override */ - protected tryEnsureDependencyVersion(dependencySpecifier: DependencySpecifier, - tempProjectName: string, tryReusingPackageVersionsFromShrinkwrap: boolean): DependencySpecifier | undefined { - + protected tryEnsureDependencyVersion( + dependencySpecifier: DependencySpecifier, + tempProjectName: string, + tryReusingPackageVersionsFromShrinkwrap: boolean + ): DependencySpecifier | undefined { // PNPM doesn't have the same advantage of NPM, where we can skip generate as long as the // shrinkwrap file puts our dependency in either the top of the node_modules folder // or underneath the package we are looking at. @@ -439,14 +457,14 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { return undefined; } - const packageDescription: IPnpmShrinkwrapDependencyYaml | undefined = - this._getPackageDescription(tempProjectDependencyKey); + const packageDescription: IPnpmShrinkwrapDependencyYaml | undefined = this._getPackageDescription( + tempProjectDependencyKey + ); if (!packageDescription) { return undefined; } if (!packageDescription.dependencies.hasOwnProperty(packageName)) { - if (tryReusingPackageVersionsFromShrinkwrap && dependencySpecifier.versionSpecifier) { // this means the current temp project doesn't provide this dependency, // however, we may be able to use a different version. we prefer the latest version @@ -454,7 +472,9 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { for (const otherTempProject of this.getTempProjectNames()) { const otherVersionSpecifier: DependencySpecifier | undefined = this._getDependencyVersion( - dependencySpecifier.packageName, otherTempProject); + dependencySpecifier.packageName, + otherTempProject + ); if (otherVersionSpecifier) { const otherVersion: string = otherVersionSpecifier.versionSpecifier; @@ -488,14 +508,18 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { /** * Returns the version of a dependency being used by a given project */ - private _getDependencyVersion(dependencyName: string, tempProjectName: string): DependencySpecifier | undefined { + private _getDependencyVersion( + dependencyName: string, + tempProjectName: string + ): DependencySpecifier | undefined { const tempProjectDependencyKey: string | undefined = this.getTempProjectDependencyKey(tempProjectName); if (!tempProjectDependencyKey) { throw new Error(`Cannot get dependency key for temp project: ${tempProjectName}`); } - const packageDescription: IPnpmShrinkwrapDependencyYaml | undefined = - this._getPackageDescription(tempProjectDependencyKey); + const packageDescription: IPnpmShrinkwrapDependencyYaml | undefined = this._getPackageDescription( + tempProjectDependencyKey + ); if (!packageDescription) { return undefined; } @@ -510,9 +534,13 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { /** * Gets the package description for a tempProject from the shrinkwrap file. */ - private _getPackageDescription(tempProjectDependencyKey: string): IPnpmShrinkwrapDependencyYaml | undefined { - const packageDescription: IPnpmShrinkwrapDependencyYaml | undefined - = BaseShrinkwrapFile.tryGetValue(this._shrinkwrapJson.packages, tempProjectDependencyKey); + private _getPackageDescription( + tempProjectDependencyKey: string + ): IPnpmShrinkwrapDependencyYaml | undefined { + const packageDescription: IPnpmShrinkwrapDependencyYaml | undefined = BaseShrinkwrapFile.tryGetValue( + this._shrinkwrapJson.packages, + tempProjectDependencyKey + ); if (!packageDescription || !packageDescription.dependencies) { return undefined; @@ -521,14 +549,21 @@ export class PnpmShrinkwrapFile extends BaseShrinkwrapFile { return packageDescription; } - private _parsePnpmDependencyKey(dependencyName: string, pnpmDependencyKey: string): DependencySpecifier | undefined { - + private _parsePnpmDependencyKey( + dependencyName: string, + pnpmDependencyKey: string + ): DependencySpecifier | undefined { if (pnpmDependencyKey) { - const result: DependencySpecifier | undefined = parsePnpmDependencyKey(dependencyName, pnpmDependencyKey); + const result: DependencySpecifier | undefined = parsePnpmDependencyKey( + dependencyName, + pnpmDependencyKey + ); if (!result) { - throw new Error(`Cannot parse PNPM shrinkwrap version specifier: "${pnpmDependencyKey}"` - + ` for "${dependencyName}"`); + throw new Error( + `Cannot parse PNPM shrinkwrap version specifier: "${pnpmDependencyKey}"` + + ` for "${dependencyName}"` + ); } return result; diff --git a/apps/rush-lib/src/logic/policy/GitEmailPolicy.ts b/apps/rush-lib/src/logic/policy/GitEmailPolicy.ts index fc1e585965c..616f763e1af 100644 --- a/apps/rush-lib/src/logic/policy/GitEmailPolicy.ts +++ b/apps/rush-lib/src/logic/policy/GitEmailPolicy.ts @@ -14,16 +14,17 @@ export class GitEmailPolicy { if (!Git.isGitPresent()) { // If Git isn't installed, or this Rush project is not under a Git working folder, // then we don't care about the Git email - console.log(colors.cyan( - 'Ignoring Git validation because the Git binary was not found in the shell path.') + os.EOL); + console.log( + colors.cyan('Ignoring Git validation because the Git binary was not found in the shell path.') + + os.EOL + ); return; } if (!Git.isPathUnderGitWorkingTree()) { // If Git isn't installed, or this Rush project is not under a Git working folder, // then we don't care about the Git email - console.log(colors.cyan( - 'Ignoring Git validation because this is not a Git working folder.' + os.EOL)); + console.log(colors.cyan('Ignoring Git validation because this is not a Git working folder.' + os.EOL)); return; } @@ -45,19 +46,23 @@ export class GitEmailPolicy { // sanity check; a valid email should not contain any whitespace // if this fails, then we have another issue to report if (!userEmail.match(/^\S+$/g)) { - console.log([ - colors.red('Your Git email address is invalid: ' + JSON.stringify(userEmail)), - '', - `To configure your Git email address, try something like this:`, - '', - ...GitEmailPolicy.getEmailExampleLines(rushConfiguration), - '' - ].join(os.EOL)); + console.log( + [ + colors.red('Your Git email address is invalid: ' + JSON.stringify(userEmail)), + '', + `To configure your Git email address, try something like this:`, + '', + ...GitEmailPolicy.getEmailExampleLines(rushConfiguration), + '', + ].join(os.EOL) + ); throw new AlreadyReportedError(); } } catch (e) { if (e instanceof AlreadyReportedError) { - console.log(colors.red('Aborting, so you can go fix your settings. (Or use --bypass-policy to skip.)')); + console.log( + colors.red('Aborting, so you can go fix your settings. (Or use --bypass-policy to skip.)') + ); throw e; } else { throw e; @@ -96,21 +101,23 @@ export class GitEmailPolicy { // but if it fails, this isn't critical, so don't bother them about it } - console.log([ - 'Hey there! To keep things tidy, this repo asks you to submit your Git commits using an email like ' + - (rushConfiguration.gitAllowedEmailRegExps.length > 1 ? 'one of these patterns:' : 'this pattern:'), - '', - ...rushConfiguration.gitAllowedEmailRegExps.map((pattern) => ' ' + colors.cyan(pattern)), - '', - '...but yours is configured like this:', - '', - ` ${fancyEmail}`, - '', - 'To fix it, you can use commands like this:', - '', - ...GitEmailPolicy.getEmailExampleLines(rushConfiguration), - '' - ].join(os.EOL)); + console.log( + [ + 'Hey there! To keep things tidy, this repo asks you to submit your Git commits using an email like ' + + (rushConfiguration.gitAllowedEmailRegExps.length > 1 ? 'one of these patterns:' : 'this pattern:'), + '', + ...rushConfiguration.gitAllowedEmailRegExps.map((pattern) => ' ' + colors.cyan(pattern)), + '', + '...but yours is configured like this:', + '', + ` ${fancyEmail}`, + '', + 'To fix it, you can use commands like this:', + '', + ...GitEmailPolicy.getEmailExampleLines(rushConfiguration), + '', + ].join(os.EOL) + ); console.log(colors.red('Aborting, so you can go fix your settings. (Or use --bypass-policy to skip.)')); throw new AlreadyReportedError(); @@ -119,7 +126,9 @@ export class GitEmailPolicy { public static getEmailExampleLines(rushConfiguration: RushConfiguration): string[] { return [ colors.cyan(' git config --local user.name "Mr. Example"'), - colors.cyan(` git config --local user.email "${rushConfiguration.gitSampleEmail || 'example@contoso.com'}"`) + colors.cyan( + ` git config --local user.email "${rushConfiguration.gitSampleEmail || 'example@contoso.com'}"` + ), ]; } } diff --git a/apps/rush-lib/src/logic/policy/PolicyValidator.ts b/apps/rush-lib/src/logic/policy/PolicyValidator.ts index 0d4d2b2532d..8574263c643 100644 --- a/apps/rush-lib/src/logic/policy/PolicyValidator.ts +++ b/apps/rush-lib/src/logic/policy/PolicyValidator.ts @@ -6,14 +6,13 @@ import { GitEmailPolicy } from './GitEmailPolicy'; import { ShrinkwrapFilePolicy } from './ShrinkwrapFilePolicy'; export interface IPolicyValidatorOptions { - bypassPolicy?: boolean, - allowShrinkwrapUpdates?: boolean, - shrinkwrapVariant?: string + bypassPolicy?: boolean; + allowShrinkwrapUpdates?: boolean; + shrinkwrapVariant?: string; } export class PolicyValidator { - public static validatePolicy( - rushConfiguration: RushConfiguration, options: IPolicyValidatorOptions): void { + public static validatePolicy(rushConfiguration: RushConfiguration, options: IPolicyValidatorOptions): void { if (options.bypassPolicy) { return; } diff --git a/apps/rush-lib/src/logic/taskRunner/ProjectTask.ts b/apps/rush-lib/src/logic/taskRunner/ProjectTask.ts index 6165f39e36d..161e6be8c36 100644 --- a/apps/rush-lib/src/logic/taskRunner/ProjectTask.ts +++ b/apps/rush-lib/src/logic/taskRunner/ProjectTask.ts @@ -89,11 +89,12 @@ export class ProjectTask implements ITaskDefinition { try { deps = { files: this._packageChangeAnalyzer.getPackageDepsHash(this._rushProject.packageName)!.files, - arguments: this._commandToRun + arguments: this._commandToRun, }; } catch (error) { - writer.writeLine('Unable to calculate incremental build state. ' + - 'Instead running full rebuild. ' + error.toString()); + writer.writeLine( + 'Unable to calculate incremental build state. ' + 'Instead running full rebuild. ' + error.toString() + ); } return deps; @@ -113,7 +114,10 @@ export class ProjectTask implements ITaskDefinition { // TODO: Remove legacyDepsPath with the next major release of Rush const legacyDepsPath: string = path.join(this._rushProject.projectFolder, 'package-deps.json'); - const currentDepsPath: string = path.join(this._rushProject.projectRushTempFolder, this._packageDepsFilename); + const currentDepsPath: string = path.join( + this._rushProject.projectRushTempFolder, + this._packageDepsFilename + ); if (FileSystem.exists(currentDepsPath)) { try { @@ -122,18 +126,16 @@ export class ProjectTask implements ITaskDefinition { // Warn and ignore - treat failing to load the file as the project being not built. writer.writeLine( `Warning: error parsing ${this._packageDepsFilename}: ${e}. Ignoring and ` + - `treating the command "${this._commandToRun}" as not run.` + `treating the command "${this._commandToRun}" as not run.` ); } } - const isPackageUnchanged: boolean = ( - !!( - lastPackageDeps && - currentPackageDeps && - (currentPackageDeps.arguments === lastPackageDeps.arguments && - _areShallowEqual(currentPackageDeps.files, lastPackageDeps.files, writer)) - ) + const isPackageUnchanged: boolean = !!( + lastPackageDeps && + currentPackageDeps && + currentPackageDeps.arguments === lastPackageDeps.arguments && + _areShallowEqual(currentPackageDeps.files, lastPackageDeps.files, writer) ); if (isPackageUnchanged && this.isIncrementalBuildAllowed) { @@ -146,13 +148,15 @@ export class ProjectTask implements ITaskDefinition { FileSystem.deleteFile(legacyDepsPath); if (!this._commandToRun) { - writer.writeLine(`The task command "${this._commandToRun}" was registered in the package.json but is blank,` - + ` so no action will be taken.`); + writer.writeLine( + `The task command "${this._commandToRun}" was registered in the package.json but is blank,` + + ` so no action will be taken.` + ); // Write deps on success. if (currentPackageDeps) { JsonFile.save(currentPackageDeps, currentDepsPath, { - ensureFolderExists: true + ensureFolderExists: true, }); } @@ -162,18 +166,15 @@ export class ProjectTask implements ITaskDefinition { // Run the task writer.writeLine(this._commandToRun); - const task: child_process.ChildProcess = Utilities.executeLifecycleCommandAsync( - this._commandToRun, - { - rushConfiguration: this._rushConfiguration, - workingDirectory: projectFolder, - initCwd: this._rushConfiguration.commonTempFolder, - handleOutput: true, - environmentPathOptions: { - includeProjectBin: true - } - } - ); + const task: child_process.ChildProcess = Utilities.executeLifecycleCommandAsync(this._commandToRun, { + rushConfiguration: this._rushConfiguration, + workingDirectory: projectFolder, + initCwd: this._rushConfiguration.commonTempFolder, + handleOutput: true, + environmentPathOptions: { + includeProjectBin: true, + }, + }); // Hook into events, in order to get live streaming of build log if (task.stdout !== null) { @@ -200,7 +201,7 @@ export class ProjectTask implements ITaskDefinition { // Write deps on success. if (currentPackageDeps) { JsonFile.save(currentPackageDeps, currentDepsPath, { - ensureFolderExists: true + ensureFolderExists: true, }); } resolve(TaskStatus.Success); @@ -230,7 +231,10 @@ export class ProjectTask implements ITaskDefinition { // eslint-disable-next-line no-control-regex const stderr: string = writer.getStdError().replace(/\x1B[[(?);]{0,2}(;?\d)*./g, ''); if (stderr) { - FileSystem.writeFile(path.join(this._rushProject.projectFolder, logFilename + '.build.error.log'), stderr); + FileSystem.writeFile( + path.join(this._rushProject.projectFolder, logFilename + '.build.error.log'), + stderr + ); } } catch (e) { console.log(`Error writing logs to disk: ${e}`); diff --git a/apps/rush-lib/src/logic/taskRunner/TaskCollection.ts b/apps/rush-lib/src/logic/taskRunner/TaskCollection.ts index 3c5cacd6a1d..ff8495bcf50 100644 --- a/apps/rush-lib/src/logic/taskRunner/TaskCollection.ts +++ b/apps/rush-lib/src/logic/taskRunner/TaskCollection.ts @@ -1,11 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - Terminal, - ConsoleTerminalProvider, - Sort -} from '@rushstack/node-core-library'; +import { Terminal, ConsoleTerminalProvider, Sort } from '@rushstack/node-core-library'; import { ITask, ITaskDefinition } from './ITask'; import { TaskStatus } from './TaskStatus'; @@ -26,10 +22,7 @@ export class TaskCollection { private _terminal: Terminal; public constructor(options: ITaskCollectionOptions) { - const { - quietMode, - terminal = new Terminal(new ConsoleTerminalProvider()) - } = options; + const { quietMode, terminal = new Terminal(new ConsoleTerminalProvider()) } = options; this._tasks = new Map(); this._quietMode = quietMode; this._terminal = terminal; @@ -121,9 +114,12 @@ export class TaskCollection { ): void { for (const task of tasks) { if (dependencyChain.indexOf(task.name) >= 0) { - throw new Error('A cyclic dependency was encountered:\n' - + ' ' + [...dependencyChain, task.name].reverse().join('\n -> ') - + '\nConsider using the cyclicDependencyProjects option for rush.json.'); + throw new Error( + 'A cyclic dependency was encountered:\n' + + ' ' + + [...dependencyChain, task.name].reverse().join('\n -> ') + + '\nConsider using the cyclicDependencyProjects option for rush.json.' + ); } if (!alreadyCheckedProjects.has(task.name)) { @@ -152,7 +148,7 @@ export class TaskCollection { } else { // Otherwise we are as long as the longest package + 1 const depsLengths: number[] = []; - task.dependents.forEach(dep => depsLengths.push(this._calculateCriticalPaths(dep))); + task.dependents.forEach((dep) => depsLengths.push(this._calculateCriticalPaths(dep))); task.criticalPathLength = Math.max(...depsLengths) + 1; return task.criticalPathLength; } diff --git a/apps/rush-lib/src/logic/taskRunner/TaskRunner.ts b/apps/rush-lib/src/logic/taskRunner/TaskRunner.ts index 33a05b7f606..e5f73d8cb04 100644 --- a/apps/rush-lib/src/logic/taskRunner/TaskRunner.ts +++ b/apps/rush-lib/src/logic/taskRunner/TaskRunner.ts @@ -3,12 +3,7 @@ import * as os from 'os'; import { Interleaver } from '@rushstack/stream-collator'; -import { - Terminal, - ConsoleTerminalProvider, - Colors, - IColorableSequence -} from '@rushstack/node-core-library'; +import { Terminal, ConsoleTerminalProvider, Colors, IColorableSequence } from '@rushstack/node-core-library'; import { Stopwatch } from '../../utilities/Stopwatch'; import { ITask } from './ITask'; @@ -50,7 +45,7 @@ export class TaskRunner { parallelism, changedProjectsOnly, allowWarningsInSuccessfulBuild, - terminal = new Terminal(new ConsoleTerminalProvider()) + terminal = new Terminal(new ConsoleTerminalProvider()), } = options; this._tasks = orderedTasks; this._buildQueue = orderedTasks.slice(0); @@ -99,7 +94,9 @@ export class TaskRunner { this._currentActiveTasks = 0; this._completedTasks = 0; this._totalTasks = this._buildQueue.length; - this._terminal.writeLine(`Executing a maximum of ${this._parallelism} simultaneous processes...${os.EOL}`); + this._terminal.writeLine( + `Executing a maximum of ${this._parallelism} simultaneous processes...${os.EOL}` + ); return this._startAvailableTasks().then(() => { this._printTaskStatus(); @@ -153,42 +150,48 @@ export class TaskRunner { task.stopwatch = Stopwatch.start(); task.writer = Interleaver.registerTask(task.name, this._quietMode); - taskPromises.push(task.execute(task.writer) - .then((result: TaskStatus) => { - task.stopwatch.stop(); - task.writer.close(); - - this._currentActiveTasks--; - this._completedTasks++; - switch (result) { - case TaskStatus.Success: - this._markTaskAsSuccess(task); - break; - case TaskStatus.SuccessWithWarning: - this._hasAnyWarnings = true; - this._markTaskAsSuccessWithWarning(task); - break; - case TaskStatus.Skipped: - this._markTaskAsSkipped(task); - break; - case TaskStatus.Failure: - this._hasAnyFailures = true; - this._markTaskAsFailed(task); - break; - } - }).catch((error: TaskError) => { - task.writer.close(); - - this._currentActiveTasks--; - - this._hasAnyFailures = true; - task.error = error; - this._markTaskAsFailed(task); - } - ).then(() => this._startAvailableTasks())); + taskPromises.push( + task + .execute(task.writer) + .then((result: TaskStatus) => { + task.stopwatch.stop(); + task.writer.close(); + + this._currentActiveTasks--; + this._completedTasks++; + switch (result) { + case TaskStatus.Success: + this._markTaskAsSuccess(task); + break; + case TaskStatus.SuccessWithWarning: + this._hasAnyWarnings = true; + this._markTaskAsSuccessWithWarning(task); + break; + case TaskStatus.Skipped: + this._markTaskAsSkipped(task); + break; + case TaskStatus.Failure: + this._hasAnyFailures = true; + this._markTaskAsFailed(task); + break; + } + }) + .catch((error: TaskError) => { + task.writer.close(); + + this._currentActiveTasks--; + + this._hasAnyFailures = true; + task.error = error; + this._markTaskAsFailed(task); + }) + .then(() => this._startAvailableTasks()) + ); } - return Promise.all(taskPromises).then(() => { /* collapse void[] to void */ }); + return Promise.all(taskPromises).then(() => { + /* collapse void[] to void */ + }); } /** @@ -208,8 +211,9 @@ export class TaskRunner { private _markTaskAsBlocked(task: ITask, failedTask: ITask): void { if (task.status === TaskStatus.Ready) { this._completedTasks++; - this._terminal.writeErrorLine(`${this._getCurrentCompletedTaskString()}` - + `[${task.name}] blocked by [${failedTask.name}]!`); + this._terminal.writeErrorLine( + `${this._getCurrentCompletedTaskString()}` + `[${task.name}] blocked by [${failedTask.name}]!` + ); task.status = TaskStatus.Blocked; task.dependents.forEach((dependent: ITask) => { this._markTaskAsBlocked(dependent, failedTask); @@ -222,11 +226,16 @@ export class TaskRunner { */ private _markTaskAsSuccess(task: ITask): void { if (task.hadEmptyScript) { - this._terminal.writeLine(Colors.green(`${this._getCurrentCompletedTaskString()}` - + `[${task.name}] had an empty script`)); + this._terminal.writeLine( + Colors.green(`${this._getCurrentCompletedTaskString()}` + `[${task.name}] had an empty script`) + ); } else { - this._terminal.writeLine(Colors.green(`${this._getCurrentCompletedTaskString()}` - + `[${task.name}] completed successfully in ${task.stopwatch.toString()}`)); + this._terminal.writeLine( + Colors.green( + `${this._getCurrentCompletedTaskString()}` + + `[${task.name}] completed successfully in ${task.stopwatch.toString()}` + ) + ); } task.status = TaskStatus.Success; @@ -243,8 +252,10 @@ export class TaskRunner { * list of all its dependents */ private _markTaskAsSuccessWithWarning(task: ITask): void { - this._terminal.writeWarningLine(`${this._getCurrentCompletedTaskString()}` - + `[${task.name}] completed with warnings in ${task.stopwatch.toString()}`); + this._terminal.writeWarningLine( + `${this._getCurrentCompletedTaskString()}` + + `[${task.name}] completed with warnings in ${task.stopwatch.toString()}` + ); task.status = TaskStatus.SuccessWithWarning; task.dependents.forEach((dependent: ITask) => { if (!this._changedProjectsOnly) { @@ -366,7 +377,7 @@ export class TaskRunner { const headSize: number = 10; const tailSize: number = 20; const margin: number = 10; - const lines: string[] = text.split(/\s*\r?\n/).filter(line => line); + const lines: string[] = text.split(/\s*\r?\n/).filter((line) => line); if (lines.length < headSize + tailSize + margin) { return lines.join(os.EOL); } @@ -375,5 +386,4 @@ export class TaskRunner { const tail: string = lines.splice(-tailSize).join(os.EOL); return `${head}${os.EOL}[...${amountRemoved} lines omitted...]${os.EOL}${tail}`; } - } diff --git a/apps/rush-lib/src/logic/taskRunner/TaskStatus.ts b/apps/rush-lib/src/logic/taskRunner/TaskStatus.ts index cad3fc3a542..a5048544f37 100644 --- a/apps/rush-lib/src/logic/taskRunner/TaskStatus.ts +++ b/apps/rush-lib/src/logic/taskRunner/TaskStatus.ts @@ -11,5 +11,5 @@ export enum TaskStatus { SuccessWithWarning = 'SUCCESS WITH WARNINGS', Skipped = 'SKIPPED', Failure = 'FAILURE', - Blocked = 'BLOCKED' + Blocked = 'BLOCKED', } diff --git a/apps/rush-lib/src/logic/taskRunner/test/ProjectTask.test.ts b/apps/rush-lib/src/logic/taskRunner/test/ProjectTask.test.ts index 1beb483f039..5d8b2844210 100644 --- a/apps/rush-lib/src/logic/taskRunner/test/ProjectTask.test.ts +++ b/apps/rush-lib/src/logic/taskRunner/test/ProjectTask.test.ts @@ -5,8 +5,9 @@ import { convertSlashesForWindows } from '../ProjectTask'; describe('convertSlashesForWindows()', () => { it('converted inputs', () => { - expect(convertSlashesForWindows('./node_modules/.bin/tslint -c config/tslint.json')) - .toEqual('.\\node_modules\\.bin\\tslint -c config/tslint.json'); + expect(convertSlashesForWindows('./node_modules/.bin/tslint -c config/tslint.json')).toEqual( + '.\\node_modules\\.bin\\tslint -c config/tslint.json' + ); expect(convertSlashesForWindows('/blah/bleep&&/bloop')).toEqual('\\blah\\bleep&&/bloop'); expect(convertSlashesForWindows('/blah/bleep')).toEqual('\\blah\\bleep'); expect(convertSlashesForWindows('/blah/bleep --path a/b')).toEqual('\\blah\\bleep --path a/b'); diff --git a/apps/rush-lib/src/logic/taskRunner/test/TaskCollection.test.ts b/apps/rush-lib/src/logic/taskRunner/test/TaskCollection.test.ts index 378c0d9e015..e6828ad4902 100644 --- a/apps/rush-lib/src/logic/taskRunner/test/TaskCollection.test.ts +++ b/apps/rush-lib/src/logic/taskRunner/test/TaskCollection.test.ts @@ -14,7 +14,7 @@ function createDummyTask(name: string, action?: () => void): ITaskDefinition { } return Promise.resolve(TaskStatus.Success); }, - hadEmptyScript: false + hadEmptyScript: false, }; } @@ -36,19 +36,17 @@ describe('TaskCollection', () => { describe('Dependencies', () => { beforeEach(() => { taskCollection = new TaskCollection({ - quietMode: false + quietMode: false, }); }); it('throwsErrorOnNonExistentTask', () => { - expect(() => taskCollection.addDependencies('foo', [])) - .toThrowErrorMatchingSnapshot(); + expect(() => taskCollection.addDependencies('foo', [])).toThrowErrorMatchingSnapshot(); }); it('throwsErrorOnNonExistentDependency', () => { taskCollection.addTask(createDummyTask('foo')); - expect(() => taskCollection.addDependencies('foo', ['bar'])) - .toThrowErrorMatchingSnapshot(); + expect(() => taskCollection.addDependencies('foo', ['bar'])).toThrowErrorMatchingSnapshot(); }); it('detectsDependencyCycle', () => { @@ -74,7 +72,7 @@ describe('TaskCollection', () => { describe('Error logging', () => { beforeEach(() => { taskCollection = new TaskCollection({ - quietMode: false + quietMode: false, }); }); }); diff --git a/apps/rush-lib/src/logic/taskRunner/test/TaskRunner.test.ts b/apps/rush-lib/src/logic/taskRunner/test/TaskRunner.test.ts index 7a3508066a1..51abc662835 100644 --- a/apps/rush-lib/src/logic/taskRunner/test/TaskRunner.test.ts +++ b/apps/rush-lib/src/logic/taskRunner/test/TaskRunner.test.ts @@ -18,7 +18,10 @@ mockGetTimeInMs.mockImplementation(() => { return mockTimeInMs; }); -function createTaskRunner(taskRunnerOptions: ITaskRunnerOptions, taskDefinition: ITaskDefinition): TaskRunner { +function createTaskRunner( + taskRunnerOptions: ITaskRunnerOptions, + taskDefinition: ITaskDefinition +): TaskRunner { const task: ITask = taskDefinition as ITask; task.dependencies = new Set(); task.dependents = new Set(); @@ -47,13 +50,16 @@ describe('TaskRunner', () => { describe('Constructor', () => { it('throwsErrorOnInvalidParallelism', () => { - expect(() => new TaskRunner([], { - quietMode: false, - parallelism: 'tequila', - changedProjectsOnly: false, - terminal, - allowWarningsInSuccessfulBuild: false - })).toThrowErrorMatchingSnapshot(); + expect( + () => + new TaskRunner([], { + quietMode: false, + parallelism: 'tequila', + changedProjectsOnly: false, + terminal, + allowWarningsInSuccessfulBuild: false, + }) + ).toThrowErrorMatchingSnapshot(); }); }); @@ -64,7 +70,7 @@ describe('TaskRunner', () => { parallelism: '1', changedProjectsOnly: false, terminal, - allowWarningsInSuccessfulBuild: false + allowWarningsInSuccessfulBuild: false, }; }); @@ -79,13 +85,13 @@ describe('TaskRunner', () => { writer.writeError('Error: step 1 failed' + EOL); return Promise.resolve(TaskStatus.Failure); }, - hadEmptyScript: false + hadEmptyScript: false, }); return taskRunner .execute() .then(() => fail(EXPECTED_FAIL)) - .catch(err => { + .catch((err) => { expect(err.message).toMatchSnapshot(); const allMessages: string = terminalProvider.getOutput(); expect(allMessages).not.toContain('Build step 1'); @@ -103,13 +109,13 @@ describe('TaskRunner', () => { writer.write('Error: step 1 failed' + EOL); return Promise.resolve(TaskStatus.Failure); }, - hadEmptyScript: false + hadEmptyScript: false, }); return taskRunner .execute() .then(() => fail(EXPECTED_FAIL)) - .catch(err => { + .catch((err) => { expect(err.message).toMatchSnapshot(); expect(terminalProvider.getOutput()).toMatch(/Build step 1.*Error: step 1 failed/); checkConsoleOutput(terminalProvider); @@ -127,16 +133,17 @@ describe('TaskRunner', () => { } return Promise.resolve(TaskStatus.Failure); }, - hadEmptyScript: false + hadEmptyScript: false, }); return taskRunner .execute() .then(() => fail(EXPECTED_FAIL)) - .catch(err => { + .catch((err) => { expect(err.message).toMatchSnapshot(); - expect(terminalProvider.getOutput()) - .toMatch(/Building units.* - unit #1;.* - unit #3;.*lines omitted.* - unit #48;.* - unit #50;/); + expect(terminalProvider.getOutput()).toMatch( + /Building units.* - unit #1;.* - unit #3;.*lines omitted.* - unit #48;.* - unit #50;/ + ); checkConsoleOutput(terminalProvider); }); }); @@ -152,16 +159,17 @@ describe('TaskRunner', () => { } return Promise.resolve(TaskStatus.Failure); }, - hadEmptyScript: false + hadEmptyScript: false, }); return taskRunner .execute() .then(() => fail(EXPECTED_FAIL)) - .catch(err => { + .catch((err) => { expect(err.message).toMatchSnapshot(); - expect(terminalProvider.getOutput()) - .toMatch(/List of errors:\S.* - error #1;\S.*lines omitted.* - error #48;\S.* - error #50;\S/); + expect(terminalProvider.getOutput()).toMatch( + /List of errors:\S.* - error #1;\S.*lines omitted.* - error #48;\S.* - error #50;\S/ + ); checkConsoleOutput(terminalProvider); }); }); @@ -175,7 +183,7 @@ describe('TaskRunner', () => { parallelism: '1', changedProjectsOnly: false, terminal, - allowWarningsInSuccessfulBuild: false + allowWarningsInSuccessfulBuild: false, }; }); @@ -188,13 +196,13 @@ describe('TaskRunner', () => { writer.write('Warning: step 1 succeeded with warnings' + EOL); return Promise.resolve(TaskStatus.SuccessWithWarning); }, - hadEmptyScript: false + hadEmptyScript: false, }); return taskRunner .execute() .then(() => fail('Promise returned by execute() resolved but was expected to fail')) - .catch(err => { + .catch((err) => { expect(err.message).toMatchSnapshot(); const allMessages: string = terminalProvider.getOutput(); expect(allMessages).toContain('Build step 1'); @@ -211,7 +219,7 @@ describe('TaskRunner', () => { parallelism: '1', changedProjectsOnly: false, terminal, - allowWarningsInSuccessfulBuild: true + allowWarningsInSuccessfulBuild: true, }; }); @@ -224,7 +232,7 @@ describe('TaskRunner', () => { writer.write('Warning: step 1 succeeded with warnings' + EOL); return Promise.resolve(TaskStatus.SuccessWithWarning); }, - hadEmptyScript: false + hadEmptyScript: false, }); return taskRunner @@ -235,7 +243,7 @@ describe('TaskRunner', () => { expect(allMessages).toContain('Warning: step 1 succeeded with warnings'); checkConsoleOutput(terminalProvider); }) - .catch(err => fail('Promise returned by execute() rejected but was expected to resolve')); + .catch((err) => fail('Promise returned by execute() rejected but was expected to resolve')); }); }); }); diff --git a/apps/rush-lib/src/logic/test/ChangeFiles.test.ts b/apps/rush-lib/src/logic/test/ChangeFiles.test.ts index 3ad2cb56d9c..f701ded27f0 100644 --- a/apps/rush-lib/src/logic/test/ChangeFiles.test.ts +++ b/apps/rush-lib/src/logic/test/ChangeFiles.test.ts @@ -48,7 +48,9 @@ describe('ChangeFiles', () => { const changeFile: string = path.join(__dirname, 'leafChange', 'change1.json'); const changedPackages: string[] = ['d']; expect(() => { - ChangeFiles.validate([changeFile], changedPackages, { hotfixChangeEnabled: true } as RushConfiguration); + ChangeFiles.validate([changeFile], changedPackages, { + hotfixChangeEnabled: true, + } as RushConfiguration); }).toThrow(Error); }); @@ -107,12 +109,12 @@ describe('ChangeFiles', () => { const updatedChangelogs: IChangelog[] = [ { name: 'a', - entries: [] + entries: [], }, { name: 'b', - entries: [] - } + entries: [], + }, ]; expect(changeFiles.deleteAll(false, updatedChangelogs)).toEqual(2); }); diff --git a/apps/rush-lib/src/logic/test/ChangeManager.test.ts b/apps/rush-lib/src/logic/test/ChangeManager.test.ts index 4ee6695b2aa..77e9467fb86 100644 --- a/apps/rush-lib/src/logic/test/ChangeManager.test.ts +++ b/apps/rush-lib/src/logic/test/ChangeManager.test.ts @@ -24,11 +24,9 @@ describe('ChangeManager', () => { expect(changeManager.allPackages.get('a')!.packageJson.version).toEqual('2.0.0'); expect(changeManager.allPackages.get('b')!.packageJson.version).toEqual('1.0.1'); - expect(changeManager.allPackages.get('b')!.packageJson.dependencies!['a']).toEqual( - '>=2.0.0 <3.0.0'); + expect(changeManager.allPackages.get('b')!.packageJson.dependencies!['a']).toEqual('>=2.0.0 <3.0.0'); expect(changeManager.allPackages.get('c')!.packageJson.version).toEqual('1.0.0'); - expect(changeManager.allPackages.get('c')!.packageJson.dependencies!['b']).toEqual( - '>=1.0.1 <2.0.0'); + expect(changeManager.allPackages.get('c')!.packageJson.dependencies!['b']).toEqual('>=1.0.1 <2.0.0'); }); it('can update explicit version dependency', () => { @@ -37,24 +35,25 @@ describe('ChangeManager', () => { expect(changeManager.allPackages.get('c')!.packageJson.version).toEqual('1.0.1'); expect(changeManager.allPackages.get('d')!.packageJson.version).toEqual('1.0.1'); - expect(changeManager.allPackages.get('d')!.packageJson.dependencies!['c']).toEqual( - '1.0.1'); + expect(changeManager.allPackages.get('d')!.packageJson.dependencies!['c']).toEqual('1.0.1'); }); it('can update explicit cyclic dependency', () => { changeManager.load(path.join(__dirname, 'cyclicDepsExplicit')); changeManager.apply(false); - expect(changeManager.allPackages.get('cyclic-dep-explicit-1')!.packageJson.version).toEqual( - '2.0.0'); - expect(changeManager.allPackages.get('cyclic-dep-explicit-1')!.packageJson.dependencies!['cyclic-dep-explicit-2']) - .toEqual( - '>=1.0.0 <2.0.0'); - expect(changeManager.allPackages.get('cyclic-dep-explicit-2')!.packageJson.version).toEqual( - '1.0.0'); - expect(changeManager.allPackages.get('cyclic-dep-explicit-2')!.packageJson.dependencies!['cyclic-dep-explicit-1']) - .toEqual( - '>=1.0.0 <2.0.0'); + expect(changeManager.allPackages.get('cyclic-dep-explicit-1')!.packageJson.version).toEqual('2.0.0'); + expect( + changeManager.allPackages.get('cyclic-dep-explicit-1')!.packageJson.dependencies![ + 'cyclic-dep-explicit-2' + ] + ).toEqual('>=1.0.0 <2.0.0'); + expect(changeManager.allPackages.get('cyclic-dep-explicit-2')!.packageJson.version).toEqual('1.0.0'); + expect( + changeManager.allPackages.get('cyclic-dep-explicit-2')!.packageJson.dependencies![ + 'cyclic-dep-explicit-1' + ] + ).toEqual('>=1.0.0 <2.0.0'); }); it('can update root with patch change for prerelease', () => { @@ -64,16 +63,16 @@ describe('ChangeManager', () => { changeManager.load(path.join(__dirname, 'rootPatchChange'), prereleaseToken); changeManager.apply(false); - expect(changeManager.allPackages.get('a')!.packageJson.version).toEqual( - '1.0.1-' + prereleaseName); - expect(changeManager.allPackages.get('b')!.packageJson.version).toEqual( - '1.0.1-' + prereleaseName); + expect(changeManager.allPackages.get('a')!.packageJson.version).toEqual('1.0.1-' + prereleaseName); + expect(changeManager.allPackages.get('b')!.packageJson.version).toEqual('1.0.1-' + prereleaseName); expect(changeManager.allPackages.get('b')!.packageJson.dependencies!['a']).toEqual( - '1.0.1-' + prereleaseName); + '1.0.1-' + prereleaseName + ); expect(changeManager.allPackages.get('c')!.packageJson.version).toEqual('1.0.1-' + prereleaseName); expect(changeManager.allPackages.get('d')!.packageJson.version).toEqual('1.0.1-' + prereleaseName); expect(changeManager.allPackages.get('d')!.packageJson.dependencies!['c']).toEqual( - '1.0.1-' + prereleaseName); + '1.0.1-' + prereleaseName + ); }); it('can update non-root with patch change for prerelease', () => { @@ -83,16 +82,14 @@ describe('ChangeManager', () => { changeManager.load(path.join(__dirname, 'explicitVersionChange'), prereleaseToken); changeManager.apply(false); - expect(changeManager.allPackages.get('a')!.packageJson.version).toEqual( - '1.0.0'); - expect(changeManager.allPackages.get('b')!.packageJson.version).toEqual( - '1.0.0'); - expect(changeManager.allPackages.get('b')!.packageJson.dependencies!['a']).toEqual( - '>=1.0.0 <2.0.0'); + expect(changeManager.allPackages.get('a')!.packageJson.version).toEqual('1.0.0'); + expect(changeManager.allPackages.get('b')!.packageJson.version).toEqual('1.0.0'); + expect(changeManager.allPackages.get('b')!.packageJson.dependencies!['a']).toEqual('>=1.0.0 <2.0.0'); expect(changeManager.allPackages.get('c')!.packageJson.version).toEqual('1.0.1-' + prereleaseName); expect(changeManager.allPackages.get('d')!.packageJson.version).toEqual('1.0.1-' + prereleaseName); expect(changeManager.allPackages.get('d')!.packageJson.dependencies!['c']).toEqual( - '1.0.1-' + prereleaseName); + '1.0.1-' + prereleaseName + ); }); it('can update cyclic dependency for non-explicit prerelease', () => { @@ -103,13 +100,17 @@ describe('ChangeManager', () => { changeManager.apply(false); expect(changeManager.allPackages.get('cyclic-dep-1')!.packageJson.version).toEqual( - '2.0.0-' + prereleaseName); + '2.0.0-' + prereleaseName + ); expect(changeManager.allPackages.get('cyclic-dep-1')!.packageJson.dependencies!['cyclic-dep-2']).toEqual( - '1.0.1-' + prereleaseName); + '1.0.1-' + prereleaseName + ); expect(changeManager.allPackages.get('cyclic-dep-2')!.packageJson.version).toEqual( - '1.0.1-' + prereleaseName); + '1.0.1-' + prereleaseName + ); expect(changeManager.allPackages.get('cyclic-dep-2')!.packageJson.dependencies!['cyclic-dep-1']).toEqual( - '2.0.0-' + prereleaseName); + '2.0.0-' + prereleaseName + ); }); it('can update root with patch change for adding version suffix', () => { @@ -119,16 +120,12 @@ describe('ChangeManager', () => { changeManager.load(path.join(__dirname, 'rootPatchChange'), prereleaseToken); changeManager.apply(false); - expect(changeManager.allPackages.get('a')!.packageJson.version).toEqual( - '1.0.0-' + suffix); - expect(changeManager.allPackages.get('b')!.packageJson.version).toEqual( - '1.0.0-' + suffix); - expect(changeManager.allPackages.get('b')!.packageJson.dependencies!['a']).toEqual( - '1.0.0-' + suffix); + expect(changeManager.allPackages.get('a')!.packageJson.version).toEqual('1.0.0-' + suffix); + expect(changeManager.allPackages.get('b')!.packageJson.version).toEqual('1.0.0-' + suffix); + expect(changeManager.allPackages.get('b')!.packageJson.dependencies!['a']).toEqual('1.0.0-' + suffix); expect(changeManager.allPackages.get('c')!.packageJson.version).toEqual('1.0.0-' + suffix); expect(changeManager.allPackages.get('d')!.packageJson.version).toEqual('1.0.0-' + suffix); - expect(changeManager.allPackages.get('d')!.packageJson.dependencies!['c']).toEqual( - '1.0.0-' + suffix); + expect(changeManager.allPackages.get('d')!.packageJson.dependencies!['c']).toEqual('1.0.0-' + suffix); }); it('can update non-root with patch change for version suffix', () => { @@ -138,16 +135,12 @@ describe('ChangeManager', () => { changeManager.load(path.join(__dirname, 'explicitVersionChange'), prereleaseToken); changeManager.apply(false); - expect(changeManager.allPackages.get('a')!.packageJson.version).toEqual( - '1.0.0'); - expect(changeManager.allPackages.get('b')!.packageJson.version).toEqual( - '1.0.0'); - expect(changeManager.allPackages.get('b')!.packageJson.dependencies!['a']).toEqual( - '>=1.0.0 <2.0.0'); + expect(changeManager.allPackages.get('a')!.packageJson.version).toEqual('1.0.0'); + expect(changeManager.allPackages.get('b')!.packageJson.version).toEqual('1.0.0'); + expect(changeManager.allPackages.get('b')!.packageJson.dependencies!['a']).toEqual('>=1.0.0 <2.0.0'); expect(changeManager.allPackages.get('c')!.packageJson.version).toEqual('1.0.0-' + suffix); expect(changeManager.allPackages.get('d')!.packageJson.version).toEqual('1.0.0-' + suffix); - expect(changeManager.allPackages.get('d')!.packageJson.dependencies!['c']).toEqual( - '1.0.0-' + suffix); + expect(changeManager.allPackages.get('d')!.packageJson.dependencies!['c']).toEqual('1.0.0-' + suffix); }); it('can update cyclic dependency for non-explicit suffix', () => { @@ -157,14 +150,14 @@ describe('ChangeManager', () => { changeManager.load(path.join(__dirname, 'cyclicDeps'), prereleaseToken); changeManager.apply(false); - expect(changeManager.allPackages.get('cyclic-dep-1')!.packageJson.version).toEqual( - '1.0.0-' + suffix); + expect(changeManager.allPackages.get('cyclic-dep-1')!.packageJson.version).toEqual('1.0.0-' + suffix); expect(changeManager.allPackages.get('cyclic-dep-1')!.packageJson.dependencies!['cyclic-dep-2']).toEqual( - '1.0.0-' + suffix); - expect(changeManager.allPackages.get('cyclic-dep-2')!.packageJson.version).toEqual( - '1.0.0-' + suffix); + '1.0.0-' + suffix + ); + expect(changeManager.allPackages.get('cyclic-dep-2')!.packageJson.version).toEqual('1.0.0-' + suffix); expect(changeManager.allPackages.get('cyclic-dep-2')!.packageJson.dependencies!['cyclic-dep-1']).toEqual( - '1.0.0-' + suffix); + '1.0.0-' + suffix + ); }); /* eslint-enable dot-notation */ }); diff --git a/apps/rush-lib/src/logic/test/ChangelogGenerator.test.ts b/apps/rush-lib/src/logic/test/ChangelogGenerator.test.ts index 28a69c8555b..8485b8a659d 100644 --- a/apps/rush-lib/src/logic/test/ChangelogGenerator.test.ts +++ b/apps/rush-lib/src/logic/test/ChangelogGenerator.test.ts @@ -24,12 +24,14 @@ describe('updateIndividualChangelog', () => { packageName: 'a', newVersion: '1.0.0', changeType: ChangeType.major, - changes: [{ - packageName: 'a', - type: 'major', - changeType: ChangeType.major, - comment: 'Patching a' - }] + changes: [ + { + packageName: 'a', + type: 'major', + changeType: ChangeType.major, + comment: 'Patching a', + }, + ], }, 'rootMajorChange', false, @@ -48,12 +50,12 @@ describe('updateIndividualChangelog', () => { { author: undefined, comment: 'Patching a', - commit: undefined - } - ] - } - } - ] + commit: undefined, + }, + ], + }, + }, + ], }; // Ignore comparing date. @@ -68,12 +70,14 @@ describe('updateIndividualChangelog', () => { packageName: 'a', newVersion: '1.0.0', changeType: ChangeType.major, - changes: [{ - packageName: 'a', - type: 'major', - changeType: ChangeType.major, - comment: 'Patching a' - }] + changes: [ + { + packageName: 'a', + type: 'major', + changeType: ChangeType.major, + comment: 'Patching a', + }, + ], }, path.resolve(__dirname, 'exampleChangelog'), false, @@ -92,10 +96,10 @@ describe('updateIndividualChangelog', () => { { author: undefined, comment: 'Patching a', - commit: undefined - } - ] - } + commit: undefined, + }, + ], + }, }, { version: '0.0.1', @@ -104,12 +108,12 @@ describe('updateIndividualChangelog', () => { comments: { patch: [ { - comment: 'Patching a' - } - ] - } - } - ] + comment: 'Patching a', + }, + ], + }, + }, + ], }; // Ignore comparing date. @@ -124,12 +128,14 @@ describe('updateIndividualChangelog', () => { packageName: 'a', newVersion: '0.0.1', changeType: ChangeType.patch, - changes: [{ - packageName: 'a', - type: 'patch', - changeType: ChangeType.patch, - comment: 'Patching a' - }] + changes: [ + { + packageName: 'a', + type: 'patch', + changeType: ChangeType.patch, + comment: 'Patching a', + }, + ], }, path.resolve(__dirname, 'exampleChangelog'), false, @@ -145,12 +151,14 @@ describe('updateIndividualChangelog', () => { packageName: 'a', newVersion: '0.0.2', changeType: ChangeType.dependency, - changes: [{ - packageName: 'a', - type: 'dependency', - changeType: ChangeType.dependency, - comment: 'Updating a' - }] + changes: [ + { + packageName: 'a', + type: 'dependency', + changeType: ChangeType.dependency, + comment: 'Updating a', + }, + ], }, path.resolve(__dirname, 'exampleChangelog'), false, @@ -169,10 +177,10 @@ describe('updateIndividualChangelog', () => { { author: undefined, comment: 'Updating a', - commit: undefined - } - ] - } + commit: undefined, + }, + ], + }, }, { version: '0.0.1', @@ -181,12 +189,12 @@ describe('updateIndividualChangelog', () => { comments: { patch: [ { - comment: 'Patching a' - } - ] - } - } - ] + comment: 'Patching a', + }, + ], + }, + }, + ], }; // Remove date. @@ -201,12 +209,14 @@ describe('updateIndividualChangelog', () => { packageName: 'a', newVersion: '0.0.2', changeType: ChangeType.none, - changes: [{ - packageName: 'a', - type: 'none', - changeType: ChangeType.none, - comment: '' - }] + changes: [ + { + packageName: 'a', + type: 'none', + changeType: ChangeType.none, + comment: '', + }, + ], }, path.resolve(__dirname, 'exampleChangelog'), false, @@ -220,7 +230,7 @@ describe('updateIndividualChangelog', () => { version: '0.0.2', tag: 'a_v0.0.2', date: undefined, - comments: {} + comments: {}, }, { version: '0.0.1', @@ -229,12 +239,12 @@ describe('updateIndividualChangelog', () => { comments: { patch: [ { - comment: 'Patching a' - } - ] - } - } - ] + comment: 'Patching a', + }, + ], + }, + }, + ], }; // Remove date. @@ -260,14 +270,14 @@ describe('updateChangelogs', () => { packageName: 'a', changeType: ChangeType.dependency, newVersion: '1.0.0', - changes: [] + changes: [], }; // Package b has version change. changeHash['b'] = { packageName: 'b', changeType: ChangeType.patch, newVersion: '1.0.1', - changes: [] + changes: [], }; const updatedChangeLogs: IChangelog[] = ChangelogGenerator.updateChangelogs( changeHash, @@ -286,14 +296,14 @@ describe('updateChangelogs', () => { packageName: 'a', changeType: ChangeType.dependency, newVersion: '1.0.1-pre.1', - changes: [] + changes: [], }; // Package b is not a prerelease changeHash['b'] = { packageName: 'b', changeType: ChangeType.patch, newVersion: '1.0.1', - changes: [] + changes: [], }; // Makes package 'a' prerelease package. const rushProjectA: RushConfigurationProject = rushConfiguration.projectsByName.get('a')!; @@ -316,14 +326,14 @@ describe('updateChangelogs', () => { packageName: 'a', changeType: ChangeType.hotfix, newVersion: '1.0.1-hotfix.1', - changes: [] + changes: [], }; // Package b is not a hotfix changeHash['b'] = { packageName: 'b', changeType: ChangeType.patch, newVersion: '1.0.1', - changes: [] + changes: [], }; // Makes package 'a' hotfix package. const rushProjectA: RushConfigurationProject = rushConfiguration.projectsByName.get('a')!; diff --git a/apps/rush-lib/src/logic/test/PackageChangeAnalyzer.test.ts b/apps/rush-lib/src/logic/test/PackageChangeAnalyzer.test.ts index e76cd297c0b..f54e846d183 100644 --- a/apps/rush-lib/src/logic/test/PackageChangeAnalyzer.test.ts +++ b/apps/rush-lib/src/logic/test/PackageChangeAnalyzer.test.ts @@ -6,9 +6,7 @@ import * as path from 'path'; import { PackageChangeAnalyzer } from '../PackageChangeAnalyzer'; import { RushConfiguration } from '../../api/RushConfiguration'; -import { - IPackageDeps -} from '@rushstack/package-deps-hash'; +import { IPackageDeps } from '@rushstack/package-deps-hash'; const packageA: string = 'project-a'; const packageAPath: string = path.join('tools', packageA); @@ -25,21 +23,23 @@ describe('PackageChangeAnalyzer', () => { const repoHashDeps: IPackageDeps = { files: { [fileA]: HASH, - [path.posix.join('common', 'config', 'rush', 'pnpm-lock.yaml')]: HASH - } + [path.posix.join('common', 'config', 'rush', 'pnpm-lock.yaml')]: HASH, + }, }; PackageChangeAnalyzer.getPackageDeps = (packagePath: string, ignored: string[]) => repoHashDeps; const rushConfiguration: RushConfiguration = { commonRushConfigFolder: '', - projects: [{ - packageName: packageA, - projectRelativeFolder: packageAPath - }], + projects: [ + { + packageName: packageA, + projectRelativeFolder: packageAPath, + }, + ], rushJsonFolder: '', getCommittedShrinkwrapFilename(): string { return 'common/config/rush/pnpm-lock.yaml'; - } + }, } as any; // eslint-disable-line @typescript-eslint/no-explicit-any const packageChangeAnalyzer: PackageChangeAnalyzer = new PackageChangeAnalyzer(rushConfiguration); diff --git a/apps/rush-lib/src/logic/test/PublishUtilities.test.ts b/apps/rush-lib/src/logic/test/PublishUtilities.test.ts index e4160ea5587..95426102c9b 100644 --- a/apps/rush-lib/src/logic/test/PublishUtilities.test.ts +++ b/apps/rush-lib/src/logic/test/PublishUtilities.test.ts @@ -3,16 +3,10 @@ import * as path from 'path'; -import { - IChangeInfo, - ChangeType -} from '../../api/ChangeManagement'; +import { IChangeInfo, ChangeType } from '../../api/ChangeManagement'; import { RushConfiguration } from '../../api/RushConfiguration'; import { RushConfigurationProject } from '../../api/RushConfigurationProject'; -import { - PublishUtilities, - IChangeInfoHash -} from '../PublishUtilities'; +import { PublishUtilities, IChangeInfoHash } from '../PublishUtilities'; import { ChangeFiles } from '../ChangeFiles'; /* eslint-disable dot-notation */ @@ -139,12 +133,14 @@ describe('findChangeRequests', () => { it('returns error when mixing hotfix and non-hotfix changes', () => { const allPackages: Map = packagesRushConfiguration.projectsByName; - expect(PublishUtilities.findChangeRequests.bind( - PublishUtilities, - allPackages, - packagesRushConfiguration, - new ChangeFiles(path.join(__dirname, 'hotfixWithPatchChanges')))) - .toThrow('Cannot apply hotfix alongside patch change on same package'); + expect( + PublishUtilities.findChangeRequests.bind( + PublishUtilities, + allPackages, + packagesRushConfiguration, + new ChangeFiles(path.join(__dirname, 'hotfixWithPatchChanges')) + ) + ).toThrow('Cannot apply hotfix alongside patch change on same package'); }); it('returns error when adding hotfix with config disabled', () => { @@ -152,12 +148,14 @@ describe('findChangeRequests', () => { // Overload hotfixChangeEnabled function packagesRushConfiguration['_hotfixChangeEnabled'] = false; - expect(PublishUtilities.findChangeRequests.bind( - PublishUtilities, - allPackages, - packagesRushConfiguration, - new ChangeFiles(path.join(__dirname, 'rootHotfixChange')))) - .toThrow('Cannot add hotfix change; hotfixChangeEnabled is false in configuration.'); + expect( + PublishUtilities.findChangeRequests.bind( + PublishUtilities, + allPackages, + packagesRushConfiguration, + new ChangeFiles(path.join(__dirname, 'rootHotfixChange')) + ) + ).toThrow('Cannot add hotfix change; hotfixChangeEnabled is false in configuration.'); }); it('can resolve multiple changes requests on the same package', () => { @@ -185,7 +183,8 @@ describe('findChangeRequests', () => { const allChanges: IChangeInfoHash = PublishUtilities.findChangeRequests( allPackages, packagesRushConfiguration, - new ChangeFiles(path.join(__dirname, 'orderedChanges'))); + new ChangeFiles(path.join(__dirname, 'orderedChanges')) + ); expect(Object.keys(allChanges)).toHaveLength(3); expect(allChanges).toHaveProperty('a'); @@ -204,7 +203,8 @@ describe('findChangeRequests', () => { const allChanges: IChangeInfoHash = PublishUtilities.findChangeRequests( allPackages, packagesRushConfiguration, - new ChangeFiles(path.join(__dirname, 'multipleHotfixChanges'))); + new ChangeFiles(path.join(__dirname, 'multipleHotfixChanges')) + ); expect(Object.keys(allChanges)).toHaveLength(4); expect(allChanges).toHaveProperty('a'); @@ -228,7 +228,8 @@ describe('findChangeRequests', () => { const allChanges: IChangeInfoHash = PublishUtilities.findChangeRequests( allPackages, packagesRushConfiguration, - new ChangeFiles(path.join(__dirname, 'explicitVersionChange'))); + new ChangeFiles(path.join(__dirname, 'explicitVersionChange')) + ); expect(Object.keys(allChanges)).toHaveLength(2); expect(allChanges).toHaveProperty('c'); @@ -245,7 +246,8 @@ describe('findChangeRequests', () => { new ChangeFiles(path.join(__dirname, 'repo', 'changes')), false, undefined, - new Set(['a', 'b', 'e'])); + new Set(['a', 'b', 'e']) + ); expect(Object.keys(allChanges)).toHaveLength(5); expect(allChanges['a'].newVersion).toEqual('1.0.0'); expect(allChanges['b'].newVersion).toEqual('2.0.0'); @@ -261,7 +263,9 @@ describe('sortChangeRequests', () => { let rushConfiguration: RushConfiguration; beforeEach(() => { - rushConfiguration = RushConfiguration.loadFromConfigurationFile(path.resolve(__dirname, 'packages', 'rush.json')); + rushConfiguration = RushConfiguration.loadFromConfigurationFile( + path.resolve(__dirname, 'packages', 'rush.json') + ); }); it('can return a sorted array of the change requests to be published in the correct order', () => { @@ -269,7 +273,8 @@ describe('sortChangeRequests', () => { const allChanges: IChangeInfoHash = PublishUtilities.findChangeRequests( allPackages, rushConfiguration, - new ChangeFiles(path.join(__dirname, 'multipleChanges'))); + new ChangeFiles(path.join(__dirname, 'multipleChanges')) + ); const orderedChanges: IChangeInfo[] = PublishUtilities.sortChangeRequests(allChanges); expect(orderedChanges).toHaveLength(3); @@ -291,44 +296,43 @@ describe('isRangeDependency', () => { describe('getNewDependencyVersion', () => { it('can update dependency versions', () => { - const dependencies: { [key: string]: string} = { - 'a': '~1.0.0', - 'b': '^1.0.0', - 'c': '>=1.0.0 <2.0.0' + const dependencies: { [key: string]: string } = { + a: '~1.0.0', + b: '^1.0.0', + c: '>=1.0.0 <2.0.0', }; - expect(PublishUtilities.getNewDependencyVersion(dependencies, - 'a', '1.1.0')).toEqual('~1.1.0'); - expect(PublishUtilities.getNewDependencyVersion(dependencies, - 'b', '1.2.0')).toEqual('^1.2.0'); - expect(PublishUtilities.getNewDependencyVersion(dependencies, - 'c', '1.3.0')).toEqual('>=1.3.0 <2.0.0'); + expect(PublishUtilities.getNewDependencyVersion(dependencies, 'a', '1.1.0')).toEqual('~1.1.0'); + expect(PublishUtilities.getNewDependencyVersion(dependencies, 'b', '1.2.0')).toEqual('^1.2.0'); + expect(PublishUtilities.getNewDependencyVersion(dependencies, 'c', '1.3.0')).toEqual('>=1.3.0 <2.0.0'); }); it('can update dependency versions with prereleases', () => { - const dependencies: { [key: string]: string} = { - 'a': '~1.0.0-pr.1', - 'b': '^1.0.0-pr.1', - 'c': '>=1.0.0-pr.1 <2.0.0' + const dependencies: { [key: string]: string } = { + a: '~1.0.0-pr.1', + b: '^1.0.0-pr.1', + c: '>=1.0.0-pr.1 <2.0.0', }; - expect(PublishUtilities.getNewDependencyVersion(dependencies, - 'a', '1.1.0-pr.1')).toEqual('~1.1.0-pr.1'); - expect(PublishUtilities.getNewDependencyVersion(dependencies, - 'b', '1.2.0-pr.2')).toEqual('^1.2.0-pr.2'); - expect(PublishUtilities.getNewDependencyVersion(dependencies, - 'c', '1.3.0-pr.3')).toEqual('>=1.3.0-pr.3 <2.0.0'); + expect(PublishUtilities.getNewDependencyVersion(dependencies, 'a', '1.1.0-pr.1')).toEqual('~1.1.0-pr.1'); + expect(PublishUtilities.getNewDependencyVersion(dependencies, 'b', '1.2.0-pr.2')).toEqual('^1.2.0-pr.2'); + expect(PublishUtilities.getNewDependencyVersion(dependencies, 'c', '1.3.0-pr.3')).toEqual( + '>=1.3.0-pr.3 <2.0.0' + ); }); it('can update to prerelease', () => { - const dependencies: { [key: string]: string} = { - 'a': '~1.0.0', - 'b': '^1.0.0', - 'c': '>=1.0.0 <2.0.0' + const dependencies: { [key: string]: string } = { + a: '~1.0.0', + b: '^1.0.0', + c: '>=1.0.0 <2.0.0', }; - expect(PublishUtilities.getNewDependencyVersion(dependencies, - 'a', '1.0.0-hotfix.0')).toEqual('~1.0.0-hotfix.0'); - expect(PublishUtilities.getNewDependencyVersion(dependencies, - 'b', '1.0.0-hotfix.0')).toEqual('^1.0.0-hotfix.0'); - expect(PublishUtilities.getNewDependencyVersion(dependencies, - 'c', '1.0.0-hotfix.0')).toEqual('>=1.0.0-hotfix.0 <2.0.0'); + expect(PublishUtilities.getNewDependencyVersion(dependencies, 'a', '1.0.0-hotfix.0')).toEqual( + '~1.0.0-hotfix.0' + ); + expect(PublishUtilities.getNewDependencyVersion(dependencies, 'b', '1.0.0-hotfix.0')).toEqual( + '^1.0.0-hotfix.0' + ); + expect(PublishUtilities.getNewDependencyVersion(dependencies, 'c', '1.0.0-hotfix.0')).toEqual( + '>=1.0.0-hotfix.0 <2.0.0' + ); }); -}); \ No newline at end of file +}); diff --git a/apps/rush-lib/src/logic/test/ShrinkwrapFile.test.ts b/apps/rush-lib/src/logic/test/ShrinkwrapFile.test.ts index 82587b0cc48..7a4d27e0a38 100644 --- a/apps/rush-lib/src/logic/test/ShrinkwrapFile.test.ts +++ b/apps/rush-lib/src/logic/test/ShrinkwrapFile.test.ts @@ -13,46 +13,72 @@ describe('npm ShrinkwrapFile', () => { const shrinkwrapFile: BaseShrinkwrapFile = ShrinkwrapFileFactory.getShrinkwrapFile('npm', {}, filename)!; it('verifies root-level dependency', () => { - expect(shrinkwrapFile.hasCompatibleTopLevelDependency(new DependencySpecifier('q', '~1.5.0'))).toEqual(true); + expect(shrinkwrapFile.hasCompatibleTopLevelDependency(new DependencySpecifier('q', '~1.5.0'))).toEqual( + true + ); }); it('verifies temp project dependencies', () => { // Found locally - expect(shrinkwrapFile.tryEnsureCompatibleDependency(new DependencySpecifier('jquery', '>=2.2.4 <3.0.0'), - '@rush-temp/project2')) - .toEqual(true); + expect( + shrinkwrapFile.tryEnsureCompatibleDependency( + new DependencySpecifier('jquery', '>=2.2.4 <3.0.0'), + '@rush-temp/project2' + ) + ).toEqual(true); // Found at root - expect(shrinkwrapFile.tryEnsureCompatibleDependency(new DependencySpecifier('q', '~1.5.0'), '@rush-temp/project2')) - .toEqual(true); + expect( + shrinkwrapFile.tryEnsureCompatibleDependency( + new DependencySpecifier('q', '~1.5.0'), + '@rush-temp/project2' + ) + ).toEqual(true); }); it('extracts temp projects successfully', () => { const tempProjectNames: ReadonlyArray = shrinkwrapFile.getTempProjectNames(); - expect(tempProjectNames).toEqual(['@rush-temp/project1', '@rush-temp/project2' ]); + expect(tempProjectNames).toEqual(['@rush-temp/project1', '@rush-temp/project2']); }); }); describe('pnpm ShrinkwrapFile', () => { -const filename: string = path.resolve(path.join( - __dirname, '../../../src/logic/test/shrinkwrapFile/pnpm-lock.yaml')); -const shrinkwrapFile: BaseShrinkwrapFile = ShrinkwrapFileFactory.getShrinkwrapFile('pnpm', {}, filename)!; + const filename: string = path.resolve( + path.join(__dirname, '../../../src/logic/test/shrinkwrapFile/pnpm-lock.yaml') + ); + const shrinkwrapFile: BaseShrinkwrapFile = ShrinkwrapFileFactory.getShrinkwrapFile('pnpm', {}, filename)!; it('verifies root-level dependency', () => { - expect(shrinkwrapFile.hasCompatibleTopLevelDependency(new DependencySpecifier('q', '~1.5.0'))).toEqual(false); + expect(shrinkwrapFile.hasCompatibleTopLevelDependency(new DependencySpecifier('q', '~1.5.0'))).toEqual( + false + ); }); it('verifies temp project dependencies', () => { - expect(shrinkwrapFile.tryEnsureCompatibleDependency(new DependencySpecifier('jquery', '>=2.0.0 <3.0.0'), - '@rush-temp/project1')) - .toEqual(true); - expect(shrinkwrapFile.tryEnsureCompatibleDependency( - new DependencySpecifier('q', '~1.5.0'), '@rush-temp/project2')).toEqual(true); - expect(shrinkwrapFile.tryEnsureCompatibleDependency( - new DependencySpecifier('left-pad', '~9.9.9'), '@rush-temp/project1')).toEqual(false); - expect(shrinkwrapFile.tryEnsureCompatibleDependency( - new DependencySpecifier('@scope/testDep', '>=1.0.0 <2.0.0'), '@rush-temp/project3')) - .toEqual(true); + expect( + shrinkwrapFile.tryEnsureCompatibleDependency( + new DependencySpecifier('jquery', '>=2.0.0 <3.0.0'), + '@rush-temp/project1' + ) + ).toEqual(true); + expect( + shrinkwrapFile.tryEnsureCompatibleDependency( + new DependencySpecifier('q', '~1.5.0'), + '@rush-temp/project2' + ) + ).toEqual(true); + expect( + shrinkwrapFile.tryEnsureCompatibleDependency( + new DependencySpecifier('left-pad', '~9.9.9'), + '@rush-temp/project1' + ) + ).toEqual(false); + expect( + shrinkwrapFile.tryEnsureCompatibleDependency( + new DependencySpecifier('@scope/testDep', '>=1.0.0 <2.0.0'), + '@rush-temp/project3' + ) + ).toEqual(true); }); it('extracts temp projects successfully', () => { @@ -62,9 +88,12 @@ const shrinkwrapFile: BaseShrinkwrapFile = ShrinkwrapFileFactory.getShrinkwrapFi }); it('can reuse the latest version that another temp package is providing', () => { - expect(shrinkwrapFile.tryEnsureCompatibleDependency(new DependencySpecifier('jquery', '>=2.0.0 <3.0.0'), - '@rush-temp/project3')) - .toEqual(true); + expect( + shrinkwrapFile.tryEnsureCompatibleDependency( + new DependencySpecifier('jquery', '>=2.0.0 <3.0.0'), + '@rush-temp/project3' + ) + ).toEqual(true); }); }); @@ -78,48 +107,56 @@ function testParsePnpmDependencyKey(packageName: string, key: string): string | describe('extractVersionFromPnpmVersionSpecifier', () => { it('extracts a simple version with no slashes', () => { - expect(testParsePnpmDependencyKey('anonymous', '0.0.5')) - .toEqual('0.0.5'); + expect(testParsePnpmDependencyKey('anonymous', '0.0.5')).toEqual('0.0.5'); }); it('extracts a simple package name', () => { - expect(testParsePnpmDependencyKey('isarray', '/isarray/2.0.5')) - .toEqual('2.0.5'); - expect(testParsePnpmDependencyKey('@scope/test-dep', '/@scope/test-dep/1.2.3-beta.3')) - .toEqual('1.2.3-beta.3'); + expect(testParsePnpmDependencyKey('isarray', '/isarray/2.0.5')).toEqual('2.0.5'); + expect(testParsePnpmDependencyKey('@scope/test-dep', '/@scope/test-dep/1.2.3-beta.3')).toEqual( + '1.2.3-beta.3' + ); }); it('extracts a registry-qualified path', () => { - expect(testParsePnpmDependencyKey('@scope/test-dep', 'example.pkgs.visualstudio.com/@scope/test-dep/1.0.0')) - .toEqual('1.0.0'); - expect(testParsePnpmDependencyKey('@scope/test-dep', 'example.pkgs.visualstudio.com/@scope/test-dep/1.2.3-beta.3')) - .toEqual('1.2.3-beta.3'); + expect( + testParsePnpmDependencyKey('@scope/test-dep', 'example.pkgs.visualstudio.com/@scope/test-dep/1.0.0') + ).toEqual('1.0.0'); + expect( + testParsePnpmDependencyKey( + '@scope/test-dep', + 'example.pkgs.visualstudio.com/@scope/test-dep/1.2.3-beta.3' + ) + ).toEqual('1.2.3-beta.3'); }); it('extracts a V3 peer dependency path', () => { - expect(testParsePnpmDependencyKey('gulp-karma', '/gulp-karma/0.0.5/karma@0.13.22')) - .toEqual('0.0.5'); - expect(testParsePnpmDependencyKey('sinon-chai', '/sinon-chai/2.8.0/chai@3.5.0+sinon@1.17.7')) - .toEqual('2.8.0'); - expect(testParsePnpmDependencyKey('@ms/sp-client-utilities', '/@ms/sp-client-utilities/3.1.1/foo@13.1.0')) - .toEqual('3.1.1'); - expect(testParsePnpmDependencyKey('tslint-microsoft-contrib', - '/tslint-microsoft-contrib/6.2.0/tslint@5.18.0+typescript@3.5.3')) - .toEqual('6.2.0'); + expect(testParsePnpmDependencyKey('gulp-karma', '/gulp-karma/0.0.5/karma@0.13.22')).toEqual('0.0.5'); + expect(testParsePnpmDependencyKey('sinon-chai', '/sinon-chai/2.8.0/chai@3.5.0+sinon@1.17.7')).toEqual( + '2.8.0' + ); + expect( + testParsePnpmDependencyKey('@ms/sp-client-utilities', '/@ms/sp-client-utilities/3.1.1/foo@13.1.0') + ).toEqual('3.1.1'); + expect( + testParsePnpmDependencyKey( + 'tslint-microsoft-contrib', + '/tslint-microsoft-contrib/6.2.0/tslint@5.18.0+typescript@3.5.3' + ) + ).toEqual('6.2.0'); }); it('extracts a V5 peer dependency path', () => { - expect(testParsePnpmDependencyKey('anonymous', '23.6.0_babel-core@6.26.3')) - .toEqual('23.6.0'); - expect(testParsePnpmDependencyKey('anonymous', '1.0.7_request@2.88.0')) - .toEqual('1.0.7'); - expect(testParsePnpmDependencyKey('anonymous', '1.0.3_@pnpm+logger@1.0.2')) - .toEqual('1.0.3'); - expect(testParsePnpmDependencyKey('tslint-microsoft-contrib', - '/tslint-microsoft-contrib/6.2.0_tslint@5.18.0+typescript@3.5.3')) - .toEqual('6.2.0'); + expect(testParsePnpmDependencyKey('anonymous', '23.6.0_babel-core@6.26.3')).toEqual('23.6.0'); + expect(testParsePnpmDependencyKey('anonymous', '1.0.7_request@2.88.0')).toEqual('1.0.7'); + expect(testParsePnpmDependencyKey('anonymous', '1.0.3_@pnpm+logger@1.0.2')).toEqual('1.0.3'); + expect( + testParsePnpmDependencyKey( + 'tslint-microsoft-contrib', + '/tslint-microsoft-contrib/6.2.0_tslint@5.18.0+typescript@3.5.3' + ) + ).toEqual('6.2.0'); }); it('detects NPM package aliases', () => { - expect(testParsePnpmDependencyKey('alias1', '/isarray/2.0.5')) - .toEqual('npm:isarray@2.0.5'); - expect(testParsePnpmDependencyKey('alias2', '/@ms/sp-client-utilities/3.1.1/foo@13.1.0')) - .toEqual('npm:@ms/sp-client-utilities@3.1.1'); + expect(testParsePnpmDependencyKey('alias1', '/isarray/2.0.5')).toEqual('npm:isarray@2.0.5'); + expect(testParsePnpmDependencyKey('alias2', '/@ms/sp-client-utilities/3.1.1/foo@13.1.0')).toEqual( + 'npm:@ms/sp-client-utilities@3.1.1' + ); }); it('handles bad cases', () => { expect(testParsePnpmDependencyKey('example', '/foo/gulp-karma/0.0.5/karma@0.13.22')).toEqual(undefined); @@ -129,6 +166,8 @@ describe('extractVersionFromPnpmVersionSpecifier', () => { expect(testParsePnpmDependencyKey('example', '/')).toEqual(undefined); expect(testParsePnpmDependencyKey('example', '//')).toEqual(undefined); expect(testParsePnpmDependencyKey('example', '/@/')).toEqual(undefined); - expect(testParsePnpmDependencyKey('example', 'example.pkgs.visualstudio.com/@scope/testDep/')).toEqual(undefined); + expect(testParsePnpmDependencyKey('example', 'example.pkgs.visualstudio.com/@scope/testDep/')).toEqual( + undefined + ); }); }); diff --git a/apps/rush-lib/src/logic/test/Telemetry.test.ts b/apps/rush-lib/src/logic/test/Telemetry.test.ts index 2685880d048..2f54d8361b7 100644 --- a/apps/rush-lib/src/logic/test/Telemetry.test.ts +++ b/apps/rush-lib/src/logic/test/Telemetry.test.ts @@ -5,10 +5,7 @@ import * as path from 'path'; import { RushConfiguration } from '../../api/RushConfiguration'; import { Rush } from '../../api/Rush'; -import { - Telemetry, - ITelemetryData - } from '../Telemetry'; +import { Telemetry, ITelemetryData } from '../Telemetry'; describe('Telemetry', () => { it('adds data to store if telemetry is enabled', () => { @@ -21,7 +18,7 @@ describe('Telemetry', () => { result: 'Succeeded', timestamp: new Date().getTime(), platform: process.platform, - rushVersion: Rush.version + rushVersion: Rush.version, }; const logData2: ITelemetryData = { @@ -30,7 +27,7 @@ describe('Telemetry', () => { result: 'Failed', timestamp: new Date().getTime(), platform: process.platform, - rushVersion: Rush.version + rushVersion: Rush.version, }; telemetry.log(logData1); @@ -48,7 +45,7 @@ describe('Telemetry', () => { result: 'Succeeded', timestamp: new Date().getTime(), platform: process.platform, - rushVersion: Rush.version + rushVersion: Rush.version, }; telemetry.log(logData); @@ -65,7 +62,7 @@ describe('Telemetry', () => { result: 'Succeeded', timestamp: new Date().getTime(), platform: process.platform, - rushVersion: Rush.version + rushVersion: Rush.version, }; telemetry.log(logData); @@ -87,7 +84,7 @@ describe('Telemetry', () => { const logData: ITelemetryData = { name: 'testData1', duration: 100, - result: 'Succeeded' + result: 'Succeeded', }; telemetry.log(logData); @@ -96,4 +93,4 @@ describe('Telemetry', () => { expect(result.rushVersion).toEqual(Rush.version); expect(result.timestamp).toBeDefined(); }); -}); \ No newline at end of file +}); diff --git a/apps/rush-lib/src/logic/test/VersionManager.test.ts b/apps/rush-lib/src/logic/test/VersionManager.test.ts index ef6420e6bd6..3fde036e6a9 100644 --- a/apps/rush-lib/src/logic/test/VersionManager.test.ts +++ b/apps/rush-lib/src/logic/test/VersionManager.test.ts @@ -10,8 +10,7 @@ import { ChangeType, IChangeInfo } from '../../api/ChangeManagement'; import { RushConfiguration } from '../../api/RushConfiguration'; import { VersionManager } from '../VersionManager'; -function _getChanges(changeFiles: Map, - packageName: string): IChangeInfo[] | undefined { +function _getChanges(changeFiles: Map, packageName: string): IChangeInfo[] | undefined { const changeFile: ChangeFile | undefined = changeFiles.get(packageName); if (!changeFile) { return undefined; @@ -25,8 +24,11 @@ describe('VersionManager', () => { let versionManager: VersionManager; beforeEach(() => { - versionManager = new VersionManager(rushConfiguration, 'test@microsoft.com', - rushConfiguration.versionPolicyConfiguration); + versionManager = new VersionManager( + rushConfiguration, + 'test@microsoft.com', + rushConfiguration.versionPolicyConfiguration + ); }); /* eslint-disable dot-notation */ diff --git a/apps/rush-lib/src/logic/test/categorizedChanges/@ms/a/changeA.json b/apps/rush-lib/src/logic/test/categorizedChanges/@ms/a/changeA.json index ea8d5e5512b..d3f1ec72409 100644 --- a/apps/rush-lib/src/logic/test/categorizedChanges/@ms/a/changeA.json +++ b/apps/rush-lib/src/logic/test/categorizedChanges/@ms/a/changeA.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "@ms/a", - "type": "patch", - "comment": "Patching a" - }] -} \ No newline at end of file + "changes": [ + { + "packageName": "@ms/a", + "type": "patch", + "comment": "Patching a" + } + ] +} diff --git a/apps/rush-lib/src/logic/test/categorizedChanges/@ms/b/changeB.json b/apps/rush-lib/src/logic/test/categorizedChanges/@ms/b/changeB.json index 04a08006251..ce8dce3708b 100644 --- a/apps/rush-lib/src/logic/test/categorizedChanges/@ms/b/changeB.json +++ b/apps/rush-lib/src/logic/test/categorizedChanges/@ms/b/changeB.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "@ms/b", - "type": "patch", - "comment": "Patching b" - }] -} \ No newline at end of file + "changes": [ + { + "packageName": "@ms/b", + "type": "patch", + "comment": "Patching b" + } + ] +} diff --git a/apps/rush-lib/src/logic/test/categorizedChanges/changeC.json b/apps/rush-lib/src/logic/test/categorizedChanges/changeC.json index 8c1bb8d1afc..81eaa9cb51c 100644 --- a/apps/rush-lib/src/logic/test/categorizedChanges/changeC.json +++ b/apps/rush-lib/src/logic/test/categorizedChanges/changeC.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "c", - "type": "patch", - "comment": "Patching c" - }] -} \ No newline at end of file + "changes": [ + { + "packageName": "c", + "type": "patch", + "comment": "Patching c" + } + ] +} diff --git a/apps/rush-lib/src/logic/test/cyclicDeps/change.json b/apps/rush-lib/src/logic/test/cyclicDeps/change.json index a00be2d78f4..dc697ac8402 100644 --- a/apps/rush-lib/src/logic/test/cyclicDeps/change.json +++ b/apps/rush-lib/src/logic/test/cyclicDeps/change.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "cyclic-dep-1", - "type": "major", - "comment": "Patching cyclic dep" - }] + "changes": [ + { + "packageName": "cyclic-dep-1", + "type": "major", + "comment": "Patching cyclic dep" + } + ] } diff --git a/apps/rush-lib/src/logic/test/cyclicDepsExplicit/change.json b/apps/rush-lib/src/logic/test/cyclicDepsExplicit/change.json index 9c2611f595c..c1683b1b8b1 100644 --- a/apps/rush-lib/src/logic/test/cyclicDepsExplicit/change.json +++ b/apps/rush-lib/src/logic/test/cyclicDepsExplicit/change.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "cyclic-dep-explicit-1", - "type": "major", - "comment": "Patching cyclic dep" - }] + "changes": [ + { + "packageName": "cyclic-dep-explicit-1", + "type": "major", + "comment": "Patching cyclic dep" + } + ] } diff --git a/apps/rush-lib/src/logic/test/explicitVersionChange/change1.json b/apps/rush-lib/src/logic/test/explicitVersionChange/change1.json index 64fa9ff4758..81eaa9cb51c 100644 --- a/apps/rush-lib/src/logic/test/explicitVersionChange/change1.json +++ b/apps/rush-lib/src/logic/test/explicitVersionChange/change1.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "c", - "type": "patch", - "comment": "Patching c" - }] + "changes": [ + { + "packageName": "c", + "type": "patch", + "comment": "Patching c" + } + ] } diff --git a/apps/rush-lib/src/logic/test/hotfixWithPatchChanges/change1.json b/apps/rush-lib/src/logic/test/hotfixWithPatchChanges/change1.json index 5e78e627b42..d16f93bde28 100644 --- a/apps/rush-lib/src/logic/test/hotfixWithPatchChanges/change1.json +++ b/apps/rush-lib/src/logic/test/hotfixWithPatchChanges/change1.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "a", - "type": "patch", - "comment": "Patch change to a" - }] + "changes": [ + { + "packageName": "a", + "type": "patch", + "comment": "Patch change to a" + } + ] } diff --git a/apps/rush-lib/src/logic/test/hotfixWithPatchChanges/change2.json b/apps/rush-lib/src/logic/test/hotfixWithPatchChanges/change2.json index 51599cdb92c..4dba9fbf026 100644 --- a/apps/rush-lib/src/logic/test/hotfixWithPatchChanges/change2.json +++ b/apps/rush-lib/src/logic/test/hotfixWithPatchChanges/change2.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "a", - "type": "hotfix", - "comment": "Hotfix change to a" - }] + "changes": [ + { + "packageName": "a", + "type": "hotfix", + "comment": "Hotfix change to a" + } + ] } diff --git a/apps/rush-lib/src/logic/test/hotfixWithPatchChanges/change3.json b/apps/rush-lib/src/logic/test/hotfixWithPatchChanges/change3.json index 5e78e627b42..d16f93bde28 100644 --- a/apps/rush-lib/src/logic/test/hotfixWithPatchChanges/change3.json +++ b/apps/rush-lib/src/logic/test/hotfixWithPatchChanges/change3.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "a", - "type": "patch", - "comment": "Patch change to a" - }] + "changes": [ + { + "packageName": "a", + "type": "patch", + "comment": "Patch change to a" + } + ] } diff --git a/apps/rush-lib/src/logic/test/leafChange/change1.json b/apps/rush-lib/src/logic/test/leafChange/change1.json index ae14879c7d5..abccc8a5d4e 100644 --- a/apps/rush-lib/src/logic/test/leafChange/change1.json +++ b/apps/rush-lib/src/logic/test/leafChange/change1.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "d", - "type": "patch", - "comment": "Patching d" - }] + "changes": [ + { + "packageName": "d", + "type": "patch", + "comment": "Patching d" + } + ] } diff --git a/apps/rush-lib/src/logic/test/lockstepRepo/common/config/rush/version-policies.json b/apps/rush-lib/src/logic/test/lockstepRepo/common/config/rush/version-policies.json index 2a6c188679c..2457e17d417 100644 --- a/apps/rush-lib/src/logic/test/lockstepRepo/common/config/rush/version-policies.json +++ b/apps/rush-lib/src/logic/test/lockstepRepo/common/config/rush/version-policies.json @@ -6,4 +6,4 @@ "nextBump": "prerelease", "mainProject": "b" } -] \ No newline at end of file +] diff --git a/apps/rush-lib/src/logic/test/multipleChangeFiles/a.json b/apps/rush-lib/src/logic/test/multipleChangeFiles/a.json index b213de70852..d16f93bde28 100644 --- a/apps/rush-lib/src/logic/test/multipleChangeFiles/a.json +++ b/apps/rush-lib/src/logic/test/multipleChangeFiles/a.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "a", - "type": "patch", - "comment": "Patch change to a" - }] -} \ No newline at end of file + "changes": [ + { + "packageName": "a", + "type": "patch", + "comment": "Patch change to a" + } + ] +} diff --git a/apps/rush-lib/src/logic/test/multipleChangeFiles/b.json b/apps/rush-lib/src/logic/test/multipleChangeFiles/b.json index 90764025208..8f9f3319744 100644 --- a/apps/rush-lib/src/logic/test/multipleChangeFiles/b.json +++ b/apps/rush-lib/src/logic/test/multipleChangeFiles/b.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "b", - "type": "patch", - "comment": "Patch change to b" - }] -} \ No newline at end of file + "changes": [ + { + "packageName": "b", + "type": "patch", + "comment": "Patch change to b" + } + ] +} diff --git a/apps/rush-lib/src/logic/test/multipleChangeFiles/c.json b/apps/rush-lib/src/logic/test/multipleChangeFiles/c.json index efd06816e7c..fbd0e950304 100644 --- a/apps/rush-lib/src/logic/test/multipleChangeFiles/c.json +++ b/apps/rush-lib/src/logic/test/multipleChangeFiles/c.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "c", - "type": "patch", - "comment": "Patch change to c" - }] -} \ No newline at end of file + "changes": [ + { + "packageName": "c", + "type": "patch", + "comment": "Patch change to c" + } + ] +} diff --git a/apps/rush-lib/src/logic/test/multipleChanges/change1.json b/apps/rush-lib/src/logic/test/multipleChanges/change1.json index 5e78e627b42..d16f93bde28 100644 --- a/apps/rush-lib/src/logic/test/multipleChanges/change1.json +++ b/apps/rush-lib/src/logic/test/multipleChanges/change1.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "a", - "type": "patch", - "comment": "Patch change to a" - }] + "changes": [ + { + "packageName": "a", + "type": "patch", + "comment": "Patch change to a" + } + ] } diff --git a/apps/rush-lib/src/logic/test/multipleChanges/change2.json b/apps/rush-lib/src/logic/test/multipleChanges/change2.json index a16b064ca9a..afd8341a20d 100644 --- a/apps/rush-lib/src/logic/test/multipleChanges/change2.json +++ b/apps/rush-lib/src/logic/test/multipleChanges/change2.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "a", - "type": "minor", - "comment": "Minor change to a" - }] + "changes": [ + { + "packageName": "a", + "type": "minor", + "comment": "Minor change to a" + } + ] } diff --git a/apps/rush-lib/src/logic/test/multipleChanges/change3.json b/apps/rush-lib/src/logic/test/multipleChanges/change3.json index f767def9023..d52e17743ff 100644 --- a/apps/rush-lib/src/logic/test/multipleChanges/change3.json +++ b/apps/rush-lib/src/logic/test/multipleChanges/change3.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "a", - "type": "major", - "comment": "Major change to a" - }] + "changes": [ + { + "packageName": "a", + "type": "major", + "comment": "Major change to a" + } + ] } diff --git a/apps/rush-lib/src/logic/test/multipleHotfixChanges/change1.json b/apps/rush-lib/src/logic/test/multipleHotfixChanges/change1.json index 51599cdb92c..4dba9fbf026 100644 --- a/apps/rush-lib/src/logic/test/multipleHotfixChanges/change1.json +++ b/apps/rush-lib/src/logic/test/multipleHotfixChanges/change1.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "a", - "type": "hotfix", - "comment": "Hotfix change to a" - }] + "changes": [ + { + "packageName": "a", + "type": "hotfix", + "comment": "Hotfix change to a" + } + ] } diff --git a/apps/rush-lib/src/logic/test/multipleHotfixChanges/change2.json b/apps/rush-lib/src/logic/test/multipleHotfixChanges/change2.json index 857ec56ac76..3a1ea989dc0 100644 --- a/apps/rush-lib/src/logic/test/multipleHotfixChanges/change2.json +++ b/apps/rush-lib/src/logic/test/multipleHotfixChanges/change2.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "b", - "type": "hotfix", - "comment": "Hotfix change to b" - }] + "changes": [ + { + "packageName": "b", + "type": "hotfix", + "comment": "Hotfix change to b" + } + ] } diff --git a/apps/rush-lib/src/logic/test/multipleHotfixChanges/change3.json b/apps/rush-lib/src/logic/test/multipleHotfixChanges/change3.json index 51599cdb92c..4dba9fbf026 100644 --- a/apps/rush-lib/src/logic/test/multipleHotfixChanges/change3.json +++ b/apps/rush-lib/src/logic/test/multipleHotfixChanges/change3.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "a", - "type": "hotfix", - "comment": "Hotfix change to a" - }] + "changes": [ + { + "packageName": "a", + "type": "hotfix", + "comment": "Hotfix change to a" + } + ] } diff --git a/apps/rush-lib/src/logic/test/orderedChanges/change1.json b/apps/rush-lib/src/logic/test/orderedChanges/change1.json index 6b8fdb90757..db3d5257919 100644 --- a/apps/rush-lib/src/logic/test/orderedChanges/change1.json +++ b/apps/rush-lib/src/logic/test/orderedChanges/change1.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "a", - "type": "major", - "comment": "Patch change to a" - }] -} \ No newline at end of file + "changes": [ + { + "packageName": "a", + "type": "major", + "comment": "Patch change to a" + } + ] +} diff --git a/apps/rush-lib/src/logic/test/orderedChanges/change2.json b/apps/rush-lib/src/logic/test/orderedChanges/change2.json index c91c5ceab65..f5648a3cdf0 100644 --- a/apps/rush-lib/src/logic/test/orderedChanges/change2.json +++ b/apps/rush-lib/src/logic/test/orderedChanges/change2.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "a", - "type": "none", - "comment": "None change to a" - }] -} \ No newline at end of file + "changes": [ + { + "packageName": "a", + "type": "none", + "comment": "None change to a" + } + ] +} diff --git a/apps/rush-lib/src/logic/test/packages/rush.json b/apps/rush-lib/src/logic/test/packages/rush.json index 6b39c9d6742..4c4825157f4 100644 --- a/apps/rush-lib/src/logic/test/packages/rush.json +++ b/apps/rush-lib/src/logic/test/packages/rush.json @@ -4,8 +4,8 @@ "projectFolderMinDepth": 1, "hotfixChangeEnabled": true, "approvedPackagesPolicy": { - "reviewCategories": [ "first-party", "third-party", "prototype" ], - "ignoredNpmScopes": [ "@types", "@internal" ] + "reviewCategories": ["first-party", "third-party", "prototype"], + "ignoredNpmScopes": ["@types", "@internal"] }, "projects": [ { @@ -55,9 +55,7 @@ "projectFolder": "cyclic-dep-explicit-2", "reviewCategory": "third-party", "shouldPublish": true, - "cyclicDependencyProjects": [ - "cyclic-dep-explicit-1" - ] + "cyclicDependencyProjects": ["cyclic-dep-explicit-1"] } ] } diff --git a/apps/rush-lib/src/logic/test/repo/changes/a.json b/apps/rush-lib/src/logic/test/repo/changes/a.json index a5c3e31e20c..43f7263c5e8 100644 --- a/apps/rush-lib/src/logic/test/repo/changes/a.json +++ b/apps/rush-lib/src/logic/test/repo/changes/a.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "a", - "type": "patch", - "comment": "Patching a" - }] -} \ No newline at end of file + "changes": [ + { + "packageName": "a", + "type": "patch", + "comment": "Patching a" + } + ] +} diff --git a/apps/rush-lib/src/logic/test/repo/changes/b.json b/apps/rush-lib/src/logic/test/repo/changes/b.json index 7376edbe1a2..6e3320bd6e8 100644 --- a/apps/rush-lib/src/logic/test/repo/changes/b.json +++ b/apps/rush-lib/src/logic/test/repo/changes/b.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "b", - "type": "patch", - "comment": "Patching b" - }] -} \ No newline at end of file + "changes": [ + { + "packageName": "b", + "type": "patch", + "comment": "Patching b" + } + ] +} diff --git a/apps/rush-lib/src/logic/test/repo/changes/c.json b/apps/rush-lib/src/logic/test/repo/changes/c.json index 8c1bb8d1afc..81eaa9cb51c 100644 --- a/apps/rush-lib/src/logic/test/repo/changes/c.json +++ b/apps/rush-lib/src/logic/test/repo/changes/c.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "c", - "type": "patch", - "comment": "Patching c" - }] -} \ No newline at end of file + "changes": [ + { + "packageName": "c", + "type": "patch", + "comment": "Patching c" + } + ] +} diff --git a/apps/rush-lib/src/logic/test/repo/changes/d.json b/apps/rush-lib/src/logic/test/repo/changes/d.json index 6e73cd4e32d..abccc8a5d4e 100644 --- a/apps/rush-lib/src/logic/test/repo/changes/d.json +++ b/apps/rush-lib/src/logic/test/repo/changes/d.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "d", - "type": "patch", - "comment": "Patching d" - }] -} \ No newline at end of file + "changes": [ + { + "packageName": "d", + "type": "patch", + "comment": "Patching d" + } + ] +} diff --git a/apps/rush-lib/src/logic/test/repo/common/config/rush/version-policies.json b/apps/rush-lib/src/logic/test/repo/common/config/rush/version-policies.json index 389fb704679..ad0b40cd496 100644 --- a/apps/rush-lib/src/logic/test/repo/common/config/rush/version-policies.json +++ b/apps/rush-lib/src/logic/test/repo/common/config/rush/version-policies.json @@ -14,4 +14,4 @@ "policyName": "testPolicy3", "definitionName": "individualVersion" } -] \ No newline at end of file +] diff --git a/apps/rush-lib/src/logic/test/repo/d/package.json b/apps/rush-lib/src/logic/test/repo/d/package.json index 5ff594492c4..c61e59ddb75 100644 --- a/apps/rush-lib/src/logic/test/repo/d/package.json +++ b/apps/rush-lib/src/logic/test/repo/d/package.json @@ -5,4 +5,4 @@ "dependencies": { "b": ">=2.0.0 <3.0.0" } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/logic/test/repo/e/package.json b/apps/rush-lib/src/logic/test/repo/e/package.json index a65f747ce6b..c10850ecdbd 100644 --- a/apps/rush-lib/src/logic/test/repo/e/package.json +++ b/apps/rush-lib/src/logic/test/repo/e/package.json @@ -5,4 +5,4 @@ "dependencies": { "c": "~3.1.1" } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/logic/test/repo/f/package.json b/apps/rush-lib/src/logic/test/repo/f/package.json index 68dea232055..78da693f5e9 100644 --- a/apps/rush-lib/src/logic/test/repo/f/package.json +++ b/apps/rush-lib/src/logic/test/repo/f/package.json @@ -5,4 +5,4 @@ "dependencies": { "a": "~1.0.0" } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/logic/test/repo/g/package.json b/apps/rush-lib/src/logic/test/repo/g/package.json index 6feb6d79954..bec763b9fae 100644 --- a/apps/rush-lib/src/logic/test/repo/g/package.json +++ b/apps/rush-lib/src/logic/test/repo/g/package.json @@ -5,4 +5,4 @@ "devDependencies": { "a": "~1.0.0" } -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/logic/test/rootHotfixChange/change1.json b/apps/rush-lib/src/logic/test/rootHotfixChange/change1.json index 36f551fc05a..31d57190f30 100644 --- a/apps/rush-lib/src/logic/test/rootHotfixChange/change1.json +++ b/apps/rush-lib/src/logic/test/rootHotfixChange/change1.json @@ -1,8 +1,9 @@ { - "changes": [{ - "packageName": "a", - "type": "hotfix", - "comment": "Hotfixing a" - }] + "changes": [ + { + "packageName": "a", + "type": "hotfix", + "comment": "Hotfixing a" + } + ] } - diff --git a/apps/rush-lib/src/logic/test/rootMajorChange/change1.json b/apps/rush-lib/src/logic/test/rootMajorChange/change1.json index 6224e378479..b36f398869d 100644 --- a/apps/rush-lib/src/logic/test/rootMajorChange/change1.json +++ b/apps/rush-lib/src/logic/test/rootMajorChange/change1.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "a", - "type": "major", - "comment": "Patching a" - }] + "changes": [ + { + "packageName": "a", + "type": "major", + "comment": "Patching a" + } + ] } diff --git a/apps/rush-lib/src/logic/test/rootPatchChange/change1.json b/apps/rush-lib/src/logic/test/rootPatchChange/change1.json index a1ef3ecbe91..43f7263c5e8 100644 --- a/apps/rush-lib/src/logic/test/rootPatchChange/change1.json +++ b/apps/rush-lib/src/logic/test/rootPatchChange/change1.json @@ -1,7 +1,9 @@ { - "changes": [{ - "packageName": "a", - "type": "patch", - "comment": "Patching a" - }] + "changes": [ + { + "packageName": "a", + "type": "patch", + "comment": "Patching a" + } + ] } diff --git a/apps/rush-lib/src/logic/test/verifyChanges/changes.json b/apps/rush-lib/src/logic/test/verifyChanges/changes.json index 5ae66e6f832..0a8e429d4e4 100644 --- a/apps/rush-lib/src/logic/test/verifyChanges/changes.json +++ b/apps/rush-lib/src/logic/test/verifyChanges/changes.json @@ -1,12 +1,14 @@ { - "changes": [{ - "packageName": "a", - "type": "patch", - "comment": "Patching a" - }, - { - "packageName": "b", - "type": "patch", - "comment": "Patching b" - }] -} \ No newline at end of file + "changes": [ + { + "packageName": "a", + "type": "patch", + "comment": "Patching a" + }, + { + "packageName": "b", + "type": "patch", + "comment": "Patching b" + } + ] +} diff --git a/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinder.ts b/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinder.ts index b779938dbfd..9527cd90c16 100644 --- a/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinder.ts +++ b/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinder.ts @@ -4,10 +4,7 @@ import * as colors from 'colors'; import { RushConfiguration } from '../../api/RushConfiguration'; -import { - PackageJsonDependency, - DependencyType -} from '../../api/PackageJsonEditor'; +import { PackageJsonDependency, DependencyType } from '../../api/PackageJsonEditor'; import { CommonVersionsConfiguration } from '../../api/CommonVersionsConfiguration'; import { VersionMismatchFinderEntity } from './VersionMismatchFinderEntity'; import { VersionMismatchFinderProject } from './VersionMismatchFinderProject'; @@ -33,7 +30,7 @@ export interface IMismatchDependency { } export interface IMismatchDependencyVersion { - version: string, + version: string; projects: string[]; } @@ -42,14 +39,14 @@ export interface IMismatchDependencies { } export class VersionMismatchFinder { - /* store it like this: - * { - * "@types/node": { - * "1.0.0": [ '@ms/rush' ] - * } - * } - */ - private _allowedAlternativeVersion: Map>; + /* store it like this: + * { + * "@types/node": { + * "1.0.0": [ '@ms/rush' ] + * } + * } + */ + private _allowedAlternativeVersion: Map>; private _mismatches: Map>; private _projects: VersionMismatchFinderEntity[]; @@ -69,7 +66,7 @@ export class VersionMismatchFinder { ): void { VersionMismatchFinder._checkForInconsistentVersions(rushConfiguration, { ...options, - isRushCheckCommand: true + isRushCheckCommand: true, }); } @@ -79,7 +76,7 @@ export class VersionMismatchFinder { ): void { VersionMismatchFinder._checkForInconsistentVersions(rushConfiguration, { ...options, - isRushCheckCommand: false + isRushCheckCommand: false, }); } @@ -101,10 +98,7 @@ export class VersionMismatchFinder { // or xstitchPreferredVersions from common-versions.json projects.push(new VersionMismatchFinderCommonVersions(commonVersions)); - return new VersionMismatchFinder( - projects, - commonVersions.allowedAlternativeVersions - ); + return new VersionMismatchFinder(projects, commonVersions.allowedAlternativeVersions); } private static _checkForInconsistentVersions( @@ -116,7 +110,10 @@ export class VersionMismatchFinder { } ): void { if (rushConfiguration.ensureConsistentVersions || options.isRushCheckCommand) { - const mismatchFinder: VersionMismatchFinder = VersionMismatchFinder.getMismatches(rushConfiguration, options); + const mismatchFinder: VersionMismatchFinder = VersionMismatchFinder.getMismatches( + rushConfiguration, + options + ); if (options.printAsJson) { mismatchFinder.printAsJson(); @@ -135,7 +132,7 @@ export class VersionMismatchFinder { } } - public get numberOfMismatches(): number { + public get numberOfMismatches(): number { return this._mismatches.size; } @@ -144,13 +141,16 @@ export class VersionMismatchFinder { } public getVersionsOfMismatch(mismatch: string): string[] | undefined { - return this._mismatches.has(mismatch) - ? this._getKeys(this._mismatches.get(mismatch)) - : undefined; + return this._mismatches.has(mismatch) ? this._getKeys(this._mismatches.get(mismatch)) : undefined; } - public getConsumersOfMismatch(mismatch: string, version: string): VersionMismatchFinderEntity[] | undefined { - const mismatchedPackage: Map | undefined = this._mismatches.get(mismatch); + public getConsumersOfMismatch( + mismatch: string, + version: string + ): VersionMismatchFinderEntity[] | undefined { + const mismatchedPackage: Map | undefined = this._mismatches.get( + mismatch + ); if (!mismatchedPackage) { return undefined; } @@ -165,25 +165,25 @@ export class VersionMismatchFinder { this.getMismatches().forEach((dependency: string) => { const mismatchDependencyVersionArray: IMismatchDependencyVersion[] = []; this.getVersionsOfMismatch(dependency)!.forEach((version: string) => { - const projects: string[] = [] + const projects: string[] = []; this.getConsumersOfMismatch(dependency, version)!.forEach((project: VersionMismatchFinderEntity) => { projects.push(project.friendlyName); }); const mismatchDependencyVersion: IMismatchDependencyVersion = { version: version, - projects: projects + projects: projects, }; mismatchDependencyVersionArray.push(mismatchDependencyVersion); }); const mismatchDependency: IMismatchDependency = { - dependencyName: dependency, - versions: mismatchDependencyVersionArray + dependencyName: dependency, + versions: mismatchDependencyVersionArray, }; mismatchDependencies.push(mismatchDependency); }); const output: IMismatchDependencies = { - mismatchedVersions: mismatchDependencies + mismatchedVersions: mismatchDependencies, }; console.log(JSON.stringify(output, undefined, 2)); @@ -229,7 +229,9 @@ export class VersionMismatchFinder { this._mismatches.set(name, new Map()); } - const dependencyVersions: Map = this._mismatches.get(name)!; + const dependencyVersions: Map = this._mismatches.get( + name + )!; if (!dependencyVersions.has(version)) { dependencyVersions.set(version, []); @@ -248,11 +250,10 @@ export class VersionMismatchFinder { }); } - private _isVersionAllowedAlternative( - dependency: string, - version: string): boolean { - - const allowedAlternatives: ReadonlyArray | undefined = this._allowedAlternativeVersion.get(dependency); + private _isVersionAllowedAlternative(dependency: string, version: string): boolean { + const allowedAlternatives: ReadonlyArray | undefined = this._allowedAlternativeVersion.get( + dependency + ); return Boolean(allowedAlternatives && allowedAlternatives.indexOf(version) > -1); } diff --git a/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinderCommonVersions.ts b/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinderCommonVersions.ts index 7b10253147e..c701e6f7d45 100644 --- a/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinderCommonVersions.ts +++ b/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinderCommonVersions.ts @@ -12,7 +12,7 @@ export class VersionMismatchFinderCommonVersions extends VersionMismatchFinderEn public constructor(commonVersionsConfiguration: CommonVersionsConfiguration) { super({ friendlyName: `preferred versions from ${RushConstants.commonVersionsFilename}`, - cyclicDependencyProjects: new Set() + cyclicDependencyProjects: new Set(), }); this._fileManager = commonVersionsConfiguration; @@ -45,9 +45,15 @@ export class VersionMismatchFinderCommonVersions extends VersionMismatchFinderEn return undefined; // common-versions.json doesn't have a distinction between dev and non-dev dependencies } - public addOrUpdateDependency(packageName: string, newVersion: string, dependencyType: DependencyType): void { + public addOrUpdateDependency( + packageName: string, + newVersion: string, + dependencyType: DependencyType + ): void { if (dependencyType !== DependencyType.Regular) { - throw new Error(`${RushConstants.commonVersionsFilename} only accepts "${DependencyType.Regular}" dependencies`); + throw new Error( + `${RushConstants.commonVersionsFilename} only accepts "${DependencyType.Regular}" dependencies` + ); } if (this._fileManager.xstitchPreferredVersions.has(packageName)) { @@ -62,11 +68,8 @@ export class VersionMismatchFinderCommonVersions extends VersionMismatchFinderEn } private _getPackageJsonDependency(dependencyName: string, version: string): PackageJsonDependency { - return new PackageJsonDependency( - dependencyName, - version, - DependencyType.Regular, - () => this.addOrUpdateDependency(dependencyName, version, DependencyType.Regular) + return new PackageJsonDependency(dependencyName, version, DependencyType.Regular, () => + this.addOrUpdateDependency(dependencyName, version, DependencyType.Regular) ); } } diff --git a/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinderEntity.ts b/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinderEntity.ts index 1056ed8a4c6..3ce9f842670 100644 --- a/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinderEntity.ts +++ b/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinderEntity.ts @@ -1,10 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - PackageJsonDependency, - DependencyType -} from '../../api/PackageJsonEditor'; +import { PackageJsonDependency, DependencyType } from '../../api/PackageJsonEditor'; export interface IVersionMismatchFinderEntityOptions { friendlyName: string; @@ -28,6 +25,10 @@ export abstract class VersionMismatchFinderEntity { public abstract tryGetDependency(packageName: string): PackageJsonDependency | undefined; public abstract tryGetDevDependency(packageName: string): PackageJsonDependency | undefined; - public abstract addOrUpdateDependency(packageName: string, newVersion: string, dependencyType: DependencyType): void; + public abstract addOrUpdateDependency( + packageName: string, + newVersion: string, + dependencyType: DependencyType + ): void; public abstract saveIfModified(): boolean; -} \ No newline at end of file +} diff --git a/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinderProject.ts b/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinderProject.ts index a483b427b2d..eb594e94800 100644 --- a/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinderProject.ts +++ b/apps/rush-lib/src/logic/versionMismatch/VersionMismatchFinderProject.ts @@ -2,11 +2,7 @@ // See LICENSE in the project root for license information. import { VersionMismatchFinderEntity } from './VersionMismatchFinderEntity'; -import { - PackageJsonEditor, - PackageJsonDependency, - DependencyType -} from '../../api/PackageJsonEditor'; +import { PackageJsonEditor, PackageJsonDependency, DependencyType } from '../../api/PackageJsonEditor'; import { RushConfigurationProject } from '../../api/RushConfigurationProject'; export class VersionMismatchFinderProject extends VersionMismatchFinderEntity { @@ -17,7 +13,7 @@ export class VersionMismatchFinderProject extends VersionMismatchFinderEntity { super({ friendlyName: project.packageName, cyclicDependencyProjects: project.cyclicDependencyProjects, - skipRushCheck: project.skipRushCheck + skipRushCheck: project.skipRushCheck, }); this._fileManager = project.packageJsonEditor; @@ -40,7 +36,11 @@ export class VersionMismatchFinderProject extends VersionMismatchFinderEntity { return this._fileManager.tryGetDevDependency(packageName); } - public addOrUpdateDependency(packageName: string, newVersion: string, dependencyType: DependencyType): void { + public addOrUpdateDependency( + packageName: string, + newVersion: string, + dependencyType: DependencyType + ): void { return this._fileManager.addOrUpdateDependency(packageName, newVersion, dependencyType); } diff --git a/apps/rush-lib/src/logic/yarn/YarnShrinkwrapFile.ts b/apps/rush-lib/src/logic/yarn/YarnShrinkwrapFile.ts index 9e6a6fa91da..f853ced6af1 100644 --- a/apps/rush-lib/src/logic/yarn/YarnShrinkwrapFile.ts +++ b/apps/rush-lib/src/logic/yarn/YarnShrinkwrapFile.ts @@ -1,8 +1,6 @@ import * as os from 'os'; import * as lockfile from '@yarnpkg/lockfile'; -import { - BaseShrinkwrapFile -} from '../base/BaseShrinkwrapFile'; +import { BaseShrinkwrapFile } from '../base/BaseShrinkwrapFile'; import { FileSystem, IParsedPackageNameOrError, InternalError } from '@rushstack/node-core-library'; import { RushConstants } from '../RushConstants'; import { DependencySpecifier } from '../DependencySpecifier'; @@ -97,18 +95,25 @@ export class YarnShrinkwrapFile extends BaseShrinkwrapFile { const packageNameAndSemVer: IPackageNameAndSemVer = YarnShrinkwrapFile._decodePackageNameAndSemVer(key); // If it starts with @rush-temp, then include it: - if (PackageNameParsers.permissive.getScope(packageNameAndSemVer.packageName) === RushConstants.rushTempNpmScope) { + if ( + PackageNameParsers.permissive.getScope(packageNameAndSemVer.packageName) === + RushConstants.rushTempNpmScope + ) { if (!/^file:/i.test(packageNameAndSemVer.semVerRange)) { // Sanity check to make sure this is a real package. // (Nobody should ever have an actual dependency on an "@rush-temp/" package. - throw new Error('Unexpected package/semver expression found in the Yarn shrinkwrap file (yarn.lock): ' - + JSON.stringify(key)); + throw new Error( + 'Unexpected package/semver expression found in the Yarn shrinkwrap file (yarn.lock): ' + + JSON.stringify(key) + ); } if (!seenEntries.add(packageNameAndSemVer.packageName)) { // Sanity check -- this should never happen - throw new Error('Duplicate @rush-temp package found in the Yarn shrinkwrap file (yarn.lock): ' - + JSON.stringify(key)); + throw new Error( + 'Duplicate @rush-temp package found in the Yarn shrinkwrap file (yarn.lock): ' + + JSON.stringify(key) + ); } this._tempProjectNames.push(packageNameAndSemVer.packageName); @@ -133,7 +138,7 @@ export class YarnShrinkwrapFile extends BaseShrinkwrapFile { } } - this._tempProjectNames.sort(); // make the result deterministic + this._tempProjectNames.sort(); // make the result deterministic } public static loadFromFile(shrinkwrapFilename: string): YarnShrinkwrapFile | undefined { @@ -161,24 +166,32 @@ export class YarnShrinkwrapFile extends BaseShrinkwrapFile { * Example output: { packageName: "js-tokens", semVerRange: "^3.0.0 || ^4.0.0" } */ private static _decodePackageNameAndSemVer(packageNameAndSemVer: string): IPackageNameAndSemVer { - const result: RegExpExecArray | null = YarnShrinkwrapFile._packageNameAndSemVerRegExp.exec(packageNameAndSemVer); + const result: RegExpExecArray | null = YarnShrinkwrapFile._packageNameAndSemVerRegExp.exec( + packageNameAndSemVer + ); if (!result) { // Sanity check -- this should never happen - throw new Error('Unable to parse package/semver expression in the Yarn shrinkwrap file (yarn.lock): ' - + JSON.stringify(packageNameAndSemVer)); + throw new Error( + 'Unable to parse package/semver expression in the Yarn shrinkwrap file (yarn.lock): ' + + JSON.stringify(packageNameAndSemVer) + ); } const packageName: string = result[1] || ''; const parsedPackageName: IParsedPackageNameOrError = PackageNameParsers.permissive.tryParse(packageName); if (parsedPackageName.error) { // Sanity check -- this should never happen - throw new Error('Invalid package name the Yarn shrinkwrap file (yarn.lock): ' - + JSON.stringify(packageNameAndSemVer) + '\n' + parsedPackageName.error); + throw new Error( + 'Invalid package name the Yarn shrinkwrap file (yarn.lock): ' + + JSON.stringify(packageNameAndSemVer) + + '\n' + + parsedPackageName.error + ); } return { packageName, - semVerRange: result[2] || '' + semVerRange: result[2] || '', }; } @@ -202,7 +215,7 @@ export class YarnShrinkwrapFile extends BaseShrinkwrapFile { // do any normalization. const key: string = YarnShrinkwrapFile._encodePackageNameAndSemVer({ packageName: dependencySpecifier.packageName, - semVerRange: dependencySpecifier.versionSpecifier + semVerRange: dependencySpecifier.versionSpecifier, }); // Check whether this exact key appears in the shrinkwrap file @@ -210,7 +223,10 @@ export class YarnShrinkwrapFile extends BaseShrinkwrapFile { } /** @override */ - public tryEnsureCompatibleDependency(dependencySpecifier: DependencySpecifier, tempProjectName: string): boolean { + public tryEnsureCompatibleDependency( + dependencySpecifier: DependencySpecifier, + tempProjectName: string + ): boolean { return this.hasCompatibleTopLevelDependency(dependencySpecifier); } @@ -225,9 +241,10 @@ export class YarnShrinkwrapFile extends BaseShrinkwrapFile { } /** @override */ - protected tryEnsureDependencyVersion(dependencySpecifier: DependencySpecifier, - tempProjectName: string): DependencySpecifier | undefined { - + protected tryEnsureDependencyVersion( + dependencySpecifier: DependencySpecifier, + tempProjectName: string + ): DependencySpecifier | undefined { throw new InternalError('Not implemented'); } } diff --git a/apps/rush-lib/src/schemas/approved-packages.schema.json b/apps/rush-lib/src/schemas/approved-packages.schema.json index f84a810e80d..0bced3cfed0 100644 --- a/apps/rush-lib/src/schemas/approved-packages.schema.json +++ b/apps/rush-lib/src/schemas/approved-packages.schema.json @@ -20,7 +20,7 @@ } }, "additionalProperties": false, - "required": [ "name" ] + "required": ["name"] } }, "type": "object", @@ -36,5 +36,5 @@ } }, "additionalProperties": false, - "required": [ "packages" ] + "required": ["packages"] } diff --git a/apps/rush-lib/src/schemas/command-line.schema.json b/apps/rush-lib/src/schemas/command-line.schema.json index 496b3b54657..565739983a2 100644 --- a/apps/rush-lib/src/schemas/command-line.schema.json +++ b/apps/rush-lib/src/schemas/command-line.schema.json @@ -5,27 +5,20 @@ "definitions": { "anything": { - "type": [ - "array", - "boolean", - "integer", - "number", - "object", - "string" - ], + "type": ["array", "boolean", "integer", "number", "object", "string"], "items": { "$ref": "#/definitions/anything" } }, "baseCommand": { "type": "object", "additionalProperties": true, - "required": [ "commandKind", "name", "summary" ], + "required": ["commandKind", "name", "summary"], "properties": { "commandKind": { "title": "Command Kind", "description": "Indicates the kind of command: \"bulk\" commands are run separately for each project; \"global\" commands are run once for the entire repository.", "type": "string", - "enum": [ "bulk", "global" ] + "enum": ["bulk", "global"] }, "name": { "title": "Custom Command Name", @@ -58,10 +51,10 @@ { "type": "object", "additionalProperties": true, - "required": [ "enableParallelism" ], + "required": ["enableParallelism"], "properties": { "commandKind": { - "enum": [ "bulk" ] + "enum": ["bulk"] }, "enableParallelism": { "title": "enableParallelism", @@ -118,10 +111,10 @@ { "type": "object", "additionalProperties": true, - "required": [ "shellCommand" ], + "required": ["shellCommand"], "properties": { "commandKind": { - "enum": [ "global" ] + "enum": ["global"] }, "shellCommand": { "title": "Shell Command", @@ -150,13 +143,13 @@ "baseParameter": { "type": "object", "additionalProperties": true, - "required": [ "parameterKind", "longName", "description", "associatedCommands" ], + "required": ["parameterKind", "longName", "description", "associatedCommands"], "properties": { "parameterKind": { "title": "Parameter Kind", "description": "Indicates the kind of syntax for this command-line parameter: \"flag\" or \"choice\" or \"string\"", "type": "string", - "enum": [ "flag", "choice", "string" ] + "enum": ["flag", "choice", "string"] }, "longName": { "title": "Long Name", @@ -202,7 +195,7 @@ "additionalProperties": true, "properties": { "parameterKind": { - "enum": [ "flag" ] + "enum": ["flag"] } } }, @@ -232,7 +225,7 @@ "required": ["argumentName"], "properties": { "parameterKind": { - "enum": [ "string" ] + "enum": ["string"] }, "argumentName": { "title": "Argument Name", @@ -266,10 +259,10 @@ { "type": "object", "additionalProperties": true, - "required": [ "alternatives" ], + "required": ["alternatives"], "properties": { "parameterKind": { - "enum": [ "choice" ] + "enum": ["choice"] }, "alternatives": { "title": "Alternatives", @@ -279,7 +272,7 @@ "items": { "type": "object", "additionalProperties": false, - "required": [ "name", "description" ], + "required": ["name", "description"], "properties": { "name": { "title": "Name of Alternative", @@ -335,10 +328,7 @@ "type": "array", "items": { "type": "object", - "oneOf": [ - { "$ref": "#/definitions/bulkCommand" }, - { "$ref": "#/definitions/globalCommand" } - ] + "oneOf": [{ "$ref": "#/definitions/bulkCommand" }, { "$ref": "#/definitions/globalCommand" }] } }, diff --git a/apps/rush-lib/src/schemas/deploy-scenario.schema.json b/apps/rush-lib/src/schemas/deploy-scenario.schema.json index 70c46040967..525c0b84d3d 100644 --- a/apps/rush-lib/src/schemas/deploy-scenario.schema.json +++ b/apps/rush-lib/src/schemas/deploy-scenario.schema.json @@ -21,7 +21,7 @@ "enableSubdeployments": { "description": "Subdeployments are an optional feature that enables multiple deployments to be processed with a single invocation of \"rush deploy\". In this mode, more than one item can be specified for \"deploymentProjectNames\". For each item, a subdeployment folder will be created under the \"rush deploy\" target folder. (The folder name can be customized using the \"subdeploymentFolderName\" project setting.) Each subdeployment folder will receive its own copy of the named project and its associated dependencies. The default value is false.", - "type": "boolean", + "type": "boolean" }, "includeDevDependencies": { @@ -37,7 +37,7 @@ "linkCreation": { "description": "Specify how links (symbolic links, hard links, and/or NTFS junctions) will be created in the deployed folder:\n\"default\": Create the links while copying the files; this is the default behavior.\n\"script\": A Node.js script called \"create-links.js\" will be written. When executed, this script will create the links described in the \"deploy-metadata.json\" output file.\n\"none\": Do nothing; some other tool may create the links later.", "type": "string", - "enum": [ "default", "script", "none" ] + "enum": ["default", "script", "none"] }, "projectSettings": { @@ -62,11 +62,11 @@ } } }, - "required": [ "projectName" ], + "required": ["projectName"], "additionalProperties": false } } }, - "required": [ "deploymentProjectNames" ], + "required": ["deploymentProjectNames"], "additionalProperties": false } diff --git a/apps/rush-lib/src/schemas/rush.schema.json b/apps/rush-lib/src/schemas/rush.schema.json index e09d90bb39e..2637f0872c1 100644 --- a/apps/rush-lib/src/schemas/rush.schema.json +++ b/apps/rush-lib/src/schemas/rush.schema.json @@ -89,10 +89,7 @@ "pnpmStore": { "description": "Specifies the location of the PNPM store. There are two possible values:\n\n\"local\" - use the \"pnpm-store\" folder in the current configured temp folder: \"common/temp/pnpm-store\" by default.\n\"global\" - use PNPM's global store, which has the benefit of being shared across multiple repo folders, but the disadvantage of less isolation for builds (e.g. bugs or incompatibilities when two repos use different releases of PNPM)\n\nIn all cases, the store path will be overridden by the environment variable RUSH_PNPM_STORE_PATH.\n\nThe default value is \"local\".", "type": "string", - "enum": [ - "local", - "global" - ] + "enum": ["local", "global"] }, "strictPeerDependencies": { "description": "If true, then Rush will add the \"--strict-peer-dependencies\" option when invoking PNPM. This causes \"rush install\" to fail if there are unsatisfied peer dependencies, which is an invalid state that can cause build failures or incompatible dependency versions. (For historical reasons, JavaScript package managers generally do not treat this invalid state as an error.) The default value is false.", @@ -101,10 +98,7 @@ "resolutionStrategy": { "description": "Configures the strategy used to select versions during installation. This feature requires PNPM version 3.1 or newer. It corresponds to the \"--resolution-strategy\" command-line option for PNPM. Possible values are \"fast\" and \"fewer-dependencies\". PNPM's default is \"fast\", but this may be incompatible with certain packages, for example the \"@types\" packages from DefinitelyTyped. Rush's default is \"fewer-dependencies\", which causes PNPM to avoid installing a newer version if an already installed version can be reused; this is more similar to NPM's algorithm.", "type": "string", - "enum": [ - "fewer-dependencies", - "fast" - ] + "enum": ["fewer-dependencies", "fast"] }, "environmentVariables": { "$ref": "#/definitions/environmentVariables" @@ -197,10 +191,7 @@ "type": "string" } }, - "required": [ - "variantName", - "description" - ] + "required": ["variantName", "description"] } }, "repository": { @@ -265,10 +256,7 @@ } }, "additionalProperties": false, - "required": [ - "packageName", - "projectFolder" - ] + "required": ["packageName", "projectFolder"] } }, "eventHooks": { @@ -308,8 +296,5 @@ } }, "additionalProperties": false, - "required": [ - "rushVersion", - "projects" - ] + "required": ["rushVersion", "projects"] } diff --git a/apps/rush-lib/src/schemas/version-policies.schema.json b/apps/rush-lib/src/schemas/version-policies.schema.json index eb18426c7a7..b3aabf0428f 100644 --- a/apps/rush-lib/src/schemas/version-policies.schema.json +++ b/apps/rush-lib/src/schemas/version-policies.schema.json @@ -8,10 +8,7 @@ "type": "object", "allOf": [ { - "oneOf": [ - { "$ref": "#/definitions/lockStepVersion" }, - { "$ref": "#/definitions/individualVersion" } - ] + "oneOf": [{ "$ref": "#/definitions/lockStepVersion" }, { "$ref": "#/definitions/individualVersion" }] }, { "type": "object", @@ -45,14 +42,7 @@ "definitions": { "any-value": { - "type": [ - "array", - "boolean", - "integer", - "number", - "object", - "string" - ], + "type": ["array", "boolean", "integer", "number", "object", "string"], "items": { "$ref": "#/definitions/any-value" } diff --git a/apps/rush-lib/src/scripts/create-links.ts b/apps/rush-lib/src/scripts/create-links.ts index 60dc2bfd074..510c456550e 100644 --- a/apps/rush-lib/src/scripts/create-links.ts +++ b/apps/rush-lib/src/scripts/create-links.ts @@ -5,8 +5,8 @@ import * as fs from 'fs'; import * as path from 'path'; -import /* type */ { IDeployMetadataJson } from '../logic/deploy/DeployManager'; -import /* type */ { IFileSystemCreateLinkOptions } from '@rushstack/node-core-library'; +import { /* type */ IDeployMetadataJson } from '../logic/deploy/DeployManager'; +import { /* type */ IFileSystemCreateLinkOptions } from '@rushstack/node-core-library'; // API borrowed from @rushstack/node-core-library, since this script avoids using any // NPM dependencies. @@ -113,7 +113,6 @@ function main(): boolean { const deployMetadataJson: string = fs.readFileSync(deployMetadataPath).toString(); const deployMetadataObject: IDeployMetadataJson = JSON.parse(deployMetadataJson); - if (args[0] === 'create') { console.log(`\nCreating links for deployment scenario "${deployMetadataObject.scenarioName}"`); removeLinks(targetSubdeploymentFolder, deployMetadataObject); diff --git a/apps/rush-lib/src/scripts/install-run-rush.ts b/apps/rush-lib/src/scripts/install-run-rush.ts index 643f408cfdd..541b2e6bb96 100644 --- a/apps/rush-lib/src/scripts/install-run-rush.ts +++ b/apps/rush-lib/src/scripts/install-run-rush.ts @@ -19,7 +19,7 @@ import { installAndRun, findRushJsonFolder, RUSH_JSON_FILENAME, - runWithErrorAndStatusCode + runWithErrorAndStatusCode, } from './install-run'; const PACKAGE_NAME: string = '@microsoft/rush'; @@ -38,21 +38,23 @@ function _getRushVersion(): string { const rushJsonContents: string = fs.readFileSync(rushJsonPath, 'utf-8'); // Use a regular expression to parse out the rushVersion value because rush.json supports comments, // but JSON.parse does not and we don't want to pull in more dependencies than we need to in this script. - const rushJsonMatches: string[] = rushJsonContents.match(/\"rushVersion\"\s*\:\s*\"([0-9a-zA-Z.+\-]+)\"/)!; + const rushJsonMatches: string[] = rushJsonContents.match( + /\"rushVersion\"\s*\:\s*\"([0-9a-zA-Z.+\-]+)\"/ + )!; return rushJsonMatches[1]; } catch (e) { throw new Error( `Unable to determine the required version of Rush from rush.json (${rushJsonFolder}). ` + - 'The \'rushVersion\' field is either not assigned in rush.json or was specified ' + - 'using an unexpected syntax.' + "The 'rushVersion' field is either not assigned in rush.json or was specified " + + 'using an unexpected syntax.' ); } } function _run(): void { const [ - nodePath, /* Ex: /bin/node */ - scriptPath, /* /repo/common/scripts/install-run-rush.js */ + nodePath /* Ex: /bin/node */, + scriptPath /* /repo/common/scripts/install-run-rush.js */, ...packageBinArgs /* [build, --to, myproject] */ ]: string[] = process.argv; diff --git a/apps/rush-lib/src/scripts/install-run.ts b/apps/rush-lib/src/scripts/install-run.ts index a11ae9645d1..c3c6f588b3a 100644 --- a/apps/rush-lib/src/scripts/install-run.ts +++ b/apps/rush-lib/src/scripts/install-run.ts @@ -105,7 +105,10 @@ function _copyAndTrimNpmrcFile(sourceNpmrcPath: string, targetNpmrcPath: string) * IMPORTANT: THIS CODE SHOULD BE KEPT UP TO DATE WITH Utilities._syncNpmrc() */ function _syncNpmrc(sourceNpmrcFolder: string, targetNpmrcFolder: string, useNpmrcPublish?: boolean): void { - const sourceNpmrcPath: string = path.join(sourceNpmrcFolder, !useNpmrcPublish ? '.npmrc' : '.npmrc-publish'); + const sourceNpmrcPath: string = path.join( + sourceNpmrcFolder, + !useNpmrcPublish ? '.npmrc' : '.npmrc-publish' + ); const targetNpmrcPath: string = path.join(targetNpmrcFolder, '.npmrc'); try { if (fs.existsSync(sourceNpmrcPath)) { @@ -178,7 +181,9 @@ function _ensureAndJoinPath(baseFolder: string, ...pathSegments: string[]): stri } } } catch (e) { - throw new Error(`Error building local installation folder (${path.join(baseFolder, ...pathSegments)}): ${e}`); + throw new Error( + `Error building local installation folder (${path.join(baseFolder, ...pathSegments)}): ${e}` + ); } return joinedPath; @@ -232,7 +237,7 @@ function _resolvePackageVersion(rushCommonFolder: string, { name, version }: IPa ['view', `${name}@${version}`, 'version', '--no-update-notifier'], { cwd: rushTempFolder, - stdio: [] + stdio: [], } ); @@ -322,15 +327,9 @@ function _cleanInstallFolder(rushTempFolder: string, packageInstallFolder: strin const nodeModulesFolder: string = path.resolve(packageInstallFolder, NODE_MODULES_FOLDER_NAME); if (fs.existsSync(nodeModulesFolder)) { - const rushRecyclerFolder: string = _ensureAndJoinPath( - rushTempFolder, - 'rush-recycler' - ); + const rushRecyclerFolder: string = _ensureAndJoinPath(rushTempFolder, 'rush-recycler'); - fs.renameSync( - nodeModulesFolder, - path.join(rushRecyclerFolder, `install-run-${Date.now().toString()}`) - ); + fs.renameSync(nodeModulesFolder, path.join(rushRecyclerFolder, `install-run-${Date.now().toString()}`)); } } catch (e) { throw new Error(`Error cleaning the package install folder (${packageInstallFolder}): ${e}`); @@ -340,14 +339,14 @@ function _cleanInstallFolder(rushTempFolder: string, packageInstallFolder: strin function _createPackageJson(packageInstallFolder: string, name: string, version: string): void { try { const packageJsonContents: IPackageJson = { - 'name': 'ci-rush', - 'version': '0.0.0', - 'dependencies': { - [name]: version + name: 'ci-rush', + version: '0.0.0', + dependencies: { + [name]: version, }, - 'description': 'DON\'T WARN', - 'repository': 'DON\'T WARN', - 'license': 'MIT' + description: "DON'T WARN", + repository: "DON'T WARN", + license: 'MIT', }; const packageJsonPath: string = path.join(packageInstallFolder, PACKAGE_JSON_FILENAME); @@ -364,15 +363,11 @@ function _installPackage(packageInstallFolder: string, name: string, version: st try { console.log(`Installing ${name}...`); const npmPath: string = getNpmPath(); - const result: childProcess.SpawnSyncReturns = childProcess.spawnSync( - npmPath, - ['install'], - { - stdio: 'inherit', - cwd: packageInstallFolder, - env: process.env - } - ); + const result: childProcess.SpawnSyncReturns = childProcess.spawnSync(npmPath, ['install'], { + stdio: 'inherit', + cwd: packageInstallFolder, + env: process.env, + }); if (result.status !== 0) { throw new Error('"npm install" encountered an error'); @@ -389,7 +384,7 @@ function _installPackage(packageInstallFolder: string, name: string, version: st */ function _getBinPath(packageInstallFolder: string, binName: string): string { const binFolderPath: string = path.resolve(packageInstallFolder, NODE_MODULES_FOLDER_NAME, '.bin'); - const resolvedBinName: string = (os.platform() === 'win32') ? `${binName}.cmd` : binName; + const resolvedBinName: string = os.platform() === 'win32' ? `${binName}.cmd` : binName; return path.resolve(binFolderPath, resolvedBinName); } @@ -438,18 +433,14 @@ export function installAndRun( const binPath: string = _getBinPath(packageInstallFolder, packageBinName); const binFolderPath: string = path.resolve(packageInstallFolder, NODE_MODULES_FOLDER_NAME, '.bin'); - const result: childProcess.SpawnSyncReturns = childProcess.spawnSync( - binPath, - packageBinArgs, - { - stdio: 'inherit', - cwd: process.cwd(), - env: { - ...process.env, - PATH: [binFolderPath, process.env.PATH].join(path.delimiter) - } - } - ); + const result: childProcess.SpawnSyncReturns = childProcess.spawnSync(binPath, packageBinArgs, { + stdio: 'inherit', + cwd: process.cwd(), + env: { + ...process.env, + PATH: [binFolderPath, process.env.PATH].join(path.delimiter), + }, + }); if (result.status !== null) { return result.status; @@ -471,10 +462,10 @@ export function runWithErrorAndStatusCode(fn: () => number): void { function _run(): void { const [ - nodePath, /* Ex: /bin/node */ - scriptPath, /* /repo/common/scripts/install-run-rush.js */ - rawPackageSpecifier, /* qrcode@^1.2.0 */ - packageBinName, /* qrcode */ + nodePath /* Ex: /bin/node */, + scriptPath /* /repo/common/scripts/install-run-rush.js */, + rawPackageSpecifier /* qrcode@^1.2.0 */, + packageBinName /* qrcode */, ...packageBinArgs /* [-f, myproject/lib] */ ]: string[] = process.argv; diff --git a/apps/rush-lib/src/utilities/AlreadyReportedError.ts b/apps/rush-lib/src/utilities/AlreadyReportedError.ts index 062fb6f8643..e87f9e95f2b 100644 --- a/apps/rush-lib/src/utilities/AlreadyReportedError.ts +++ b/apps/rush-lib/src/utilities/AlreadyReportedError.ts @@ -7,7 +7,6 @@ * block should not print any error. */ export class AlreadyReportedError extends Error { - public constructor() { super('An error occurred.'); diff --git a/apps/rush-lib/src/utilities/AsyncRecycler.ts b/apps/rush-lib/src/utilities/AsyncRecycler.ts index 579694c8459..ca7a02532a9 100644 --- a/apps/rush-lib/src/utilities/AsyncRecycler.ts +++ b/apps/rush-lib/src/utilities/AsyncRecycler.ts @@ -6,11 +6,7 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { - Text, - Path, - FileSystem -} from '@rushstack/node-core-library'; +import { Text, Path, FileSystem } from '@rushstack/node-core-library'; import { Utilities } from './Utilities'; @@ -75,8 +71,11 @@ export class AsyncRecycler { Utilities.retryUntilTimeout( () => FileSystem.move({ sourcePath: folderPath, destinationPath: newFolderPath }), maxWaitTimeMs, - (e) => new Error(`Error: ${e}${os.EOL}Often this is caused by a file lock ` + - 'from a process like the virus scanner.'), + (e) => + new Error( + `Error: ${e}${os.EOL}Often this is caused by a file lock ` + + 'from a process like the virus scanner.' + ), 'recycleFolder' ); } @@ -89,9 +88,7 @@ export class AsyncRecycler { public moveAllItemsInFolder(folderPath: string, membersToExclude?: ReadonlyArray): void { const resolvedFolderPath: string = path.resolve(folderPath); - const excludeSet: Set = new Set( - (membersToExclude || []).map(x => x.toUpperCase()) - ); + const excludeSet: Set = new Set((membersToExclude || []).map((x) => x.toUpperCase())); for (const memberPath of FileSystem.readFolder(resolvedFolderPath, { absolutePaths: true })) { const normalizedMemberName: string = path.basename(memberPath).toUpperCase(); @@ -138,7 +135,7 @@ export class AsyncRecycler { const options: child_process.SpawnOptions = { detached: true, // The child won't stay alive unless we detach its stdio - stdio: 'ignore' + stdio: 'ignore', }; if (os.platform() === 'win32') { @@ -147,24 +144,24 @@ export class AsyncRecycler { command = 'cmd.exe'; // In PowerShell single-quote literals, single quotes are escaped by doubling them - const escapedRecyclerFolder: string = Text.replaceAll(this.recyclerFolder, '\'', '\'\''); + const escapedRecyclerFolder: string = Text.replaceAll(this.recyclerFolder, "'", "''"); // As of PowerShell 3.0, the "\\?" prefix can be used for paths that exceed MAX_PATH. // (This prefix does not seem to work for cmd.exe's "rd" command.) args = [ '/c', '"' + - 'PowerShell.exe -Version 3.0 -NoLogo -NonInteractive -WindowStyle Hidden -Command' - + ` Get-ChildItem -Force '${escapedRecyclerFolder}'` + 'PowerShell.exe -Version 3.0 -NoLogo -NonInteractive -WindowStyle Hidden -Command' + + ` Get-ChildItem -Force '${escapedRecyclerFolder}'` + // The "^|" here prevents cmd.exe from interpreting the "|" symbol - + ` ^| ForEach ($_) { Remove-Item -ErrorAction Ignore -Force -Recurse "\\\\?\\$($_.FullName)" }` - + '"' + ` ^| ForEach ($_) { Remove-Item -ErrorAction Ignore -Force -Recurse "\\\\?\\$($_.FullName)" }` + + '"', ]; options.windowsVerbatimArguments = true; } else { command = 'rm'; - args = [ '-rf' ]; + args = ['-rf']; let pathCount: number = 0; @@ -189,5 +186,4 @@ export class AsyncRecycler { // The child won't stay alive unless we unlink it from the parent process process.unref(); } - } diff --git a/apps/rush-lib/src/utilities/Npm.ts b/apps/rush-lib/src/utilities/Npm.ts index 5d3cb8aaed5..3e10352abfe 100644 --- a/apps/rush-lib/src/utilities/Npm.ts +++ b/apps/rush-lib/src/utilities/Npm.ts @@ -13,14 +13,15 @@ export class Npm { ): string[] { const versions: string[] = []; try { - const packageTime: string = Utilities.executeCommandAndCaptureOutput('npm', + const packageTime: string = Utilities.executeCommandAndCaptureOutput( + 'npm', ['view', packageName, 'time', '--json', ...extraArgs], cwd, env, true ); if (packageTime && packageTime !== '') { - Object.keys(JSON.parse(packageTime)).forEach(v => { + Object.keys(JSON.parse(packageTime)).forEach((v) => { if (semver.valid(v)) { versions.push(v); } @@ -28,14 +29,15 @@ export class Npm { } else { console.log(`Package ${packageName} time value does not exist. Fall back to versions.`); // time property does not exist. It happens sometimes. Fall back to versions. - const packageVersions: string = Utilities.executeCommandAndCaptureOutput('npm', + const packageVersions: string = Utilities.executeCommandAndCaptureOutput( + 'npm', ['view', packageName, 'versions', '--json', ...extraArgs], cwd, env, true ); if (packageVersions && packageVersions.length > 0) { - (JSON.parse(packageVersions)).forEach(v => { + JSON.parse(packageVersions).forEach((v) => { versions.push(v); }); } else { diff --git a/apps/rush-lib/src/utilities/Stopwatch.ts b/apps/rush-lib/src/utilities/Stopwatch.ts index d31fd754768..359837775e3 100644 --- a/apps/rush-lib/src/utilities/Stopwatch.ts +++ b/apps/rush-lib/src/utilities/Stopwatch.ts @@ -8,7 +8,7 @@ import { Utilities } from './Utilities'; */ export enum StopwatchState { Stopped = 1, - Started = 2 + Started = 2, } /** @@ -36,7 +36,7 @@ export class Stopwatch { return new Stopwatch().start(); } - public get state(): StopwatchState { + public get state(): StopwatchState { return this._state; } @@ -58,7 +58,7 @@ export class Stopwatch { * Stops executing the stopwatch and saves the current timestamp */ public stop(): Stopwatch { - this._endTime = (this._startTime !== undefined ? this._getTime() : undefined); + this._endTime = this._startTime !== undefined ? this._getTime() : undefined; this._state = StopwatchState.Stopped; return this; } @@ -85,8 +85,7 @@ export class Stopwatch { const minutes: number = Math.floor(totalSeconds / 60); const seconds: number = totalSeconds % 60.0; - return `${minutes.toFixed(0)} minute${minutes === 1 ? '' : 's'}` + - ` ${seconds.toFixed(1)} seconds`; + return `${minutes.toFixed(0)} minute${minutes === 1 ? '' : 's'}` + ` ${seconds.toFixed(1)} seconds`; } else { return `${totalSeconds.toFixed(2)} seconds`; } @@ -99,10 +98,8 @@ export class Stopwatch { if (this._startTime === undefined) { return 0; } - const curTime: number = this._endTime !== undefined - ? this._endTime - : this._getTime(); + const curTime: number = this._endTime !== undefined ? this._endTime : this._getTime(); - return ((curTime - this._startTime) / 1000.0); + return (curTime - this._startTime) / 1000.0; } } diff --git a/apps/rush-lib/src/utilities/Utilities.ts b/apps/rush-lib/src/utilities/Utilities.ts index 41abb827dee..adfac550ca8 100644 --- a/apps/rush-lib/src/utilities/Utilities.ts +++ b/apps/rush-lib/src/utilities/Utilities.ts @@ -7,12 +7,7 @@ import * as os from 'os'; import * as tty from 'tty'; import * as path from 'path'; import * as wordwrap from 'wordwrap'; -import { - JsonFile, - IPackageJson, - FileSystem, - FileConstants -} from '@rushstack/node-core-library'; +import { JsonFile, IPackageJson, FileSystem, FileConstants } from '@rushstack/node-core-library'; import { RushConfiguration } from '../api/RushConfiguration'; import { Stream } from 'stream'; @@ -105,10 +100,9 @@ export class Utilities { * this looks something like "/usr/username/" */ public static getHomeDirectory(): string { - const unresolvedUserFolder: string | undefined = process.env[ - (process.platform === 'win32') ? 'USERPROFILE' : 'HOME' - ]; - const dirError: string = 'Unable to determine the current user\'s home directory'; + const unresolvedUserFolder: string | undefined = + process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME']; + const dirError: string = "Unable to determine the current user's home directory"; if (unresolvedUserFolder === undefined) { throw new Error(dirError); } @@ -200,11 +194,12 @@ export class Utilities { return Utilities.retryUntilTimeout( () => FileSystem.ensureFolder(folderName), maxWaitTimeMs, - (e) => new Error( - `Error: ${e}${os.EOL}Often this is caused by a file lock ` + - 'from a process such as your text editor, command prompt, ' + - 'or a filesystem watcher.' - ), + (e) => + new Error( + `Error: ${e}${os.EOL}Often this is caused by a file lock ` + + 'from a process such as your text editor, command prompt, ' + + 'or a filesystem watcher.' + ), 'createFolderWithRetry' ); } @@ -218,7 +213,9 @@ export class Utilities { try { const lstat: fs.Stats = FileSystem.getLinkStatistics(filePath); exists = lstat.isFile(); - } catch (e) { /* no-op */ } + } catch (e) { + /* no-op */ + } return exists; } @@ -232,7 +229,9 @@ export class Utilities { try { const lstat: fs.Stats = FileSystem.getLinkStatistics(directoryPath); exists = lstat.isDirectory(); - } catch (e) { /* no-op */ } + } catch (e) { + /* no-op */ + } return exists; } @@ -248,7 +247,7 @@ export class Utilities { } catch (e) { throw new Error( `${e.message}${os.EOL}Often this is caused by a file lock from a process ` + - 'such as your text editor, command prompt, or a filesystem watcher' + 'such as your text editor, command prompt, or a filesystem watcher' ); } } @@ -322,12 +321,18 @@ export class Utilities { * Executes the command with the specified command-line parameters, and waits for it to complete. * The current directory will be set to the specified workingDirectory. */ - public static executeCommand(command: string, args: string[], workingDirectory: string, - environment?: IEnvironment, suppressOutput: boolean = false, + public static executeCommand( + command: string, + args: string[], + workingDirectory: string, + environment?: IEnvironment, + suppressOutput: boolean = false, keepEnvironment: boolean = false ): void { - - Utilities._executeCommandInternal(command, args, workingDirectory, + Utilities._executeCommandInternal( + command, + args, + workingDirectory, suppressOutput ? undefined : [0, 1, 2], environment, keepEnvironment @@ -338,12 +343,14 @@ export class Utilities { * Executes the command with the specified command-line parameters, and waits for it to complete. * The current directory will be set to the specified workingDirectory. */ - public static executeCommandAndCaptureOutput(command: string, args: string[], workingDirectory: string, + public static executeCommandAndCaptureOutput( + command: string, + args: string[], + workingDirectory: string, environment?: IEnvironment, keepEnvironment: boolean = false ): string { - - const result: child_process.SpawnSyncReturns = Utilities._executeCommandInternal( + const result: child_process.SpawnSyncReturns = Utilities._executeCommandInternal( command, args, workingDirectory, @@ -358,10 +365,15 @@ export class Utilities { /** * Attempts to run Utilities.executeCommand() up to maxAttempts times before giving up. */ - public static executeCommandWithRetry(maxAttempts: number, command: string, args: string[], - workingDirectory: string, environment?: IEnvironment, suppressOutput: boolean = false, - retryCallback?: () => void): void { - + public static executeCommandWithRetry( + maxAttempts: number, + command: string, + args: string[], + workingDirectory: string, + environment?: IEnvironment, + suppressOutput: boolean = false, + retryCallback?: () => void + ): void { if (maxAttempts < 1) { throw new Error('The maxAttempts parameter cannot be less than 1'); } @@ -399,10 +411,7 @@ export class Utilities { * @param command - the command to run on shell * @param options - options for how the command should be run */ - public static executeLifecycleCommand( - command: string, - options: ILifecycleCommandOptions - ): number { + public static executeLifecycleCommand(command: string, options: ILifecycleCommandOptions): number { const result: child_process.SpawnSyncReturns = Utilities._executeLifecycleCommandInternal( command, child_process.spawnSync, @@ -429,11 +438,7 @@ export class Utilities { command: string, options: ILifecycleCommandOptions ): child_process.ChildProcess { - return Utilities._executeLifecycleCommandInternal( - command, - child_process.spawn, - options - ); + return Utilities._executeLifecycleCommandInternal(command, child_process.spawn, options); } /** @@ -459,12 +464,12 @@ export class Utilities { const npmPackageJson: IPackageJson = { dependencies: { - [options.packageName]: options.version + [options.packageName]: options.version, }, description: 'Temporary file generated by the Rush tool', name: options.tempPackageTitle, private: true, - version: '0.0.0' + version: '0.0.0', }; JsonFile.save(npmPackageJson, path.join(directory, FileConstants.PackageJson)); @@ -485,22 +490,24 @@ export class Utilities { ); } - public static withFinally(options: { promise: Promise, finally: () => void }): Promise { - return options.promise.then((result: T) => { - try { - options.finally(); - } catch (error) { + public static withFinally(options: { promise: Promise; finally: () => void }): Promise { + return options.promise + .then((result: T) => { + try { + options.finally(); + } catch (error) { + return Promise.reject(error); + } + return result; + }) + .catch((error: Error) => { + try { + options.finally(); + } catch (innerError) { + return Promise.reject(innerError); + } return Promise.reject(error); - } - return result; - }).catch((error: Error) => { - try { - options.finally(); - } catch (innerError) { - return Promise.reject(innerError); - } - return Promise.reject(error); - }); + }); } /** @@ -556,8 +563,15 @@ export class Utilities { * * IMPORTANT: THIS CODE SHOULD BE KEPT UP TO DATE WITH _syncNpmrc() FROM scripts/install-run.ts */ - public static syncNpmrc(sourceNpmrcFolder: string, targetNpmrcFolder: string, useNpmrcPublish?: boolean): void { - const sourceNpmrcPath: string = path.join(sourceNpmrcFolder, !useNpmrcPublish ? '.npmrc' : '.npmrc-publish'); + public static syncNpmrc( + sourceNpmrcFolder: string, + targetNpmrcFolder: string, + useNpmrcPublish?: boolean + ): void { + const sourceNpmrcPath: string = path.join( + sourceNpmrcFolder, + !useNpmrcPublish ? '.npmrc' : '.npmrc-publish' + ); const targetNpmrcPath: string = path.join(targetNpmrcFolder, '.npmrc'); try { if (FileSystem.exists(sourceNpmrcPath)) { @@ -582,7 +596,11 @@ export class Utilities { private static _executeLifecycleCommandInternal( command: string, - spawnFunction: (command: string, args: string[], spawnOptions: child_process.SpawnOptions) => TCommandResult, + spawnFunction: ( + command: string, + args: string[], + spawnOptions: child_process.SpawnOptions + ) => TCommandResult, options: ILifecycleCommandOptions ): TCommandResult { let shellCommand: string = process.env.comspec || 'cmd'; @@ -594,34 +612,30 @@ export class Utilities { useShell = false; } - const environment: IEnvironment = Utilities._createEnvironmentForRushCommand( - { - initCwd: options.initCwd, - pathOptions: { - ...options.environmentPathOptions, - projectRoot: options.workingDirectory, - commonTempFolder: options.rushConfiguration ? options.rushConfiguration.commonTempFolder : undefined - } - } - ); + const environment: IEnvironment = Utilities._createEnvironmentForRushCommand({ + initCwd: options.initCwd, + pathOptions: { + ...options.environmentPathOptions, + projectRoot: options.workingDirectory, + commonTempFolder: options.rushConfiguration ? options.rushConfiguration.commonTempFolder : undefined, + }, + }); - return spawnFunction( - shellCommand, - [commandFlags, command], - { - cwd: options.workingDirectory, - shell: useShell, - env: environment, - stdio: options.handleOutput ? ['pipe', 'pipe', 'pipe'] : [0, 1, 2] - } - ); + return spawnFunction(shellCommand, [commandFlags, command], { + cwd: options.workingDirectory, + shell: useShell, + env: environment, + stdio: options.handleOutput ? ['pipe', 'pipe', 'pipe'] : [0, 1, 2], + }); } /** * Returns a process.env environment suitable for executing lifecycle scripts. * @param initialEnvironment - an existing environment to copy instead of process.env */ - private static _createEnvironmentForRushCommand(options: ICreateEnvironmentForRushCommandOptions): IEnvironment { + private static _createEnvironmentForRushCommand( + options: ICreateEnvironmentForRushCommandOptions + ): IEnvironment { if (options.initialEnvironment === undefined) { options.initialEnvironment = process.env; } @@ -686,7 +700,10 @@ export class Utilities { * if `rootDirectory` is "/foobar" and `existingPath` is "/bin", this function will return * "/foobar/node_modules/.bin:/bin" */ - private static _prependNodeModulesBinToPath(existingPath: string | undefined, rootDirectory: string): string { + private static _prependNodeModulesBinToPath( + existingPath: string | undefined, + rootDirectory: string + ): string { const binPath: string = path.resolve(rootDirectory, 'node_modules', '.bin'); if (existingPath) { return `${binPath}${path.delimiter}${existingPath}`; @@ -700,8 +717,15 @@ export class Utilities { * The current directory will be set to the specified workingDirectory. */ private static _executeCommandInternal( - command: string, args: string[], workingDirectory: string, - stdio: 'pipe'|'ignore'|'inherit'|(number|'pipe'|'ignore'|'inherit'|'ipc'|Stream|null|undefined)[]|undefined, + command: string, + args: string[], + workingDirectory: string, + stdio: + | 'pipe' + | 'ignore' + | 'inherit' + | (number | 'pipe' | 'ignore' | 'inherit' | 'ipc' | Stream | null | undefined)[] + | undefined, environment?: IEnvironment, keepEnvironment: boolean = false ): child_process.SpawnSyncReturns { @@ -711,7 +735,7 @@ export class Utilities { stdio: stdio, env: keepEnvironment ? environment - : Utilities._createEnvironmentForRushCommand({ initialEnvironment: environment }) + : Utilities._createEnvironmentForRushCommand({ initialEnvironment: environment }), }; // This is needed since we specify shell=true below. @@ -727,16 +751,19 @@ export class Utilities { // into node-core-library, but for now this hack will unblock people: // Only escape the command if it actually contains spaces: - const escapedCommand: string = command.indexOf(' ') < 0 - ? command - : Utilities.escapeShellParameter(command); + const escapedCommand: string = + command.indexOf(' ') < 0 ? command : Utilities.escapeShellParameter(command); const escapedArgs: string[] = args.map((x) => Utilities.escapeShellParameter(x)); - let result: child_process.SpawnSyncReturns = child_process.spawnSync(escapedCommand, - escapedArgs, options); + let result: child_process.SpawnSyncReturns = child_process.spawnSync( + escapedCommand, + escapedArgs, + options + ); - if (result.error && (result.error as any).errno === 'ENOENT') { // eslint-disable-line @typescript-eslint/no-explicit-any + if (result.error && (result.error as any).errno === 'ENOENT') { + // eslint-disable-line @typescript-eslint/no-explicit-any // This is a workaround for GitHub issue #25330 // https://github.com/nodejs/node-v0.x-archive/issues/25330 result = child_process.spawnSync(command + '.cmd', args, options); @@ -753,8 +780,12 @@ export class Utilities { } if (result.status) { - throw new Error('The command failed with exit code ' + result.status + os.EOL + - (result.stderr ? result.stderr.toString() : '')); + throw new Error( + 'The command failed with exit code ' + + result.status + + os.EOL + + (result.stderr ? result.stderr.toString() : '') + ); } } } diff --git a/apps/rush-lib/src/utilities/VersionControl.ts b/apps/rush-lib/src/utilities/VersionControl.ts index 8b6fb368969..154ee64068a 100644 --- a/apps/rush-lib/src/utilities/VersionControl.ts +++ b/apps/rush-lib/src/utilities/VersionControl.ts @@ -3,18 +3,15 @@ import * as child_process from 'child_process'; import * as colors from 'colors'; -import { - Executable, - Path -} from '@rushstack/node-core-library'; +import { Executable, Path } from '@rushstack/node-core-library'; import { RushConfiguration } from '../api/RushConfiguration'; export class VersionControl { public static getRepositoryRootPath(): string | undefined { - const output: child_process.SpawnSyncReturns = Executable.spawnSync( - 'git', - ['rev-parse', '--show-toplevel'] - ); + const output: child_process.SpawnSyncReturns = Executable.spawnSync('git', [ + 'rev-parse', + '--show-toplevel', + ]); if (output.status !== 0) { return undefined; @@ -51,26 +48,33 @@ export class VersionControl { * those in the provided {@param targetBranch}. If a {@param pathPrefix} is provided, * this function only returns results under the that path. */ - public static getChangedFiles(targetBranch: string, skipFetch: boolean = false, pathPrefix?: string): string[] { + public static getChangedFiles( + targetBranch: string, + skipFetch: boolean = false, + pathPrefix?: string + ): string[] { if (!skipFetch) { VersionControl._fetchRemoteBranch(targetBranch); } - const output: string = child_process.execSync( - `git diff ${targetBranch}... --name-only --no-renames --diff-filter=A` - ).toString(); - return output.split('\n').map((line) => { - if (line) { - const trimmedLine: string = line.trim(); - if (!pathPrefix || Path.isUnderOrEqual(trimmedLine, pathPrefix)) { - return trimmedLine; + const output: string = child_process + .execSync(`git diff ${targetBranch}... --name-only --no-renames --diff-filter=A`) + .toString(); + return output + .split('\n') + .map((line) => { + if (line) { + const trimmedLine: string = line.trim(); + if (!pathPrefix || Path.isUnderOrEqual(trimmedLine, pathPrefix)) { + return trimmedLine; + } + } else { + return undefined; } - } else { - return undefined; - } - }).filter((line) => { - return line && line.length > 0; - }) as string[]; + }) + .filter((line) => { + return line && line.length > 0; + }) as string[]; } /** @@ -84,13 +88,12 @@ export class VersionControl { */ public static getRemoteMasterBranch(rushConfiguration: RushConfiguration): string { if (rushConfiguration.repositoryUrl) { - const output: string = child_process - .execSync(`git remote`) - .toString(); + const output: string = child_process.execSync(`git remote`).toString(); const normalizedRepositoryUrl: string = rushConfiguration.repositoryUrl.toUpperCase(); const matchingRemotes: string[] = output.split('\n').filter((remoteName) => { if (remoteName) { - const remoteUrl: string = child_process.execSync(`git remote get-url ${remoteName}`) + const remoteUrl: string = child_process + .execSync(`git remote get-url ${remoteName}`) .toString() .trim(); @@ -123,17 +126,21 @@ export class VersionControl { return `${matchingRemotes[0]}/${rushConfiguration.repositoryDefaultBranch}`; } else { - console.log(colors.yellow( - `Unable to find a git remote matching the repository URL (${rushConfiguration.repositoryUrl}). ` + - 'Detected changes are likely to be incorrect.' - )); + console.log( + colors.yellow( + `Unable to find a git remote matching the repository URL (${rushConfiguration.repositoryUrl}). ` + + 'Detected changes are likely to be incorrect.' + ) + ); return rushConfiguration.repositoryDefaultFullyQualifiedRemoteBranch; } } else { - console.log(colors.yellow( - 'A git remote URL has not been specified in rush.json. Setting the baseline remote URL is recommended.' - )); + console.log( + colors.yellow( + 'A git remote URL has not been specified in rush.json. Setting the baseline remote URL is recommended.' + ) + ); return rushConfiguration.repositoryDefaultFullyQualifiedRemoteBranch; } } @@ -150,22 +157,18 @@ export class VersionControl { changes.push(...VersionControl._getUntrackedChanges()); changes.push(...VersionControl._getDiffOnHEAD()); - return changes.filter(change => { + return changes.filter((change) => { return change.trim().length > 0; }); } private static _getUntrackedChanges(): string[] { - const output: string = child_process - .execSync(`git ls-files --exclude-standard --others`) - .toString(); + const output: string = child_process.execSync(`git ls-files --exclude-standard --others`).toString(); return output.trim().split('\n'); } private static _getDiffOnHEAD(): string[] { - const output: string = child_process - .execSync(`git diff HEAD --name-only`) - .toString(); + const output: string = child_process.execSync(`git diff HEAD --name-only`).toString(); return output.trim().split('\n'); } @@ -174,7 +177,7 @@ export class VersionControl { if (firstSlashIndex === -1) { throw new Error( `Unexpected git remote branch format: ${remoteBranchName}. ` + - 'Expected branch to be in the / format.' + 'Expected branch to be in the / format.' ); } @@ -184,7 +187,7 @@ export class VersionControl { 'git', ['fetch', remoteName, branchName], { - stdio: 'ignore' + stdio: 'ignore', } ); return spawnResult.status === 0; @@ -194,9 +197,11 @@ export class VersionControl { console.log(`Checking for updates to ${remoteBranchName}...`); const fetchResult: boolean = VersionControl._tryFetchRemoteBranch(remoteBranchName); if (!fetchResult) { - console.log(colors.yellow( - `Error fetching git remote branch ${remoteBranchName}. Detected changed files may be incorrect.` - )); + console.log( + colors.yellow( + `Error fetching git remote branch ${remoteBranchName}. Detected changed files may be incorrect.` + ) + ); } } } diff --git a/apps/rush-lib/src/utilities/test/Npm.test.ts b/apps/rush-lib/src/utilities/test/Npm.test.ts index fc772147f39..d7ae4fa2f40 100644 --- a/apps/rush-lib/src/utilities/test/Npm.test.ts +++ b/apps/rush-lib/src/utilities/test/Npm.test.ts @@ -30,12 +30,15 @@ describe('npm', () => { }`; stub.mockImplementationOnce(() => json); - const versions: string[] = Npm.publishedVersions(packageName, - __dirname, - process.env); + const versions: string[] = Npm.publishedVersions(packageName, __dirname, process.env); - expect(stub).toHaveBeenCalledWith('npm', `view ${packageName} time --json`.split(' '), - expect.anything(), expect.anything(), expect.anything()); + expect(stub).toHaveBeenCalledWith( + 'npm', + `view ${packageName} time --json`.split(' '), + expect.anything(), + expect.anything(), + expect.anything() + ); expect(versions).toHaveLength(4); expect(versions).toMatchObject(['0.0.0', '1.4.0', '1.4.1', '2.4.0-alpha.1']); @@ -51,14 +54,22 @@ describe('npm', () => { stub.mockImplementationOnce(() => ''); stub.mockImplementationOnce(() => json); - const versions: string[] = Npm.publishedVersions(packageName, - __dirname, - process.env); + const versions: string[] = Npm.publishedVersions(packageName, __dirname, process.env); - expect(stub).toHaveBeenCalledWith('npm', `view ${packageName} time --json`.split(' '), - expect.anything(), expect.anything(), expect.anything()); - expect(stub).toHaveBeenCalledWith('npm', `view ${packageName} versions --json`.split(' '), - expect.anything(), expect.anything(), expect.anything()); + expect(stub).toHaveBeenCalledWith( + 'npm', + `view ${packageName} time --json`.split(' '), + expect.anything(), + expect.anything(), + expect.anything() + ); + expect(stub).toHaveBeenCalledWith( + 'npm', + `view ${packageName} versions --json`.split(' '), + expect.anything(), + expect.anything(), + expect.anything() + ); expect(versions).toHaveLength(4); expect(versions).toMatchObject(['0.0.0', '1.4.0', '1.4.1', '2.4.0-alpha.1']); diff --git a/apps/rush-lib/src/utilities/test/Stopwatch.test.ts b/apps/rush-lib/src/utilities/test/Stopwatch.test.ts index d370cc6485e..642213d7ca0 100644 --- a/apps/rush-lib/src/utilities/test/Stopwatch.test.ts +++ b/apps/rush-lib/src/utilities/test/Stopwatch.test.ts @@ -8,7 +8,7 @@ function pseudoTimeMilliseconds(times: number[]): () => number { } function pseudoTimeSeconds(times: number[]): () => number { - return pseudoTimeMilliseconds(times.map(time => time * 1000)); + return pseudoTimeMilliseconds(times.map((time) => time * 1000)); } describe('Stopwatch', () => { @@ -24,7 +24,7 @@ describe('Stopwatch', () => { done(); }); - it('can\'t start twice', (done: jest.DoneCallback) => { + it("can't start twice", (done: jest.DoneCallback) => { const watch: Stopwatch = new Stopwatch(); expect(() => { watch.start(); diff --git a/apps/rush-lib/tsconfig.json b/apps/rush-lib/tsconfig.json index 76f0d945025..8f1cbebe335 100644 --- a/apps/rush-lib/tsconfig.json +++ b/apps/rush-lib/tsconfig.json @@ -1,9 +1,6 @@ { "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "jest", - "node" - ] + "types": ["jest", "node"] } } diff --git a/apps/rush/.eslintrc.js b/apps/rush/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/apps/rush/.eslintrc.js +++ b/apps/rush/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/apps/rush/config/jest.json b/apps/rush/config/jest.json index b4a7ec97a56..902b00ea176 100644 --- a/apps/rush/config/jest.json +++ b/apps/rush/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": true -} \ No newline at end of file +} diff --git a/apps/rush/src/MinimalRushConfiguration.ts b/apps/rush/src/MinimalRushConfiguration.ts index e24ca989eed..f12cc016cca 100644 --- a/apps/rush/src/MinimalRushConfiguration.ts +++ b/apps/rush/src/MinimalRushConfiguration.ts @@ -21,13 +21,20 @@ export class MinimalRushConfiguration { private _commonRushConfigFolder: string; private constructor(minimalRushConfigurationJson: IMinimalRushConfigurationJson, rushJsonFilename: string) { - this._rushVersion = minimalRushConfigurationJson.rushVersion || minimalRushConfigurationJson.rushMinimumVersion; - this._commonRushConfigFolder = path.join(path.dirname(rushJsonFilename), - RushConstants.commonFolderName, 'config', 'rush'); + this._rushVersion = + minimalRushConfigurationJson.rushVersion || minimalRushConfigurationJson.rushMinimumVersion; + this._commonRushConfigFolder = path.join( + path.dirname(rushJsonFilename), + RushConstants.commonFolderName, + 'config', + 'rush' + ); } public static loadFromDefaultLocation(): MinimalRushConfiguration | undefined { - const rushJsonLocation: string | undefined = RushConfiguration.tryFindRushJsonLocation({ showVerbose: true }); + const rushJsonLocation: string | undefined = RushConfiguration.tryFindRushJsonLocation({ + showVerbose: true, + }); if (rushJsonLocation) { return MinimalRushConfiguration._loadFromConfigurationFile(rushJsonLocation); } else { diff --git a/apps/rush/src/RushCommandSelector.ts b/apps/rush/src/RushCommandSelector.ts index 9e076e161b3..c9068920a22 100644 --- a/apps/rush/src/RushCommandSelector.ts +++ b/apps/rush/src/RushCommandSelector.ts @@ -17,13 +17,18 @@ type CommandName = 'rush' | 'rushx' | undefined; export class RushCommandSelector { public static failIfNotInvokedAsRush(version: string): void { if (RushCommandSelector._getCommandName() === 'rushx') { - RushCommandSelector._failWithError(`This repository is using Rush version ${version}` - + ` which does not support the "rushx" command`); + RushCommandSelector._failWithError( + `This repository is using Rush version ${version}` + ` which does not support the "rushx" command` + ); } } // eslint-disable-next-line @typescript-eslint/no-explicit-any - public static execute(launcherVersion: string, selectedRushLib: any, options: rushLib.ILaunchOptions): void { + public static execute( + launcherVersion: string, + selectedRushLib: any, + options: rushLib.ILaunchOptions + ): void { const Rush: typeof rushLib.Rush = selectedRushLib.Rush; if (!Rush) { @@ -33,24 +38,20 @@ export class RushCommandSelector { if (RushCommandSelector._getCommandName() === 'rushx') { if (!Rush.launchRushX) { - RushCommandSelector._failWithError(`This repository is using Rush version ${Rush.version}` - + ` which does not support the "rushx" command`); + RushCommandSelector._failWithError( + `This repository is using Rush version ${Rush.version}` + + ` which does not support the "rushx" command` + ); } - Rush.launchRushX( - launcherVersion, - { - isManaged: options.isManaged, - alreadyReportedNodeTooNewError: options.alreadyReportedNodeTooNewError - } - ); + Rush.launchRushX(launcherVersion, { + isManaged: options.isManaged, + alreadyReportedNodeTooNewError: options.alreadyReportedNodeTooNewError, + }); } else { - Rush.launch( - launcherVersion, - { - isManaged: options.isManaged, - alreadyReportedNodeTooNewError: options.alreadyReportedNodeTooNewError - } - ); + Rush.launch(launcherVersion, { + isManaged: options.isManaged, + alreadyReportedNodeTooNewError: options.alreadyReportedNodeTooNewError, + }); } } diff --git a/apps/rush/src/RushVersionSelector.ts b/apps/rush/src/RushVersionSelector.ts index f0f69ed4d6e..8757dae27d1 100644 --- a/apps/rush/src/RushVersionSelector.ts +++ b/apps/rush/src/RushVersionSelector.ts @@ -6,11 +6,7 @@ import * as semver from 'semver'; import { LockFile } from '@rushstack/node-core-library'; import { Utilities } from '@microsoft/rush-lib/lib/utilities/Utilities'; -import { - _LastInstallFlag, - _RushGlobalFolder, - ILaunchOptions -} from '@microsoft/rush-lib'; +import { _LastInstallFlag, _RushGlobalFolder, ILaunchOptions } from '@microsoft/rush-lib'; import { RushCommandSelector } from './RushCommandSelector'; import { MinimalRushConfiguration } from './MinimalRushConfiguration'; @@ -31,14 +27,12 @@ export class RushVersionSelector { configuration: MinimalRushConfiguration | undefined, executeOptions: ILaunchOptions ): Promise { - const isLegacyRushVersion: boolean = semver.lt(version, '4.0.0'); const expectedRushPath: string = path.join(this._rushGlobalFolder.nodeSpecificPath, `rush-${version}`); - const installMarker: _LastInstallFlag = new _LastInstallFlag( - expectedRushPath, - { node: process.versions.node } - ); + const installMarker: _LastInstallFlag = new _LastInstallFlag(expectedRushPath, { + node: process.versions.node, + }); let installPromise: Promise = Promise.resolve(); @@ -51,36 +45,34 @@ export class RushVersionSelector { console.log(`Trying to acquire lock for ${resourceName}`); - return LockFile.acquire(expectedRushPath, resourceName) - .then((lock: LockFile) => { - - if (installMarker.isValid()) { - console.log('Another process performed the installation.'); - } else { - Utilities.installPackageInDirectory({ - directory: expectedRushPath, - packageName: isLegacyRushVersion ? '@microsoft/rush' : '@microsoft/rush-lib', - version: version, - tempPackageTitle: 'rush-local-install', - maxInstallAttempts: MAX_INSTALL_ATTEMPTS, - // This is using a local configuration to install a package in a shared global location. - // Generally that's a bad practice, but in this case if we can successfully install - // the package at all, we can reasonably assume it's good for all the repositories. - // In particular, we'll assume that two different NPM registries cannot have two - // different implementations of the same version of the same package. - // This was needed for: https://github.com/microsoft/rushstack/issues/691 - commonRushConfigFolder: configuration ? configuration.commonRushConfigFolder : undefined, - suppressOutput: true - }); - - console.log(`Successfully installed Rush version ${version} in ${expectedRushPath}.`); - - // If we've made it here without exception, write the flag file - installMarker.create(); - - lock.release(); - } - }); + return LockFile.acquire(expectedRushPath, resourceName).then((lock: LockFile) => { + if (installMarker.isValid()) { + console.log('Another process performed the installation.'); + } else { + Utilities.installPackageInDirectory({ + directory: expectedRushPath, + packageName: isLegacyRushVersion ? '@microsoft/rush' : '@microsoft/rush-lib', + version: version, + tempPackageTitle: 'rush-local-install', + maxInstallAttempts: MAX_INSTALL_ATTEMPTS, + // This is using a local configuration to install a package in a shared global location. + // Generally that's a bad practice, but in this case if we can successfully install + // the package at all, we can reasonably assume it's good for all the repositories. + // In particular, we'll assume that two different NPM registries cannot have two + // different implementations of the same version of the same package. + // This was needed for: https://github.com/microsoft/rushstack/issues/691 + commonRushConfigFolder: configuration ? configuration.commonRushConfigFolder : undefined, + suppressOutput: true, + }); + + console.log(`Successfully installed Rush version ${version} in ${expectedRushPath}.`); + + // If we've made it here without exception, write the flag file + installMarker.create(); + + lock.release(); + } + }); }); } @@ -89,30 +81,16 @@ export class RushVersionSelector { // In old versions, requiring the entry point invoked the command-line parser immediately, // so fail if "rushx" was used RushCommandSelector.failIfNotInvokedAsRush(version); - require(path.join( - expectedRushPath, - 'node_modules', - '@microsoft', - 'rush', - 'lib', - 'rush' - )); + require(path.join(expectedRushPath, 'node_modules', '@microsoft', 'rush', 'lib', 'rush')); } else if (semver.lt(version, '4.0.0')) { // In old versions, requiring the entry point invoked the command-line parser immediately, // so fail if "rushx" was used RushCommandSelector.failIfNotInvokedAsRush(version); - require(path.join( - expectedRushPath, - 'node_modules', - '@microsoft', - 'rush', - 'lib', - 'start' - )); + require(path.join(expectedRushPath, 'node_modules', '@microsoft', 'rush', 'lib', 'start')); } else { // For newer rush-lib, RushCommandSelector can test whether "rushx" is supported or not // eslint-disable-next-line @typescript-eslint/no-var-requires - const rushCliEntrypoint: { } = require(path.join( + const rushCliEntrypoint: {} = require(path.join( expectedRushPath, 'node_modules', '@microsoft', diff --git a/apps/rush/src/start.ts b/apps/rush/src/start.ts index 6600ca8c6e8..44fcb99f692 100644 --- a/apps/rush/src/start.ts +++ b/apps/rush/src/start.ts @@ -14,17 +14,14 @@ if (NodeJsCompatibility.warnAboutVersionTooOld()) { const alreadyReportedNodeTooNewError: boolean = NodeJsCompatibility.warnAboutVersionTooNew({ isRushLib: false, - alreadyReportedNodeTooNewError: false + alreadyReportedNodeTooNewError: false, }); import * as colors from 'colors'; import * as os from 'os'; import * as semver from 'semver'; -import { - Text, - PackageJsonLookup -} from '@rushstack/node-core-library'; +import { Text, PackageJsonLookup } from '@rushstack/node-core-library'; import { EnvironmentVariableNames } from '@microsoft/rush-lib'; import * as rushLib from '@microsoft/rush-lib'; @@ -33,7 +30,9 @@ import { RushVersionSelector } from './RushVersionSelector'; import { MinimalRushConfiguration } from './MinimalRushConfiguration'; // Load the configuration -const configuration: MinimalRushConfiguration | undefined = MinimalRushConfiguration.loadFromDefaultLocation(); +const configuration: + | MinimalRushConfiguration + | undefined = MinimalRushConfiguration.loadFromDefaultLocation(); const currentPackageVersion: string = PackageJsonLookup.loadOwnPackageJson(__dirname).version; @@ -43,7 +42,9 @@ const previewVersion: string | undefined = process.env[EnvironmentVariableNames. if (previewVersion) { if (!semver.valid(previewVersion, false)) { - console.error(colors.red(`Invalid value for RUSH_PREVIEW_VERSION environment variable: "${previewVersion}"`)); + console.error( + colors.red(`Invalid value for RUSH_PREVIEW_VERSION environment variable: "${previewVersion}"`) + ); process.exit(1); } @@ -58,9 +59,7 @@ if (previewVersion) { ); if (configuration) { - lines.push( - `* The rush.json configuration asks for: ${Text.padEnd(configuration.rushVersion, 25)} *` - ); + lines.push(`* The rush.json configuration asks for: ${Text.padEnd(configuration.rushVersion, 25)} *`); } lines.push( @@ -70,10 +69,7 @@ if (previewVersion) { `*********************************************************************` ); - console.error(lines - .map(line => colors.black(colors.bgYellow(line))) - .join(os.EOL)); - + console.error(lines.map((line) => colors.black(colors.bgYellow(line))).join(os.EOL)); } else if (configuration) { rushVersionToLoad = configuration.rushVersion; } @@ -92,7 +88,8 @@ const launchOptions: rushLib.ILaunchOptions = { isManaged, alreadyReportedNodeTo // install it if (rushVersionToLoad && rushVersionToLoad !== currentPackageVersion) { const versionSelector: RushVersionSelector = new RushVersionSelector(currentPackageVersion); - versionSelector.ensureRushVersionInstalled(rushVersionToLoad, configuration, launchOptions) + versionSelector + .ensureRushVersionInstalled(rushVersionToLoad, configuration, launchOptions) .catch((error: Error) => { console.log(colors.red('Error: ' + error.message)); }); diff --git a/apps/rush/src/test/MinimalRushConfiguration.test.ts b/apps/rush/src/test/MinimalRushConfiguration.test.ts index 1e9d614fec1..37fc95b8e22 100644 --- a/apps/rush/src/test/MinimalRushConfiguration.test.ts +++ b/apps/rush/src/test/MinimalRushConfiguration.test.ts @@ -24,8 +24,7 @@ describe('MinimalRushConfiguration', () => { }); it('correctly loads the rush.json file', () => { - const config: MinimalRushConfiguration = - MinimalRushConfiguration.loadFromDefaultLocation() as MinimalRushConfiguration; + const config: MinimalRushConfiguration = MinimalRushConfiguration.loadFromDefaultLocation() as MinimalRushConfiguration; assert.equal(config.rushVersion, '2.5.0'); }); }); @@ -36,8 +35,7 @@ describe('MinimalRushConfiguration', () => { }); it('correctly loads the rush.json file', () => { - const config: MinimalRushConfiguration = - MinimalRushConfiguration.loadFromDefaultLocation() as MinimalRushConfiguration; + const config: MinimalRushConfiguration = MinimalRushConfiguration.loadFromDefaultLocation() as MinimalRushConfiguration; assert.equal(config.rushVersion, '4.0.0'); }); }); diff --git a/apps/rush/src/test/sandbox/legacy-repo/rush.json b/apps/rush/src/test/sandbox/legacy-repo/rush.json index f975dce05b9..0f78380f94a 100644 --- a/apps/rush/src/test/sandbox/legacy-repo/rush.json +++ b/apps/rush/src/test/sandbox/legacy-repo/rush.json @@ -5,29 +5,18 @@ "projectFolderMinDepth": 1, "projectFolderMaxDepth": 99, "approvedPackagesPolicy": { - "reviewCategories": [ - "first-party", - "third-party", - "prototype" - ], - "ignoredNpmScopes": [ - "@types", - "@internal" - ] + "reviewCategories": ["first-party", "third-party", "prototype"], + "ignoredNpmScopes": ["@types", "@internal"] }, "repository": { "url": "someFakeUrl" }, "gitPolicy": { - "allowedEmailRegExps": [ - "[^@]+@contoso\\.com" - ], + "allowedEmailRegExps": ["[^@]+@contoso\\.com"], "sampleEmail": "mrexample@contoso.com" }, "eventHooks": { - "postRushBuild": [ - "do something" - ] + "postRushBuild": ["do something"] }, "projects": [ { @@ -36,4 +25,4 @@ "reviewCategory": "third-party" } ] -} \ No newline at end of file +} diff --git a/apps/rush/src/test/sandbox/repo/rush.json b/apps/rush/src/test/sandbox/repo/rush.json index 8601f7eadc7..a30846e627c 100644 --- a/apps/rush/src/test/sandbox/repo/rush.json +++ b/apps/rush/src/test/sandbox/repo/rush.json @@ -5,29 +5,18 @@ "projectFolderMinDepth": 1, "projectFolderMaxDepth": 99, "approvedPackagesPolicy": { - "reviewCategories": [ - "first-party", - "third-party", - "prototype" - ], - "ignoredNpmScopes": [ - "@types", - "@internal" - ] + "reviewCategories": ["first-party", "third-party", "prototype"], + "ignoredNpmScopes": ["@types", "@internal"] }, "repository": { "url": "someFakeUrl" }, "gitPolicy": { - "allowedEmailRegExps": [ - "[^@]+@contoso\\.com" - ], + "allowedEmailRegExps": ["[^@]+@contoso\\.com"], "sampleEmail": "mrexample@contoso.com" }, "eventHooks": { - "postRushBuild": [ - "do something" - ] + "postRushBuild": ["do something"] }, "projects": [ { @@ -36,4 +25,4 @@ "reviewCategory": "third-party" } ] -} \ No newline at end of file +} diff --git a/apps/rush/tsconfig.json b/apps/rush/tsconfig.json index 76f0d945025..8f1cbebe335 100644 --- a/apps/rush/tsconfig.json +++ b/apps/rush/tsconfig.json @@ -1,9 +1,6 @@ { "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "jest", - "node" - ] + "types": ["jest", "node"] } } diff --git a/build-tests/api-documenter-test/build.js b/build-tests/api-documenter-test/build.js index c2bd5b29fd0..ecf61a017a2 100644 --- a/build-tests/api-documenter-test/build.js +++ b/build-tests/api-documenter-test/build.js @@ -25,9 +25,13 @@ if (process.argv.indexOf('--production') >= 0) { } // Run the API Documenter command-line -executeCommand('node node_modules/@microsoft/api-documenter/lib/start ' - + 'generate --input-folder etc --output-folder etc/yaml'); -executeCommand('node node_modules/@microsoft/api-documenter/lib/start ' - + 'markdown --input-folder etc --output-folder etc/markdown'); +executeCommand( + 'node node_modules/@microsoft/api-documenter/lib/start ' + + 'generate --input-folder etc --output-folder etc/yaml' +); +executeCommand( + 'node node_modules/@microsoft/api-documenter/lib/start ' + + 'markdown --input-folder etc --output-folder etc/markdown' +); console.log(`==> Finished build.js for ${path.basename(process.cwd())}`); diff --git a/build-tests/api-documenter-test/config/api-documenter.json b/build-tests/api-documenter-test/config/api-documenter.json index 59dddf06166..59b666c3b35 100644 --- a/build-tests/api-documenter-test/config/api-documenter.json +++ b/build-tests/api-documenter-test/config/api-documenter.json @@ -28,9 +28,7 @@ }, { "name": "References", - "items": [ - { "name": "InjectedCustomItem", "uid": "customUrl" } - ] + "items": [{ "name": "InjectedCustomItem", "uid": "customUrl" }] } ] } diff --git a/build-tests/api-documenter-test/config/api-extractor.json b/build-tests/api-documenter-test/config/api-extractor.json index c5af368ca6a..af587d938bf 100644 --- a/build-tests/api-documenter-test/config/api-extractor.json +++ b/build-tests/api-documenter-test/config/api-extractor.json @@ -6,7 +6,7 @@ "newlineKind": "crlf", "apiReport": { - "enabled": true, + "enabled": true }, "docModel": { diff --git a/build-tests/api-documenter-test/src/DocClass1.ts b/build-tests/api-documenter-test/src/DocClass1.ts index ea726712368..544fea83745 100644 --- a/build-tests/api-documenter-test/src/DocClass1.ts +++ b/build-tests/api-documenter-test/src/DocClass1.ts @@ -1,4 +1,3 @@ - /** * A class used to exposed events. * @public @@ -8,8 +7,7 @@ export class SystemEvent { /** * Adds an handler for the event. */ - public addHandler(handler: () => void): void { - } + public addHandler(handler: () => void): void {} } /** @@ -28,8 +26,7 @@ export class DocBaseClass { */ public constructor(x: number); - public constructor(x?: number) { - } + public constructor(x?: number) {} } /** @@ -80,7 +77,7 @@ export interface IDocInterface3 { /** * Construct signature */ - new(): IDocInterface1; + new (): IDocInterface1; /** * Indexer @@ -96,19 +93,19 @@ export interface IDocInterface3 { /** * A quoted identifier with redundant quotes. */ - "redundantQuotes": string; + redundantQuotes: string; /** * An identifier that does needs quotes. It misleadingly looks like an ECMAScript symbol. */ - "[not.a.symbol]": string + '[not.a.symbol]': string; } /** * Generic class. * @public */ -export class Generic { } +export class Generic {} /** * Type union in an interface. @@ -185,8 +182,7 @@ export class DocClass1 extends DocBaseClass implements IDocInterface1, IDocInter public get writeableProperty(): string { return 'hello'; } - public set writeableProperty(value: string) { - } + public set writeableProperty(value: string) {} /** * This event is fired whenever the object is modified. @@ -215,22 +211,19 @@ export class DocClass1 extends DocBaseClass implements IDocInterface1, IDocInter * * */ - tableExample(): void { - } + tableExample(): void {} /** * Example: "\{ \\"maxItemsToShow\\": 123 \}" * * The regular expression used to validate the constraints is /^[a-zA-Z0-9\\-_]+$/ */ - interestingEdgeCases(): void { - } + interestingEdgeCases(): void {} /** * @deprecated Use `otherThing()` instead. */ - public deprecatedExample(): void { - } + public deprecatedExample(): void {} /** * Returns the sum of two numbers. @@ -299,12 +292,10 @@ export interface IDocInterface6 { * Class that merges with interface * @public */ -export class DocClassInterfaceMerge { -} +export class DocClassInterfaceMerge {} /** * Interface that merges with class * @public */ -export interface DocClassInterfaceMerge { -} \ No newline at end of file +export interface DocClassInterfaceMerge {} diff --git a/build-tests/api-documenter-test/src/DocEnums.ts b/build-tests/api-documenter-test/src/DocEnums.ts index 7428c569f15..2a1c1119909 100644 --- a/build-tests/api-documenter-test/src/DocEnums.ts +++ b/build-tests/api-documenter-test/src/DocEnums.ts @@ -20,5 +20,5 @@ export enum DocEnum { /** * These are some docs for Two */ - Two = DocEnum.One + 1 + Two = DocEnum.One + 1, } diff --git a/build-tests/api-documenter-test/src/index.ts b/build-tests/api-documenter-test/src/index.ts index 3eb7667c25b..c64dca9ba1d 100644 --- a/build-tests/api-documenter-test/src/index.ts +++ b/build-tests/api-documenter-test/src/index.ts @@ -35,7 +35,7 @@ export const constVariable: number = 123; * @public */ export function exampleFunction(x: ExampleTypeAlias, y: number): IDocInterface1 { - return undefined as unknown as IDocInterface1; + return (undefined as unknown) as IDocInterface1; } /** @@ -74,4 +74,4 @@ export type TypeAlias = number; /** * @public */ -export type GenericTypeAlias = T[]; \ No newline at end of file +export type GenericTypeAlias = T[]; diff --git a/build-tests/api-documenter-test/tsconfig.json b/build-tests/api-documenter-test/tsconfig.json index de8969fb815..1799652cc42 100644 --- a/build-tests/api-documenter-test/tsconfig.json +++ b/build-tests/api-documenter-test/tsconfig.json @@ -8,22 +8,9 @@ "declarationMap": true, "experimentalDecorators": true, "strictNullChecks": true, - "types": [ - "node", - "jest" - ], - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ], + "types": ["node", "jest"], + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"], "outDir": "lib" }, - "include": [ - "src/**/*.ts", - "typings/tsd.d.ts" - ] -} \ No newline at end of file + "include": ["src/**/*.ts", "typings/tsd.d.ts"] +} diff --git a/build-tests/api-extractor-lib1-test/config/api-extractor.json b/build-tests/api-extractor-lib1-test/config/api-extractor.json index 2a20b332f5f..609b62dc032 100644 --- a/build-tests/api-extractor-lib1-test/config/api-extractor.json +++ b/build-tests/api-extractor-lib1-test/config/api-extractor.json @@ -4,7 +4,7 @@ "mainEntryPointFilePath": "/lib/index.d.ts", "apiReport": { - "enabled": true, + "enabled": true }, "docModel": { diff --git a/build-tests/api-extractor-lib1-test/src/Lib1ForgottenExport.ts b/build-tests/api-extractor-lib1-test/src/Lib1ForgottenExport.ts index 32b51d5afd1..0705243922a 100644 --- a/build-tests/api-extractor-lib1-test/src/Lib1ForgottenExport.ts +++ b/build-tests/api-extractor-lib1-test/src/Lib1ForgottenExport.ts @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export class Lib1ForgottenExport { -} +export class Lib1ForgottenExport {} diff --git a/build-tests/api-extractor-lib1-test/src/index.ts b/build-tests/api-extractor-lib1-test/src/index.ts index 8ec896a452e..7fd1ac2cc47 100644 --- a/build-tests/api-extractor-lib1-test/src/index.ts +++ b/build-tests/api-extractor-lib1-test/src/index.ts @@ -21,10 +21,8 @@ export class Lib1Class extends Lib1ForgottenExport { public get writeableProperty(): string { return 'hello'; } - public set writeableProperty(value: string) { - } + public set writeableProperty(value: string) {} } /** @alpha */ -export interface Lib1Interface { -} +export interface Lib1Interface {} diff --git a/build-tests/api-extractor-lib1-test/tsconfig.json b/build-tests/api-extractor-lib1-test/tsconfig.json index 62004a26807..d8d1b791011 100644 --- a/build-tests/api-extractor-lib1-test/tsconfig.json +++ b/build-tests/api-extractor-lib1-test/tsconfig.json @@ -7,21 +7,9 @@ "sourceMap": true, "experimentalDecorators": true, "strictNullChecks": true, - "types": [ - "node" - ], - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ], + "types": ["node"], + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"], "outDir": "lib" }, - "include": [ - "src/**/*.ts", - "typings/tsd.d.ts" - ] -} \ No newline at end of file + "include": ["src/**/*.ts", "typings/tsd.d.ts"] +} diff --git a/build-tests/api-extractor-lib2-test/config/api-extractor.json b/build-tests/api-extractor-lib2-test/config/api-extractor.json index 2a20b332f5f..609b62dc032 100644 --- a/build-tests/api-extractor-lib2-test/config/api-extractor.json +++ b/build-tests/api-extractor-lib2-test/config/api-extractor.json @@ -4,7 +4,7 @@ "mainEntryPointFilePath": "/lib/index.d.ts", "apiReport": { - "enabled": true, + "enabled": true }, "docModel": { diff --git a/build-tests/api-extractor-lib2-test/src/index.ts b/build-tests/api-extractor-lib2-test/src/index.ts index 852d8076d30..3297eaa5dd6 100644 --- a/build-tests/api-extractor-lib2-test/src/index.ts +++ b/build-tests/api-extractor-lib2-test/src/index.ts @@ -11,9 +11,7 @@ */ /** @public */ -export class Lib2Class { -} +export class Lib2Class {} /** @alpha */ -export interface Lib2Interface { -} +export interface Lib2Interface {} diff --git a/build-tests/api-extractor-lib2-test/tsconfig.json b/build-tests/api-extractor-lib2-test/tsconfig.json index de8969fb815..1799652cc42 100644 --- a/build-tests/api-extractor-lib2-test/tsconfig.json +++ b/build-tests/api-extractor-lib2-test/tsconfig.json @@ -8,22 +8,9 @@ "declarationMap": true, "experimentalDecorators": true, "strictNullChecks": true, - "types": [ - "node", - "jest" - ], - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ], + "types": ["node", "jest"], + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"], "outDir": "lib" }, - "include": [ - "src/**/*.ts", - "typings/tsd.d.ts" - ] -} \ No newline at end of file + "include": ["src/**/*.ts", "typings/tsd.d.ts"] +} diff --git a/build-tests/api-extractor-lib3-test/config/api-extractor.json b/build-tests/api-extractor-lib3-test/config/api-extractor.json index 2a20b332f5f..609b62dc032 100644 --- a/build-tests/api-extractor-lib3-test/config/api-extractor.json +++ b/build-tests/api-extractor-lib3-test/config/api-extractor.json @@ -4,7 +4,7 @@ "mainEntryPointFilePath": "/lib/index.d.ts", "apiReport": { - "enabled": true, + "enabled": true }, "docModel": { diff --git a/build-tests/api-extractor-lib3-test/tsconfig.json b/build-tests/api-extractor-lib3-test/tsconfig.json index de8969fb815..1799652cc42 100644 --- a/build-tests/api-extractor-lib3-test/tsconfig.json +++ b/build-tests/api-extractor-lib3-test/tsconfig.json @@ -8,22 +8,9 @@ "declarationMap": true, "experimentalDecorators": true, "strictNullChecks": true, - "types": [ - "node", - "jest" - ], - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ], + "types": ["node", "jest"], + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"], "outDir": "lib" }, - "include": [ - "src/**/*.ts", - "typings/tsd.d.ts" - ] -} \ No newline at end of file + "include": ["src/**/*.ts", "typings/tsd.d.ts"] +} diff --git a/build-tests/api-extractor-scenarios/src/ambientNameConflict/localFile.ts b/build-tests/api-extractor-scenarios/src/ambientNameConflict/localFile.ts index 593832bd5b3..a5745a7f86c 100644 --- a/build-tests/api-extractor-scenarios/src/ambientNameConflict/localFile.ts +++ b/build-tests/api-extractor-scenarios/src/ambientNameConflict/localFile.ts @@ -5,6 +5,5 @@ * @public */ export class Promise { - public notTheRealPromise(arg: T): void { - } + public notTheRealPromise(arg: T): void {} } diff --git a/build-tests/api-extractor-scenarios/src/ambientNameConflict2/Date.ts b/build-tests/api-extractor-scenarios/src/ambientNameConflict2/Date.ts index 0bf5c8ed4ac..30d166a4102 100644 --- a/build-tests/api-extractor-scenarios/src/ambientNameConflict2/Date.ts +++ b/build-tests/api-extractor-scenarios/src/ambientNameConflict2/Date.ts @@ -5,4 +5,4 @@ * A local class declaration whose name is the same as the system `Date` global symbol. * @public */ -export class Date { } +export class Date {} diff --git a/build-tests/api-extractor-scenarios/src/ancillaryDeclarations/index.ts b/build-tests/api-extractor-scenarios/src/ancillaryDeclarations/index.ts index 92773479649..337fc9b47d1 100644 --- a/build-tests/api-extractor-scenarios/src/ancillaryDeclarations/index.ts +++ b/build-tests/api-extractor-scenarios/src/ancillaryDeclarations/index.ts @@ -13,6 +13,5 @@ export class MyClass { return { title: 'thing' }; } // The setter should also be considered @internal because the getter was marked as internal. - public set _thing(value: _IInternalThing) { - } + public set _thing(value: _IInternalThing) {} } diff --git a/build-tests/api-extractor-scenarios/src/apiItemKinds/classes.ts b/build-tests/api-extractor-scenarios/src/apiItemKinds/classes.ts index 9168cd6bd5b..58da2c55b12 100644 --- a/build-tests/api-extractor-scenarios/src/apiItemKinds/classes.ts +++ b/build-tests/api-extractor-scenarios/src/apiItemKinds/classes.ts @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. - /** @public */ export abstract class AbstractClass { public abstract member(): void; @@ -9,8 +8,7 @@ export abstract class AbstractClass { /** @public */ export class SimpleClass { - public member(): void { - } + public member(): void {} public get readonlyProperty(): string { return 'hello'; @@ -19,6 +17,5 @@ export class SimpleClass { public get writeableProperty(): string { return 'hello'; } - public set writeableProperty(value: string) { - } + public set writeableProperty(value: string) {} } diff --git a/build-tests/api-extractor-scenarios/src/apiItemKinds/enums.ts b/build-tests/api-extractor-scenarios/src/apiItemKinds/enums.ts index be7f4409a97..b7aa1a522fb 100644 --- a/build-tests/api-extractor-scenarios/src/apiItemKinds/enums.ts +++ b/build-tests/api-extractor-scenarios/src/apiItemKinds/enums.ts @@ -16,12 +16,12 @@ export enum RegularEnum { /** * These are some docs for Two */ - Two = RegularEnum.One + 1 + Two = RegularEnum.One + 1, } /** @public */ export const enum ConstEnum { Zero, One = 1, - Two = RegularEnum.One + 1 -} \ No newline at end of file + Two = RegularEnum.One + 1, +} diff --git a/build-tests/api-extractor-scenarios/src/apiItemKinds/typeLiterals.ts b/build-tests/api-extractor-scenarios/src/apiItemKinds/typeLiterals.ts index 4ae6655cd23..42e5f88f785 100644 --- a/build-tests/api-extractor-scenarios/src/apiItemKinds/typeLiterals.ts +++ b/build-tests/api-extractor-scenarios/src/apiItemKinds/typeLiterals.ts @@ -4,11 +4,10 @@ /** @public */ export class ClassWithTypeLiterals { /** type literal in */ - public method1(vector: { x :number, y :number}): void { - } + public method1(vector: { x: number; y: number }): void {} /** type literal output */ - public method2(): { classValue: ClassWithTypeLiterals, callback: () => number } | undefined { + public method2(): { classValue: ClassWithTypeLiterals; callback: () => number } | undefined { return undefined; } } diff --git a/build-tests/api-extractor-scenarios/src/apiItemKinds/variables.ts b/build-tests/api-extractor-scenarios/src/apiItemKinds/variables.ts index d0d4bf439fa..766c2a3f5e5 100644 --- a/build-tests/api-extractor-scenarios/src/apiItemKinds/variables.ts +++ b/build-tests/api-extractor-scenarios/src/apiItemKinds/variables.ts @@ -6,7 +6,7 @@ export const VARIABLE: string = 'hello'; /** @public */ export namespace NamespaceContainingVariable { - export let variable: object[] = [] + export let variable: object[] = []; - export let constVariable: object[] = [] + export let constVariable: object[] = []; } diff --git a/build-tests/api-extractor-scenarios/src/bundledPackages/config/api-extractor-overrides.json b/build-tests/api-extractor-scenarios/src/bundledPackages/config/api-extractor-overrides.json index ee390b1793d..0b497a09ba1 100644 --- a/build-tests/api-extractor-scenarios/src/bundledPackages/config/api-extractor-overrides.json +++ b/build-tests/api-extractor-scenarios/src/bundledPackages/config/api-extractor-overrides.json @@ -1,5 +1,3 @@ { - "bundledPackages": [ - "api-extractor-lib1-test" - ] -} \ No newline at end of file + "bundledPackages": ["api-extractor-lib1-test"] +} diff --git a/build-tests/api-extractor-scenarios/src/bundledPackages/index.ts b/build-tests/api-extractor-scenarios/src/bundledPackages/index.ts index f9aad34fe5b..00f7e90cd2f 100644 --- a/build-tests/api-extractor-scenarios/src/bundledPackages/index.ts +++ b/build-tests/api-extractor-scenarios/src/bundledPackages/index.ts @@ -1,9 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { Lib1Class } from "api-extractor-lib1-test/lib/index"; -import { Lib2Class } from "api-extractor-lib2-test/lib/index"; +import { Lib1Class } from 'api-extractor-lib1-test/lib/index'; +import { Lib2Class } from 'api-extractor-lib2-test/lib/index'; /** @public */ -export function f(arg1: Lib1Class, arg2: Lib2Class): void { -} +export function f(arg1: Lib1Class, arg2: Lib2Class): void {} diff --git a/build-tests/api-extractor-scenarios/src/circularImport/IFile.ts b/build-tests/api-extractor-scenarios/src/circularImport/IFile.ts index 95b34b4a458..8137ec7a376 100644 --- a/build-tests/api-extractor-scenarios/src/circularImport/IFile.ts +++ b/build-tests/api-extractor-scenarios/src/circularImport/IFile.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { IFolder } from "./IFolder"; +import { IFolder } from './IFolder'; /** @public */ export class IFile { diff --git a/build-tests/api-extractor-scenarios/src/circularImport/IFolder.ts b/build-tests/api-extractor-scenarios/src/circularImport/IFolder.ts index 317bfa89814..d8ac129b32c 100644 --- a/build-tests/api-extractor-scenarios/src/circularImport/IFolder.ts +++ b/build-tests/api-extractor-scenarios/src/circularImport/IFolder.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { IFile } from "./IFile"; +import { IFile } from './IFile'; /** @public */ export class IFolder { diff --git a/build-tests/api-extractor-scenarios/src/circularImport2/IFile.ts b/build-tests/api-extractor-scenarios/src/circularImport2/IFile.ts index 09334c31efc..3ef9e76c9be 100644 --- a/build-tests/api-extractor-scenarios/src/circularImport2/IFile.ts +++ b/build-tests/api-extractor-scenarios/src/circularImport2/IFile.ts @@ -1,8 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export * from "./IFolder"; -import { IFolder } from "./IFolder"; +export * from './IFolder'; +import { IFolder } from './IFolder'; /** @public */ export class IFile { @@ -10,4 +10,4 @@ export class IFile { } /** @public */ -export class A { } +export class A {} diff --git a/build-tests/api-extractor-scenarios/src/circularImport2/IFolder.ts b/build-tests/api-extractor-scenarios/src/circularImport2/IFolder.ts index 0cfcc5983cc..cc1723a85c2 100644 --- a/build-tests/api-extractor-scenarios/src/circularImport2/IFolder.ts +++ b/build-tests/api-extractor-scenarios/src/circularImport2/IFolder.ts @@ -1,8 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export * from "./IFile"; -import { IFile } from "./IFile"; +export * from './IFile'; +import { IFile } from './IFile'; /** @public */ export class IFolder { @@ -11,4 +11,4 @@ export class IFolder { } /** @public */ -export class B { } +export class B {} diff --git a/build-tests/api-extractor-scenarios/src/circularImport2/index.ts b/build-tests/api-extractor-scenarios/src/circularImport2/index.ts index 0573a7b0838..eac1858f930 100644 --- a/build-tests/api-extractor-scenarios/src/circularImport2/index.ts +++ b/build-tests/api-extractor-scenarios/src/circularImport2/index.ts @@ -3,4 +3,3 @@ export * from './IFile'; export * from './IFolder'; - diff --git a/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint/index.ts b/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint/index.ts index 45329c9b987..012b65909e7 100644 --- a/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint/index.ts +++ b/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint/index.ts @@ -2,4 +2,4 @@ // See LICENSE in the project root for license information. /** @public */ -export default class DefaultClass { }; +export default class DefaultClass {} diff --git a/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint2/index.ts b/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint2/index.ts index 305a777b919..034bb1bfb7e 100644 --- a/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint2/index.ts +++ b/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint2/index.ts @@ -2,6 +2,6 @@ // See LICENSE in the project root for license information. /** @public */ -const defaultFunctionStatement = () => { }; +const defaultFunctionStatement = () => {}; export default defaultFunctionStatement; diff --git a/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint3/index.ts b/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint3/index.ts index e9977a59451..c468b59ad4e 100644 --- a/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint3/index.ts +++ b/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint3/index.ts @@ -4,4 +4,4 @@ /** * @public */ -export default function defaultFunctionDeclaration() { }; +export default function defaultFunctionDeclaration() {} diff --git a/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint4/index.ts b/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint4/index.ts index c97b7761d63..4587a388a9c 100644 --- a/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint4/index.ts +++ b/build-tests/api-extractor-scenarios/src/defaultExportOfEntryPoint4/index.ts @@ -2,4 +2,4 @@ // See LICENSE in the project root for license information. /** @public */ -export default "literal"; +export default 'literal'; diff --git a/build-tests/api-extractor-scenarios/src/docReferences/index.ts b/build-tests/api-extractor-scenarios/src/docReferences/index.ts index 7b6f83c618a..e07677f55cf 100644 --- a/build-tests/api-extractor-scenarios/src/docReferences/index.ts +++ b/build-tests/api-extractor-scenarios/src/docReferences/index.ts @@ -27,8 +27,7 @@ export namespace MyNamespace { * but its `@beta` tag will not get copied. * @public */ -export function testSimple(): void { -} +export function testSimple(): void {} /** * {@inheritDoc nonexistent-package#MyNamespace.MyClass.nonExistentMethod} @@ -39,20 +38,16 @@ export function testSimple(): void { * * @public */ -export function succeedForNow(): void { -} - +export function succeedForNow(): void {} /** * {@inheritDoc MyNamespace.MyClass.nonExistentMethod} * @public */ -export function failWithBrokenLink(): void { -} +export function failWithBrokenLink(): void {} /** * {@inheritDoc} * @public */ -export function failWithMissingReference(): void { -} +export function failWithMissingReference(): void {} diff --git a/build-tests/api-extractor-scenarios/src/docReferences2/index.ts b/build-tests/api-extractor-scenarios/src/docReferences2/index.ts index 9c5530e7e1c..0fa5b23018b 100644 --- a/build-tests/api-extractor-scenarios/src/docReferences2/index.ts +++ b/build-tests/api-extractor-scenarios/src/docReferences2/index.ts @@ -4,29 +4,23 @@ /** @public */ export class CyclicA { /** {@inheritDoc CyclicB.methodB2} */ - public methodA1(): void { - } + public methodA1(): void {} /** {@inheritDoc CyclicB.methodB4} */ - public methodA3(): void { - } + public methodA3(): void {} } /** @public */ export class CyclicB { /** {@inheritDoc CyclicA.methodA3} */ - public methodB2(): void { - } + public methodB2(): void {} /** THE COMMENT */ - public methodB4(): void { - } + public methodB4(): void {} } /** @public */ export class FailWithSelfReference { /** {@inheritDoc FailWithSelfReference.method2} */ - public method1(): void { - } + public method1(): void {} /** {@inheritDoc FailWithSelfReference.method1} */ - public method2(): void { - } + public method2(): void {} } diff --git a/build-tests/api-extractor-scenarios/src/docReferences3/index.ts b/build-tests/api-extractor-scenarios/src/docReferences3/index.ts index 967d05b3e23..1b6ba3cd98c 100644 --- a/build-tests/api-extractor-scenarios/src/docReferences3/index.ts +++ b/build-tests/api-extractor-scenarios/src/docReferences3/index.ts @@ -4,8 +4,7 @@ /** @public */ export namespace A { export class B { - public myMethod(): void { - } + public myMethod(): void {} } } @@ -18,16 +17,14 @@ export interface A { * {@link MyNamespace.MyClass.myMethod | the method} * @public */ -export function failWithAmbiguity() { -} +export function failWithAmbiguity() {} /** * {@link (A:namespace).B.myMethod | the method} * {@link (A:interface).myProperty | the property} * @public */ -export function succeedWithSelector() { -} +export function succeedWithSelector() {} /** * NOTE: The broken link checker currently is not able to validate references to external packages. @@ -35,5 +32,4 @@ export function succeedWithSelector() { * {@link nonexistent#nonexistent} * @public */ -export function succeedWithExternalReference(): void { -} +export function succeedWithExternalReference(): void {} diff --git a/build-tests/api-extractor-scenarios/src/exportDuplicate/index.ts b/build-tests/api-extractor-scenarios/src/exportDuplicate/index.ts index 179b32c7b5d..a1108c2623f 100644 --- a/build-tests/api-extractor-scenarios/src/exportDuplicate/index.ts +++ b/build-tests/api-extractor-scenarios/src/exportDuplicate/index.ts @@ -2,11 +2,11 @@ // See LICENSE in the project root for license information. /** @public */ -export class X { } -export { X as Y } +export class X {} +export { X as Y }; /** @internal */ -class A { } +class A {} // The underscore warning should get printed next to these export statements, not next to the class declaration -export { A as B } -export { A as C } +export { A as B }; +export { A as C }; diff --git a/build-tests/api-extractor-scenarios/src/exportImportedExternal/index.ts b/build-tests/api-extractor-scenarios/src/exportImportedExternal/index.ts index 78162619ac5..089e8283aa5 100644 --- a/build-tests/api-extractor-scenarios/src/exportImportedExternal/index.ts +++ b/build-tests/api-extractor-scenarios/src/exportImportedExternal/index.ts @@ -2,10 +2,10 @@ // See LICENSE in the project root for license information. import { Lib1Interface } from 'api-extractor-lib1-test'; -export { Lib1Interface } +export { Lib1Interface }; import { Lib2Class as RenamedLib2Class } from 'api-extractor-lib2-test'; -export { RenamedLib2Class as DoubleRenamedLib2Class } +export { RenamedLib2Class as DoubleRenamedLib2Class }; export { Lib1Class } from 'api-extractor-lib1-test'; export { Lib2Class as RenamedLib2Class } from 'api-extractor-lib2-test'; diff --git a/build-tests/api-extractor-scenarios/src/exportStar/localFile.ts b/build-tests/api-extractor-scenarios/src/exportStar/localFile.ts index 95fbe424bb5..beeb886bd75 100644 --- a/build-tests/api-extractor-scenarios/src/exportStar/localFile.ts +++ b/build-tests/api-extractor-scenarios/src/exportStar/localFile.ts @@ -2,7 +2,7 @@ // See LICENSE in the project root for license information. /** @public */ -export class A { } +export class A {} /** @public */ -export class B { } +export class B {} diff --git a/build-tests/api-extractor-scenarios/src/exportStar/reexportStar.ts b/build-tests/api-extractor-scenarios/src/exportStar/reexportStar.ts index b382f373b00..10f0fc318f0 100644 --- a/build-tests/api-extractor-scenarios/src/exportStar/reexportStar.ts +++ b/build-tests/api-extractor-scenarios/src/exportStar/reexportStar.ts @@ -4,4 +4,4 @@ export * from './localFile'; /** @public */ -export class C { } +export class C {} diff --git a/build-tests/api-extractor-scenarios/src/exportStar2/reexportStar.ts b/build-tests/api-extractor-scenarios/src/exportStar2/reexportStar.ts index f2ed3c7966f..4511ea5b7db 100644 --- a/build-tests/api-extractor-scenarios/src/exportStar2/reexportStar.ts +++ b/build-tests/api-extractor-scenarios/src/exportStar2/reexportStar.ts @@ -4,4 +4,4 @@ export * from 'api-extractor-lib1-test'; /** @public */ -export class A { } +export class A {} diff --git a/build-tests/api-extractor-scenarios/src/exportStar3/reexportStar.ts b/build-tests/api-extractor-scenarios/src/exportStar3/reexportStar.ts index b08a7ea8776..4c0cd610a17 100644 --- a/build-tests/api-extractor-scenarios/src/exportStar3/reexportStar.ts +++ b/build-tests/api-extractor-scenarios/src/exportStar3/reexportStar.ts @@ -5,4 +5,4 @@ export * from 'api-extractor-lib1-test'; export * from 'api-extractor-lib2-test'; /** @public */ -export class A { } +export class A {} diff --git a/build-tests/api-extractor-scenarios/src/functionOverload/config/api-extractor-overrides.json b/build-tests/api-extractor-scenarios/src/functionOverload/config/api-extractor-overrides.json index 3894423ef64..b402f3c9adf 100644 --- a/build-tests/api-extractor-scenarios/src/functionOverload/config/api-extractor-overrides.json +++ b/build-tests/api-extractor-scenarios/src/functionOverload/config/api-extractor-overrides.json @@ -4,5 +4,5 @@ "untrimmedFilePath": "/etc/test-outputs/functionOverload/rollup.d.ts", "betaTrimmedFilePath": "/etc/test-outputs/functionOverload/beta-rollup.d.ts", "publicTrimmedFilePath": "/etc/test-outputs/functionOverload/public-rollup.d.ts" - }, -} \ No newline at end of file + } +} diff --git a/build-tests/api-extractor-scenarios/src/functionOverload/index.ts b/build-tests/api-extractor-scenarios/src/functionOverload/index.ts index 2a6e5093a21..b57f6dc04ee 100644 --- a/build-tests/api-extractor-scenarios/src/functionOverload/index.ts +++ b/build-tests/api-extractor-scenarios/src/functionOverload/index.ts @@ -17,7 +17,10 @@ export function combine(x: string, y: string): string; export function combine(x: number, y: number): number; // implementation -export function combine(x: string|number|boolean, y: string|number|boolean): string|number|boolean { +export function combine( + x: string | number | boolean, + y: string | number | boolean +): string | number | boolean { return 42; } @@ -32,7 +35,7 @@ export function _combine(x: string, y: string): string; export function _combine(x: number, y: number): number; // implementation -export function _combine(x: string|number, y: string|number): string|number { +export function _combine(x: string | number, y: string | number): string | number { return 42; } @@ -56,7 +59,7 @@ export class Combiner { public combine(x: number, y: number): number; // implementation - public combine(x: string|number|boolean, y: string|number|boolean): string|number|boolean { + public combine(x: string | number | boolean, y: string | number | boolean): string | number | boolean { return 42; } -} \ No newline at end of file +} diff --git a/build-tests/api-extractor-scenarios/src/inconsistentReleaseTags/index.ts b/build-tests/api-extractor-scenarios/src/inconsistentReleaseTags/index.ts index 3814e88e852..c6b73fcf0f9 100644 --- a/build-tests/api-extractor-scenarios/src/inconsistentReleaseTags/index.ts +++ b/build-tests/api-extractor-scenarios/src/inconsistentReleaseTags/index.ts @@ -23,4 +23,3 @@ export function alphaFunctionReturnsBeta(): IBeta { export function publicFunctionReturnsBeta(): IBeta { return { x: 123 }; } - diff --git a/build-tests/api-extractor-scenarios/src/internationalCharacters/index.ts b/build-tests/api-extractor-scenarios/src/internationalCharacters/index.ts index f7dba2bac82..9cb799ae800 100644 --- a/build-tests/api-extractor-scenarios/src/internationalCharacters/index.ts +++ b/build-tests/api-extractor-scenarios/src/internationalCharacters/index.ts @@ -7,11 +7,9 @@ export class ClassΞ { return this; } - public 'invalid chars'(): void { - } + public 'invalid chars'(): void {} - public 'validChars'(): void { - } + public validChars(): void {} } -export { ClassΞ as ClassΣ } +export { ClassΞ as ClassΣ }; diff --git a/build-tests/api-extractor-scenarios/src/preapproved/index.ts b/build-tests/api-extractor-scenarios/src/preapproved/index.ts index 33b61c3f7c3..3fca29ccb67 100644 --- a/build-tests/api-extractor-scenarios/src/preapproved/index.ts +++ b/build-tests/api-extractor-scenarios/src/preapproved/index.ts @@ -4,7 +4,7 @@ /** @internal @preapproved */ export enum _PreapprovedEnum { ONE = 1, - TWO + TWO, } /** @internal @preapproved */ @@ -14,15 +14,12 @@ export interface _PreapprovedInterface { /** @internal @preapproved */ export class _PreapprovedClass { - public member(): void { - } + public member(): void {} } /** @internal @preapproved */ export namespace _PreapprovedNamespace { - export class X { - } + export class X {} - export function f(): void { - } + export function f(): void {} } diff --git a/build-tests/api-extractor-scenarios/src/runScenarios.ts b/build-tests/api-extractor-scenarios/src/runScenarios.ts index 1fba2a97408..b0372544404 100644 --- a/build-tests/api-extractor-scenarios/src/runScenarios.ts +++ b/build-tests/api-extractor-scenarios/src/runScenarios.ts @@ -11,7 +11,7 @@ import { ExtractorResult, ExtractorMessage, ConsoleMessageId, - ExtractorLogLevel + ExtractorLogLevel, } from '@microsoft/api-extractor'; export function runScenarios(buildConfigPath: string): void { @@ -28,42 +28,42 @@ export function runScenarios(buildConfigPath: string): void { const overridesPath = path.resolve(`./src/${scenarioFolderName}/config/api-extractor-overrides.json`); const apiExtractorJsonOverrides = fs.existsSync(overridesPath) ? JsonFile.load(overridesPath) : {}; const apiExtractorJson = { - '$schema': 'https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json', + $schema: 'https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json', - 'mainEntryPointFilePath': entryPoint, + mainEntryPointFilePath: entryPoint, - 'apiReport': { - 'enabled': true, - 'reportFolder': `/etc/test-outputs/${scenarioFolderName}` + apiReport: { + enabled: true, + reportFolder: `/etc/test-outputs/${scenarioFolderName}`, }, - 'dtsRollup': { - 'enabled': true, - 'untrimmedFilePath': `/etc/test-outputs/${scenarioFolderName}/rollup.d.ts` + dtsRollup: { + enabled: true, + untrimmedFilePath: `/etc/test-outputs/${scenarioFolderName}/rollup.d.ts`, }, - 'docModel': { - 'enabled': true, - 'apiJsonFilePath': `/etc/test-outputs/${scenarioFolderName}/.api.json` + docModel: { + enabled: true, + apiJsonFilePath: `/etc/test-outputs/${scenarioFolderName}/.api.json`, }, - 'messages': { - 'extractorMessageReporting': { + messages: { + extractorMessageReporting: { // For test purposes, write these warnings into .api.md // TODO: Capture the full list of warnings in the tracked test output file 'ae-cyclic-inherit-doc': { - 'logLevel': 'warning', - 'addToApiReportFile': true + logLevel: 'warning', + addToApiReportFile: true, }, 'ae-unresolved-link': { - 'logLevel': 'warning', - 'addToApiReportFile': true - } - } + logLevel: 'warning', + addToApiReportFile: true, + }, + }, }, - 'testMode': true, - ...apiExtractorJsonOverrides + testMode: true, + ...apiExtractorJsonOverrides, }; const apiExtractorJsonPath: string = `./temp/configs/api-extractor-${scenarioFolderName}.json`; @@ -85,7 +85,7 @@ export function runScenarios(buildConfigPath: string): void { if (!compilerState) { compilerState = CompilerState.create(extractorConfig, { - additionalEntryPoints: entryPoints + additionalEntryPoints: entryPoints, }); } @@ -98,7 +98,7 @@ export function runScenarios(buildConfigPath: string): void { message.logLevel = ExtractorLogLevel.None; } }, - compilerState + compilerState, }); if (extractorResult.errorCount > 0) { diff --git a/build-tests/api-extractor-scenarios/src/typeOf/index.ts b/build-tests/api-extractor-scenarios/src/typeOf/index.ts index ba957d977bb..0fc5933058f 100644 --- a/build-tests/api-extractor-scenarios/src/typeOf/index.ts +++ b/build-tests/api-extractor-scenarios/src/typeOf/index.ts @@ -11,7 +11,7 @@ export function f(): typeof Lib1Class | undefined { return undefined; } -class ForgottenExport { } +class ForgottenExport {} /** * Reference IForgottenExport via "typeof" diff --git a/build-tests/api-extractor-scenarios/src/typeOf2/index.ts b/build-tests/api-extractor-scenarios/src/typeOf2/index.ts index 07728912e65..ddc2cf47ebf 100644 --- a/build-tests/api-extractor-scenarios/src/typeOf2/index.ts +++ b/build-tests/api-extractor-scenarios/src/typeOf2/index.ts @@ -3,7 +3,7 @@ /** @public */ export function f(): { a: number } { - return { a: 1}; + return { a: 1 }; } /** @public */ diff --git a/build-tests/api-extractor-scenarios/src/typeParameters/index.ts b/build-tests/api-extractor-scenarios/src/typeParameters/index.ts index 34e03e6c81b..40a39219505 100644 --- a/build-tests/api-extractor-scenarios/src/typeParameters/index.ts +++ b/build-tests/api-extractor-scenarios/src/typeParameters/index.ts @@ -2,26 +2,21 @@ // See LICENSE in the project root for license information. /** @public */ -export class GenericClass { -} +export class GenericClass {} /** @public */ -export class GenericClassWithConstraint { -} +export class GenericClassWithConstraint {} /** @public */ -export class GenericClassWithDefault { -} +export class GenericClassWithDefault {} /** @public */ export class ClassWithGenericMethod { - public method() { - } + public method() {} } /** @public */ -export interface GenericInterface { -} +export interface GenericInterface {} /** @public */ export interface InterfaceWithGenericCallSignature { @@ -34,8 +29,7 @@ export interface InterfaceWithGenericConstructSignature { } /** @public */ -export function genericFunction(): void { -} +export function genericFunction(): void {} /** @public */ export type GenericTypeAlias = T; diff --git a/build-tests/api-extractor-scenarios/tsconfig.json b/build-tests/api-extractor-scenarios/tsconfig.json index de8969fb815..1799652cc42 100644 --- a/build-tests/api-extractor-scenarios/tsconfig.json +++ b/build-tests/api-extractor-scenarios/tsconfig.json @@ -8,22 +8,9 @@ "declarationMap": true, "experimentalDecorators": true, "strictNullChecks": true, - "types": [ - "node", - "jest" - ], - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ], + "types": ["node", "jest"], + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"], "outDir": "lib" }, - "include": [ - "src/**/*.ts", - "typings/tsd.d.ts" - ] -} \ No newline at end of file + "include": ["src/**/*.ts", "typings/tsd.d.ts"] +} diff --git a/build-tests/api-extractor-test-01/config/api-extractor.json b/build-tests/api-extractor-test-01/config/api-extractor.json index cfb37d95019..f1ecda4020f 100644 --- a/build-tests/api-extractor-test-01/config/api-extractor.json +++ b/build-tests/api-extractor-test-01/config/api-extractor.json @@ -4,7 +4,7 @@ "mainEntryPointFilePath": "/lib/index.d.ts", "apiReport": { - "enabled": true, + "enabled": true }, "docModel": { diff --git a/build-tests/api-extractor-test-01/src/AccessModifiers.ts b/build-tests/api-extractor-test-01/src/AccessModifiers.ts index faf391265a8..0267dca4171 100644 --- a/build-tests/api-extractor-test-01/src/AccessModifiers.ts +++ b/build-tests/api-extractor-test-01/src/AccessModifiers.ts @@ -10,8 +10,7 @@ export class ClassWithAccessModifiers { private _privateField: number = 123; /** Doc comment */ - private privateMethod(): void { - } + private privateMethod(): void {} /** Doc comment */ private get privateGetter(): string { @@ -19,17 +18,13 @@ export class ClassWithAccessModifiers { } /** Doc comment */ - private privateSetter(x: string) { - } + private privateSetter(x: string) {} /** Doc comment */ - private constructor() { - } + private constructor() {} /** Doc comment */ - private static privateStaticMethod() { - } - + private static privateStaticMethod() {} /** Doc comment */ protected protectedField: number; @@ -40,13 +35,11 @@ export class ClassWithAccessModifiers { } /** Doc comment */ - protected protectedSetter(x: string) { - } + protected protectedSetter(x: string) {} /** Doc comment */ public static publicStaticField: number = 123; /** Doc comment */ - defaultPublicMethod(): void { - } + defaultPublicMethod(): void {} } diff --git a/build-tests/api-extractor-test-01/src/ClassWithTypeLiterals.ts b/build-tests/api-extractor-test-01/src/ClassWithTypeLiterals.ts index 9fe4497ebad..071dc824668 100644 --- a/build-tests/api-extractor-test-01/src/ClassWithTypeLiterals.ts +++ b/build-tests/api-extractor-test-01/src/ClassWithTypeLiterals.ts @@ -7,11 +7,10 @@ */ export class ClassWithTypeLiterals { /** type literal in */ - public method1(vector: { x :number, y :number}): void { - } + public method1(vector: { x: number; y: number }): void {} /** type literal output */ - public method2(): { classValue: ClassWithTypeLiterals, callback: () => number } | undefined { + public method2(): { classValue: ClassWithTypeLiterals; callback: () => number } | undefined { return undefined; } } diff --git a/build-tests/api-extractor-test-01/src/DeclarationMerging.ts b/build-tests/api-extractor-test-01/src/DeclarationMerging.ts index 6a86d38a10b..b9dac3157a2 100644 --- a/build-tests/api-extractor-test-01/src/DeclarationMerging.ts +++ b/build-tests/api-extractor-test-01/src/DeclarationMerging.ts @@ -4,8 +4,7 @@ /** * @alpha */ -export interface IMergedInterfaceReferencee { -} +export interface IMergedInterfaceReferencee {} /** * IMergedInterface instance 1. diff --git a/build-tests/api-extractor-test-01/src/DefaultExportEdgeCase.ts b/build-tests/api-extractor-test-01/src/DefaultExportEdgeCase.ts index a955fed845f..b39682ef1ed 100644 --- a/build-tests/api-extractor-test-01/src/DefaultExportEdgeCase.ts +++ b/build-tests/api-extractor-test-01/src/DefaultExportEdgeCase.ts @@ -16,5 +16,4 @@ export class DefaultExportEdgeCase { * Referenced by DefaultExportEdgeCaseReferencer. * @public */ -export default class ClassExportedAsDefault { -} +export default class ClassExportedAsDefault {} diff --git a/build-tests/api-extractor-test-01/src/EcmaScriptSymbols.ts b/build-tests/api-extractor-test-01/src/EcmaScriptSymbols.ts index be0106bc3d1..ac3a264e29d 100644 --- a/build-tests/api-extractor-test-01/src/EcmaScriptSymbols.ts +++ b/build-tests/api-extractor-test-01/src/EcmaScriptSymbols.ts @@ -29,17 +29,15 @@ export class ClassWithSymbols { return 'hello'; } - public [fullyExportedCustomSymbol](): void { - } + public [fullyExportedCustomSymbol](): void {} public get [ANamespace.locallyExportedCustomSymbol](): string { return 'hello'; } - public [ANamespace.fullyExportedCustomSymbol](): void { - } + public [ANamespace.fullyExportedCustomSymbol](): void {} public get [Symbol.toStringTag](): string { - return "ClassWithSymbols"; + return 'ClassWithSymbols'; } } diff --git a/build-tests/api-extractor-test-01/src/Enums.ts b/build-tests/api-extractor-test-01/src/Enums.ts index 782dd5544d5..f4292598681 100644 --- a/build-tests/api-extractor-test-01/src/Enums.ts +++ b/build-tests/api-extractor-test-01/src/Enums.ts @@ -18,7 +18,7 @@ export enum RegularEnum { /** * These are some docs for Two */ - Two = RegularEnum.One + 1 + Two = RegularEnum.One + 1, } /** @@ -27,6 +27,5 @@ export enum RegularEnum { export const enum ConstEnum { Zero, One = 1, - Two = RegularEnum.One + 1 + Two = RegularEnum.One + 1, } - diff --git a/build-tests/api-extractor-test-01/src/ForgottenExportConsumer3.ts b/build-tests/api-extractor-test-01/src/ForgottenExportConsumer3.ts index 55aa7c04138..433bb2b37e6 100644 --- a/build-tests/api-extractor-test-01/src/ForgottenExportConsumer3.ts +++ b/build-tests/api-extractor-test-01/src/ForgottenExportConsumer3.ts @@ -4,10 +4,7 @@ /** * This class is indirectly consumed by ForgottenExportConsumer3. */ -export interface IForgottenIndirectDependency { - -} - +export interface IForgottenIndirectDependency {} /** * This class is directly consumed by ForgottenExportConsumer3. diff --git a/build-tests/api-extractor-test-01/src/ReexportedClass3/index.ts b/build-tests/api-extractor-test-01/src/ReexportedClass3/index.ts index cc7a6009a8d..02904c4af2a 100644 --- a/build-tests/api-extractor-test-01/src/ReexportedClass3/index.ts +++ b/build-tests/api-extractor-test-01/src/ReexportedClass3/index.ts @@ -1 +1 @@ -export { ReexportedClass2 } from '../ReexportedClass2'; \ No newline at end of file +export { ReexportedClass2 } from '../ReexportedClass2'; diff --git a/build-tests/api-extractor-test-01/src/ReferenceLibDirective.ts b/build-tests/api-extractor-test-01/src/ReferenceLibDirective.ts index eda831c2354..cf3079db914 100644 --- a/build-tests/api-extractor-test-01/src/ReferenceLibDirective.ts +++ b/build-tests/api-extractor-test-01/src/ReferenceLibDirective.ts @@ -4,5 +4,4 @@ /// /** @public */ -export class ReferenceLibDirective extends Intl.PluralRules { -} +export class ReferenceLibDirective extends Intl.PluralRules {} diff --git a/build-tests/api-extractor-test-01/src/index.ts b/build-tests/api-extractor-test-01/src/index.ts index dc17d75d595..d4c2dcb4338 100644 --- a/build-tests/api-extractor-test-01/src/index.ts +++ b/build-tests/api-extractor-test-01/src/index.ts @@ -16,8 +16,7 @@ * A simple, normal definition * @public */ -export interface ISimpleInterface { -} +export interface ISimpleInterface {} /** * Test different kinds of ambient definitions @@ -35,7 +34,9 @@ export class AmbientConsumer { * Found via tsconfig.json's "lib" setting, which specifies the built-in "es2015.promise" */ public builtinDefinition2(): Promise { - return new Promise(() => { /* */ }); + return new Promise(() => { + /* */ + }); } /** @@ -60,8 +61,11 @@ export class AmbientConsumer { * Example decorator * @public */ -export function virtual(target: Object, propertyKey: string | symbol, - descriptor: TypedPropertyDescriptor): void { +export function virtual( + target: Object, + propertyKey: string | symbol, + descriptor: TypedPropertyDescriptor +): void { // Eventually we may implement runtime validation (e.g. in DEBUG builds) // but currently this decorator is only used by the build tools. } @@ -91,15 +95,12 @@ export * from './DeclarationMerging'; export * from './Enums'; -export { - DefaultExportEdgeCase, - default as ClassExportedAsDefault -} from './DefaultExportEdgeCase'; +export { DefaultExportEdgeCase, default as ClassExportedAsDefault } from './DefaultExportEdgeCase'; /** * Test that we can correctly carry default imports into the rollup .d.ts file */ -import Long, { MAX_UNSIGNED_VALUE } from "long"; +import Long, { MAX_UNSIGNED_VALUE } from 'long'; export { MAX_UNSIGNED_VALUE }; /** @public */ export declare class UseLong { diff --git a/build-tests/api-extractor-test-01/src/variableDeclarations.ts b/build-tests/api-extractor-test-01/src/variableDeclarations.ts index ed5390ce6ee..bba6ad6f7d3 100644 --- a/build-tests/api-extractor-test-01/src/variableDeclarations.ts +++ b/build-tests/api-extractor-test-01/src/variableDeclarations.ts @@ -7,5 +7,5 @@ export const VARIABLE: string = 'hello'; /** @public */ export namespace NamespaceContainingVariable { /** @internal */ - export let variable: object[] = [] + export let variable: object[] = []; } diff --git a/build-tests/api-extractor-test-01/tsconfig.json b/build-tests/api-extractor-test-01/tsconfig.json index fb5d521a29c..a48293c1057 100644 --- a/build-tests/api-extractor-test-01/tsconfig.json +++ b/build-tests/api-extractor-test-01/tsconfig.json @@ -9,22 +9,9 @@ "experimentalDecorators": true, "strictNullChecks": true, "esModuleInterop": true, - "types": [ - "node", - "jest" - ], - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ], + "types": ["node", "jest"], + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"], "outDir": "lib" }, - "include": [ - "src/**/*.ts", - "typings/tsd.d.ts" - ] -} \ No newline at end of file + "include": ["src/**/*.ts", "typings/tsd.d.ts"] +} diff --git a/build-tests/api-extractor-test-02/config/api-extractor.json b/build-tests/api-extractor-test-02/config/api-extractor.json index cfb37d95019..f1ecda4020f 100644 --- a/build-tests/api-extractor-test-02/config/api-extractor.json +++ b/build-tests/api-extractor-test-02/config/api-extractor.json @@ -4,7 +4,7 @@ "mainEntryPointFilePath": "/lib/index.d.ts", "apiReport": { - "enabled": true, + "enabled": true }, "docModel": { diff --git a/build-tests/api-extractor-test-02/src/RenamedReexportedClass.ts b/build-tests/api-extractor-test-02/src/RenamedReexportedClass.ts index 099c42b60a6..fbd22dcec94 100644 --- a/build-tests/api-extractor-test-02/src/RenamedReexportedClass.ts +++ b/build-tests/api-extractor-test-02/src/RenamedReexportedClass.ts @@ -2,4 +2,3 @@ // See LICENSE in the project root for license information. export { ReexportedClass as RenamedReexportedClass } from 'api-extractor-test-01'; - diff --git a/build-tests/api-extractor-test-02/src/TypeFromImportedModule.ts b/build-tests/api-extractor-test-02/src/TypeFromImportedModule.ts index 066535b759e..466c7012e36 100644 --- a/build-tests/api-extractor-test-02/src/TypeFromImportedModule.ts +++ b/build-tests/api-extractor-test-02/src/TypeFromImportedModule.ts @@ -33,5 +33,4 @@ export function importedModuleAsGenericParameter(): GenericInterface/lib/index.d.ts", "apiReport": { - "enabled": true, + "enabled": true }, "docModel": { diff --git a/build-tests/api-extractor-test-04/src/AlphaClass.ts b/build-tests/api-extractor-test-04/src/AlphaClass.ts index a762f97e5c4..3166c1240dc 100644 --- a/build-tests/api-extractor-test-04/src/AlphaClass.ts +++ b/build-tests/api-extractor-test-04/src/AlphaClass.ts @@ -9,13 +9,11 @@ export class AlphaClass { /** * This is a comment */ - public undecoratedMember(): void { - } + public undecoratedMember(): void {} /** * This is an internal member * @internal */ - public _internalMember(): void { - } + public _internalMember(): void {} } diff --git a/build-tests/api-extractor-test-04/src/BetaClass.ts b/build-tests/api-extractor-test-04/src/BetaClass.ts index 3a068b0b43c..2a8251ec1a1 100644 --- a/build-tests/api-extractor-test-04/src/BetaClass.ts +++ b/build-tests/api-extractor-test-04/src/BetaClass.ts @@ -11,20 +11,17 @@ export class BetaClass implements BetaInterface { /** * This is a comment */ - public undecoratedMember(): void { - } + public undecoratedMember(): void {} /** * This is an alpha comment * @alpha */ - public alphaMember(): void { - } + public alphaMember(): void {} /** * This is an internal member * @internal */ - public _internalMember(): void { - } + public _internalMember(): void {} } diff --git a/build-tests/api-extractor-test-04/src/EntangledNamespace.ts b/build-tests/api-extractor-test-04/src/EntangledNamespace.ts index f73a70a6fc5..8f7b3cd5fbe 100644 --- a/build-tests/api-extractor-test-04/src/EntangledNamespace.ts +++ b/build-tests/api-extractor-test-04/src/EntangledNamespace.ts @@ -6,13 +6,11 @@ * @beta */ export namespace EntangledNamespace { - /** * This is a nested namespace. * The "beta" release tag is inherited from the parent. */ export namespace N2 { - /** * This class is in a nested namespace. * @alpha diff --git a/build-tests/api-extractor-test-04/src/EnumExamples.ts b/build-tests/api-extractor-test-04/src/EnumExamples.ts index 5b7c18aaae3..a5f8de79309 100644 --- a/build-tests/api-extractor-test-04/src/EnumExamples.ts +++ b/build-tests/api-extractor-test-04/src/EnumExamples.ts @@ -21,7 +21,7 @@ export enum RegularEnum { * This member is marked as \@internal * @internal */ - _InternalMember + _InternalMember, } /** @@ -44,5 +44,5 @@ export const enum ConstEnum { * This member is marked as \@internal * @internal */ - _InternalMember = '_InternalMember' + _InternalMember = '_InternalMember', } diff --git a/build-tests/api-extractor-test-04/src/IPublicComplexInterface.ts b/build-tests/api-extractor-test-04/src/IPublicComplexInterface.ts index dcd9b70d6ee..7c689feebe5 100644 --- a/build-tests/api-extractor-test-04/src/IPublicComplexInterface.ts +++ b/build-tests/api-extractor-test-04/src/IPublicComplexInterface.ts @@ -18,5 +18,5 @@ export interface IPublicComplexInterface { * Example of trimming a construct signature. * @internal */ - new(); + new (); } diff --git a/build-tests/api-extractor-test-04/src/InternalClass.ts b/build-tests/api-extractor-test-04/src/InternalClass.ts index 00480567960..8bed22c51c1 100644 --- a/build-tests/api-extractor-test-04/src/InternalClass.ts +++ b/build-tests/api-extractor-test-04/src/InternalClass.ts @@ -9,6 +9,5 @@ export class InternalClass { /** * This is a comment */ - public undecoratedMember(): void { - } + public undecoratedMember(): void {} } diff --git a/build-tests/api-extractor-test-04/src/PublicClass.ts b/build-tests/api-extractor-test-04/src/PublicClass.ts index ce66004aef3..d2adf4d8d05 100644 --- a/build-tests/api-extractor-test-04/src/PublicClass.ts +++ b/build-tests/api-extractor-test-04/src/PublicClass.ts @@ -5,8 +5,7 @@ * These are internal constructor parameters for PublicClass's internal constructor. * @internal */ -export interface IPublicClassInternalParameters { -} +export interface IPublicClassInternalParameters {} /** * This is a public class @@ -14,8 +13,7 @@ export interface IPublicClassInternalParameters { */ export class PublicClass { /** @internal */ - constructor(parameters: IPublicClassInternalParameters) { - } + constructor(parameters: IPublicClassInternalParameters) {} /** * This is a beta field @@ -26,27 +24,23 @@ export class PublicClass { /** * This is a comment */ - public undecoratedMember(): void { - } + public undecoratedMember(): void {} /** * This is a beta comment * @beta */ - public betaMember(): void { - } + public betaMember(): void {} /** * This is an alpha comment * @alpha */ - public alphaMember(): void { - } + public alphaMember(): void {} /** * This is an internal member * @internal */ - public _internalMember(): void { - } + public _internalMember(): void {} } diff --git a/build-tests/api-extractor-test-04/tsconfig.json b/build-tests/api-extractor-test-04/tsconfig.json index f6c01bb8017..7e2cba55d35 100644 --- a/build-tests/api-extractor-test-04/tsconfig.json +++ b/build-tests/api-extractor-test-04/tsconfig.json @@ -9,20 +9,9 @@ "experimentalDecorators": true, "strictNullChecks": true, "esModuleInterop": true, - "types": [ - ], - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ], + "types": [], + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"], "outDir": "lib" }, - "include": [ - "src/**/*.ts", - "typings/tsd.d.ts" - ] -} \ No newline at end of file + "include": ["src/**/*.ts", "typings/tsd.d.ts"] +} diff --git a/build-tests/localization-plugin-test-01/src/chunks/chunkWithoutStrings.ts b/build-tests/localization-plugin-test-01/src/chunks/chunkWithoutStrings.ts index e2ce851c3fc..5e19d5f1060 100644 --- a/build-tests/localization-plugin-test-01/src/chunks/chunkWithoutStrings.ts +++ b/build-tests/localization-plugin-test-01/src/chunks/chunkWithoutStrings.ts @@ -2,4 +2,4 @@ export class ChunkWithoutStringsClass { public doStuff(): void { console.log('STATIC STRING'); } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-01/src/indexA.ts b/build-tests/localization-plugin-test-01/src/indexA.ts index d3980eaf35a..c30ebb90d7b 100644 --- a/build-tests/localization-plugin-test-01/src/indexA.ts +++ b/build-tests/localization-plugin-test-01/src/indexA.ts @@ -1,5 +1,6 @@ - -import(/* webpackChunkName: 'chunk-without-strings' */ './chunks/chunkWithoutStrings').then(({ ChunkWithoutStringsClass }) => { - const chunk = new ChunkWithoutStringsClass(); - chunk.doStuff(); -}); +import(/* webpackChunkName: 'chunk-without-strings' */ './chunks/chunkWithoutStrings').then( + ({ ChunkWithoutStringsClass }) => { + const chunk = new ChunkWithoutStringsClass(); + chunk.doStuff(); + } +); diff --git a/build-tests/localization-plugin-test-01/tsconfig.json b/build-tests/localization-plugin-test-01/tsconfig.json index 400b3ad0871..443e016ec69 100644 --- a/build-tests/localization-plugin-test-01/tsconfig.json +++ b/build-tests/localization-plugin-test-01/tsconfig.json @@ -1,12 +1,7 @@ { "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-web.json", "compilerOptions": { - "rootDirs": [ - "./src", - "./temp/loc-json-ts/" - ], - "types": [ - "webpack-env" - ] + "rootDirs": ["./src", "./temp/loc-json-ts/"], + "types": ["webpack-env"] } } diff --git a/build-tests/localization-plugin-test-01/webpack.config.js b/build-tests/localization-plugin-test-01/webpack.config.js index 6ae0f49eb98..7300223e32e 100644 --- a/build-tests/localization-plugin-test-01/webpack.config.js +++ b/build-tests/localization-plugin-test-01/webpack.config.js @@ -20,13 +20,13 @@ function generateConfiguration(mode, outputFolderName) { options: { compiler: require.resolve('@microsoft/rush-stack-compiler-3.5/node_modules/typescript'), logLevel: 'ERROR', - configFile: path.resolve(__dirname, 'tsconfig.json') - } - } - ] + configFile: path.resolve(__dirname, 'tsconfig.json'), + }, + }, + ], }, resolve: { - extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'] + extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'], }, entry: { 'localization-test-A': path.join(__dirname, 'src', 'indexA.ts'), @@ -35,29 +35,29 @@ function generateConfiguration(mode, outputFolderName) { output: { path: path.join(__dirname, outputFolderName), filename: '[name]_[locale]_[contenthash].js', - chunkFilename: '[id].[name]_[locale]_[contenthash].js' + chunkFilename: '[id].[name]_[locale]_[contenthash].js', }, optimization: { - minimize: false + minimize: false, }, plugins: [ new webpack.optimize.ModuleConcatenationPlugin(), new LocalizationPlugin({ localizedData: { defaultLocale: { - localeName: 'en-us' + localeName: 'en-us', }, passthroughLocale: { - usePassthroughLocale: true - } + usePassthroughLocale: true, + }, }, typingsOptions: { generatedTsFolder: path.resolve(__dirname, 'temp', 'loc-json-ts'), - sourceRoot: path.resolve(__dirname, 'src') + sourceRoot: path.resolve(__dirname, 'src'), }, localizationStats: { - dropPath: path.resolve(__dirname, 'temp', 'localization-stats.json') - } + dropPath: path.resolve(__dirname, 'temp', 'localization-stats.json'), + }, }), new BundleAnalyzerPlugin({ openAnalyzer: false, @@ -65,15 +65,15 @@ function generateConfiguration(mode, outputFolderName) { reportFilename: path.resolve(__dirname, 'temp', 'stats.html'), generateStatsFile: true, statsFilename: path.resolve(__dirname, 'temp', 'stats.json'), - logLevel: 'error' + logLevel: 'error', }), new SetPublicPathPlugin({ scriptName: { - useAssetName: true - } + useAssetName: true, + }, }), - new HtmlWebpackPlugin() - ] + new HtmlWebpackPlugin(), + ], }; } diff --git a/build-tests/localization-plugin-test-02/src/chunks/chunkWithStrings.ts b/build-tests/localization-plugin-test-02/src/chunks/chunkWithStrings.ts index 1bcb409d023..87c09c23463 100644 --- a/build-tests/localization-plugin-test-02/src/chunks/chunkWithStrings.ts +++ b/build-tests/localization-plugin-test-02/src/chunks/chunkWithStrings.ts @@ -6,4 +6,4 @@ export class ChunkWithStringsClass { public doStuff(): void { console.log(lodash.escape(strings.string1)); } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-02/src/chunks/chunkWithoutStrings.ts b/build-tests/localization-plugin-test-02/src/chunks/chunkWithoutStrings.ts index 78470d2bd6f..f9467f5c909 100644 --- a/build-tests/localization-plugin-test-02/src/chunks/chunkWithoutStrings.ts +++ b/build-tests/localization-plugin-test-02/src/chunks/chunkWithoutStrings.ts @@ -4,4 +4,4 @@ export class ChunkWithoutStringsClass { public doStuff(): void { console.log(lodash.escape('STATIC STRING')); } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-02/src/chunks/strings2.loc.json b/build-tests/localization-plugin-test-02/src/chunks/strings2.loc.json index 1bdda294e59..abc4a74f9df 100644 --- a/build-tests/localization-plugin-test-02/src/chunks/strings2.loc.json +++ b/build-tests/localization-plugin-test-02/src/chunks/strings2.loc.json @@ -3,4 +3,4 @@ "value": "string two", "comment": "the second string" } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-02/src/indexA.ts b/build-tests/localization-plugin-test-02/src/indexA.ts index b00ce0f5c86..b8fa76cb941 100644 --- a/build-tests/localization-plugin-test-02/src/indexA.ts +++ b/build-tests/localization-plugin-test-02/src/indexA.ts @@ -6,15 +6,19 @@ console.log(string1); console.log(strings3.string2); -import(/* webpackChunkName: 'chunk-with-strings' */ './chunks/chunkWithStrings').then(({ ChunkWithStringsClass }) => { - const chunk = new ChunkWithStringsClass(); - chunk.doStuff(); -}); +import(/* webpackChunkName: 'chunk-with-strings' */ './chunks/chunkWithStrings').then( + ({ ChunkWithStringsClass }) => { + const chunk = new ChunkWithStringsClass(); + chunk.doStuff(); + } +); -import(/* webpackChunkName: 'chunk-without-strings' */ './chunks/chunkWithoutStrings').then(({ ChunkWithoutStringsClass }) => { - const chunk = new ChunkWithoutStringsClass(); - chunk.doStuff(); -}); +import(/* webpackChunkName: 'chunk-without-strings' */ './chunks/chunkWithoutStrings').then( + ({ ChunkWithoutStringsClass }) => { + const chunk = new ChunkWithoutStringsClass(); + chunk.doStuff(); + } +); console.log(strings5.string1); console.log(strings5.stringWithQuotes); diff --git a/build-tests/localization-plugin-test-02/src/indexB.ts b/build-tests/localization-plugin-test-02/src/indexB.ts index fe23890e2c0..ee1d8396f4a 100644 --- a/build-tests/localization-plugin-test-02/src/indexB.ts +++ b/build-tests/localization-plugin-test-02/src/indexB.ts @@ -1,7 +1,4 @@ -import { - string1, - string2 -} from './strings3.loc.json'; +import { string1, string2 } from './strings3.loc.json'; const strings4: string = require('./strings4.loc.json'); console.log(string1); diff --git a/build-tests/localization-plugin-test-02/src/indexC.ts b/build-tests/localization-plugin-test-02/src/indexC.ts index 832cce59692..c30ebb90d7b 100644 --- a/build-tests/localization-plugin-test-02/src/indexC.ts +++ b/build-tests/localization-plugin-test-02/src/indexC.ts @@ -1,4 +1,6 @@ -import(/* webpackChunkName: 'chunk-without-strings' */ './chunks/chunkWithoutStrings').then(({ ChunkWithoutStringsClass }) => { - const chunk = new ChunkWithoutStringsClass(); - chunk.doStuff(); -}); +import(/* webpackChunkName: 'chunk-without-strings' */ './chunks/chunkWithoutStrings').then( + ({ ChunkWithoutStringsClass }) => { + const chunk = new ChunkWithoutStringsClass(); + chunk.doStuff(); + } +); diff --git a/build-tests/localization-plugin-test-02/src/strings1.loc.json b/build-tests/localization-plugin-test-02/src/strings1.loc.json index da6f5831d81..b997eef7518 100644 --- a/build-tests/localization-plugin-test-02/src/strings1.loc.json +++ b/build-tests/localization-plugin-test-02/src/strings1.loc.json @@ -3,4 +3,4 @@ "value": "string one", "comment": "the first string" } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-02/src/strings3.loc.json b/build-tests/localization-plugin-test-02/src/strings3.loc.json index 532ce03159c..c85ab94c731 100644 --- a/build-tests/localization-plugin-test-02/src/strings3.loc.json +++ b/build-tests/localization-plugin-test-02/src/strings3.loc.json @@ -11,4 +11,4 @@ "value": "UNUSED STRING", "comment": "UNUSED STRING" } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-02/src/strings4.loc.json b/build-tests/localization-plugin-test-02/src/strings4.loc.json index f48eafff641..2215f933c17 100644 --- a/build-tests/localization-plugin-test-02/src/strings4.loc.json +++ b/build-tests/localization-plugin-test-02/src/strings4.loc.json @@ -3,4 +3,4 @@ "value": "\"String with quotemarks\"", "comment": "string with quotemarks" } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-02/tsconfig.json b/build-tests/localization-plugin-test-02/tsconfig.json index 400b3ad0871..443e016ec69 100644 --- a/build-tests/localization-plugin-test-02/tsconfig.json +++ b/build-tests/localization-plugin-test-02/tsconfig.json @@ -1,12 +1,7 @@ { "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-web.json", "compilerOptions": { - "rootDirs": [ - "./src", - "./temp/loc-json-ts/" - ], - "types": [ - "webpack-env" - ] + "rootDirs": ["./src", "./temp/loc-json-ts/"], + "types": ["webpack-env"] } } diff --git a/build-tests/localization-plugin-test-02/webpack.config.js b/build-tests/localization-plugin-test-02/webpack.config.js index 983b2d29d62..34fb4dcdc6b 100644 --- a/build-tests/localization-plugin-test-02/webpack.config.js +++ b/build-tests/localization-plugin-test-02/webpack.config.js @@ -20,13 +20,13 @@ function generateConfiguration(mode, outputFolderName) { options: { compiler: require.resolve('@microsoft/rush-stack-compiler-3.5/node_modules/typescript'), logLevel: 'ERROR', - configFile: path.resolve(__dirname, 'tsconfig.json') - } - } - ] + configFile: path.resolve(__dirname, 'tsconfig.json'), + }, + }, + ], }, resolve: { - extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'] + extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'], }, entry: { 'localization-test-A': path.join(__dirname, 'src', 'indexA.ts'), @@ -36,10 +36,10 @@ function generateConfiguration(mode, outputFolderName) { output: { path: path.join(__dirname, outputFolderName), filename: '[name]_[locale]_[contenthash].js', - chunkFilename: '[id].[name]_[locale]_[contenthash].js' + chunkFilename: '[id].[name]_[locale]_[contenthash].js', }, optimization: { - minimize: false + minimize: false, }, devtool: 'source-map', plugins: [ @@ -48,35 +48,35 @@ function generateConfiguration(mode, outputFolderName) { localizedData: { defaultLocale: { localeName: 'en-us', - fillMissingTranslationStrings: true + fillMissingTranslationStrings: true, }, translatedStrings: { - "es-es": { - "./src/strings1.loc.json": { - "string1": "la primera cadena de texto" + 'es-es': { + './src/strings1.loc.json': { + string1: 'la primera cadena de texto', }, - "./src/chunks/strings2.loc.json": { - "string1": "la segunda cadena de texto" + './src/chunks/strings2.loc.json': { + string1: 'la segunda cadena de texto', }, - "./src/strings4.loc.json": { - "string1": "\"cadena de texto con comillas\"" + './src/strings4.loc.json': { + string1: '"cadena de texto con comillas"', }, - "./src/strings5.resx": "./localization/es-es/strings5.resx" - } + './src/strings5.resx': './localization/es-es/strings5.resx', + }, }, passthroughLocale: { usePassthroughLocale: true, - passthroughLocaleName: 'default' + passthroughLocaleName: 'default', }, - normalizeResxNewlines: 'crlf' + normalizeResxNewlines: 'crlf', }, typingsOptions: { generatedTsFolder: path.resolve(__dirname, 'temp', 'loc-json-ts'), - sourceRoot: path.resolve(__dirname, 'src') + sourceRoot: path.resolve(__dirname, 'src'), }, localizationStats: { - dropPath: path.resolve(__dirname, 'temp', 'localization-stats.json') - } + dropPath: path.resolve(__dirname, 'temp', 'localization-stats.json'), + }, }), new BundleAnalyzerPlugin({ openAnalyzer: false, @@ -84,15 +84,15 @@ function generateConfiguration(mode, outputFolderName) { reportFilename: path.resolve(__dirname, 'temp', 'stats.html'), generateStatsFile: true, statsFilename: path.resolve(__dirname, 'temp', 'stats.json'), - logLevel: 'error' + logLevel: 'error', }), new SetPublicPathPlugin({ scriptName: { - useAssetName: true - } + useAssetName: true, + }, }), - new HtmlWebpackPlugin() - ] + new HtmlWebpackPlugin(), + ], }; } diff --git a/build-tests/localization-plugin-test-03/localization/es-es/chunks/strings2.loc.json b/build-tests/localization-plugin-test-03/localization/es-es/chunks/strings2.loc.json index 4be0b16ea3b..ce2cbb4e739 100644 --- a/build-tests/localization-plugin-test-03/localization/es-es/chunks/strings2.loc.json +++ b/build-tests/localization-plugin-test-03/localization/es-es/chunks/strings2.loc.json @@ -2,4 +2,4 @@ "string1": { "value": "la segunda cadena de texto" } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-03/localization/es-es/combinedStringsData.json b/build-tests/localization-plugin-test-03/localization/es-es/combinedStringsData.json index 29273ed40be..b1fe6fe2e79 100644 --- a/build-tests/localization-plugin-test-03/localization/es-es/combinedStringsData.json +++ b/build-tests/localization-plugin-test-03/localization/es-es/combinedStringsData.json @@ -4,4 +4,4 @@ "string2": "cadena de texto cuatro con un ' apóstrofe", "string3": "UNUSED STRING!" } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-03/src/chunks/chunkWithStrings.ts b/build-tests/localization-plugin-test-03/src/chunks/chunkWithStrings.ts index 22987fa8c2f..faca96a0bf2 100644 --- a/build-tests/localization-plugin-test-03/src/chunks/chunkWithStrings.ts +++ b/build-tests/localization-plugin-test-03/src/chunks/chunkWithStrings.ts @@ -4,4 +4,4 @@ export class ChunkWithStringsClass { public doStuff(): void { console.log(strings.string1); } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-03/src/chunks/chunkWithoutStrings.ts b/build-tests/localization-plugin-test-03/src/chunks/chunkWithoutStrings.ts index e2ce851c3fc..5e19d5f1060 100644 --- a/build-tests/localization-plugin-test-03/src/chunks/chunkWithoutStrings.ts +++ b/build-tests/localization-plugin-test-03/src/chunks/chunkWithoutStrings.ts @@ -2,4 +2,4 @@ export class ChunkWithoutStringsClass { public doStuff(): void { console.log('STATIC STRING'); } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-03/src/chunks/strings2.loc.json b/build-tests/localization-plugin-test-03/src/chunks/strings2.loc.json index 1bdda294e59..abc4a74f9df 100644 --- a/build-tests/localization-plugin-test-03/src/chunks/strings2.loc.json +++ b/build-tests/localization-plugin-test-03/src/chunks/strings2.loc.json @@ -3,4 +3,4 @@ "value": "string two", "comment": "the second string" } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-03/src/chunks/unnamedChunkWithStrings.ts b/build-tests/localization-plugin-test-03/src/chunks/unnamedChunkWithStrings.ts index c153fc75b25..dded761545a 100644 --- a/build-tests/localization-plugin-test-03/src/chunks/unnamedChunkWithStrings.ts +++ b/build-tests/localization-plugin-test-03/src/chunks/unnamedChunkWithStrings.ts @@ -6,4 +6,4 @@ export class UnnamedChunkWithStringsClass { console.log(strings2.string1); console.log(strings6.string); } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-03/src/indexA.ts b/build-tests/localization-plugin-test-03/src/indexA.ts index 6ba31eacfe9..14f8db846d3 100644 --- a/build-tests/localization-plugin-test-03/src/indexA.ts +++ b/build-tests/localization-plugin-test-03/src/indexA.ts @@ -6,15 +6,19 @@ console.log(strings1.string1); console.log(strings3.string2); -import(/* webpackChunkName: 'chunk-with-strings' */ './chunks/chunkWithStrings').then(({ ChunkWithStringsClass }) => { - const chunk = new ChunkWithStringsClass(); - chunk.doStuff(); -}); +import(/* webpackChunkName: 'chunk-with-strings' */ './chunks/chunkWithStrings').then( + ({ ChunkWithStringsClass }) => { + const chunk = new ChunkWithStringsClass(); + chunk.doStuff(); + } +); -import(/* webpackChunkName: 'chunk-without-strings' */ './chunks/chunkWithoutStrings').then(({ ChunkWithoutStringsClass }) => { - const chunk = new ChunkWithoutStringsClass(); - chunk.doStuff(); -}); +import(/* webpackChunkName: 'chunk-without-strings' */ './chunks/chunkWithoutStrings').then( + ({ ChunkWithoutStringsClass }) => { + const chunk = new ChunkWithoutStringsClass(); + chunk.doStuff(); + } +); import('./chunks/unnamedChunkWithStrings').then(({ UnnamedChunkWithStringsClass }) => { const chunk = new UnnamedChunkWithStringsClass(); diff --git a/build-tests/localization-plugin-test-03/src/indexC.ts b/build-tests/localization-plugin-test-03/src/indexC.ts index 3ebb7f0ac61..3fa730ce3b4 100644 --- a/build-tests/localization-plugin-test-03/src/indexC.ts +++ b/build-tests/localization-plugin-test-03/src/indexC.ts @@ -1,4 +1,6 @@ -import(/* webpackChunkName: 'chunk-with-strings' */ './chunks/chunkWithStrings').then(({ ChunkWithStringsClass }) => { - const chunk = new ChunkWithStringsClass(); - chunk.doStuff(); -}); +import(/* webpackChunkName: 'chunk-with-strings' */ './chunks/chunkWithStrings').then( + ({ ChunkWithStringsClass }) => { + const chunk = new ChunkWithStringsClass(); + chunk.doStuff(); + } +); diff --git a/build-tests/localization-plugin-test-03/src/indexD.ts b/build-tests/localization-plugin-test-03/src/indexD.ts index 832cce59692..c30ebb90d7b 100644 --- a/build-tests/localization-plugin-test-03/src/indexD.ts +++ b/build-tests/localization-plugin-test-03/src/indexD.ts @@ -1,4 +1,6 @@ -import(/* webpackChunkName: 'chunk-without-strings' */ './chunks/chunkWithoutStrings').then(({ ChunkWithoutStringsClass }) => { - const chunk = new ChunkWithoutStringsClass(); - chunk.doStuff(); -}); +import(/* webpackChunkName: 'chunk-without-strings' */ './chunks/chunkWithoutStrings').then( + ({ ChunkWithoutStringsClass }) => { + const chunk = new ChunkWithoutStringsClass(); + chunk.doStuff(); + } +); diff --git a/build-tests/localization-plugin-test-03/src/strings1.loc.json b/build-tests/localization-plugin-test-03/src/strings1.loc.json index da6f5831d81..b997eef7518 100644 --- a/build-tests/localization-plugin-test-03/src/strings1.loc.json +++ b/build-tests/localization-plugin-test-03/src/strings1.loc.json @@ -3,4 +3,4 @@ "value": "string one", "comment": "the first string" } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-03/src/strings3.loc.json b/build-tests/localization-plugin-test-03/src/strings3.loc.json index 2009ac17ad4..70081042a94 100644 --- a/build-tests/localization-plugin-test-03/src/strings3.loc.json +++ b/build-tests/localization-plugin-test-03/src/strings3.loc.json @@ -11,4 +11,4 @@ "value": "UNUSED STRING", "comment": "UNUSED STRING" } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-03/src/strings4.loc.json b/build-tests/localization-plugin-test-03/src/strings4.loc.json index f48eafff641..2215f933c17 100644 --- a/build-tests/localization-plugin-test-03/src/strings4.loc.json +++ b/build-tests/localization-plugin-test-03/src/strings4.loc.json @@ -3,4 +3,4 @@ "value": "\"String with quotemarks\"", "comment": "string with quotemarks" } -} \ No newline at end of file +} diff --git a/build-tests/localization-plugin-test-03/tsconfig.json b/build-tests/localization-plugin-test-03/tsconfig.json index 400b3ad0871..443e016ec69 100644 --- a/build-tests/localization-plugin-test-03/tsconfig.json +++ b/build-tests/localization-plugin-test-03/tsconfig.json @@ -1,12 +1,7 @@ { "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-web.json", "compilerOptions": { - "rootDirs": [ - "./src", - "./temp/loc-json-ts/" - ], - "types": [ - "webpack-env" - ] + "rootDirs": ["./src", "./temp/loc-json-ts/"], + "types": ["webpack-env"] } } diff --git a/build-tests/localization-plugin-test-03/webpack.config.js b/build-tests/localization-plugin-test-03/webpack.config.js index 82668e97885..4b76c665fbd 100644 --- a/build-tests/localization-plugin-test-03/webpack.config.js +++ b/build-tests/localization-plugin-test-03/webpack.config.js @@ -18,7 +18,12 @@ function resolveMissingString(localeNames, localizedResourcePath) { const result = {}; for (const localeName of localeNames) { - const expectedCombinedStringsPath = path.resolve(__dirname, 'localization', localeName, 'combinedStringsData.json'); + const expectedCombinedStringsPath = path.resolve( + __dirname, + 'localization', + localeName, + 'combinedStringsData.json' + ); try { const loadedCombinedStringsPath = JsonFile.load(expectedCombinedStringsPath); result[localeName] = loadedCombinedStringsPath[contextRelativePath]; @@ -44,77 +49,77 @@ function generateConfiguration(mode, outputFolderName) { options: { compiler: require.resolve('@microsoft/rush-stack-compiler-3.5/node_modules/typescript'), logLevel: 'ERROR', - configFile: path.resolve(__dirname, 'tsconfig.json') - } - } - ] + configFile: path.resolve(__dirname, 'tsconfig.json'), + }, + }, + ], }, resolve: { - extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'] + extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'], }, entry: { 'localization-test-A': path.join(__dirname, 'src', 'indexA.ts'), 'localization-test-B': path.join(__dirname, 'src', 'indexB.ts'), 'localization-test-C': path.join(__dirname, 'src', 'indexC.ts'), - 'localization-test-D': path.join(__dirname, 'src', 'indexD.ts') + 'localization-test-D': path.join(__dirname, 'src', 'indexD.ts'), }, output: { path: path.join(__dirname, outputFolderName), filename: '[name]_[locale]_[contenthash].js', - chunkFilename: '[id].[name]_[locale]_[contenthash].js' + chunkFilename: '[id].[name]_[locale]_[contenthash].js', }, optimization: { - minimize: true + minimize: true, }, plugins: [ new webpack.optimize.ModuleConcatenationPlugin(), new LocalizationPlugin({ localizedData: { defaultLocale: { - localeName: 'en-us' + localeName: 'en-us', }, translatedStrings: { - "es-es": { - "./src/strings1.loc.json": { - "string1": "la primera cadena de texto" + 'es-es': { + './src/strings1.loc.json': { + string1: 'la primera cadena de texto', }, - "./src/chunks/strings2.loc.json": "./localization/es-es/chunks/strings2.loc.json", - "./src/strings4.loc.json": { - "string1": "\"cadena de texto con comillas\"" + './src/chunks/strings2.loc.json': './localization/es-es/chunks/strings2.loc.json', + './src/strings4.loc.json': { + string1: '"cadena de texto con comillas"', }, - "./src/strings5.resx": { - "string1": "La primera cadena de texto RESX", - "stringWithQuotes": "\"cadena de texto RESX con comillas\"" + './src/strings5.resx': { + string1: 'La primera cadena de texto RESX', + stringWithQuotes: '"cadena de texto RESX con comillas"', }, - "./src/chunks/strings6.resx": { - "string": "cadena de texto RESX" - } - } + './src/chunks/strings6.resx': { + string: 'cadena de texto RESX', + }, + }, }, resolveMissingTranslatedStrings: resolveMissingString, passthroughLocale: { - usePassthroughLocale: true + usePassthroughLocale: true, }, pseudolocales: { 'qps-ploca': { append: '', - prepend: '' + prepend: '', }, 'qps-ploc': { append: '##--!!]', - prepend: '[!!--##' - } + prepend: '[!!--##', + }, }, - normalizeResxNewlines: 'lf' + normalizeResxNewlines: 'lf', }, typingsOptions: { generatedTsFolder: path.resolve(__dirname, 'temp', 'loc-json-ts'), sourceRoot: path.resolve(__dirname, 'src'), - exportAsDefault: true + exportAsDefault: true, }, localizationStats: { - dropPath: path.resolve(__dirname, 'temp', 'localization-stats.json') - } + dropPath: path.resolve(__dirname, 'temp', 'localization-stats.json'), + }, }), new BundleAnalyzerPlugin({ openAnalyzer: false, @@ -122,15 +127,15 @@ function generateConfiguration(mode, outputFolderName) { reportFilename: path.resolve(__dirname, 'temp', 'stats.html'), generateStatsFile: true, statsFilename: path.resolve(__dirname, 'temp', 'stats.json'), - logLevel: 'error' + logLevel: 'error', }), new SetPublicPathPlugin({ scriptName: { - useAssetName: true - } + useAssetName: true, + }, }), - new HtmlWebpackPlugin() - ] + new HtmlWebpackPlugin(), + ], }; } diff --git a/build-tests/node-library-build-eslint-test/.eslintrc.js b/build-tests/node-library-build-eslint-test/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/build-tests/node-library-build-eslint-test/.eslintrc.js +++ b/build-tests/node-library-build-eslint-test/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/build-tests/node-library-build-eslint-test/src/index.ts b/build-tests/node-library-build-eslint-test/src/index.ts index bdaeb7a05ad..c11271004f5 100644 --- a/build-tests/node-library-build-eslint-test/src/index.ts +++ b/build-tests/node-library-build-eslint-test/src/index.ts @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export class TestClass { -} +export class TestClass {} diff --git a/build-tests/node-library-build-eslint-test/tsconfig.json b/build-tests/node-library-build-eslint-test/tsconfig.json index cac4ac48cb1..a9d93bbacad 100644 --- a/build-tests/node-library-build-eslint-test/tsconfig.json +++ b/build-tests/node-library-build-eslint-test/tsconfig.json @@ -1,8 +1,6 @@ { "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "node" - ] + "types": ["node"] } } diff --git a/build-tests/node-library-build-tslint-test/src/index.ts b/build-tests/node-library-build-tslint-test/src/index.ts index ca48574e62a..091d6dd85af 100644 --- a/build-tests/node-library-build-tslint-test/src/index.ts +++ b/build-tests/node-library-build-tslint-test/src/index.ts @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -class TestClass { -} +class TestClass {} diff --git a/build-tests/rush-stack-compiler-2.4-library-test/src/TestClass.ts b/build-tests/rush-stack-compiler-2.4-library-test/src/TestClass.ts index bdaeb7a05ad..c11271004f5 100644 --- a/build-tests/rush-stack-compiler-2.4-library-test/src/TestClass.ts +++ b/build-tests/rush-stack-compiler-2.4-library-test/src/TestClass.ts @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export class TestClass { -} +export class TestClass {} diff --git a/build-tests/rush-stack-compiler-2.7-library-test/src/TestClass.ts b/build-tests/rush-stack-compiler-2.7-library-test/src/TestClass.ts index bdaeb7a05ad..c11271004f5 100644 --- a/build-tests/rush-stack-compiler-2.7-library-test/src/TestClass.ts +++ b/build-tests/rush-stack-compiler-2.7-library-test/src/TestClass.ts @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export class TestClass { -} +export class TestClass {} diff --git a/build-tests/rush-stack-compiler-2.8-library-test/src/TestClass.ts b/build-tests/rush-stack-compiler-2.8-library-test/src/TestClass.ts index bdaeb7a05ad..c11271004f5 100644 --- a/build-tests/rush-stack-compiler-2.8-library-test/src/TestClass.ts +++ b/build-tests/rush-stack-compiler-2.8-library-test/src/TestClass.ts @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export class TestClass { -} +export class TestClass {} diff --git a/build-tests/rush-stack-compiler-2.9-library-test/src/TestClass.ts b/build-tests/rush-stack-compiler-2.9-library-test/src/TestClass.ts index bdaeb7a05ad..c11271004f5 100644 --- a/build-tests/rush-stack-compiler-2.9-library-test/src/TestClass.ts +++ b/build-tests/rush-stack-compiler-2.9-library-test/src/TestClass.ts @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export class TestClass { -} +export class TestClass {} diff --git a/build-tests/rush-stack-compiler-3.0-library-test/src/TestClass.ts b/build-tests/rush-stack-compiler-3.0-library-test/src/TestClass.ts index bdaeb7a05ad..c11271004f5 100644 --- a/build-tests/rush-stack-compiler-3.0-library-test/src/TestClass.ts +++ b/build-tests/rush-stack-compiler-3.0-library-test/src/TestClass.ts @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export class TestClass { -} +export class TestClass {} diff --git a/build-tests/rush-stack-compiler-3.1-library-test/src/TestClass.ts b/build-tests/rush-stack-compiler-3.1-library-test/src/TestClass.ts index bdaeb7a05ad..c11271004f5 100644 --- a/build-tests/rush-stack-compiler-3.1-library-test/src/TestClass.ts +++ b/build-tests/rush-stack-compiler-3.1-library-test/src/TestClass.ts @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export class TestClass { -} +export class TestClass {} diff --git a/build-tests/rush-stack-compiler-3.2-library-test/src/TestClass.ts b/build-tests/rush-stack-compiler-3.2-library-test/src/TestClass.ts index bdaeb7a05ad..c11271004f5 100644 --- a/build-tests/rush-stack-compiler-3.2-library-test/src/TestClass.ts +++ b/build-tests/rush-stack-compiler-3.2-library-test/src/TestClass.ts @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export class TestClass { -} +export class TestClass {} diff --git a/build-tests/rush-stack-compiler-3.3-library-test/src/TestClass.ts b/build-tests/rush-stack-compiler-3.3-library-test/src/TestClass.ts index bdaeb7a05ad..c11271004f5 100644 --- a/build-tests/rush-stack-compiler-3.3-library-test/src/TestClass.ts +++ b/build-tests/rush-stack-compiler-3.3-library-test/src/TestClass.ts @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export class TestClass { -} +export class TestClass {} diff --git a/build-tests/rush-stack-compiler-3.4-library-test/src/TestClass.ts b/build-tests/rush-stack-compiler-3.4-library-test/src/TestClass.ts index bdaeb7a05ad..c11271004f5 100644 --- a/build-tests/rush-stack-compiler-3.4-library-test/src/TestClass.ts +++ b/build-tests/rush-stack-compiler-3.4-library-test/src/TestClass.ts @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export class TestClass { -} +export class TestClass {} diff --git a/build-tests/rush-stack-compiler-3.5-library-test/src/TestClass.ts b/build-tests/rush-stack-compiler-3.5-library-test/src/TestClass.ts index bdaeb7a05ad..c11271004f5 100644 --- a/build-tests/rush-stack-compiler-3.5-library-test/src/TestClass.ts +++ b/build-tests/rush-stack-compiler-3.5-library-test/src/TestClass.ts @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export class TestClass { -} +export class TestClass {} diff --git a/build-tests/rush-stack-compiler-3.6-library-test/src/TestClass.ts b/build-tests/rush-stack-compiler-3.6-library-test/src/TestClass.ts index bdaeb7a05ad..c11271004f5 100644 --- a/build-tests/rush-stack-compiler-3.6-library-test/src/TestClass.ts +++ b/build-tests/rush-stack-compiler-3.6-library-test/src/TestClass.ts @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export class TestClass { -} +export class TestClass {} diff --git a/build-tests/rush-stack-compiler-3.7-library-test/src/TestClass.ts b/build-tests/rush-stack-compiler-3.7-library-test/src/TestClass.ts index bdaeb7a05ad..c11271004f5 100644 --- a/build-tests/rush-stack-compiler-3.7-library-test/src/TestClass.ts +++ b/build-tests/rush-stack-compiler-3.7-library-test/src/TestClass.ts @@ -1,5 +1,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export class TestClass { -} +export class TestClass {} diff --git a/build-tests/ts-command-line-test/src/PushAction.ts b/build-tests/ts-command-line-test/src/PushAction.ts index a8ac4ae3927..e24a3d43287 100644 --- a/build-tests/ts-command-line-test/src/PushAction.ts +++ b/build-tests/ts-command-line-test/src/PushAction.ts @@ -1,7 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { CommandLineFlagParameter, CommandLineAction, CommandLineChoiceParameter } from '@rushstack/ts-command-line'; +import { + CommandLineFlagParameter, + CommandLineAction, + CommandLineChoiceParameter, +} from '@rushstack/ts-command-line'; import { BusinessLogic } from './BusinessLogic'; export class PushAction extends CommandLineAction { @@ -12,19 +16,21 @@ export class PushAction extends CommandLineAction { super({ actionName: 'push', summary: 'Pushes a widget to the service', - documentation: 'Here we provide a longer description of how our action works.' + documentation: 'Here we provide a longer description of how our action works.', }); } - protected onExecute(): Promise { // abstract - return BusinessLogic.doTheWork(this._force.value, this._protocol.value || "(none)"); + protected onExecute(): Promise { + // abstract + return BusinessLogic.doTheWork(this._force.value, this._protocol.value || '(none)'); } - protected onDefineParameters(): void { // abstract + protected onDefineParameters(): void { + // abstract this._force = this.defineFlagParameter({ parameterLongName: '--force', parameterShortName: '-f', - description: 'Push and overwrite any existing state' + description: 'Push and overwrite any existing state', }); this._protocol = this.defineChoiceParameter({ @@ -32,7 +38,7 @@ export class PushAction extends CommandLineAction { description: 'Specify the protocol to use', alternatives: ['ftp', 'webdav', 'scp'], environmentVariable: 'WIDGET_PROTOCOL', - defaultValue: 'scp' + defaultValue: 'scp', }); } } diff --git a/build-tests/ts-command-line-test/src/RunAction.ts b/build-tests/ts-command-line-test/src/RunAction.ts index a4fb5a1ecc0..fcaece891e8 100644 --- a/build-tests/ts-command-line-test/src/RunAction.ts +++ b/build-tests/ts-command-line-test/src/RunAction.ts @@ -3,7 +3,6 @@ import { CommandLineAction, CommandLineStringParameter } from '@rushstack/ts-command-line'; - export class RunAction extends CommandLineAction { private _title: CommandLineStringParameter; @@ -11,27 +10,29 @@ export class RunAction extends CommandLineAction { super({ actionName: 'run', summary: 'This action (hypothetically) passes its command line arguments to the shell to be executed.', - documentation: 'This demonstrates how to use the defineCommandLineRemainder() API.' + documentation: 'This demonstrates how to use the defineCommandLineRemainder() API.', }); } - protected onExecute(): Promise { // abstract + protected onExecute(): Promise { + // abstract console.log(`Console Title: ${this._title.value || '(none)'}`); console.log('Arguments to be executed: ' + JSON.stringify(this.remainder!.values)); return Promise.resolve(); } - protected onDefineParameters(): void { // abstract + protected onDefineParameters(): void { + // abstract this._title = this.defineStringParameter({ parameterLongName: '--title', argumentName: 'TITLE', environmentVariable: 'WIDGET_TITLE', - description: 'An optional title to show in the console window' + description: 'An optional title to show in the console window', }); this.defineCommandLineRemainder({ - description: 'The remaining arguments are passed along to the command shell.' + description: 'The remaining arguments are passed along to the command shell.', }); } } diff --git a/build-tests/ts-command-line-test/src/WidgetCommandLine.ts b/build-tests/ts-command-line-test/src/WidgetCommandLine.ts index fc21ea2e223..807025f4db0 100644 --- a/build-tests/ts-command-line-test/src/WidgetCommandLine.ts +++ b/build-tests/ts-command-line-test/src/WidgetCommandLine.ts @@ -12,23 +12,25 @@ export class WidgetCommandLine extends CommandLineParser { public constructor() { super({ toolFilename: 'widget', - toolDescription: 'The "widget" tool is a code sample for using the @rushstack/ts-command-line library.' + toolDescription: 'The "widget" tool is a code sample for using the @rushstack/ts-command-line library.', }); this.addAction(new PushAction()); this.addAction(new RunAction()); } - protected onDefineParameters(): void { // abstract + protected onDefineParameters(): void { + // abstract this._verbose = this.defineFlagParameter({ parameterLongName: '--verbose', parameterShortName: '-v', - description: 'Show extra logging detail' + description: 'Show extra logging detail', }); } - protected onExecute(): Promise { // override + protected onExecute(): Promise { + // override BusinessLogic.configureLogger(this._verbose.value); return super.onExecute(); } -} \ No newline at end of file +} diff --git a/build-tests/ts-command-line-test/tsconfig.json b/build-tests/ts-command-line-test/tsconfig.json index 6b91bd7ea45..3b5e127e2c0 100644 --- a/build-tests/ts-command-line-test/tsconfig.json +++ b/build-tests/ts-command-line-test/tsconfig.json @@ -7,20 +7,9 @@ "sourceMap": true, "experimentalDecorators": true, "strictNullChecks": true, - "types": [ - "node" - ], - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ], + "types": ["node"], + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"], "outDir": "lib" }, - "include": [ - "src/**/*.ts" - ] -} \ No newline at end of file + "include": ["src/**/*.ts"] +} diff --git a/build-tests/web-library-build-test/config/jest.json b/build-tests/web-library-build-test/config/jest.json index b4a7ec97a56..902b00ea176 100644 --- a/build-tests/web-library-build-test/config/jest.json +++ b/build-tests/web-library-build-test/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": true -} \ No newline at end of file +} diff --git a/build-tests/web-library-build-test/config/jest/jest.config.json b/build-tests/web-library-build-test/config/jest/jest.config.json index 20402f6805d..0fbe818b4ad 100644 --- a/build-tests/web-library-build-test/config/jest/jest.config.json +++ b/build-tests/web-library-build-test/config/jest/jest.config.json @@ -6,13 +6,11 @@ "packageJson": "package.json" } }, - "moduleFileExtensions": [ - "js" - ], + "moduleFileExtensions": ["js"], "moduleNameMapper": { "ts-jest": "/node_modules/ts-jest/index.js" }, "transform": { "^.+\\.(js|ts|tsx)$": "ts-jest" } -} \ No newline at end of file +} diff --git a/build-tests/web-library-build-test/config/pre-copy.json b/build-tests/web-library-build-test/config/pre-copy.json index 7f8e3ce6a56..5bdc61d35cc 100644 --- a/build-tests/web-library-build-test/config/pre-copy.json +++ b/build-tests/web-library-build-test/config/pre-copy.json @@ -1,7 +1,5 @@ { "copyTo": { - "lib": [ - "preCopyTest.js" - ] + "lib": ["preCopyTest.js"] } -} \ No newline at end of file +} diff --git a/build-tests/web-library-build-test/src/preCopyTest.js b/build-tests/web-library-build-test/src/preCopyTest.js index 0d1a2a3d122..5f7f15b63e3 100644 --- a/build-tests/web-library-build-test/src/preCopyTest.js +++ b/build-tests/web-library-build-test/src/preCopyTest.js @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); function preCopyTest() { - /* no-op */ + /* no-op */ } exports.default = preCopyTest; - diff --git a/build-tests/web-library-build-test/tsconfig.json b/build-tests/web-library-build-test/tsconfig.json index 27f33d4cc16..9d919e33b85 100644 --- a/build-tests/web-library-build-test/tsconfig.json +++ b/build-tests/web-library-build-test/tsconfig.json @@ -1,8 +1,6 @@ { "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-web.json", "compilerOptions": { - "types": [ - "jest" - ] + "types": ["jest"] } } diff --git a/common/config/azure-pipelines/ci.yaml b/common/config/azure-pipelines/ci.yaml index 811f20895e5..25b16f8dea1 100644 --- a/common/config/azure-pipelines/ci.yaml +++ b/common/config/azure-pipelines/ci.yaml @@ -1,18 +1,18 @@ pool: vmImage: 'ubuntu-latest' jobs: -- job: PRBuild - condition: succeeded() - strategy: - matrix: - 'NodeJs 8': - NodeVersion: 8 - 'NodeJs 10': - NodeVersion: 10 - 'NodeJs 12': - NodeVersion: 12 - 'NodeJs 14': - NodeVersion: 14 - steps: - - checkout: self - - template: templates/build.yaml + - job: PRBuild + condition: succeeded() + strategy: + matrix: + 'NodeJs 8': + NodeVersion: 8 + 'NodeJs 10': + NodeVersion: 10 + 'NodeJs 12': + NodeVersion: 12 + 'NodeJs 14': + NodeVersion: 14 + steps: + - checkout: self + - template: templates/build.yaml diff --git a/common/config/azure-pipelines/npm-publish-rush.yaml b/common/config/azure-pipelines/npm-publish-rush.yaml index b64df02698d..6dc6c9e7f5f 100644 --- a/common/config/azure-pipelines/npm-publish-rush.yaml +++ b/common/config/azure-pipelines/npm-publish-rush.yaml @@ -4,4 +4,4 @@ variables: NodeVersion: 12 VersionPolicy: rush steps: -- template: templates/buildAndPublish.yaml + - template: templates/buildAndPublish.yaml diff --git a/common/config/azure-pipelines/npm-publish.yaml b/common/config/azure-pipelines/npm-publish.yaml index 14449423e40..8d9b0b787e3 100644 --- a/common/config/azure-pipelines/npm-publish.yaml +++ b/common/config/azure-pipelines/npm-publish.yaml @@ -4,4 +4,4 @@ variables: NodeVersion: 12 VersionPolicy: noRush steps: -- template: templates/buildAndPublish.yaml + - template: templates/buildAndPublish.yaml diff --git a/common/config/azure-pipelines/templates/build.yaml b/common/config/azure-pipelines/templates/build.yaml index 3a77161242b..8a98f72439f 100644 --- a/common/config/azure-pipelines/templates/build.yaml +++ b/common/config/azure-pipelines/templates/build.yaml @@ -1,16 +1,16 @@ steps: -- task: NodeTool@0 - displayName: 'Use Node $(NodeVersion).x' - inputs: - versionSpec: '$(NodeVersion).x' - checkLatest: true -- script: 'git config --local user.email rushbot@users.noreply.github.com' - displayName: 'git config email' -- script: 'git config --local user.name Rushbot' - displayName: 'git config name' -- script: 'node common/scripts/install-run-rush.js change --verify' - displayName: 'Verify Change Logs' -- script: 'node common/scripts/install-run-rush.js install' - displayName: 'Rush Install' -- script: 'node common/scripts/install-run-rush.js rebuild --verbose --production' - displayName: 'Rush Rebuild' + - task: NodeTool@0 + displayName: 'Use Node $(NodeVersion).x' + inputs: + versionSpec: '$(NodeVersion).x' + checkLatest: true + - script: 'git config --local user.email rushbot@users.noreply.github.com' + displayName: 'git config email' + - script: 'git config --local user.name Rushbot' + displayName: 'git config name' + - script: 'node common/scripts/install-run-rush.js change --verify' + displayName: 'Verify Change Logs' + - script: 'node common/scripts/install-run-rush.js install' + displayName: 'Rush Install' + - script: 'node common/scripts/install-run-rush.js rebuild --verbose --production' + displayName: 'Rush Rebuild' diff --git a/common/config/azure-pipelines/templates/buildAndPublish.yaml b/common/config/azure-pipelines/templates/buildAndPublish.yaml index 5675650c399..778ac7fec5d 100644 --- a/common/config/azure-pipelines/templates/buildAndPublish.yaml +++ b/common/config/azure-pipelines/templates/buildAndPublish.yaml @@ -1,10 +1,10 @@ steps: -- checkout: self - persistCredentials: true -- template: ./build.yaml -- script: 'node common/scripts/install-run-rush.js version --bump --version-policy $(VersionPolicy) --target-branch $(Build.SourceBranchName)' - displayName: 'Rush Version' -- script: 'node common/scripts/install-run-rush.js publish --apply --publish --include-all --target-branch $(Build.SourceBranchName) --add-commit-details --set-access-level public' - displayName: 'Rush Publish' - env: - NPM_AUTH_TOKEN: $(npmToken) \ No newline at end of file + - checkout: self + persistCredentials: true + - template: ./build.yaml + - script: 'node common/scripts/install-run-rush.js version --bump --version-policy $(VersionPolicy) --target-branch $(Build.SourceBranchName)' + displayName: 'Rush Version' + - script: 'node common/scripts/install-run-rush.js publish --apply --publish --include-all --target-branch $(Build.SourceBranchName) --add-commit-details --set-access-level public' + displayName: 'Rush Publish' + env: + NPM_AUTH_TOKEN: $(npmToken) diff --git a/common/config/rush/command-line.json b/common/config/rush/command-line.json index 32eb1b4737b..7e9ed229538 100644 --- a/common/config/rush/command-line.json +++ b/common/config/rush/command-line.json @@ -253,13 +253,13 @@ "longName": "--no-color", "parameterKind": "flag", "description": "disable colors in the build log, defaults to 'true'", - "associatedCommands": [ "build", "rebuild" ] + "associatedCommands": ["build", "rebuild"] }, { "longName": "--production", "parameterKind": "flag", "description": "Perform a production build, including minification and localization steps", - "associatedCommands": [ "build", "rebuild" ] + "associatedCommands": ["build", "rebuild"] } ] } diff --git a/common/config/rush/common-versions.json b/common/config/rush/common-versions.json index 169070d68ff..e3994fac2d8 100644 --- a/common/config/rush/common-versions.json +++ b/common/config/rush/common-versions.json @@ -19,7 +19,6 @@ * will recalculate all version selections. */ "preferredVersions": { - /** * When someone asks for "^1.0.0" make sure they get "1.2.3" when working in this repo, * instead of the latest version. @@ -62,8 +61,7 @@ * USUAL VERSION (WHICH IS INFERRED BY LOOKING AT ALL PROJECTS IN THE REPO). * This design avoids unnecessary churn in this file. */ - "allowedAlternativeVersions": { - + "allowedAlternativeVersions": { /** * For example, allow some projects to use an older TypeScript compiler * (in addition to whatever "usual" version is being used by other projects in the repo): diff --git a/common/config/rush/experiments.json b/common/config/rush/experiments.json index b233e6a6a99..5dcf5643e63 100644 --- a/common/config/rush/experiments.json +++ b/common/config/rush/experiments.json @@ -3,14 +3,14 @@ * Rush features. For full documentation, please see https://rushjs.io */ { - "$schema": "https://developer.microsoft.com/json-schemas/rush/v5/experiments.schema.json", + "$schema": "https://developer.microsoft.com/json-schemas/rush/v5/experiments.schema.json" /** - * Rush 5.14.0 improved incremental builds to ignore spurious changes in the pnpm-lock.json file. - * This optimization is enabled by default. If you encounter a problem where "rush build" is neglecting - * to build some projects, please open a GitHub issue. As a workaround you can uncomment this line - * to temporarily restore the old behavior where everything must be rebuilt whenever pnpm-lock.json - * is modified. - */ + * Rush 5.14.0 improved incremental builds to ignore spurious changes in the pnpm-lock.json file. + * This optimization is enabled by default. If you encounter a problem where "rush build" is neglecting + * to build some projects, please open a GitHub issue. As a workaround you can uncomment this line + * to temporarily restore the old behavior where everything must be rebuilt whenever pnpm-lock.json + * is modified. + */ // "legacyIncrementalBuildDependencyDetection": true } diff --git a/common/config/rush/nonbrowser-approved-packages.json b/common/config/rush/nonbrowser-approved-packages.json index 21691d2c4d3..5f4a36fa39f 100644 --- a/common/config/rush/nonbrowser-approved-packages.json +++ b/common/config/rush/nonbrowser-approved-packages.json @@ -4,667 +4,667 @@ "packages": [ { "name": "@jest/core", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@jest/reporters", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@microsoft/api-documenter", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@microsoft/api-extractor", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@microsoft/api-extractor-model", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@microsoft/decorators", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@microsoft/gulp-core-build", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@microsoft/gulp-core-build-mocha", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@microsoft/gulp-core-build-sass", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@microsoft/gulp-core-build-serve", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@microsoft/gulp-core-build-typescript", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@microsoft/gulp-core-build-webpack", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@microsoft/load-themed-styles", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@microsoft/node-library-build", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@microsoft/rush-lib", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@microsoft/rush-stack", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@microsoft/rush-stack-compiler-2.4", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "@microsoft/rush-stack-compiler-2.7", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@microsoft/rush-stack-compiler-2.8", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "@microsoft/rush-stack-compiler-2.9", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "@microsoft/rush-stack-compiler-3.0", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@microsoft/rush-stack-compiler-3.1", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@microsoft/rush-stack-compiler-3.2", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@microsoft/rush-stack-compiler-3.3", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "@microsoft/rush-stack-compiler-3.4", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@microsoft/rush-stack-compiler-3.5", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@microsoft/rush-stack-compiler-3.6", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "@microsoft/rush-stack-compiler-3.7", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@microsoft/rush-stack-compiler-shared", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@microsoft/sp-tslint-rules", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@microsoft/teams-js", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "@microsoft/ts-command-line", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "@microsoft/tsdoc", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@microsoft/web-library-build", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@pnpm/link-bins", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@pnpm/logger", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@rushstack/debug-certificate-manager", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@rushstack/eslint-config", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@rushstack/eslint-plugin", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@rushstack/localization-plugin", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "@rushstack/node-core-library", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@rushstack/package-deps-hash", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@rushstack/set-webpack-public-path-plugin", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@rushstack/stream-collator", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@rushstack/ts-command-line", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "@rushstack/typings-generator", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@typescript-eslint/eslint-plugin", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@typescript-eslint/experimental-utils", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@typescript-eslint/parser", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@typescript-eslint/typescript-estree", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "@yarnpkg/lockfile", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "api-extractor-lib1-test", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "api-extractor-lib2-test", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "api-extractor-lib3-test", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "api-extractor-test-01", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "api-extractor-test-02", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "argparse", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "autoprefixer", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "builtin-modules", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "chai", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "chalk", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "chokidar", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "clean-css", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "cli-table", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "colors", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "deasync", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "decache", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "decomment", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "del", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "doc-plugin-rush-stack", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "end-of-stream", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "eslint", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "eslint-plugin-promise", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "eslint-plugin-react", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "eslint-plugin-security", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "eslint-plugin-tsdoc", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "express", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "fs-extra", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "fsevents", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "git-repo-info", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "glob", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "glob-escape", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "globby", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "gulp-cache", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-changed", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-clean-css", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-clip-empty-files", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-clone", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-connect", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-decomment", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-flatten", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-if", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-istanbul", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-mocha", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-open", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-plumber", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-postcss", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-replace", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-sass", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-sourcemaps", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-texttojs", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "gulp-typescript", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "html-webpack-plugin", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "https-proxy-agent", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "ignore", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "import-lazy", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "inquirer", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "istanbul-instrumenter-loader", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "jest", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "jest-cli", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "jest-environment-jsdom", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "jest-nunit-reporter", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "jest-resolve", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "jju", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "js-yaml", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "jsdom", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "loader-utils", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "lodash", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "lodash.merge", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "lolex", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "long", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "md5", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "merge2", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "minimatch", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "mocha", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "node-fetch", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "node-forge", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "node-notifier", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "node-sass", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "npm-package-arg", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "npm-packlist", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "object-assign", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "orchestrator", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "postcss", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "postcss-modules", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "pretty-hrtime", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "pseudolocale", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "read-package-tree", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "resolve", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "semver", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "sinon", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "sinon-chai", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "source-map", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "strict-uri-encode", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "sudo", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "tar", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "through2", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "timsort", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "true-case-path", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "ts-jest", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "ts-loader", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "tslint", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "tslint-microsoft-contrib", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "typescript", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "uglify-js", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "vinyl", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "webpack", - "allowedCategories": [ "libraries", "tests" ] + "allowedCategories": ["libraries", "tests"] }, { "name": "webpack-bundle-analyzer", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "webpack-cli", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "webpack-dev-server", - "allowedCategories": [ "tests" ] + "allowedCategories": ["tests"] }, { "name": "wordwrap", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "xml", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "xmldoc", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "yargs", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] }, { "name": "z-schema", - "allowedCategories": [ "libraries" ] + "allowedCategories": ["libraries"] } ] } diff --git a/common/config/rush/pnpmfile.js b/common/config/rush/pnpmfile.js index cb453b3531d..031c4951500 100644 --- a/common/config/rush/pnpmfile.js +++ b/common/config/rush/pnpmfile.js @@ -1,4 +1,4 @@ -"use strict"; +'use strict'; /** * When using the PNPM package manager, you can use pnpmfile.js to workaround @@ -14,8 +14,8 @@ */ module.exports = { hooks: { - readPackage - } + readPackage, + }, }; /** @@ -27,7 +27,6 @@ module.exports = { * The return value is the updated object. */ function readPackage(packageJson, context) { - // Pin babel-jest until gulp-core-build with jest@25 is published if (packageJson && packageJson.dependencies) { if (packageJson.dependencies['babel-jest']) { @@ -38,11 +37,15 @@ function readPackage(packageJson, context) { } } - // these packages have peerDependencies on typescript, but now we have multiple copies // in the repo so it doesn't know which one to pick // See this issue: https://github.com/pnpm/pnpm/issues/1187 - if (packageJson.name === 'tslint-microsoft-contrib' || packageJson.name === 'tslint' || packageJson.name === 'ts-jest' || packageJson.name === 'ts-loader') { + if ( + packageJson.name === 'tslint-microsoft-contrib' || + packageJson.name === 'tslint' || + packageJson.name === 'ts-jest' || + packageJson.name === 'ts-loader' + ) { packageJson.dependencies['typescript'] = '~3.0.0'; delete packageJson.peerDependencies['typescript']; } diff --git a/common/config/rush/version-policies.json b/common/config/rush/version-policies.json index 995a6ba5a90..05cc2baf890 100644 --- a/common/config/rush/version-policies.json +++ b/common/config/rush/version-policies.json @@ -3,11 +3,11 @@ * For full documentation, please see https://rushjs.io */ - /** - * A list of version policy definitions. A "version policy" is a custom package versioning - * strategy that affects "rush change", "rush version", and "rush publish". The strategy applies - * to a set of projects that are specified using the "versionPolicyName" field in rush.json. - */ +/** + * A list of version policy definitions. A "version policy" is a custom package versioning + * strategy that affects "rush change", "rush version", and "rush publish". The strategy applies + * to a set of projects that are specified using the "versionPolicyName" field in rush.json. + */ [ // { // /** diff --git a/common/scripts/install-run-rush.js b/common/scripts/install-run-rush.js index 7fc381d5640..43908596e52 100644 --- a/common/scripts/install-run-rush.js +++ b/common/scripts/install-run-rush.js @@ -1,7 +1,7 @@ -"use strict"; +'use strict'; // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See the @microsoft/rush package's LICENSE file for license information. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, '__esModule', { value: true }); // THIS FILE WAS GENERATED BY A TOOL. ANY MANUAL MODIFICATIONS WILL GET OVERWRITTEN WHENEVER RUSH IS UPGRADED. // // This script is intended for usage in an automated build environment where the Rush command may not have @@ -12,56 +12,60 @@ Object.defineProperty(exports, "__esModule", { value: true }); // node common/scripts/install-run-rush.js install // // For more information, see: https://rushjs.io/pages/maintainer/setup_new_repo/ -const path = require("path"); -const fs = require("fs"); -const install_run_1 = require("./install-run"); +const path = require('path'); +const fs = require('fs'); +const install_run_1 = require('./install-run'); const PACKAGE_NAME = '@microsoft/rush'; const RUSH_PREVIEW_VERSION = 'RUSH_PREVIEW_VERSION'; function _getRushVersion() { - const rushPreviewVersion = process.env[RUSH_PREVIEW_VERSION]; - if (rushPreviewVersion !== undefined) { - console.log(`Using Rush version from environment variable ${RUSH_PREVIEW_VERSION}=${rushPreviewVersion}`); - return rushPreviewVersion; - } - const rushJsonFolder = install_run_1.findRushJsonFolder(); - const rushJsonPath = path.join(rushJsonFolder, install_run_1.RUSH_JSON_FILENAME); - try { - const rushJsonContents = fs.readFileSync(rushJsonPath, 'utf-8'); - // Use a regular expression to parse out the rushVersion value because rush.json supports comments, - // but JSON.parse does not and we don't want to pull in more dependencies than we need to in this script. - const rushJsonMatches = rushJsonContents.match(/\"rushVersion\"\s*\:\s*\"([0-9a-zA-Z.+\-]+)\"/); - return rushJsonMatches[1]; - } - catch (e) { - throw new Error(`Unable to determine the required version of Rush from rush.json (${rushJsonFolder}). ` + - 'The \'rushVersion\' field is either not assigned in rush.json or was specified ' + - 'using an unexpected syntax.'); - } + const rushPreviewVersion = process.env[RUSH_PREVIEW_VERSION]; + if (rushPreviewVersion !== undefined) { + console.log(`Using Rush version from environment variable ${RUSH_PREVIEW_VERSION}=${rushPreviewVersion}`); + return rushPreviewVersion; + } + const rushJsonFolder = install_run_1.findRushJsonFolder(); + const rushJsonPath = path.join(rushJsonFolder, install_run_1.RUSH_JSON_FILENAME); + try { + const rushJsonContents = fs.readFileSync(rushJsonPath, 'utf-8'); + // Use a regular expression to parse out the rushVersion value because rush.json supports comments, + // but JSON.parse does not and we don't want to pull in more dependencies than we need to in this script. + const rushJsonMatches = rushJsonContents.match(/\"rushVersion\"\s*\:\s*\"([0-9a-zA-Z.+\-]+)\"/); + return rushJsonMatches[1]; + } catch (e) { + throw new Error( + `Unable to determine the required version of Rush from rush.json (${rushJsonFolder}). ` + + "The 'rushVersion' field is either not assigned in rush.json or was specified " + + 'using an unexpected syntax.' + ); + } } function _run() { - const [nodePath, /* Ex: /bin/node */ scriptPath, /* /repo/common/scripts/install-run-rush.js */ ...packageBinArgs /* [build, --to, myproject] */] = process.argv; - // Detect if this script was directly invoked, or if the install-run-rushx script was invokved to select the - // appropriate binary inside the rush package to run - const scriptName = path.basename(scriptPath); - const bin = scriptName.toLowerCase() === 'install-run-rushx.js' ? 'rushx' : 'rush'; - if (!nodePath || !scriptPath) { - throw new Error('Unexpected exception: could not detect node path or script path'); - } - if (process.argv.length < 3) { - console.log(`Usage: ${scriptName} [args...]`); - if (scriptName === 'install-run-rush.js') { - console.log(`Example: ${scriptName} build --to myproject`); - } - else { - console.log(`Example: ${scriptName} custom-command`); - } - process.exit(1); + const [ + nodePath, + /* Ex: /bin/node */ scriptPath, + /* /repo/common/scripts/install-run-rush.js */ ...packageBinArgs /* [build, --to, myproject] */ + ] = process.argv; + // Detect if this script was directly invoked, or if the install-run-rushx script was invokved to select the + // appropriate binary inside the rush package to run + const scriptName = path.basename(scriptPath); + const bin = scriptName.toLowerCase() === 'install-run-rushx.js' ? 'rushx' : 'rush'; + if (!nodePath || !scriptPath) { + throw new Error('Unexpected exception: could not detect node path or script path'); + } + if (process.argv.length < 3) { + console.log(`Usage: ${scriptName} [args...]`); + if (scriptName === 'install-run-rush.js') { + console.log(`Example: ${scriptName} build --to myproject`); + } else { + console.log(`Example: ${scriptName} custom-command`); } - install_run_1.runWithErrorAndStatusCode(() => { - const version = _getRushVersion(); - console.log(`The rush.json configuration requests Rush version ${version}`); - return install_run_1.installAndRun(PACKAGE_NAME, version, bin, packageBinArgs); - }); + process.exit(1); + } + install_run_1.runWithErrorAndStatusCode(() => { + const version = _getRushVersion(); + console.log(`The rush.json configuration requests Rush version ${version}`); + return install_run_1.installAndRun(PACKAGE_NAME, version, bin, packageBinArgs); + }); } _run(); -//# sourceMappingURL=install-run-rush.js.map \ No newline at end of file +//# sourceMappingURL=install-run-rush.js.map diff --git a/common/scripts/install-run-rushx.js b/common/scripts/install-run-rushx.js index bf26eb5e50a..d856f9f39f4 100644 --- a/common/scripts/install-run-rushx.js +++ b/common/scripts/install-run-rushx.js @@ -1,7 +1,7 @@ -"use strict"; +'use strict'; // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See the @microsoft/rush package's LICENSE file for license information. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, '__esModule', { value: true }); // THIS FILE WAS GENERATED BY A TOOL. ANY MANUAL MODIFICATIONS WILL GET OVERWRITTEN WHENEVER RUSH IS UPGRADED. // // This script is intended for usage in an automated build environment where the Rush command may not have @@ -14,5 +14,5 @@ Object.defineProperty(exports, "__esModule", { value: true }); // node common/scripts/install-run-rushx.js custom-command // // For more information, see: https://rushjs.io/pages/maintainer/setup_new_repo/ -require("./install-run-rush"); -//# sourceMappingURL=install-run-rushx.js.map \ No newline at end of file +require('./install-run-rush'); +//# sourceMappingURL=install-run-rushx.js.map diff --git a/common/scripts/install-run.js b/common/scripts/install-run.js index e12534c87cf..cdc616f2005 100644 --- a/common/scripts/install-run.js +++ b/common/scripts/install-run.js @@ -1,7 +1,7 @@ -"use strict"; +'use strict'; // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See the @microsoft/rush package's LICENSE file for license information. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, '__esModule', { value: true }); // THIS FILE WAS GENERATED BY A TOOL. ANY MANUAL MODIFICATIONS WILL GET OVERWRITTEN WHENEVER RUSH IS UPGRADED. // // This script is intended for usage in an automated build environment where a Node tool may not have @@ -12,10 +12,10 @@ Object.defineProperty(exports, "__esModule", { value: true }); // node common/scripts/install-run.js qrcode@1.2.2 qrcode https://rushjs.io // // For more information, see: https://rushjs.io/pages/maintainer/setup_new_repo/ -const childProcess = require("child_process"); -const fs = require("fs"); -const os = require("os"); -const path = require("path"); +const childProcess = require('child_process'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); exports.RUSH_JSON_FILENAME = 'rush.json'; const RUSH_TEMP_FOLDER_ENV_VARIABLE_NAME = 'RUSH_TEMP_FOLDER'; const INSTALLED_FLAG_FILENAME = 'installed.flag'; @@ -25,26 +25,24 @@ const PACKAGE_JSON_FILENAME = 'package.json'; * Parse a package specifier (in the form of name\@version) into name and version parts. */ function _parsePackageSpecifier(rawPackageSpecifier) { - rawPackageSpecifier = (rawPackageSpecifier || '').trim(); - const separatorIndex = rawPackageSpecifier.lastIndexOf('@'); - let name; - let version = undefined; - if (separatorIndex === 0) { - // The specifier starts with a scope and doesn't have a version specified - name = rawPackageSpecifier; - } - else if (separatorIndex === -1) { - // The specifier doesn't have a version - name = rawPackageSpecifier; - } - else { - name = rawPackageSpecifier.substring(0, separatorIndex); - version = rawPackageSpecifier.substring(separatorIndex + 1); - } - if (!name) { - throw new Error(`Invalid package specifier: ${rawPackageSpecifier}`); - } - return { name, version }; + rawPackageSpecifier = (rawPackageSpecifier || '').trim(); + const separatorIndex = rawPackageSpecifier.lastIndexOf('@'); + let name; + let version = undefined; + if (separatorIndex === 0) { + // The specifier starts with a scope and doesn't have a version specified + name = rawPackageSpecifier; + } else if (separatorIndex === -1) { + // The specifier doesn't have a version + name = rawPackageSpecifier; + } else { + name = rawPackageSpecifier.substring(0, separatorIndex); + version = rawPackageSpecifier.substring(separatorIndex + 1); + } + if (!name) { + throw new Error(`Invalid package specifier: ${rawPackageSpecifier}`); + } + return { name, version }; } /** * As a workaround, copyAndTrimNpmrcFile() copies the .npmrc file to the target folder, and also trims @@ -60,36 +58,35 @@ function _parsePackageSpecifier(rawPackageSpecifier) { * IMPORTANT: THIS CODE SHOULD BE KEPT UP TO DATE WITH Utilities._copyNpmrcFile() */ function _copyAndTrimNpmrcFile(sourceNpmrcPath, targetNpmrcPath) { - console.log(`Copying ${sourceNpmrcPath} --> ${targetNpmrcPath}`); // Verbose - let npmrcFileLines = fs.readFileSync(sourceNpmrcPath).toString().split('\n'); - npmrcFileLines = npmrcFileLines.map((line) => (line || '').trim()); - const resultLines = []; - // Trim out lines that reference environment variables that aren't defined - for (const line of npmrcFileLines) { - // This finds environment variable tokens that look like "${VAR_NAME}" - const regex = /\$\{([^\}]+)\}/g; - const environmentVariables = line.match(regex); - let lineShouldBeTrimmed = false; - if (environmentVariables) { - for (const token of environmentVariables) { - // Remove the leading "${" and the trailing "}" from the token - const environmentVariableName = token.substring(2, token.length - 1); - if (!process.env[environmentVariableName]) { - lineShouldBeTrimmed = true; - break; - } - } - } - if (lineShouldBeTrimmed) { - // Example output: - // "; MISSING ENVIRONMENT VARIABLE: //my-registry.com/npm/:_authToken=${MY_AUTH_TOKEN}" - resultLines.push('; MISSING ENVIRONMENT VARIABLE: ' + line); - } - else { - resultLines.push(line); + console.log(`Copying ${sourceNpmrcPath} --> ${targetNpmrcPath}`); // Verbose + let npmrcFileLines = fs.readFileSync(sourceNpmrcPath).toString().split('\n'); + npmrcFileLines = npmrcFileLines.map((line) => (line || '').trim()); + const resultLines = []; + // Trim out lines that reference environment variables that aren't defined + for (const line of npmrcFileLines) { + // This finds environment variable tokens that look like "${VAR_NAME}" + const regex = /\$\{([^\}]+)\}/g; + const environmentVariables = line.match(regex); + let lineShouldBeTrimmed = false; + if (environmentVariables) { + for (const token of environmentVariables) { + // Remove the leading "${" and the trailing "}" from the token + const environmentVariableName = token.substring(2, token.length - 1); + if (!process.env[environmentVariableName]) { + lineShouldBeTrimmed = true; + break; } + } } - fs.writeFileSync(targetNpmrcPath, resultLines.join(os.EOL)); + if (lineShouldBeTrimmed) { + // Example output: + // "; MISSING ENVIRONMENT VARIABLE: //my-registry.com/npm/:_authToken=${MY_AUTH_TOKEN}" + resultLines.push('; MISSING ENVIRONMENT VARIABLE: ' + line); + } else { + resultLines.push(line); + } + } + fs.writeFileSync(targetNpmrcPath, resultLines.join(os.EOL)); } /** * syncNpmrc() copies the .npmrc file to the target folder, and also trims unusable lines from the .npmrc file. @@ -98,59 +95,55 @@ function _copyAndTrimNpmrcFile(sourceNpmrcPath, targetNpmrcPath) { * IMPORTANT: THIS CODE SHOULD BE KEPT UP TO DATE WITH Utilities._syncNpmrc() */ function _syncNpmrc(sourceNpmrcFolder, targetNpmrcFolder, useNpmrcPublish) { - const sourceNpmrcPath = path.join(sourceNpmrcFolder, !useNpmrcPublish ? '.npmrc' : '.npmrc-publish'); - const targetNpmrcPath = path.join(targetNpmrcFolder, '.npmrc'); - try { - if (fs.existsSync(sourceNpmrcPath)) { - _copyAndTrimNpmrcFile(sourceNpmrcPath, targetNpmrcPath); - } - else if (fs.existsSync(targetNpmrcPath)) { - // If the source .npmrc doesn't exist and there is one in the target, delete the one in the target - console.log(`Deleting ${targetNpmrcPath}`); // Verbose - fs.unlinkSync(targetNpmrcPath); - } - } - catch (e) { - throw new Error(`Error syncing .npmrc file: ${e}`); - } + const sourceNpmrcPath = path.join(sourceNpmrcFolder, !useNpmrcPublish ? '.npmrc' : '.npmrc-publish'); + const targetNpmrcPath = path.join(targetNpmrcFolder, '.npmrc'); + try { + if (fs.existsSync(sourceNpmrcPath)) { + _copyAndTrimNpmrcFile(sourceNpmrcPath, targetNpmrcPath); + } else if (fs.existsSync(targetNpmrcPath)) { + // If the source .npmrc doesn't exist and there is one in the target, delete the one in the target + console.log(`Deleting ${targetNpmrcPath}`); // Verbose + fs.unlinkSync(targetNpmrcPath); + } + } catch (e) { + throw new Error(`Error syncing .npmrc file: ${e}`); + } } let _npmPath = undefined; /** * Get the absolute path to the npm executable */ function getNpmPath() { - if (!_npmPath) { - try { - if (os.platform() === 'win32') { - // We're on Windows - const whereOutput = childProcess.execSync('where npm', { stdio: [] }).toString(); - const lines = whereOutput.split(os.EOL).filter((line) => !!line); - // take the last result, we are looking for a .cmd command - // see https://github.com/microsoft/rushstack/issues/759 - _npmPath = lines[lines.length - 1]; - } - else { - // We aren't on Windows - assume we're on *NIX or Darwin - _npmPath = childProcess.execSync('which npm', { stdio: [] }).toString(); - } - } - catch (e) { - throw new Error(`Unable to determine the path to the NPM tool: ${e}`); - } - _npmPath = _npmPath.trim(); - if (!fs.existsSync(_npmPath)) { - throw new Error('The NPM executable does not exist'); - } - } - return _npmPath; + if (!_npmPath) { + try { + if (os.platform() === 'win32') { + // We're on Windows + const whereOutput = childProcess.execSync('where npm', { stdio: [] }).toString(); + const lines = whereOutput.split(os.EOL).filter((line) => !!line); + // take the last result, we are looking for a .cmd command + // see https://github.com/microsoft/rushstack/issues/759 + _npmPath = lines[lines.length - 1]; + } else { + // We aren't on Windows - assume we're on *NIX or Darwin + _npmPath = childProcess.execSync('which npm', { stdio: [] }).toString(); + } + } catch (e) { + throw new Error(`Unable to determine the path to the NPM tool: ${e}`); + } + _npmPath = _npmPath.trim(); + if (!fs.existsSync(_npmPath)) { + throw new Error('The NPM executable does not exist'); + } + } + return _npmPath; } exports.getNpmPath = getNpmPath; function _ensureFolder(folderPath) { - if (!fs.existsSync(folderPath)) { - const parentDir = path.dirname(folderPath); - _ensureFolder(parentDir); - fs.mkdirSync(folderPath); - } + if (!fs.existsSync(folderPath)) { + const parentDir = path.dirname(folderPath); + _ensureFolder(parentDir); + fs.mkdirSync(folderPath); + } } /** * Create missing directories under the specified base directory, and return the resolved directory. @@ -159,120 +152,120 @@ function _ensureFolder(folderPath) { * Assumes the baseFolder exists. */ function _ensureAndJoinPath(baseFolder, ...pathSegments) { - let joinedPath = baseFolder; - try { - for (let pathSegment of pathSegments) { - pathSegment = pathSegment.replace(/[\\\/]/g, '+'); - joinedPath = path.join(joinedPath, pathSegment); - if (!fs.existsSync(joinedPath)) { - fs.mkdirSync(joinedPath); - } - } - } - catch (e) { - throw new Error(`Error building local installation folder (${path.join(baseFolder, ...pathSegments)}): ${e}`); - } - return joinedPath; + let joinedPath = baseFolder; + try { + for (let pathSegment of pathSegments) { + pathSegment = pathSegment.replace(/[\\\/]/g, '+'); + joinedPath = path.join(joinedPath, pathSegment); + if (!fs.existsSync(joinedPath)) { + fs.mkdirSync(joinedPath); + } + } + } catch (e) { + throw new Error( + `Error building local installation folder (${path.join(baseFolder, ...pathSegments)}): ${e}` + ); + } + return joinedPath; } function _getRushTempFolder(rushCommonFolder) { - const rushTempFolder = process.env[RUSH_TEMP_FOLDER_ENV_VARIABLE_NAME]; - if (rushTempFolder !== undefined) { - _ensureFolder(rushTempFolder); - return rushTempFolder; - } - else { - return _ensureAndJoinPath(rushCommonFolder, 'temp'); - } + const rushTempFolder = process.env[RUSH_TEMP_FOLDER_ENV_VARIABLE_NAME]; + if (rushTempFolder !== undefined) { + _ensureFolder(rushTempFolder); + return rushTempFolder; + } else { + return _ensureAndJoinPath(rushCommonFolder, 'temp'); + } } /** * Resolve a package specifier to a static version */ function _resolvePackageVersion(rushCommonFolder, { name, version }) { - if (!version) { - version = '*'; // If no version is specified, use the latest version - } - if (version.match(/^[a-zA-Z0-9\-\+\.]+$/)) { - // If the version contains only characters that we recognize to be used in static version specifiers, - // pass the version through - return version; - } - else { - // version resolves to - try { - const rushTempFolder = _getRushTempFolder(rushCommonFolder); - const sourceNpmrcFolder = path.join(rushCommonFolder, 'config', 'rush'); - _syncNpmrc(sourceNpmrcFolder, rushTempFolder); - const npmPath = getNpmPath(); - // This returns something that looks like: - // @microsoft/rush@3.0.0 '3.0.0' - // @microsoft/rush@3.0.1 '3.0.1' - // ... - // @microsoft/rush@3.0.20 '3.0.20' - // - const npmVersionSpawnResult = childProcess.spawnSync(npmPath, ['view', `${name}@${version}`, 'version', '--no-update-notifier'], { - cwd: rushTempFolder, - stdio: [] - }); - if (npmVersionSpawnResult.status !== 0) { - throw new Error(`"npm view" returned error code ${npmVersionSpawnResult.status}`); - } - const npmViewVersionOutput = npmVersionSpawnResult.stdout.toString(); - const versionLines = npmViewVersionOutput.split('\n').filter((line) => !!line); - const latestVersion = versionLines[versionLines.length - 1]; - if (!latestVersion) { - throw new Error('No versions found for the specified version range.'); - } - const versionMatches = latestVersion.match(/^.+\s\'(.+)\'$/); - if (!versionMatches) { - throw new Error(`Invalid npm output ${latestVersion}`); - } - return versionMatches[1]; - } - catch (e) { - throw new Error(`Unable to resolve version ${version} of package ${name}: ${e}`); + if (!version) { + version = '*'; // If no version is specified, use the latest version + } + if (version.match(/^[a-zA-Z0-9\-\+\.]+$/)) { + // If the version contains only characters that we recognize to be used in static version specifiers, + // pass the version through + return version; + } else { + // version resolves to + try { + const rushTempFolder = _getRushTempFolder(rushCommonFolder); + const sourceNpmrcFolder = path.join(rushCommonFolder, 'config', 'rush'); + _syncNpmrc(sourceNpmrcFolder, rushTempFolder); + const npmPath = getNpmPath(); + // This returns something that looks like: + // @microsoft/rush@3.0.0 '3.0.0' + // @microsoft/rush@3.0.1 '3.0.1' + // ... + // @microsoft/rush@3.0.20 '3.0.20' + // + const npmVersionSpawnResult = childProcess.spawnSync( + npmPath, + ['view', `${name}@${version}`, 'version', '--no-update-notifier'], + { + cwd: rushTempFolder, + stdio: [], } - } + ); + if (npmVersionSpawnResult.status !== 0) { + throw new Error(`"npm view" returned error code ${npmVersionSpawnResult.status}`); + } + const npmViewVersionOutput = npmVersionSpawnResult.stdout.toString(); + const versionLines = npmViewVersionOutput.split('\n').filter((line) => !!line); + const latestVersion = versionLines[versionLines.length - 1]; + if (!latestVersion) { + throw new Error('No versions found for the specified version range.'); + } + const versionMatches = latestVersion.match(/^.+\s\'(.+)\'$/); + if (!versionMatches) { + throw new Error(`Invalid npm output ${latestVersion}`); + } + return versionMatches[1]; + } catch (e) { + throw new Error(`Unable to resolve version ${version} of package ${name}: ${e}`); + } + } } let _rushJsonFolder; /** * Find the absolute path to the folder containing rush.json */ function findRushJsonFolder() { + if (!_rushJsonFolder) { + let basePath = __dirname; + let tempPath = __dirname; + do { + const testRushJsonPath = path.join(basePath, exports.RUSH_JSON_FILENAME); + if (fs.existsSync(testRushJsonPath)) { + _rushJsonFolder = basePath; + break; + } else { + basePath = tempPath; + } + } while (basePath !== (tempPath = path.dirname(basePath))); // Exit the loop when we hit the disk root if (!_rushJsonFolder) { - let basePath = __dirname; - let tempPath = __dirname; - do { - const testRushJsonPath = path.join(basePath, exports.RUSH_JSON_FILENAME); - if (fs.existsSync(testRushJsonPath)) { - _rushJsonFolder = basePath; - break; - } - else { - basePath = tempPath; - } - } while (basePath !== (tempPath = path.dirname(basePath))); // Exit the loop when we hit the disk root - if (!_rushJsonFolder) { - throw new Error('Unable to find rush.json.'); - } + throw new Error('Unable to find rush.json.'); } - return _rushJsonFolder; + } + return _rushJsonFolder; } exports.findRushJsonFolder = findRushJsonFolder; /** * Detects if the package in the specified directory is installed */ function _isPackageAlreadyInstalled(packageInstallFolder) { - try { - const flagFilePath = path.join(packageInstallFolder, INSTALLED_FLAG_FILENAME); - if (!fs.existsSync(flagFilePath)) { - return false; - } - const fileContents = fs.readFileSync(flagFilePath).toString(); - return fileContents.trim() === process.version; - } - catch (e) { - return false; - } + try { + const flagFilePath = path.join(packageInstallFolder, INSTALLED_FLAG_FILENAME); + if (!fs.existsSync(flagFilePath)) { + return false; + } + const fileContents = fs.readFileSync(flagFilePath).toString(); + return fileContents.trim() === process.version; + } catch (e) { + return false; + } } /** * Removes the following files and directories under the specified folder path: @@ -281,153 +274,161 @@ function _isPackageAlreadyInstalled(packageInstallFolder) { * - node_modules */ function _cleanInstallFolder(rushTempFolder, packageInstallFolder) { - try { - const flagFile = path.resolve(packageInstallFolder, INSTALLED_FLAG_FILENAME); - if (fs.existsSync(flagFile)) { - fs.unlinkSync(flagFile); - } - const packageLockFile = path.resolve(packageInstallFolder, 'package-lock.json'); - if (fs.existsSync(packageLockFile)) { - fs.unlinkSync(packageLockFile); - } - const nodeModulesFolder = path.resolve(packageInstallFolder, NODE_MODULES_FOLDER_NAME); - if (fs.existsSync(nodeModulesFolder)) { - const rushRecyclerFolder = _ensureAndJoinPath(rushTempFolder, 'rush-recycler', `install-run-${Date.now().toString()}`); - fs.renameSync(nodeModulesFolder, rushRecyclerFolder); - } - } - catch (e) { - throw new Error(`Error cleaning the package install folder (${packageInstallFolder}): ${e}`); - } + try { + const flagFile = path.resolve(packageInstallFolder, INSTALLED_FLAG_FILENAME); + if (fs.existsSync(flagFile)) { + fs.unlinkSync(flagFile); + } + const packageLockFile = path.resolve(packageInstallFolder, 'package-lock.json'); + if (fs.existsSync(packageLockFile)) { + fs.unlinkSync(packageLockFile); + } + const nodeModulesFolder = path.resolve(packageInstallFolder, NODE_MODULES_FOLDER_NAME); + if (fs.existsSync(nodeModulesFolder)) { + const rushRecyclerFolder = _ensureAndJoinPath( + rushTempFolder, + 'rush-recycler', + `install-run-${Date.now().toString()}` + ); + fs.renameSync(nodeModulesFolder, rushRecyclerFolder); + } + } catch (e) { + throw new Error(`Error cleaning the package install folder (${packageInstallFolder}): ${e}`); + } } function _createPackageJson(packageInstallFolder, name, version) { - try { - const packageJsonContents = { - 'name': 'ci-rush', - 'version': '0.0.0', - 'dependencies': { - [name]: version - }, - 'description': 'DON\'T WARN', - 'repository': 'DON\'T WARN', - 'license': 'MIT' - }; - const packageJsonPath = path.join(packageInstallFolder, PACKAGE_JSON_FILENAME); - fs.writeFileSync(packageJsonPath, JSON.stringify(packageJsonContents, undefined, 2)); - } - catch (e) { - throw new Error(`Unable to create package.json: ${e}`); - } + try { + const packageJsonContents = { + name: 'ci-rush', + version: '0.0.0', + dependencies: { + [name]: version, + }, + description: "DON'T WARN", + repository: "DON'T WARN", + license: 'MIT', + }; + const packageJsonPath = path.join(packageInstallFolder, PACKAGE_JSON_FILENAME); + fs.writeFileSync(packageJsonPath, JSON.stringify(packageJsonContents, undefined, 2)); + } catch (e) { + throw new Error(`Unable to create package.json: ${e}`); + } } /** * Run "npm install" in the package install folder. */ function _installPackage(packageInstallFolder, name, version) { - try { - console.log(`Installing ${name}...`); - const npmPath = getNpmPath(); - const result = childProcess.spawnSync(npmPath, ['install'], { - stdio: 'inherit', - cwd: packageInstallFolder, - env: process.env - }); - if (result.status !== 0) { - throw new Error('"npm install" encountered an error'); - } - console.log(`Successfully installed ${name}@${version}`); - } - catch (e) { - throw new Error(`Unable to install package: ${e}`); + try { + console.log(`Installing ${name}...`); + const npmPath = getNpmPath(); + const result = childProcess.spawnSync(npmPath, ['install'], { + stdio: 'inherit', + cwd: packageInstallFolder, + env: process.env, + }); + if (result.status !== 0) { + throw new Error('"npm install" encountered an error'); } + console.log(`Successfully installed ${name}@${version}`); + } catch (e) { + throw new Error(`Unable to install package: ${e}`); + } } /** * Get the ".bin" path for the package. */ function _getBinPath(packageInstallFolder, binName) { - const binFolderPath = path.resolve(packageInstallFolder, NODE_MODULES_FOLDER_NAME, '.bin'); - const resolvedBinName = (os.platform() === 'win32') ? `${binName}.cmd` : binName; - return path.resolve(binFolderPath, resolvedBinName); + const binFolderPath = path.resolve(packageInstallFolder, NODE_MODULES_FOLDER_NAME, '.bin'); + const resolvedBinName = os.platform() === 'win32' ? `${binName}.cmd` : binName; + return path.resolve(binFolderPath, resolvedBinName); } /** * Write a flag file to the package's install directory, signifying that the install was successful. */ function _writeFlagFile(packageInstallFolder) { - try { - const flagFilePath = path.join(packageInstallFolder, INSTALLED_FLAG_FILENAME); - fs.writeFileSync(flagFilePath, process.version); - } - catch (e) { - throw new Error(`Unable to create installed.flag file in ${packageInstallFolder}`); - } + try { + const flagFilePath = path.join(packageInstallFolder, INSTALLED_FLAG_FILENAME); + fs.writeFileSync(flagFilePath, process.version); + } catch (e) { + throw new Error(`Unable to create installed.flag file in ${packageInstallFolder}`); + } } function installAndRun(packageName, packageVersion, packageBinName, packageBinArgs) { - const rushJsonFolder = findRushJsonFolder(); - const rushCommonFolder = path.join(rushJsonFolder, 'common'); - const rushTempFolder = _getRushTempFolder(rushCommonFolder); - const packageInstallFolder = _ensureAndJoinPath(rushTempFolder, 'install-run', `${packageName}@${packageVersion}`); - if (!_isPackageAlreadyInstalled(packageInstallFolder)) { - // The package isn't already installed - _cleanInstallFolder(rushTempFolder, packageInstallFolder); - const sourceNpmrcFolder = path.join(rushCommonFolder, 'config', 'rush'); - _syncNpmrc(sourceNpmrcFolder, packageInstallFolder); - _createPackageJson(packageInstallFolder, packageName, packageVersion); - _installPackage(packageInstallFolder, packageName, packageVersion); - _writeFlagFile(packageInstallFolder); - } - const statusMessage = `Invoking "${packageBinName} ${packageBinArgs.join(' ')}"`; - const statusMessageLine = new Array(statusMessage.length + 1).join('-'); - console.log(os.EOL + statusMessage + os.EOL + statusMessageLine + os.EOL); - const binPath = _getBinPath(packageInstallFolder, packageBinName); - const result = childProcess.spawnSync(binPath, packageBinArgs, { - stdio: 'inherit', - cwd: process.cwd(), - env: process.env - }); - if (result.status !== null) { - return result.status; - } - else { - throw result.error || new Error('An unknown error occurred.'); - } + const rushJsonFolder = findRushJsonFolder(); + const rushCommonFolder = path.join(rushJsonFolder, 'common'); + const rushTempFolder = _getRushTempFolder(rushCommonFolder); + const packageInstallFolder = _ensureAndJoinPath( + rushTempFolder, + 'install-run', + `${packageName}@${packageVersion}` + ); + if (!_isPackageAlreadyInstalled(packageInstallFolder)) { + // The package isn't already installed + _cleanInstallFolder(rushTempFolder, packageInstallFolder); + const sourceNpmrcFolder = path.join(rushCommonFolder, 'config', 'rush'); + _syncNpmrc(sourceNpmrcFolder, packageInstallFolder); + _createPackageJson(packageInstallFolder, packageName, packageVersion); + _installPackage(packageInstallFolder, packageName, packageVersion); + _writeFlagFile(packageInstallFolder); + } + const statusMessage = `Invoking "${packageBinName} ${packageBinArgs.join(' ')}"`; + const statusMessageLine = new Array(statusMessage.length + 1).join('-'); + console.log(os.EOL + statusMessage + os.EOL + statusMessageLine + os.EOL); + const binPath = _getBinPath(packageInstallFolder, packageBinName); + const result = childProcess.spawnSync(binPath, packageBinArgs, { + stdio: 'inherit', + cwd: process.cwd(), + env: process.env, + }); + if (result.status !== null) { + return result.status; + } else { + throw result.error || new Error('An unknown error occurred.'); + } } exports.installAndRun = installAndRun; function runWithErrorAndStatusCode(fn) { - process.exitCode = 1; - try { - const exitCode = fn(); - process.exitCode = exitCode; - } - catch (e) { - console.error(os.EOL + os.EOL + e.toString() + os.EOL + os.EOL); - } + process.exitCode = 1; + try { + const exitCode = fn(); + process.exitCode = exitCode; + } catch (e) { + console.error(os.EOL + os.EOL + e.toString() + os.EOL + os.EOL); + } } exports.runWithErrorAndStatusCode = runWithErrorAndStatusCode; function _run() { - const [nodePath, /* Ex: /bin/node */ scriptPath, /* /repo/common/scripts/install-run-rush.js */ rawPackageSpecifier, /* qrcode@^1.2.0 */ packageBinName, /* qrcode */ ...packageBinArgs /* [-f, myproject/lib] */] = process.argv; - if (!nodePath) { - throw new Error('Unexpected exception: could not detect node path'); - } - if (path.basename(scriptPath).toLowerCase() !== 'install-run.js') { - // If install-run.js wasn't directly invoked, don't execute the rest of this function. Return control - // to the script that (presumably) imported this file - return; - } - if (process.argv.length < 4) { - console.log('Usage: install-run.js @ [args...]'); - console.log('Example: install-run.js qrcode@1.2.2 qrcode https://rushjs.io'); - process.exit(1); - } - runWithErrorAndStatusCode(() => { - const rushJsonFolder = findRushJsonFolder(); - const rushCommonFolder = _ensureAndJoinPath(rushJsonFolder, 'common'); - const packageSpecifier = _parsePackageSpecifier(rawPackageSpecifier); - const name = packageSpecifier.name; - const version = _resolvePackageVersion(rushCommonFolder, packageSpecifier); - if (packageSpecifier.version !== version) { - console.log(`Resolved to ${name}@${version}`); - } - return installAndRun(name, version, packageBinName, packageBinArgs); - }); + const [ + nodePath, + /* Ex: /bin/node */ scriptPath, + /* /repo/common/scripts/install-run-rush.js */ rawPackageSpecifier, + /* qrcode@^1.2.0 */ packageBinName, + /* qrcode */ ...packageBinArgs /* [-f, myproject/lib] */ + ] = process.argv; + if (!nodePath) { + throw new Error('Unexpected exception: could not detect node path'); + } + if (path.basename(scriptPath).toLowerCase() !== 'install-run.js') { + // If install-run.js wasn't directly invoked, don't execute the rest of this function. Return control + // to the script that (presumably) imported this file + return; + } + if (process.argv.length < 4) { + console.log('Usage: install-run.js @ [args...]'); + console.log('Example: install-run.js qrcode@1.2.2 qrcode https://rushjs.io'); + process.exit(1); + } + runWithErrorAndStatusCode(() => { + const rushJsonFolder = findRushJsonFolder(); + const rushCommonFolder = _ensureAndJoinPath(rushJsonFolder, 'common'); + const packageSpecifier = _parsePackageSpecifier(rawPackageSpecifier); + const name = packageSpecifier.name; + const version = _resolvePackageVersion(rushCommonFolder, packageSpecifier); + if (packageSpecifier.version !== version) { + console.log(`Resolved to ${name}@${version}`); + } + return installAndRun(name, version, packageBinName, packageBinArgs); + }); } _run(); -//# sourceMappingURL=install-run.js.map \ No newline at end of file +//# sourceMappingURL=install-run.js.map diff --git a/core-build/gulp-core-build-mocha/.eslintrc.js b/core-build/gulp-core-build-mocha/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/core-build/gulp-core-build-mocha/.eslintrc.js +++ b/core-build/gulp-core-build-mocha/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/core-build/gulp-core-build-mocha/src/InstrumentTask.ts b/core-build/gulp-core-build-mocha/src/InstrumentTask.ts index 2a3b8ac50be..ff255910349 100644 --- a/core-build/gulp-core-build-mocha/src/InstrumentTask.ts +++ b/core-build/gulp-core-build-mocha/src/InstrumentTask.ts @@ -11,31 +11,28 @@ export interface IInstrumentTaskConfig { export class InstrumentTask extends GulpTask { public constructor() { - super( - 'instrument', - { - coverageMatch: ['lib/**/*.js', '!lib/**/*.test.js'] - } - ); + super('instrument', { + coverageMatch: ['lib/**/*.js', '!lib/**/*.test.js'], + }); } public isEnabled(buildConfig: IBuildConfig): boolean { - return ( - super.isEnabled(buildConfig) && - !buildConfig.jestEnabled - ); + return super.isEnabled(buildConfig) && !buildConfig.jestEnabled; } public executeTask(gulp: typeof Gulp, completeCallback?: (error?: string) => void): NodeJS.ReadWriteStream { // eslint-disable-next-line @typescript-eslint/no-var-requires const istanbul: typeof gulpIstanbul = require('gulp-istanbul'); - return gulp.src(this.taskConfig.coverageMatch) - // Covering files - .pipe(istanbul()) - // Force `require` to return covered files - .pipe(istanbul.hookRequire()) - // Write the covered files to a temporary directory - .pipe(gulp.dest(this.buildConfig.tempFolder)); + return ( + gulp + .src(this.taskConfig.coverageMatch) + // Covering files + .pipe(istanbul()) + // Force `require` to return covered files + .pipe(istanbul.hookRequire()) + // Write the covered files to a temporary directory + .pipe(gulp.dest(this.buildConfig.tempFolder)) + ); } } diff --git a/core-build/gulp-core-build-mocha/src/MochaTask.ts b/core-build/gulp-core-build-mocha/src/MochaTask.ts index 07511809e7e..6b316228e36 100644 --- a/core-build/gulp-core-build-mocha/src/MochaTask.ts +++ b/core-build/gulp-core-build-mocha/src/MochaTask.ts @@ -14,25 +14,20 @@ export interface IMochaTaskConfig { export class MochaTask extends GulpTask { public constructor() { - super( - 'mocha', - { - testMatch: ['lib/**/*.test.js'], - reportDir: 'coverage' - } - ); + super('mocha', { + testMatch: ['lib/**/*.test.js'], + reportDir: 'coverage', + }); } public isEnabled(buildConfig: IBuildConfig): boolean { - return ( - super.isEnabled(buildConfig) && - !buildConfig.jestEnabled - ); + return super.isEnabled(buildConfig) && !buildConfig.jestEnabled; } - public executeTask(gulp: typeof Gulp, completeCallback: (error?: string) => void): NodeJS.ReadWriteStream - | Promise { - + public executeTask( + gulp: typeof Gulp, + completeCallback: (error?: string) => void + ): NodeJS.ReadWriteStream | Promise { // eslint-disable-next-line @typescript-eslint/no-var-requires const istanbul: typeof gulpIstanbul = require('gulp-istanbul'); // eslint-disable-next-line @typescript-eslint/no-var-requires @@ -48,17 +43,20 @@ export class MochaTask extends GulpTask { // eslint-disable-next-line dot-notation const matchString: string = this.buildConfig.args['match'] as string; - return gulp.src(this.taskConfig.testMatch, { read: false }) + return gulp + .src(this.taskConfig.testMatch, { read: false }) .pipe( mocha({ grep: matchString, - timeout: 15000 + timeout: 15000, }).on('error', (error: Error) => { completeCallback(error.toString()); }) ) - .pipe(istanbul.writeReports({ - dir: this.taskConfig.reportDir - })); + .pipe( + istanbul.writeReports({ + dir: this.taskConfig.reportDir, + }) + ); } } diff --git a/core-build/gulp-core-build-sass/.eslintrc.js b/core-build/gulp-core-build-sass/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/core-build/gulp-core-build-sass/.eslintrc.js +++ b/core-build/gulp-core-build-sass/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/core-build/gulp-core-build-sass/config/jest.json b/core-build/gulp-core-build-sass/config/jest.json index b4a7ec97a56..902b00ea176 100644 --- a/core-build/gulp-core-build-sass/config/jest.json +++ b/core-build/gulp-core-build-sass/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": true -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build-sass/src/CSSModules.ts b/core-build/gulp-core-build-sass/src/CSSModules.ts index c0b13895835..a90cd17e204 100644 --- a/core-build/gulp-core-build-sass/src/CSSModules.ts +++ b/core-build/gulp-core-build-sass/src/CSSModules.ts @@ -45,7 +45,7 @@ export default class CSSModules implements ICSSModules { public getPlugin(): postcss.AcceptedPlugin { return cssModules({ getJSON: this.saveJson.bind(this), - generateScopedName: this.generateScopedName.bind(this) + generateScopedName: this.generateScopedName.bind(this), }); } @@ -57,14 +57,14 @@ export default class CSSModules implements ICSSModules { this._classMap = json; } - protected generateScopedName(name: string, fileName: string, css: string) - : string { + protected generateScopedName(name: string, fileName: string, css: string): string { const fileBaseName: string = path.relative(this._rootPath, fileName); const safeFileBaseName: string = fileBaseName.replace(/\\/g, '/'); - const hash: string = crypto.createHmac('sha1', safeFileBaseName) - .update(css) - .digest('hex') - .substring(0, 8); + const hash: string = crypto + .createHmac('sha1', safeFileBaseName) + .update(css) + .digest('hex') + .substring(0, 8); return `${name}_${hash}`; } } diff --git a/core-build/gulp-core-build-sass/src/SassTask.ts b/core-build/gulp-core-build-sass/src/SassTask.ts index 3899c4479a8..93c0998fd2d 100644 --- a/core-build/gulp-core-build-sass/src/SassTask.ts +++ b/core-build/gulp-core-build-sass/src/SassTask.ts @@ -7,12 +7,7 @@ import { EOL } from 'os'; import { GulpTask } from '@microsoft/gulp-core-build'; import { splitStyles } from '@microsoft/load-themed-styles'; -import { - FileSystem, - JsonFile, - LegacyAdapters, - JsonObject -} from '@rushstack/node-core-library'; +import { FileSystem, JsonFile, LegacyAdapters, JsonObject } from '@rushstack/node-core-library'; import * as glob from 'glob'; import * as nodeSass from 'node-sass'; import * as postcss from 'postcss'; @@ -86,32 +81,23 @@ export interface ISassTaskConfig { } export class SassTask extends GulpTask { - public cleanMatch: string[] = [ - 'src/**/*.sass.ts', - 'src/**/*.scss.ts' - ]; + public cleanMatch: string[] = ['src/**/*.sass.ts', 'src/**/*.scss.ts']; private get _postCSSPlugins(): postcss.AcceptedPlugin[] { return [autoprefixer(this.taskConfig.autoprefixerOptions)]; } public constructor() { - super( - 'sass', - { - preamble: '/* tslint:disable */', - postamble: '/* tslint:enable */', - sassMatch: [ - 'src/**/*.scss', - 'src/**/*.sass' - ], - useCSSModules: false, - warnOnCssInvalidPropertyName: true, - dropCssFiles: false, - warnOnNonCSSModules: false, - autoprefixerOptions: { overrideBrowserslist: ['> 1%', 'last 2 versions', 'ie >= 10'] } - } - ); + super('sass', { + preamble: '/* tslint:disable */', + postamble: '/* tslint:enable */', + sassMatch: ['src/**/*.scss', 'src/**/*.sass'], + useCSSModules: false, + warnOnCssInvalidPropertyName: true, + dropCssFiles: false, + warnOnNonCSSModules: false, + autoprefixerOptions: { overrideBrowserslist: ['> 1%', 'last 2 versions', 'ie >= 10'] }, + }); } public loadSchema(): JsonObject { @@ -123,9 +109,13 @@ export class SassTask extends GulpTask { return Promise.reject(new Error('taskConfig.sassMatch must be defined')); } - return this._globAll(...this.taskConfig.sassMatch).then((matches: string[]) => { - return Promise.all(matches.map((match) => this._processFile(match))); - }).then(() => { /* collapse void[] to void */ }); + return this._globAll(...this.taskConfig.sassMatch) + .then((matches: string[]) => { + return Promise.all(matches.map((match) => this._processFile(match))); + }) + .then(() => { + /* collapse void[] to void */ + }); } private _processFile(filePath: string): Promise { @@ -139,12 +129,8 @@ export class SassTask extends GulpTask { const cssModules: ICSSModules = new CSSModules(this.buildConfig.rootPath); if (!processAsModuleCss && this.taskConfig.warnOnNonCSSModules) { - const relativeFilePath: string = path.relative( - this.buildConfig.rootPath, filePath - ); - this.logWarning( - `${relativeFilePath}: filename should end with module.sass or module.scss` - ); + const relativeFilePath: string = path.relative(this.buildConfig.rootPath, filePath); + this.logWarning(`${relativeFilePath}: filename should end with module.sass or module.scss`); } let cssOutputPath: string | undefined = undefined; @@ -159,105 +145,102 @@ export class SassTask extends GulpTask { cssOutputPathAbsolute = path.join(this.buildConfig.rootPath, cssOutputPath); } - return LegacyAdapters.convertCallbackToPromise( - nodeSass.render, - { - file: filePath, - importer: (url: string) => ({ file: this._patchSassUrl(url) }), - sourceMap: this.taskConfig.dropCssFiles, - sourceMapContents: true, - omitSourceMapUrl: true, - outFile: cssOutputPath - } - ).catch((error: nodeSass.SassError) => { - this.fileError(filePath, error.line, error.column, error.name, error.message); - throw new Error(error.message); - }).then((result: nodeSass.Result) => { - const options: postcss.ProcessOptions = { - from: filePath - }; - if (result.map && !this.buildConfig.production) { - options.map = { - prev: result.map.toString() // Pass the source map through to postcss + return LegacyAdapters.convertCallbackToPromise(nodeSass.render, { + file: filePath, + importer: (url: string) => ({ file: this._patchSassUrl(url) }), + sourceMap: this.taskConfig.dropCssFiles, + sourceMapContents: true, + omitSourceMapUrl: true, + outFile: cssOutputPath, + }) + .catch((error: nodeSass.SassError) => { + this.fileError(filePath, error.line, error.column, error.name, error.message); + throw new Error(error.message); + }) + .then((result: nodeSass.Result) => { + const options: postcss.ProcessOptions = { + from: filePath, }; - } - - const plugins: postcss.AcceptedPlugin[] = [...this._postCSSPlugins]; - if (processAsModuleCss) { - plugins.push(cssModules.getPlugin()); - } - return postcss(plugins).process(result.css.toString(), options) as PromiseLike; - }).then((result: postcss.Result) => { - let cleanCssOptions: CleanCss.Options = { level: 1, returnPromise: true }; - if (this.taskConfig.cleanCssOptions) { - cleanCssOptions = { ...this.taskConfig.cleanCssOptions, returnPromise: true }; - } - cleanCssOptions.sourceMap = !!result.map; - - const cleanCss: CleanCss.MinifierPromise = new CleanCss(cleanCssOptions); - return cleanCss.minify(result.css.toString(), result.map ? result.map.toString() : undefined); - }).then((result: CleanCss.Output) => { - if (cssOutputPathAbsolute) { - const generatedFileLines: string[] = [ - result.styles.toString() - ]; - if (result.sourceMap && !this.buildConfig.production) { - const encodedSourceMap: string = Buffer.from(result.sourceMap.toString()).toString('base64'); - generatedFileLines.push( - `/*# sourceMappingURL=data:application/json;base64,${encodedSourceMap} */` - ); + if (result.map && !this.buildConfig.production) { + options.map = { + prev: result.map.toString(), // Pass the source map through to postcss + }; } - FileSystem.writeFile( - cssOutputPathAbsolute, - generatedFileLines.join(EOL), - { ensureFolderExists: true } - ); - } + const plugins: postcss.AcceptedPlugin[] = [...this._postCSSPlugins]; + if (processAsModuleCss) { + plugins.push(cssModules.getPlugin()); + } + return postcss(plugins).process(result.css.toString(), options) as PromiseLike; + }) + .then((result: postcss.Result) => { + let cleanCssOptions: CleanCss.Options = { level: 1, returnPromise: true }; + if (this.taskConfig.cleanCssOptions) { + cleanCssOptions = { ...this.taskConfig.cleanCssOptions, returnPromise: true }; + } + cleanCssOptions.sourceMap = !!result.map; + + const cleanCss: CleanCss.MinifierPromise = new CleanCss(cleanCssOptions); + return cleanCss.minify(result.css.toString(), result.map ? result.map.toString() : undefined); + }) + .then((result: CleanCss.Output) => { + if (cssOutputPathAbsolute) { + const generatedFileLines: string[] = [result.styles.toString()]; + if (result.sourceMap && !this.buildConfig.production) { + const encodedSourceMap: string = Buffer.from(result.sourceMap.toString()).toString('base64'); + generatedFileLines.push( + `/*# sourceMappingURL=data:application/json;base64,${encodedSourceMap} */` + ); + } + + FileSystem.writeFile(cssOutputPathAbsolute, generatedFileLines.join(EOL), { + ensureFolderExists: true, + }); + } - const scssTsOutputPath: string = `${filePath}.ts`; - const classMap: IClassMap = cssModules.getClassMap(); - const stylesExportString: string = this._getStylesExportString(classMap); - const content: string | undefined = result.styles; - - let lines: string[] = []; - lines.push(this.taskConfig.preamble || ''); - - if (cssOutputPathAbsolute) { - lines = lines.concat([ - `require(${JSON.stringify(`./${path.basename(cssOutputPathAbsolute)}`)});`, - stylesExportString - ]); - } else if (content) { - lines = lines.concat([ - 'import { loadStyles } from \'@microsoft/load-themed-styles\';', - '', - stylesExportString, - '', - `loadStyles(${JSON.stringify(splitStyles(content))});` - ]); - } + const scssTsOutputPath: string = `${filePath}.ts`; + const classMap: IClassMap = cssModules.getClassMap(); + const stylesExportString: string = this._getStylesExportString(classMap); + const content: string | undefined = result.styles; + + let lines: string[] = []; + lines.push(this.taskConfig.preamble || ''); + + if (cssOutputPathAbsolute) { + lines = lines.concat([ + `require(${JSON.stringify(`./${path.basename(cssOutputPathAbsolute)}`)});`, + stylesExportString, + ]); + } else if (content) { + lines = lines.concat([ + "import { loadStyles } from '@microsoft/load-themed-styles';", + '', + stylesExportString, + '', + `loadStyles(${JSON.stringify(splitStyles(content))});`, + ]); + } - lines.push(this.taskConfig.postamble || ''); + lines.push(this.taskConfig.postamble || ''); - const generatedTsFile: string = ( - lines + const generatedTsFile: string = lines .join(EOL) .replace(new RegExp(`(${EOL}){3,}`, 'g'), `${EOL}${EOL}`) - .replace(new RegExp(`(${EOL})+$`, 'm'), EOL) - ); + .replace(new RegExp(`(${EOL})+$`, 'm'), EOL); - FileSystem.writeFile(scssTsOutputPath, generatedTsFile); - }); + FileSystem.writeFile(scssTsOutputPath, generatedTsFile); + }); } private _globAll(...patterns: string[]): Promise { - return Promise.all(patterns.map((pattern) => - LegacyAdapters.convertCallbackToPromise( - glob, - path.isAbsolute(pattern) ? pattern : path.join(this.buildConfig.rootPath, pattern) + return Promise.all( + patterns.map((pattern) => + LegacyAdapters.convertCallbackToPromise( + glob, + path.isAbsolute(pattern) ? pattern : path.join(this.buildConfig.rootPath, pattern) + ) ) - )).then((matchSets: string[][]) => { + ).then((matchSets: string[][]) => { const result: { [path: string]: boolean } = {}; for (const matchSet of matchSets) { for (const match of matchSet) { @@ -286,8 +269,8 @@ export class SassTask extends GulpTask { classKeys.forEach((key: string) => { const value: string = classMap[key]; if (key.indexOf('-') !== -1) { - const message: string = `The local CSS class '${key}' is not ` + - `camelCase and will not be type-safe.`; + const message: string = + `The local CSS class '${key}' is not ` + `camelCase and will not be type-safe.`; if (this.taskConfig.warnOnCssInvalidPropertyName) { this.logWarning(message); } else { @@ -306,12 +289,6 @@ export class SassTask extends GulpTask { // exportString = `export const ${this.taskConfig.moduleExportName} = styles;`; } - return [ - 'const styles = {', - styleLines.join(`,${EOL}`), - '};', - '', - exportString - ].join(EOL); + return ['const styles = {', styleLines.join(`,${EOL}`), '};', '', exportString].join(EOL); } } diff --git a/core-build/gulp-core-build-sass/src/test/CSSModules.test.ts b/core-build/gulp-core-build-sass/src/test/CSSModules.test.ts index 8b16897a927..8326e119d20 100644 --- a/core-build/gulp-core-build-sass/src/test/CSSModules.test.ts +++ b/core-build/gulp-core-build-sass/src/test/CSSModules.test.ts @@ -15,8 +15,7 @@ interface ITestCSSModules { } class TestCSSModules extends CSSModules { - public testGenerateScopedName(name: string, fileName: string, css: string) - : string { + public testGenerateScopedName(name: string, fileName: string, css: string): string { return this.generateScopedName(name, fileName, css); } } @@ -25,20 +24,16 @@ test('will generate different hashes for different content', () => { const version1: IScopedNameArgs = { name: 'Button', fileName: path.join(__dirname, 'Sally', 'src', 'main.sass'), - css: 'color: blue;' + css: 'color: blue;', }; const version2: IScopedNameArgs = { name: 'Button', fileName: path.join(__dirname, 'Sally', 'src', 'main.sass'), - css: 'color: pink;' + css: 'color: pink;', }; const cssModules: ITestCSSModules = new TestCSSModules(); - const output1: string = cssModules.testGenerateScopedName( - version1.name, version1.fileName, version1.css - ); - const output2: string = cssModules.testGenerateScopedName( - version2.name, version2.fileName, version2.css - ); + const output1: string = cssModules.testGenerateScopedName(version1.name, version1.fileName, version1.css); + const output2: string = cssModules.testGenerateScopedName(version2.name, version2.fileName, version2.css); expect(output1).not.toBe(output2); }); @@ -46,25 +41,17 @@ test('will generate the same hash in a different root path', () => { const version1: IScopedNameArgs = { name: 'Button', fileName: path.join(__dirname, 'Sally', 'src', 'main.sass'), - css: 'color: blue;' + css: 'color: blue;', }; const version2: IScopedNameArgs = { name: 'Button', fileName: path.join(__dirname, 'Suzan', 'workspace', 'src', 'main.sass'), - css: 'color: blue;' + css: 'color: blue;', }; - const cssModules: ITestCSSModules = new TestCSSModules( - path.join(__dirname, 'Sally') - ); - const output1: string = cssModules.testGenerateScopedName( - version1.name, version1.fileName, version1.css - ); - const cssModules2: ITestCSSModules = new TestCSSModules( - path.join(__dirname, 'Suzan', 'workspace') - ); - const output2: string = cssModules2.testGenerateScopedName( - version2.name, version2.fileName, version2.css - ); + const cssModules: ITestCSSModules = new TestCSSModules(path.join(__dirname, 'Sally')); + const output1: string = cssModules.testGenerateScopedName(version1.name, version1.fileName, version1.css); + const cssModules2: ITestCSSModules = new TestCSSModules(path.join(__dirname, 'Suzan', 'workspace')); + const output2: string = cssModules2.testGenerateScopedName(version2.name, version2.fileName, version2.css); expect(output1).toBe(output2); }); @@ -72,19 +59,15 @@ test('will generate a different hash in a different src path', () => { const version1: IScopedNameArgs = { name: 'Button', fileName: path.join(__dirname, 'Sally', 'src', 'main.sass'), - css: 'color: blue;' + css: 'color: blue;', }; const version2: IScopedNameArgs = { name: 'Button', fileName: path.join(__dirname, 'Sally', 'src', 'lib', 'main.sass'), - css: 'color: blue;' + css: 'color: blue;', }; const cssModules: ITestCSSModules = new TestCSSModules(); - const output1: string = cssModules.testGenerateScopedName( - version1.name, version1.fileName, version1.css - ); - const output2: string = cssModules.testGenerateScopedName( - version2.name, version2.fileName, version2.css - ); + const output1: string = cssModules.testGenerateScopedName(version1.name, version1.fileName, version1.css); + const output2: string = cssModules.testGenerateScopedName(version2.name, version2.fileName, version2.css); expect(output1).not.toBe(output2); }); diff --git a/core-build/gulp-core-build-sass/tsconfig.json b/core-build/gulp-core-build-sass/tsconfig.json index 47e75f9f181..f81ee11ef26 100644 --- a/core-build/gulp-core-build-sass/tsconfig.json +++ b/core-build/gulp-core-build-sass/tsconfig.json @@ -1,8 +1,6 @@ { "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "jest" - ] + "types": ["jest"] } } diff --git a/core-build/gulp-core-build-serve/.eslintrc.js b/core-build/gulp-core-build-serve/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/core-build/gulp-core-build-serve/.eslintrc.js +++ b/core-build/gulp-core-build-serve/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/core-build/gulp-core-build-serve/src/ReloadTask.ts b/core-build/gulp-core-build-serve/src/ReloadTask.ts index 0d45507c1c7..95696d366b7 100644 --- a/core-build/gulp-core-build-serve/src/ReloadTask.ts +++ b/core-build/gulp-core-build-serve/src/ReloadTask.ts @@ -13,8 +13,7 @@ export class ReloadTask extends GulpTask { // eslint-disable-next-line const gulpConnect = require('gulp-connect'); - gulp.src('') - .pipe(gulpConnect.reload()); + gulp.src('').pipe(gulpConnect.reload()); completeCallback(); } diff --git a/core-build/gulp-core-build-serve/src/ServeTask.ts b/core-build/gulp-core-build-serve/src/ServeTask.ts index 7a6705d8583..26cde139b0c 100644 --- a/core-build/gulp-core-build-serve/src/ServeTask.ts +++ b/core-build/gulp-core-build-serve/src/ServeTask.ts @@ -13,10 +13,7 @@ import * as ExpressType from 'express'; /* eslint-disable @typescript-eslint/no-var-requires */ -import { - ICertificate, - CertificateManager -} from '@rushstack/debug-certificate-manager'; +import { ICertificate, CertificateManager } from '@rushstack/debug-certificate-manager'; /** * @remarks @@ -32,12 +29,12 @@ export interface IServeTaskConfig { /** * The port on which to run the API server */ - port: number, + port: number; /** * The path to the script to run as the API server */ - entryPath: string + entryPath: string; }; /** @@ -91,7 +88,7 @@ export interface IServeTaskConfig { } interface IApiMap { - [ route: string ]: Function; + [route: string]: Function; } export class ServeTask extends GulpTask { @@ -99,18 +96,15 @@ export class ServeTask extends GulpTask extends GulpTask void): void { - /* eslint-disable @typescript-eslint/typedef */ const gulpConnect = require('gulp-connect'); const open = require('gulp-open'); @@ -130,14 +123,14 @@ export class ServeTask extends GulpTask= 0 && process.argv.length > (portArgumentIndex + 1)) { + if (portArgumentIndex >= 0 && process.argv.length > portArgumentIndex + 1) { port = Number(process.argv[portArgumentIndex + 1]); } @@ -149,7 +142,7 @@ export class ServeTask extends GulpTask extends GulpTask extends GulpTask extends GulpTask extends GulpTask extends GulpTask { +export class ApiExtractorTask extends RSCTask { public constructor() { - super( - 'api-extractor', - {} - ); + super('api-extractor', {}); } public loadSchema(): JsonObject { @@ -43,7 +35,7 @@ export class ApiExtractorTask extends RSCTask { this.initializeRushStackCompiler(); const extractorOptions: IExtractorInvokeOptions = { - localBuild: !this.buildConfig.production + localBuild: !this.buildConfig.production, }; const ApiExtractorRunner: typeof TApiExtractorRunner = this._rushStackCompiler.ApiExtractorRunner; @@ -54,7 +46,7 @@ export class ApiExtractorTask extends RSCTask { const apiExtractorRunner: TApiExtractorRunner = new ApiExtractorRunner( { fileError: this.fileError.bind(this), - fileWarning: this.fileWarning.bind(this) + fileWarning: this.fileWarning.bind(this), }, extractorConfig, extractorOptions, diff --git a/core-build/gulp-core-build-typescript/src/LintCmdTask.ts b/core-build/gulp-core-build-typescript/src/LintCmdTask.ts index cbcc31c6d1a..dbff858a429 100644 --- a/core-build/gulp-core-build-typescript/src/LintCmdTask.ts +++ b/core-build/gulp-core-build-typescript/src/LintCmdTask.ts @@ -5,10 +5,7 @@ import * as path from 'path'; import { JsonFile, JsonObject } from '@rushstack/node-core-library'; import { LintRunner as TLintRunner } from '@microsoft/rush-stack-compiler-3.1'; -import { - RSCTask, - IRSCTaskConfig -} from './RSCTask'; +import { RSCTask, IRSCTaskConfig } from './RSCTask'; /** * @public @@ -25,12 +22,9 @@ export interface ILintCmdTaskConfig extends IRSCTaskConfig { */ export class LintCmdTask extends RSCTask { public constructor() { - super( - 'lint', - { - displayAsError: false - } - ); + super('lint', { + displayAsError: false, + }); } public loadSchema(): JsonObject { @@ -45,7 +39,7 @@ export class LintCmdTask extends RSCTask { displayAsError: this.taskConfig.displayAsError, fileError: this.fileError.bind(this), - fileWarning: this.fileWarning.bind(this) + fileWarning: this.fileWarning.bind(this), }, this.buildFolder, this._terminalProvider diff --git a/core-build/gulp-core-build-typescript/src/RSCTask.ts b/core-build/gulp-core-build-typescript/src/RSCTask.ts index cda27c50588..d617a7d3165 100644 --- a/core-build/gulp-core-build-typescript/src/RSCTask.ts +++ b/core-build/gulp-core-build-typescript/src/RSCTask.ts @@ -9,12 +9,9 @@ import { IPackageJson, FileSystem, PackageJsonLookup, - Terminal + Terminal, } from '@rushstack/node-core-library'; -import { - GulpTask, - GCBTerminalProvider -} from '@microsoft/gulp-core-build'; +import { GulpTask, GCBTerminalProvider } from '@microsoft/gulp-core-build'; import * as TRushStackCompiler from '@microsoft/rush-stack-compiler-3.1'; export interface IRSCTaskConfig extends Object { @@ -28,7 +25,6 @@ interface ITsconfig { } export abstract class RSCTask extends GulpTask { - // For a given folder that contains a tsconfig.json file, return the absolute path of the folder // containing "@microsoft/rush-stack-compiler-*" private static _rushStackCompilerPackagePathCache: Map = new Map(); @@ -79,10 +75,7 @@ export abstract class RSCTask extends GulpTa } } - RSCTask._rushStackCompilerPackagePathCache.set( - this.buildFolder, - compilerPath - ); + RSCTask._rushStackCompilerPackagePathCache.set(this.buildFolder, compilerPath); } return RSCTask._rushStackCompilerPackagePathCache.get(this.buildFolder)!; @@ -93,13 +86,10 @@ export abstract class RSCTask extends GulpTa } public constructor(taskName: string, defaultConfig: Partial) { - super( - taskName, - { - allowBuiltinCompiler: false, - ...defaultConfig - } as TTaskConfig - ); + super(taskName, { + allowBuiltinCompiler: false, + ...defaultConfig, + } as TTaskConfig); } protected initializeRushStackCompiler(): void { @@ -126,7 +116,10 @@ export abstract class RSCTask extends GulpTa * @returns The absolute path of the folder containing "@microsoft/rush-stack-compiler-*" which should be used * to compile this tsconfig.json project */ - private _resolveRushStackCompilerFromTsconfig(tsconfigPath: string, visitedTsconfigPaths: Set): string { + private _resolveRushStackCompilerFromTsconfig( + tsconfigPath: string, + visitedTsconfigPaths: Set + ): string { this._terminal.writeVerboseLine(`Examining ${tsconfigPath}`); visitedTsconfigPaths.add(tsconfigPath); @@ -143,7 +136,9 @@ export abstract class RSCTask extends GulpTa if (!tsconfig.extends) { // Does the chain end with a file in the rush-stack-compiler package? - const packageJsonPath: string | undefined = RSCTask._packageJsonLookup.tryGetPackageJsonFilePathFor(tsconfigPath); + const packageJsonPath: string | undefined = RSCTask._packageJsonLookup.tryGetPackageJsonFilePathFor( + tsconfigPath + ); if (packageJsonPath) { const packageJson: IPackageJson = JsonFile.load(packageJsonPath); if (packageJson.name.match(/^@microsoft\/rush-stack-compiler-[0-9\.]+$/)) { @@ -155,8 +150,8 @@ export abstract class RSCTask extends GulpTa throw new Error( 'Rush Stack determines your TypeScript compiler by following the "extends" field in your tsconfig.json ' + - 'file, until it reaches a package folder that depends on a variant of @microsoft/rush-stack-compiler-*. ' + - `This lookup failed when it reached this file: ${tsconfigPath}` + 'file, until it reaches a package folder that depends on a variant of @microsoft/rush-stack-compiler-*. ' + + `This lookup failed when it reached this file: ${tsconfigPath}` ); } @@ -173,28 +168,27 @@ export abstract class RSCTask extends GulpTa extendsPathKind = 'a relative path'; } else { // Package path - baseTsconfigPath = resolve.sync( - tsconfig.extends, - { - basedir: this.buildConfig.rootPath, - packageFilter: (pkg: IPackageJson) => { - return { - ...pkg, - main: 'package.json' - }; - } - } - ); + baseTsconfigPath = resolve.sync(tsconfig.extends, { + basedir: this.buildConfig.rootPath, + packageFilter: (pkg: IPackageJson) => { + return { + ...pkg, + main: 'package.json', + }; + }, + }); extendsPathKind = 'a package path'; } this._terminal.writeVerboseLine( `Found tsconfig.extends property ${tsconfig.extends}. It appears ` + - `to be ${extendsPathKind}. Resolved to ${baseTsconfigPath}` + `to be ${extendsPathKind}. Resolved to ${baseTsconfigPath}` ); if (visitedTsconfigPaths.has(baseTsconfigPath)) { - throw new Error(`The file "${baseTsconfigPath}" has an "extends" field that creates a circular reference`); + throw new Error( + `The file "${baseTsconfigPath}" has an "extends" field that creates a circular reference` + ); } return this._resolveRushStackCompilerFromTsconfig(baseTsconfigPath, visitedTsconfigPaths); diff --git a/core-build/gulp-core-build-typescript/src/TsParseConfigHost.ts b/core-build/gulp-core-build-typescript/src/TsParseConfigHost.ts index d2fe3f133b9..a9dedfbdbe7 100644 --- a/core-build/gulp-core-build-typescript/src/TsParseConfigHost.ts +++ b/core-build/gulp-core-build-typescript/src/TsParseConfigHost.ts @@ -10,7 +10,12 @@ import { FileSystem } from '@rushstack/node-core-library'; export class TsParseConfigHost implements TTypescript.ParseConfigHost { public useCaseSensitiveFileNames: boolean = false; - public readDirectory(rootDir: string, extensions: string[], excludes: string[], includes: string[]): string[] { + public readDirectory( + rootDir: string, + extensions: string[], + excludes: string[], + includes: string[] + ): string[] { return FileSystem.readFolder(rootDir); } diff --git a/core-build/gulp-core-build-typescript/src/TscCmdTask.ts b/core-build/gulp-core-build-typescript/src/TscCmdTask.ts index ef7564914c1..a8ebb122cb1 100644 --- a/core-build/gulp-core-build-typescript/src/TscCmdTask.ts +++ b/core-build/gulp-core-build-typescript/src/TscCmdTask.ts @@ -2,24 +2,16 @@ // See LICENSE in the project root for license information. import * as path from 'path'; -import { - JsonFile, - FileSystem, - LegacyAdapters, - JsonObject -} from '@rushstack/node-core-library'; +import { JsonFile, FileSystem, LegacyAdapters, JsonObject } from '@rushstack/node-core-library'; import * as glob from 'glob'; import * as globEscape from 'glob-escape'; import * as decomment from 'decomment'; import { TypescriptCompiler as TTypescriptCompiler, - Typescript as TTypescript + Typescript as TTypescript, } from '@microsoft/rush-stack-compiler-3.1'; -import { - RSCTask, - IRSCTaskConfig -} from './RSCTask'; +import { RSCTask, IRSCTaskConfig } from './RSCTask'; import { TsParseConfigHost } from './TsParseConfigHost'; /** @@ -48,17 +40,10 @@ export interface ITscCmdTaskConfig extends IRSCTaskConfig { */ export class TscCmdTask extends RSCTask { public constructor() { - super( - 'tsc', - { - staticMatch: [ - 'src/**/*.js', - 'src/**/*.json', - 'src/**/*.jsx' - ], - removeCommentsFromJavaScript: false - } - ); + super('tsc', { + staticMatch: ['src/**/*.js', 'src/**/*.json', 'src/**/*.jsx'], + removeCommentsFromJavaScript: false, + }); } public loadSchema(): JsonObject { @@ -83,27 +68,30 @@ export class TscCmdTask extends RSCTask { libFolders.push(this.buildConfig.libESNextFolder); } - const resolvedLibFolders: string[] = libFolders.map((libFolder) => path.join(this.buildConfig.rootPath, libFolder)); + const resolvedLibFolders: string[] = libFolders.map((libFolder) => + path.join(this.buildConfig.rootPath, libFolder) + ); const promises: Promise[] = (this.taskConfig.staticMatch || []).map((pattern) => - LegacyAdapters.convertCallbackToPromise(glob, path.join(globEscape(this.buildConfig.rootPath), pattern)).then( - (matchPaths: string[]) => { - for (const matchPath of matchPaths) { - const fileContents: string = FileSystem.readFile(matchPath); - const relativePath: string = path.relative(srcPath, matchPath); - for (const resolvedLibFolder of resolvedLibFolders) { - const destPath: string = path.join(resolvedLibFolder, relativePath); - FileSystem.writeFile(destPath, fileContents, { ensureFolderExists: true }); - } + LegacyAdapters.convertCallbackToPromise( + glob, + path.join(globEscape(this.buildConfig.rootPath), pattern) + ).then((matchPaths: string[]) => { + for (const matchPath of matchPaths) { + const fileContents: string = FileSystem.readFile(matchPath); + const relativePath: string = path.relative(srcPath, matchPath); + for (const resolvedLibFolder of resolvedLibFolders) { + const destPath: string = path.join(resolvedLibFolder, relativePath); + FileSystem.writeFile(destPath, fileContents, { ensureFolderExists: true }); } } - ) + }) ); const typescriptCompiler: TTypescriptCompiler = new this._rushStackCompiler.TypescriptCompiler( { customArgs: this.taskConfig.customArgs, fileError: this.fileError.bind(this), - fileWarning: this.fileWarning.bind(this) + fileWarning: this.fileWarning.bind(this), }, this.buildFolder, this._terminalProvider @@ -114,12 +102,12 @@ export class TscCmdTask extends RSCTask { promises.push(basePromise); } - let buildPromise: Promise = Promise.all(promises).then(() => { /* collapse void[] to void */ }); + let buildPromise: Promise = Promise.all(promises).then(() => { + /* collapse void[] to void */ + }); if (this.taskConfig.removeCommentsFromJavaScript === true) { - buildPromise = buildPromise.then( - () => this._removeComments(this._rushStackCompiler.Typescript) - ); + buildPromise = buildPromise.then(() => this._removeComments(this._rushStackCompiler.Typescript)); } return buildPromise; @@ -142,7 +130,10 @@ export class TscCmdTask extends RSCTask { } private _removeComments(typescript: typeof TTypescript): Promise { - const configFilePath: string | undefined = typescript.findConfigFile(this.buildConfig.rootPath, FileSystem.exists); + const configFilePath: string | undefined = typescript.findConfigFile( + this.buildConfig.rootPath, + FileSystem.exists + ); if (!configFilePath) { return Promise.reject(new Error('Unable to resolve tsconfig file to determine outDir.')); } @@ -163,13 +154,10 @@ export class TscCmdTask extends RSCTask { ).then((matches: string[]) => { for (const match of matches) { const sourceText: string = FileSystem.readFile(match); - const decommentedText: string = decomment( - sourceText, - { - // This option preserves comments that start with /*!, /**! or //! - typically copyright comments - safe: true - } - ); + const decommentedText: string = decomment(sourceText, { + // This option preserves comments that start with /*!, /**! or //! - typically copyright comments + safe: true, + }); FileSystem.writeFile(match, decommentedText); } }); diff --git a/core-build/gulp-core-build-typescript/src/TslintCmdTask.ts b/core-build/gulp-core-build-typescript/src/TslintCmdTask.ts index 99fd9f5bae0..b4af2e3bde2 100644 --- a/core-build/gulp-core-build-typescript/src/TslintCmdTask.ts +++ b/core-build/gulp-core-build-typescript/src/TslintCmdTask.ts @@ -5,10 +5,7 @@ import * as path from 'path'; import { JsonFile, JsonObject } from '@rushstack/node-core-library'; import { TslintRunner as TTslintRunner } from '@microsoft/rush-stack-compiler-3.1'; -import { - RSCTask, - IRSCTaskConfig -} from './RSCTask'; +import { RSCTask, IRSCTaskConfig } from './RSCTask'; /** * @public @@ -25,12 +22,9 @@ export interface ITslintCmdTaskConfig extends IRSCTaskConfig { */ export class TslintCmdTask extends RSCTask { public constructor() { - super( - 'tslint', - { - displayAsError: false - } - ); + super('tslint', { + displayAsError: false, + }); } public loadSchema(): JsonObject { @@ -45,7 +39,7 @@ export class TslintCmdTask extends RSCTask { displayAsError: this.taskConfig.displayAsError, fileError: this.fileError.bind(this), - fileWarning: this.fileWarning.bind(this) + fileWarning: this.fileWarning.bind(this), }, this.buildFolder, this._terminalProvider diff --git a/core-build/gulp-core-build-typescript/src/index.ts b/core-build/gulp-core-build-typescript/src/index.ts index 9759879bc77..4dc29ddbbab 100644 --- a/core-build/gulp-core-build-typescript/src/index.ts +++ b/core-build/gulp-core-build-typescript/src/index.ts @@ -1,18 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - TscCmdTask, - ITscCmdTaskConfig -} from './TscCmdTask'; -import { - LintCmdTask, - ILintCmdTaskConfig -} from './LintCmdTask'; -import { - TslintCmdTask, - ITslintCmdTaskConfig -} from './TslintCmdTask'; +import { TscCmdTask, ITscCmdTaskConfig } from './TscCmdTask'; +import { LintCmdTask, ILintCmdTaskConfig } from './LintCmdTask'; +import { TslintCmdTask, ITslintCmdTaskConfig } from './TslintCmdTask'; import { ApiExtractorTask } from './ApiExtractorTask'; export { @@ -21,7 +12,7 @@ export { TslintCmdTask, ITslintCmdTaskConfig, LintCmdTask, - ILintCmdTaskConfig + ILintCmdTaskConfig, }; /** @public */ diff --git a/core-build/gulp-core-build-typescript/src/schemas/api-extractor.schema.json b/core-build/gulp-core-build-typescript/src/schemas/api-extractor.schema.json index 2497b4b1046..ddb1c7d0905 100644 --- a/core-build/gulp-core-build-typescript/src/schemas/api-extractor.schema.json +++ b/core-build/gulp-core-build-typescript/src/schemas/api-extractor.schema.json @@ -11,6 +11,6 @@ "type": "string" } }, - "required": [ "enabled" ], + "required": ["enabled"], "additionalProperties": false } diff --git a/core-build/gulp-core-build-typescript/src/schemas/lint-cmd.schema.json b/core-build/gulp-core-build-typescript/src/schemas/lint-cmd.schema.json index cd2bd48a205..51f4de52ca3 100644 --- a/core-build/gulp-core-build-typescript/src/schemas/lint-cmd.schema.json +++ b/core-build/gulp-core-build-typescript/src/schemas/lint-cmd.schema.json @@ -20,4 +20,4 @@ "type": "boolean" } } -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build-typescript/src/schemas/tsc-cmd.schema.json b/core-build/gulp-core-build-typescript/src/schemas/tsc-cmd.schema.json index ebfbafcdfae..0447a03ca54 100644 --- a/core-build/gulp-core-build-typescript/src/schemas/tsc-cmd.schema.json +++ b/core-build/gulp-core-build-typescript/src/schemas/tsc-cmd.schema.json @@ -14,15 +14,15 @@ "staticMatch": { "description": "Glob matches for files to be passed through the build", "type": "array", - "items": { - "type": "string", - "minLength": 1 - }, - "minItems": 1 + "items": { + "type": "string", + "minLength": 1 + }, + "minItems": 1 }, "buildDirectory": { "description": "The directory in which the typescript compiler should be invoked.", "type": "string" } } -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build-typescript/src/schemas/tslint-cmd.schema.json b/core-build/gulp-core-build-typescript/src/schemas/tslint-cmd.schema.json index 9944b45a3ed..d9aaf9db0b3 100644 --- a/core-build/gulp-core-build-typescript/src/schemas/tslint-cmd.schema.json +++ b/core-build/gulp-core-build-typescript/src/schemas/tslint-cmd.schema.json @@ -20,4 +20,4 @@ "type": "boolean" } } -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build-webpack/.eslintrc.js b/core-build/gulp-core-build-webpack/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/core-build/gulp-core-build-webpack/.eslintrc.js +++ b/core-build/gulp-core-build-webpack/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/core-build/gulp-core-build-webpack/src/WebpackTask.ts b/core-build/gulp-core-build-webpack/src/WebpackTask.ts index 73cb44b5625..ab70494e0b2 100644 --- a/core-build/gulp-core-build-webpack/src/WebpackTask.ts +++ b/core-build/gulp-core-build-webpack/src/WebpackTask.ts @@ -59,7 +59,7 @@ export class WebpackTask extends GulpTask extends GulpTask extends GulpTask void): void { - const shouldInitWebpack: boolean = (process.argv.indexOf('--initwebpack') > -1); + const shouldInitWebpack: boolean = process.argv.indexOf('--initwebpack') > -1; // eslint-disable-next-line const path = require('path'); @@ -94,7 +94,8 @@ export class WebpackTask extends GulpTask extends GulpTask { - if (!this.buildConfig.properties) { - this.buildConfig.properties = {}; - } + webpack(webpackConfig, (error, stats) => { + if (!this.buildConfig.properties) { + this.buildConfig.properties = {}; + } - // eslint-disable-next-line dot-notation - this.buildConfig.properties['webpackStats'] = stats; + // eslint-disable-next-line dot-notation + this.buildConfig.properties['webpackStats'] = stats; - const statsResult: Webpack.Stats.ToJsonOutput = stats.toJson({ - hash: false, - source: false - }); + const statsResult: Webpack.Stats.ToJsonOutput = stats.toJson({ + hash: false, + source: false, + }); - if (statsResult.errors && statsResult.errors.length) { - this.logError(`'${outputDir}':` + EOL + statsResult.errors.join(EOL) + EOL); - } + if (statsResult.errors && statsResult.errors.length) { + this.logError(`'${outputDir}':` + EOL + statsResult.errors.join(EOL) + EOL); + } - if (statsResult.warnings && statsResult.warnings.length) { - const unsuppressedWarnings: string[] = []; - const warningSuppressionRegexes: RegExp[] = (this.taskConfig.suppressWarnings || []).map((regex: string) => { + if (statsResult.warnings && statsResult.warnings.length) { + const unsuppressedWarnings: string[] = []; + const warningSuppressionRegexes: RegExp[] = (this.taskConfig.suppressWarnings || []).map( + (regex: string) => { return new RegExp(regex); - }); - - statsResult.warnings.forEach((warning: string) => { - let suppressed: boolean = false; - for (let i: number = 0; i < warningSuppressionRegexes.length; i++) { - const suppressionRegex: RegExp = warningSuppressionRegexes[i]; - if (warning.match(suppressionRegex)) { - suppressed = true; - break; - } - } - - if (!suppressed) { - unsuppressedWarnings.push(warning); + } + ); + + statsResult.warnings.forEach((warning: string) => { + let suppressed: boolean = false; + for (let i: number = 0; i < warningSuppressionRegexes.length; i++) { + const suppressionRegex: RegExp = warningSuppressionRegexes[i]; + if (warning.match(suppressionRegex)) { + suppressed = true; + break; } - }); - - if (unsuppressedWarnings.length > 0) { - this.logWarning(`'${outputDir}':` + EOL + unsuppressedWarnings.join(EOL) + EOL); } - } - const duration: number = (new Date().getTime() - startTime); - const statsResultChildren: Webpack.Stats.ToJsonOutput[] = statsResult.children ? statsResult.children : [statsResult]; - - statsResultChildren.forEach(child => { - if (child.chunks) { - child.chunks.forEach(chunk => { - if (chunk.files && this.taskConfig.printStats) { - chunk.files.forEach(file => ( - this.log(`Bundled: '${colors.cyan(path.basename(file))}', ` + - `size: ${colors.magenta(chunk.size.toString())} bytes, ` + - `took ${colors.magenta(duration.toString(10))} ms.`) - )); // end file - } - }); // end chunk + if (!suppressed) { + unsuppressedWarnings.push(warning); } - }); // end child + }); - completeCallback(); - }); // endwebpack callback + if (unsuppressedWarnings.length > 0) { + this.logWarning(`'${outputDir}':` + EOL + unsuppressedWarnings.join(EOL) + EOL); + } + } + + const duration: number = new Date().getTime() - startTime; + const statsResultChildren: Webpack.Stats.ToJsonOutput[] = statsResult.children + ? statsResult.children + : [statsResult]; + + statsResultChildren.forEach((child) => { + if (child.chunks) { + child.chunks.forEach((chunk) => { + if (chunk.files && this.taskConfig.printStats) { + chunk.files.forEach((file) => + this.log( + `Bundled: '${colors.cyan(path.basename(file))}', ` + + `size: ${colors.magenta(chunk.size.toString())} bytes, ` + + `took ${colors.magenta(duration.toString(10))} ms.` + ) + ); // end file + } + }); // end chunk + } + }); // end child + + completeCallback(); + }); // endwebpack callback } } } @@ -192,7 +197,8 @@ export class WebpackTask extends GulpTask void): - Promise | NodeJS.ReadWriteStream | void; + | Promise + | NodeJS.ReadWriteStream + | void; } /** @public */ @@ -168,8 +176,10 @@ class CustomTask extends GulpTask { this._fn = fn.bind(this); } - public executeTask(gulp: typeof Gulp | GulpProxy, completeCallback?: (error?: string | Error) => void): - Promise | NodeJS.ReadWriteStream | void { + public executeTask( + gulp: typeof Gulp | GulpProxy, + completeCallback?: (error?: string | Error) => void + ): Promise | NodeJS.ReadWriteStream | void { return this._fn(gulp, getConfig(), completeCallback); } } @@ -209,7 +219,6 @@ export function watch(watchMatch: string | string[], taskExecutable: IExecutable return { execute: (buildConfig: IBuildConfig): Promise => { return new Promise(() => { - function _runWatch(): Promise { if (isWatchRunning) { shouldRerunWatch = true; @@ -225,8 +234,8 @@ export function watch(watchMatch: string | string[], taskExecutable: IExecutable if (buildConfig.showToast) { notifier.notify({ title: successMessage, - message: (builtPackage ? builtPackage.name : ''), - icon: buildConfig.buildSuccessIconPath + message: builtPackage ? builtPackage.name : '', + icon: buildConfig.buildSuccessIconPath, }); } else { log(successMessage); @@ -242,7 +251,7 @@ export function watch(watchMatch: string | string[], taskExecutable: IExecutable notifier.notify({ title: failureMessage, message: error.toString(), - icon: buildConfig.buildErrorIconPath + icon: buildConfig.buildErrorIconPath, }); } else { log(failureMessage); @@ -269,7 +278,7 @@ export function watch(watchMatch: string | string[], taskExecutable: IExecutable _runWatch().catch(console.error); }); - } + }, }; } @@ -278,7 +287,7 @@ export function watch(watchMatch: string | string[], taskExecutable: IExecutable * @public */ export function serial(...tasks: (IExecutable[] | IExecutable)[]): IExecutable { - const flatTasks: IExecutable[] = _flatten(tasks).filter(taskExecutable => { + const flatTasks: IExecutable[] = _flatten(tasks).filter((taskExecutable) => { // eslint-disable-next-line @rushstack/no-null return taskExecutable !== null && taskExecutable !== undefined; }); @@ -296,7 +305,7 @@ export function serial(...tasks: (IExecutable[] | IExecutable)[]): IExecutable { } return output; - } + }, }; } @@ -305,7 +314,7 @@ export function serial(...tasks: (IExecutable[] | IExecutable)[]): IExecutable { * @public */ export function parallel(...tasks: (IExecutable[] | IExecutable)[]): IExecutable { - const flatTasks: IExecutable[] = _flatten(tasks).filter(taskExecutable => { + const flatTasks: IExecutable[] = _flatten(tasks).filter((taskExecutable) => { // eslint-disable-next-line @rushstack/no-null return taskExecutable !== null && taskExecutable !== undefined; }); @@ -326,7 +335,7 @@ export function parallel(...tasks: (IExecutable[] | IExecutable)[]): IExecutable // Use promise all to make sure errors are propagated correctly Promise.all(promises).then(resolve, reject); }); - } + }, }; } @@ -350,7 +359,7 @@ export function initialize(gulp: typeof Gulp): void { initializeLogging(gulp, getConfig(), undefined, undefined); - Object.keys(_taskMap).forEach(taskName => _registerTask(gulp, taskName, _taskMap[taskName])); + Object.keys(_taskMap).forEach((taskName) => _registerTask(gulp, taskName, _taskMap[taskName])); markTaskCreationTime(); } @@ -360,20 +369,19 @@ export function initialize(gulp: typeof Gulp): void { */ function _registerTask(gulp: typeof Gulp, taskName: string, taskExecutable: IExecutable): void { gulp.task(taskName, (cb) => { - const maxBuildTimeMs: number = taskExecutable.maxBuildTimeMs === undefined - ? _buildConfig.maxBuildTimeMs - : taskExecutable.maxBuildTimeMs; - const timer: NodeJS.Timer | undefined = maxBuildTimeMs === 0 - ? undefined - : setTimeout( - () => { + const maxBuildTimeMs: number = + taskExecutable.maxBuildTimeMs === undefined + ? _buildConfig.maxBuildTimeMs + : taskExecutable.maxBuildTimeMs; + const timer: NodeJS.Timer | undefined = + maxBuildTimeMs === 0 + ? undefined + : setTimeout(() => { logError( `Build ran for ${maxBuildTimeMs} milliseconds without completing. Cancelling build with error.` ); cb(new Error('Timeout')); - }, - maxBuildTimeMs - ); + }, maxBuildTimeMs); _executeTask(taskExecutable, _buildConfig).then( () => { if (timer) { @@ -408,7 +416,11 @@ function _executeTask(taskExecutable: IExecutable, buildConfig: IBuildConfig): P // If the task is missing, throw a meaningful error. if (!taskExecutable || !taskExecutable.execute) { - return Promise.reject(new Error(`A task was scheduled, but the task was null. This probably means the task wasn't imported correctly.`)); + return Promise.reject( + new Error( + `A task was scheduled, but the task was null. This probably means the task wasn't imported correctly.` + ) + ); } if (taskExecutable.isEnabled === undefined || taskExecutable.isEnabled(buildConfig)) { @@ -418,8 +430,8 @@ function _executeTask(taskExecutable: IExecutable, buildConfig: IBuildConfig): P buildConfig.onTaskStart(taskExecutable.name); } - const taskPromise: Promise = taskExecutable.execute(buildConfig) - .then(() => { + const taskPromise: Promise = taskExecutable.execute(buildConfig).then( + () => { if (buildConfig.onTaskEnd && taskExecutable.name) { buildConfig.onTaskEnd(taskExecutable.name, process.hrtime(startTime)); } @@ -430,7 +442,8 @@ function _executeTask(taskExecutable: IExecutable, buildConfig: IBuildConfig): P } return Promise.reject(error); - }); + } + ); return taskPromise; } diff --git a/core-build/gulp-core-build/src/logging.ts b/core-build/gulp-core-build/src/logging.ts index d592fe57a1e..92ddd7c1a59 100644 --- a/core-build/gulp-core-build/src/logging.ts +++ b/core-build/gulp-core-build/src/logging.ts @@ -55,7 +55,7 @@ let duringFastExit: boolean = false; // eslint-disable-next-line @typescript-eslint/no-explicit-any const globalInstance: any = global as any; -const localCache: ILocalCache = globalInstance.__loggingCache = globalInstance.__loggingCache || { +const localCache: ILocalCache = (globalInstance.__loggingCache = globalInstance.__loggingCache || { warnings: [], errors: [], testsRun: 0, @@ -81,8 +81,8 @@ const localCache: ILocalCache = globalInstance.__loggingCache = globalInstance._ gulpErrorCallback: undefined, gulpStopCallback: undefined, shouldLogErrorsDuringSummary: false, - shouldLogWarningsDuringSummary: false -}; + shouldLogWarningsDuringSummary: false, +}); if (!localCache.start) { localCache.start = process.hrtime(); @@ -94,7 +94,6 @@ function isVerbose(): boolean { // eslint-disable-next-line @typescript-eslint/no-explicit-any function formatError(e: any): string | undefined { - if (!e.err) { if (isVerbose()) { return e.message + '\r\n' + e.stack; @@ -118,7 +117,7 @@ function formatError(e: any): string | undefined { } // unknown (string, number, etc.) - if (typeof (Error) === 'undefined') { + if (typeof Error === 'undefined') { if (isVerbose()) { return e.message + '\r\n' + e.stack; } else { @@ -135,7 +134,7 @@ function formatError(e: any): string | undefined { if (isVerbose()) { return new Error(output).stack; - } else { + } else { return new Error(output).message; } } @@ -170,7 +169,6 @@ function afterStreamsFlushed(callback: () => void): void { } function writeSummary(callback: () => void): void { - localCache.writeSummaryCallbacks.push(callback); if (!localCache.writingSummary) { @@ -213,19 +211,28 @@ function writeSummary(callback: () => void): void { // `Subtasks run: ${colors.yellow(localCache.subTasksRun + '')}`); if (localCache.testsRun > 0) { - log('Tests results -', - 'Passed:', colors.green(localCache.testsPassed + ''), - 'Failed:', colors.red(localCache.testsFailed + ''), + log( + 'Tests results -', + 'Passed:', + colors.green(localCache.testsPassed + ''), + 'Failed:', + colors.red(localCache.testsFailed + ''), // 'Flaky:', colors.yellow(localCache.testsFlakyFailed + ''), - 'Skipped:', colors.yellow(localCache.testsSkipped + '')); + 'Skipped:', + colors.yellow(localCache.testsSkipped + '') + ); } if (localCache.coverageResults > 0) { log( 'Coverage results -', - 'Passed:', colors.green(localCache.coveragePass + ''), - 'Failed:', colors.red((localCache.coverageResults - localCache.coveragePass) + ''), - 'Avg. Cov.:', colors.yellow(Math.floor(localCache.coverageTotal / localCache.coverageResults) + '%')); + 'Passed:', + colors.green(localCache.coveragePass + ''), + 'Failed:', + colors.red(localCache.coverageResults - localCache.coveragePass + ''), + 'Avg. Cov.:', + colors.yellow(Math.floor(localCache.coverageTotal / localCache.coverageResults) + '%') + ); } if (getWarnings().length) { @@ -235,7 +242,7 @@ function writeSummary(callback: () => void): void { let totalErrors: number = 0; if (localCache.taskErrors > 0 || getErrors().length) { - totalErrors = (localCache.taskErrors + getErrors().length); + totalErrors = localCache.taskErrors + getErrors().length; log('Task errors:', colors.red(totalErrors + '')); } @@ -291,12 +298,15 @@ function wireUpProcessErrorHandling(shouldWarningsFailBuild: boolean): void { process.on('exit', (code: number) => { duringFastExit = true; - if (!global['dontWatchExit']) { // eslint-disable-line dot-notation + if (!global['dontWatchExit']) { + // eslint-disable-line dot-notation if (!localCache.wroteSummary) { localCache.wroteSummary = true; console.log('About to exit with code:', code); - console.error('Process terminated before summary could be written, possible error in async code not ' + - 'continuing!'); + console.error( + 'Process terminated before summary could be written, possible error in async code not ' + + 'continuing!' + ); console.log('Trying to exit with exit code 1'); exitProcess(1); } else { @@ -312,19 +322,18 @@ function wireUpProcessErrorHandling(shouldWarningsFailBuild: boolean): void { } }); - process.on('uncaughtException', - (err: Error) => { - console.error(err); + process.on('uncaughtException', (err: Error) => { + console.error(err); - _writeTaskError(err); - writeSummary(() => { - exitProcess(1); + _writeTaskError(err); + writeSummary(() => { + exitProcess(1); - if (localCache.gulpErrorCallback) { - localCache.gulpErrorCallback(err); - } - }); + if (localCache.gulpErrorCallback) { + localCache.gulpErrorCallback(err); + } }); + }); } } @@ -353,10 +362,12 @@ export function logSummary(value: string): void { export function log(...args: string[]): void { const currentTime: Date = new Date(); const timestamp: string = colors.gray( - [padTimePart(currentTime.getHours()), - padTimePart(currentTime.getMinutes()), - padTimePart(currentTime.getSeconds())] - .join(':')); + [ + padTimePart(currentTime.getHours()), + padTimePart(currentTime.getMinutes()), + padTimePart(currentTime.getSeconds()), + ].join(':') + ); console.log(`[${timestamp}] ${args.join('')}`); } @@ -399,7 +410,7 @@ export enum TestResultState { Passed, Failed, FlakyFailed, - Skipped + Skipped, } /** @@ -477,7 +488,6 @@ const colorCodeRegex: RegExp = /\x1B[[(?);]{0,2}(;?\d)*./g; * @public */ export function addSuppression(suppression: string | RegExp): void { - if (typeof suppression === 'string') { suppression = normalizeMessage(suppression); } @@ -542,7 +552,6 @@ export function fileLog( errorCode: string, message: string ): void { - if (!filePath) { filePath = ''; } else if (path.isAbsolute(filePath)) { @@ -598,7 +607,6 @@ export function fileError( * @public */ export function verbose(...args: string[]): void { - if (getFlagValue('verbose')) { log.apply(undefined, args); } @@ -615,7 +623,7 @@ export function generateGulpError(err: any): any { showStack: false, toString: (): string => { return ''; - } + }, }; markErrorAsWritten(output); @@ -639,7 +647,7 @@ export function writeError(e: any): void { const time: string = prettyTime(e.hrDuration); error( - '\'' + colors.cyan(e.task) + '\'', + "'" + colors.cyan(e.task) + "'", colors.red(e.subTask ? 'sub task errored after' : 'errored after'), colors.magenta(time), '\r\n', @@ -653,30 +661,18 @@ export function writeError(e: any): void { error( e.message, '\r\n', - e.plugin + ': \'' + colors.yellow(e.fileName) + '\':' + e.lineNumber, + e.plugin + ": '" + colors.yellow(e.fileName) + "':" + e.lineNumber, '\r\n', e.stack ); } else { - error( - e.message, - '\r\n', - e.plugin + ': \'' + colors.yellow(e.fileName) + '\':' + e.lineNumber - ); + error(e.message, '\r\n', e.plugin + ": '" + colors.yellow(e.fileName) + "':" + e.lineNumber); } } else { if (isVerbose()) { - error( - 'Unknown', - '\r\n', - colors.red(e.message), - '\r\n', - e.stack); + error('Unknown', '\r\n', colors.red(e.message), '\r\n', e.stack); } else { - error( - 'Unknown', - '\r\n', - colors.red(e.message)); + error('Unknown', '\r\n', colors.red(e.message)); } } markErrorAsWritten(e); @@ -751,7 +747,7 @@ export function logEndSubtask(name: string, startTime: [number, number], errorOb err: errorObject, task: name, subTask: true, - hrDuration: duration + hrDuration: duration, }); } } @@ -772,31 +768,33 @@ export function initialize( wireUpProcessErrorHandling(config.shouldWarningsFailBuild); - localCache.gulpErrorCallback = gulpErrorCallback || (() => { - - // Do Nothing - }); - - localCache.gulpStopCallback = gulpStopCallback || (() => { + localCache.gulpErrorCallback = + gulpErrorCallback || + (() => { + // Do Nothing + }); - // Do Nothing - }); + localCache.gulpStopCallback = + gulpStopCallback || + (() => { + // Do Nothing + }); // eslint-disable-next-line @typescript-eslint/no-explicit-any gulp.on('start', (err: any) => { - log('Starting gulp'); }); // eslint-disable-next-line @typescript-eslint/no-explicit-any gulp.on('stop', (err: any) => { - writeSummary(() => { // error if we have any errors - if (localCache.taskErrors > 0 || + if ( + localCache.taskErrors > 0 || (getWarnings().length && config.shouldWarningsFailBuild) || getErrors().length || - localCache.testsFailed > 0) { + localCache.testsFailed > 0 + ) { exitProcess(1); } @@ -809,7 +807,6 @@ export function initialize( // eslint-disable-next-line @typescript-eslint/no-explicit-any gulp.on('err', (err: any) => { - _writeTaskError(err); writeSummary(() => { exitProcess(1); @@ -821,9 +818,8 @@ export function initialize( // eslint-disable-next-line @typescript-eslint/no-explicit-any gulp.on('task_start', (e: any) => { - if (localCache.fromRunGulp) { - log('Starting', '\'' + colors.cyan(e.task) + '\'...'); + log('Starting', "'" + colors.cyan(e.task) + "'..."); } localCache.taskRun++; @@ -831,20 +827,15 @@ export function initialize( // eslint-disable-next-line @typescript-eslint/no-explicit-any gulp.on('task_stop', (e: any) => { - const time: string = prettyTime(e.hrDuration); if (localCache.fromRunGulp) { - log( - 'Finished', '\'' + colors.cyan(e.task) + '\'', - 'after', colors.magenta(time) - ); + log('Finished', "'" + colors.cyan(e.task) + "'", 'after', colors.magenta(time)); } }); // eslint-disable-next-line @typescript-eslint/no-explicit-any gulp.on('task_err', (err: any) => { - _writeTaskError(err); writeSummary(() => { exitProcess(1); @@ -853,10 +844,7 @@ export function initialize( // eslint-disable-next-line @typescript-eslint/no-explicit-any gulp.on('task_not_found', (err: any) => { - - log( - colors.red('Task \'' + err.task + '\' is not in your gulpfile') - ); + log(colors.red("Task '" + err.task + "' is not in your gulpfile")); log('Please check the documentation for proper gulpfile formatting'); exitProcess(1); }); diff --git a/core-build/gulp-core-build/src/tasks/CleanFlagTask.ts b/core-build/gulp-core-build/src/tasks/CleanFlagTask.ts index 7a54f79f062..16c2399f4fe 100644 --- a/core-build/gulp-core-build/src/tasks/CleanFlagTask.ts +++ b/core-build/gulp-core-build/src/tasks/CleanFlagTask.ts @@ -18,19 +18,16 @@ export class CleanFlagTask extends CleanTask { } public isEnabled(buildConfig: IBuildConfig): boolean { - // eslint-disable-next-line dot-notation - const shouldRun: boolean = (!!buildConfig.args['clean'] || !!buildConfig.args['c']) - && this._hasRun === false; - return shouldRun; -} + // eslint-disable-next-line dot-notation + const shouldRun: boolean = + (!!buildConfig.args['clean'] || !!buildConfig.args['c']) && this._hasRun === false; + return shouldRun; + } - public executeTask( - gulp: typeof Gulp, - completeCallback: (error?: string | Error) => void - ): void { + public executeTask(gulp: typeof Gulp, completeCallback: (error?: string | Error) => void): void { super.executeTask(gulp, () => { this._hasRun = true; completeCallback(); }); } -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build/src/tasks/CleanTask.ts b/core-build/gulp-core-build/src/tasks/CleanTask.ts index c68063bceac..7b4bb01700e 100644 --- a/core-build/gulp-core-build/src/tasks/CleanTask.ts +++ b/core-build/gulp-core-build/src/tasks/CleanTask.ts @@ -26,16 +26,9 @@ export class CleanTask extends GulpTask { * to the build, and by calling the getCleanMatch() function, collects a list of * glob patterns which are then passed to the `del` plugin to delete them from disk. */ - public executeTask( - gulp: typeof Gulp, - completeCallback: (error?: string | Error) => void - ): void { + public executeTask(gulp: typeof Gulp, completeCallback: (error?: string | Error) => void): void { const { distFolder, libFolder, libAMDFolder, tempFolder }: IBuildConfig = this.buildConfig; - let cleanPaths: string[] = [ - distFolder, - libFolder, - tempFolder - ]; + let cleanPaths: string[] = [distFolder, libFolder, tempFolder]; if (libAMDFolder) { cleanPaths.push(libAMDFolder); @@ -52,7 +45,7 @@ export class CleanTask extends GulpTask { const uniquePaths: { [key: string]: string } = {}; // Create dictionary of unique paths. (Could be replaced with ES6 set.) - cleanPaths.forEach(cleanPath => { + cleanPaths.forEach((cleanPath) => { if (cleanPath) { uniquePaths[cleanPath] = cleanPath; } @@ -73,4 +66,4 @@ export class CleanTask extends GulpTask { completeCallback(e); } } -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build/src/tasks/CopyTask.ts b/core-build/gulp-core-build/src/tasks/CopyTask.ts index e3536924a3b..e6482aa59b5 100644 --- a/core-build/gulp-core-build/src/tasks/CopyTask.ts +++ b/core-build/gulp-core-build/src/tasks/CopyTask.ts @@ -36,13 +36,10 @@ export class CopyTask extends GulpTask { * Instantiates a CopyTask with an empty configuration */ public constructor() { - super( - 'copy', - { - copyTo: {}, - shouldFlatten: true - } - ); + super('copy', { + copyTo: {}, + shouldFlatten: true, + }); } /** @@ -58,7 +55,8 @@ export class CopyTask extends GulpTask { public executeTask( gulp: typeof Gulp, completeCallback: (error?: string | Error) => void - ): Promise | NodeJS.ReadWriteStream | void { // eslint-disable-line @typescript-eslint/no-explicit-any + ): Promise | NodeJS.ReadWriteStream | void { + // eslint-disable-line @typescript-eslint/no-explicit-any /* eslint-disable */ const flatten = require('gulp-flatten'); const gulpif = require('gulp-if'); @@ -73,11 +71,14 @@ export class CopyTask extends GulpTask { if (copyTo.hasOwnProperty(copyDest)) { const sources: string[] = copyTo[copyDest]; - sources.forEach(sourceMatch => allStreams.push( - gulp.src(sourceMatch, { allowEmpty: true }) - .pipe(gulpif(shouldFlatten, flatten())) - .pipe(gulp.dest(copyDest)) - )); + sources.forEach((sourceMatch) => + allStreams.push( + gulp + .src(sourceMatch, { allowEmpty: true }) + .pipe(gulpif(shouldFlatten, flatten())) + .pipe(gulp.dest(copyDest)) + ) + ); } } diff --git a/core-build/gulp-core-build/src/tasks/GenerateShrinkwrapTask.ts b/core-build/gulp-core-build/src/tasks/GenerateShrinkwrapTask.ts index 7fdf60295f4..64c4e1e3946 100644 --- a/core-build/gulp-core-build/src/tasks/GenerateShrinkwrapTask.ts +++ b/core-build/gulp-core-build/src/tasks/GenerateShrinkwrapTask.ts @@ -58,4 +58,4 @@ export class GenerateShrinkwrapTask extends GulpTask { such as your text editor, command prompt, or "gulp serve"`); } } -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build/src/tasks/GulpTask.ts b/core-build/gulp-core-build/src/tasks/GulpTask.ts index 0263fe7f32f..43853236e2d 100644 --- a/core-build/gulp-core-build/src/tasks/GulpTask.ts +++ b/core-build/gulp-core-build/src/tasks/GulpTask.ts @@ -16,7 +16,7 @@ import { fileWarning, warn, logEndSubtask, - logStartSubtask + logStartSubtask, } from '../logging'; import Vinyl = require('vinyl'); import gulp = require('gulp'); @@ -208,7 +208,13 @@ export abstract class GulpTask implements IExecutable { * @param warningCode - the custom warning code representing this warning * @param message - a description of the warning */ - public fileWarning(filePath: string, line: number, column: number, warningCode: string, message: string): void { + public fileWarning( + filePath: string, + line: number, + column: number, + warningCode: string, + message: string + ): void { fileWarning(this.name, filePath, line, column, warningCode, message); } @@ -265,43 +271,50 @@ export abstract class GulpTask implements IExecutable { } else if (stream.pipe) { // wait for stream to end - eos(stream, { - error: true, - readable: stream.readable, - writable: stream.writable && !stream.readable - }, (err: any) => { // eslint-disable-line @typescript-eslint/no-explicit-any - if (err) { - reject(err); - } else { - resolve(); + eos( + stream, + { + error: true, + readable: stream.readable, + writable: stream.writable && !stream.readable, + }, + (err: any) => { + // eslint-disable-line @typescript-eslint/no-explicit-any + if (err) { + reject(err); + } else { + resolve(); + } } - }); + ); // Make sure the stream is completely read - stream.pipe(through2.obj( - (file: Vinyl, - encoding: string, - callback: (p?: any) => void) => { // eslint-disable-line @typescript-eslint/no-explicit-any + stream.pipe( + through2.obj( + (file: Vinyl, encoding: string, callback: (p?: any) => void) => { + // eslint-disable-line @typescript-eslint/no-explicit-any callback(); - }, - (callback: () => void) => { - callback(); - })); - + }, + (callback: () => void) => { + callback(); + } + ) + ); } else if (this.executeTask.length === 1) { resolve(stream); } } else if (this.executeTask.length === 1) { resolve(stream); } - }) - .then(() => { + }).then( + () => { logEndSubtask(this.name, startTime); }, (ex) => { logEndSubtask(this.name, startTime, ex); throw ex; - }); + } + ); } /** @@ -328,7 +341,9 @@ export abstract class GulpTask implements IExecutable { try { doesExist = FileSystem.getStatistics(fullPath).isFile(); - } catch (e) { /* no-op */ } + } catch (e) { + /* no-op */ + } return doesExist; } @@ -342,11 +357,12 @@ export abstract class GulpTask implements IExecutable { const fullSourcePath: string = path.resolve(__dirname, localSourcePath); const fullDestPath: string = path.resolve( this.buildConfig.rootPath, - (localDestPath || path.basename(localSourcePath))); + localDestPath || path.basename(localSourcePath) + ); FileSystem.copyFile({ sourcePath: fullSourcePath, - destinationPath: fullDestPath + destinationPath: fullDestPath, }); } @@ -361,7 +377,9 @@ export abstract class GulpTask implements IExecutable { try { const content: string = FileSystem.readFile(fullPath); result = JSON.parse(content); - } catch (e) { /* no-op */ } + } catch (e) { + /* no-op */ + } return result; } @@ -392,7 +410,8 @@ export abstract class GulpTask implements IExecutable { if (!FileSystem.exists(filePath)) { return undefined; } else { - if (args['verbose']) { // eslint-disable-line dot-notation + if (args['verbose']) { + // eslint-disable-line dot-notation console.log(`Found config file: ${path.basename(filePath)}`); } diff --git a/core-build/gulp-core-build/src/tasks/JestReporter.ts b/core-build/gulp-core-build/src/tasks/JestReporter.ts index bf891ed84f9..e9277e6479f 100644 --- a/core-build/gulp-core-build/src/tasks/JestReporter.ts +++ b/core-build/gulp-core-build/src/tasks/JestReporter.ts @@ -40,8 +40,8 @@ class JestReporter extends (DefaultReporter as { new (globalConfig: Config.Globa } interface IReporterOptions { - outputFilePath?: string, - writeNUnitResults?: boolean + outputFilePath?: string; + writeNUnitResults?: boolean; } -module.exports = JestReporter; \ No newline at end of file +module.exports = JestReporter; diff --git a/core-build/gulp-core-build/src/tasks/JestTask.ts b/core-build/gulp-core-build/src/tasks/JestTask.ts index 94e285ad60a..d29156ad68e 100644 --- a/core-build/gulp-core-build/src/tasks/JestTask.ts +++ b/core-build/gulp-core-build/src/tasks/JestTask.ts @@ -97,19 +97,17 @@ export function _isJestEnabled(rootFolder: string): boolean { * @alpha */ export class JestTask extends GulpTask { - public constructor() { - super('jest', - { - cache: true, - collectCoverageFrom: ['lib/**/*.js?(x)', '!lib/**/test/**'], - coverage: true, - coverageReporters: ['json' /*, 'html' */], // Remove HTML reporter temporarily until the Handlebars issue is fixed - testPathIgnorePatterns: ['/(src|lib-amd|lib-es6|coverage|build|docs|node_modules)/'], - // Some unit tests rely on data folders that look like packages. This confuses jest-hast-map - // when it tries to scan for package.json files. - modulePathIgnorePatterns: ['/(src|lib)/.*/package.json'] - }); + super('jest', { + cache: true, + collectCoverageFrom: ['lib/**/*.js?(x)', '!lib/**/test/**'], + coverage: true, + coverageReporters: ['json' /*, 'html' */], // Remove HTML reporter temporarily until the Handlebars issue is fixed + testPathIgnorePatterns: ['/(src|lib-amd|lib-es6|coverage|build|docs|node_modules)/'], + // Some unit tests rely on data folders that look like packages. This confuses jest-hast-map + // when it tries to scan for package.json files. + modulePathIgnorePatterns: ['/(src|lib)/.*/package.json'], + }); } public isEnabled(buildConfig: IBuildConfig): boolean { @@ -123,12 +121,13 @@ export class JestTask extends GulpTask { return require('./jest.schema.json'); } - public executeTask( - gulp: typeof Gulp, - completeCallback: (error?: string | Error) => void - ): void { - const configFileFullPath: string = path.join(this.buildConfig.rootPath, - 'config', 'jest', DEFAULT_JEST_CONFIG_FILE_NAME); + public executeTask(gulp: typeof Gulp, completeCallback: (error?: string | Error) => void): void { + const configFileFullPath: string = path.join( + this.buildConfig.rootPath, + 'config', + 'jest', + DEFAULT_JEST_CONFIG_FILE_NAME + ); this._copySnapshots(this.buildConfig.srcFolder, this.buildConfig.libFolder); @@ -141,23 +140,21 @@ export class JestTask extends GulpTask { coverage: this.taskConfig.coverage, coverageReporters: this.taskConfig.coverageReporters, coverageDirectory: path.join(this.buildConfig.tempFolder, 'coverage'), - maxWorkers: this.taskConfig.maxWorkers ? - this.taskConfig.maxWorkers : 1, - moduleDirectories: this.taskConfig.moduleDirectories ? - this.taskConfig.moduleDirectories : - ['node_modules', this.buildConfig.libFolder], + maxWorkers: this.taskConfig.maxWorkers ? this.taskConfig.maxWorkers : 1, + moduleDirectories: this.taskConfig.moduleDirectories + ? this.taskConfig.moduleDirectories + : ['node_modules', this.buildConfig.libFolder], reporters: [ [ path.join(__dirname, 'JestReporter.js'), { outputFilePath: path.join(this.buildConfig.tempFolder, 'jest-results', 'test-results.xml'), - writeNUnitResults: this.taskConfig.writeNUnitResults - } - ] + writeNUnitResults: this.taskConfig.writeNUnitResults, + }, + ], ], rootDir: this.buildConfig.rootPath, - testMatch: this.taskConfig.testMatch ? - this.taskConfig.testMatch : ['**/*.test.js?(x)'], + testMatch: this.taskConfig.testMatch ? this.taskConfig.testMatch : ['**/*.test.js?(x)'], testPathIgnorePatterns: this.taskConfig.testPathIgnorePatterns, modulePathIgnorePatterns: this.taskConfig.modulePathIgnorePatterns, updateSnapshot: !this.buildConfig.production, @@ -166,34 +163,34 @@ export class JestTask extends GulpTask { // https://github.com/facebook/jest/issues/5913 // As a workaround, resolve it for Jest: testEnvironment: require.resolve('jest-environment-jsdom'), - cacheDirectory: path.join(this.buildConfig.rootPath, this.buildConfig.tempFolder, 'jest-cache') + cacheDirectory: path.join(this.buildConfig.rootPath, this.buildConfig.tempFolder, 'jest-cache'), }; // suppress 'Running coverage on untested files...' warning const oldTTY: true | undefined = process.stdout.isTTY; process.stdout.isTTY = undefined; - runCLI(jestConfig, - [this.buildConfig.rootPath]).then( - (result: { results: AggregatedResult, globalConfig: Config.GlobalConfig }) => { - process.stdout.isTTY = oldTTY; - if (result.results.numFailedTests || result.results.numFailedTestSuites) { - completeCallback(new Error('Jest tests failed')); - } else { - if (!this.buildConfig.production) { - this._copySnapshots(this.buildConfig.libFolder, this.buildConfig.srcFolder); - } - completeCallback(); + runCLI(jestConfig, [this.buildConfig.rootPath]) + .then((result: { results: AggregatedResult; globalConfig: Config.GlobalConfig }) => { + process.stdout.isTTY = oldTTY; + if (result.results.numFailedTests || result.results.numFailedTestSuites) { + completeCallback(new Error('Jest tests failed')); + } else { + if (!this.buildConfig.production) { + this._copySnapshots(this.buildConfig.libFolder, this.buildConfig.srcFolder); } - }).catch((err) => { - process.stdout.isTTY = oldTTY; - completeCallback(err); - }); + completeCallback(); + } + }) + .catch((err) => { + process.stdout.isTTY = oldTTY; + completeCallback(err); + }); } private _copySnapshots(srcRoot: string, destRoot: string): void { const pattern: string = path.join(srcRoot, '**', '__snapshots__', '*.snap'); - glob.sync(pattern).forEach(snapFile => { + glob.sync(pattern).forEach((snapFile) => { const destination: string = snapFile.replace(srcRoot, destRoot); if (this._copyIfMatchExtension(snapFile, destination, '.test.tsx.snap')) { this.logVerbose(`Snapshot file ${snapFile} is copied to match extension ".test.tsx.snap".`); @@ -204,7 +201,9 @@ export class JestTask extends GulpTask { } else if (this._copyIfMatchExtension(snapFile, destination, '.test.js.snap')) { this.logVerbose(`Snapshot file ${snapFile} is copied to match extension ".test.js.snap".`); } else { - this.logWarning(`Snapshot file ${snapFile} is not copied because don't find that matching test file.`); + this.logWarning( + `Snapshot file ${snapFile} is not copied because don't find that matching test file.` + ); } }); } @@ -216,11 +215,11 @@ export class JestTask extends GulpTask { if (FileSystem.exists(testFile)) { FileSystem.copyFile({ sourcePath: snapSourceFile, - destinationPath: snapDestFile + destinationPath: snapDestFile, }); return true; } else { return false; } } -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build/src/tasks/ValidateShrinkwrapTask.ts b/core-build/gulp-core-build/src/tasks/ValidateShrinkwrapTask.ts index b1db8538323..cc83122bdde 100644 --- a/core-build/gulp-core-build/src/tasks/ValidateShrinkwrapTask.ts +++ b/core-build/gulp-core-build/src/tasks/ValidateShrinkwrapTask.ts @@ -8,12 +8,12 @@ import * as semver from 'semver'; import { FileConstants } from '@rushstack/node-core-library'; interface IShrinkwrapDep { - [name: string]: { version: string } -}; + [name: string]: { version: string }; +} interface IPackageDep { - [name: string]: string -}; + [name: string]: string; +} /** * Partial representation of the contents of a `package.json` file @@ -51,7 +51,10 @@ export class ValidateShrinkwrapTask extends GulpTask { * Iterates through dependencies listed in a project's package.json and ensures that they are all * resolvable in the npm-shrinkwrap file. */ - public executeTask(gulp: gulpType.Gulp, completeCallback: (error: string) => void): NodeJS.ReadWriteStream | void { + public executeTask( + gulp: gulpType.Gulp, + completeCallback: (error: string) => void + ): NodeJS.ReadWriteStream | void { const pathToPackageJson: string = path.join(this.buildConfig.rootPath, FileConstants.PackageJson); const pathToShrinkwrap: string = path.join(this.buildConfig.rootPath, 'npm-shrinkwrap.json'); diff --git a/core-build/gulp-core-build/src/tasks/copy.schema.json b/core-build/gulp-core-build/src/tasks/copy.schema.json index 54046d01381..85f8a4ddb7d 100644 --- a/core-build/gulp-core-build/src/tasks/copy.schema.json +++ b/core-build/gulp-core-build/src/tasks/copy.schema.json @@ -29,4 +29,4 @@ "type": "boolean" } } -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build/src/tasks/copyStaticAssets/CopyStaticAssetsTask.ts b/core-build/gulp-core-build/src/tasks/copyStaticAssets/CopyStaticAssetsTask.ts index 8e889ea4bd0..366ffd00dde 100644 --- a/core-build/gulp-core-build/src/tasks/copyStaticAssets/CopyStaticAssetsTask.ts +++ b/core-build/gulp-core-build/src/tasks/copyStaticAssets/CopyStaticAssetsTask.ts @@ -47,15 +47,12 @@ export interface ICopyStaticAssetsTaskConfig { */ export class CopyStaticAssetsTask extends GulpTask { public constructor() { - super( - 'copy-static-assets', - { - includeExtensions: [], - excludeExtensions: [], - includeFiles: [], - excludeFiles: [] - } - ); + super('copy-static-assets', { + includeExtensions: [], + excludeExtensions: [], + includeFiles: [], + excludeFiles: [], + }); } public loadSchema(): JsonObject { @@ -68,7 +65,12 @@ export class CopyStaticAssetsTask extends GulpTask const globPatterns: string[] = []; - const allExtensions: string[] = (this.taskConfig.includeExtensions || []).concat(['json', 'html', 'css', 'md']); + const allExtensions: string[] = (this.taskConfig.includeExtensions || []).concat([ + 'json', + 'html', + 'css', + 'md', + ]); for (let ext of allExtensions) { if (this.taskConfig.excludeExtensions) { @@ -98,8 +100,9 @@ export class CopyStaticAssetsTask extends GulpTask globPatterns.push(`!${path.join(rootPath, file)}`); } - return gulp.src(globPatterns, { base: rootPath }) - .pipe(gulp.dest(libPath)) - .on('finish', () => completeCallback()); + return gulp + .src(globPatterns, { base: rootPath }) + .pipe(gulp.dest(libPath)) + .on('finish', () => completeCallback()); } } diff --git a/core-build/gulp-core-build/src/tasks/copyStaticAssets/copy-static-assets.schema.json b/core-build/gulp-core-build/src/tasks/copyStaticAssets/copy-static-assets.schema.json index 011546271fe..d43f45d7d3c 100644 --- a/core-build/gulp-core-build/src/tasks/copyStaticAssets/copy-static-assets.schema.json +++ b/core-build/gulp-core-build/src/tasks/copyStaticAssets/copy-static-assets.schema.json @@ -54,4 +54,4 @@ } } } -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build/src/tasks/jest.schema.json b/core-build/gulp-core-build/src/tasks/jest.schema.json index 895d15791bb..d92ed4164e7 100644 --- a/core-build/gulp-core-build/src/tasks/jest.schema.json +++ b/core-build/gulp-core-build/src/tasks/jest.schema.json @@ -67,4 +67,4 @@ } }, "additionalProperties": false -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build/src/test/GulpTask.test.ts b/core-build/gulp-core-build/src/test/GulpTask.test.ts index d5ca9997326..e4a286edb10 100644 --- a/core-build/gulp-core-build/src/test/GulpTask.test.ts +++ b/core-build/gulp-core-build/src/test/GulpTask.test.ts @@ -2,19 +2,14 @@ // See LICENSE in the project root for license information. import Vinyl = require('vinyl'); -import * as Gulp from 'gulp'; +import * as Gulp from 'gulp'; import { Readable } from 'stream'; import * as path from 'path'; -import { - serial, - parallel, - GulpTask -} from '../index'; +import { serial, parallel, GulpTask } from '../index'; import { mockBuildConfig } from './mockBuildConfig'; -interface IConfig { -} +interface IConfig {} let testArray: string[] = []; @@ -36,19 +31,20 @@ class StreamTask extends GulpTask { super('stream', {}); } - public executeTask(gulp: typeof Gulp): any { // eslint-disable-line @typescript-eslint/no-explicit-any + public executeTask(gulp: typeof Gulp): any { + // eslint-disable-line @typescript-eslint/no-explicit-any const stream: Readable = new Readable({ objectMode: true }); // Add no opt function to make it compat with through - stream['_read'] = () => { // eslint-disable-line dot-notation + stream['_read'] = () => { + // eslint-disable-line dot-notation // Do Nothing }; setTimeout(() => { - const file: Vinyl = new Vinyl({ path: 'test.js', - contents: Buffer.from('test') + contents: Buffer.from('test'), }); stream.push(file); @@ -101,12 +97,9 @@ class SchemaTask extends GulpTask { public name: string = ''; public constructor() { - super( - 'schema-task', - { - shouldDoThings: false - } - ); + super('schema-task', { + shouldDoThings: false, + }); } public executeTask(gulp: typeof Gulp, callback: (error?: string | Error) => void): void { @@ -118,8 +111,7 @@ class SchemaTask extends GulpTask { } } -const tasks: GulpTask[] = [ -]; +const tasks: GulpTask[] = []; tasks.push(new PromiseTask()); tasks.push(new StreamTask()); @@ -132,19 +124,25 @@ describe('GulpTask', () => { it(`${task.name} serial`, (done) => { testArray = []; task.setConfig({ addToMe: testArray }); - serial(task).execute(mockBuildConfig).then(() => { - expect(testArray).toEqual([task.name]); - done(); - }).catch(done); + serial(task) + .execute(mockBuildConfig) + .then(() => { + expect(testArray).toEqual([task.name]); + done(); + }) + .catch(done); }); it(`${task.name} parallel`, (done) => { testArray = []; task.setConfig({ addToMe: testArray }); - parallel(task).execute(mockBuildConfig).then(() => { - expect(testArray).toEqual([task.name]); - done(); - }).catch(done); + parallel(task) + .execute(mockBuildConfig) + .then(() => { + expect(testArray).toEqual([task.name]); + done(); + }) + .catch(done); }); } @@ -153,12 +151,15 @@ describe('GulpTask', () => { for (const task of tasks) { task.setConfig({ addToMe: testArray }); } - serial(tasks).execute(mockBuildConfig).then(() => { - for (const task of tasks) { - expect(testArray.indexOf(task.name)).toBeGreaterThan(-1); - } - done(); - }).catch(done); + serial(tasks) + .execute(mockBuildConfig) + .then(() => { + for (const task of tasks) { + expect(testArray.indexOf(task.name)).toBeGreaterThan(-1); + } + done(); + }) + .catch(done); }); it(`all tasks parallel`, (done) => { @@ -166,12 +167,15 @@ describe('GulpTask', () => { for (const task of tasks) { task.setConfig({ addToMe: testArray }); } - parallel(tasks).execute(mockBuildConfig).then(() => { - for (const task of tasks) { - expect(testArray.indexOf(task.name)).toBeGreaterThan(-1); - } - done(); - }).catch(done); + parallel(tasks) + .execute(mockBuildConfig) + .then(() => { + for (const task of tasks) { + expect(testArray.indexOf(task.name)).toBeGreaterThan(-1); + } + done(); + }) + .catch(done); }); it(`reads schema file if loadSchema is implemented`, (done) => { diff --git a/core-build/gulp-core-build/src/test/index.test.ts b/core-build/gulp-core-build/src/test/index.test.ts index 1761b8d21ae..f34b39c561a 100644 --- a/core-build/gulp-core-build/src/test/index.test.ts +++ b/core-build/gulp-core-build/src/test/index.test.ts @@ -1,14 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - serial, - parallel, - getConfig, - setConfig, - IExecutable, - IBuildConfig -} from '../index'; +import { serial, parallel, getConfig, setConfig, IExecutable, IBuildConfig } from '../index'; import { mockBuildConfig } from './mockBuildConfig'; // disable the exit watching @@ -17,52 +10,60 @@ global['dontWatchExit'] = true; // eslint-disable-line dot-notation describe('serial', () => { it('can run a set of tasks in serial', (done) => { const execution: string[] = []; - const tasks: IExecutable[] = createTasks('task', 3, command => execution.push(command)); - - serial(tasks).execute(mockBuildConfig).then(() => { - expect(execution).toEqual([ - 'executing task 0', - 'complete task 0', - 'executing task 1', - 'complete task 1', - 'executing task 2', - 'complete task 2' - ]); - done(); - }).catch(error => done(error)); - }); + const tasks: IExecutable[] = createTasks('task', 3, (command) => execution.push(command)); + serial(tasks) + .execute(mockBuildConfig) + .then(() => { + expect(execution).toEqual([ + 'executing task 0', + 'complete task 0', + 'executing task 1', + 'complete task 1', + 'executing task 2', + 'complete task 2', + ]); + done(); + }) + .catch((error) => done(error)); + }); }); describe('parallel', () => { it('can run a set of tasks in parallel', (done) => { const execution: string[] = []; - const tasks: IExecutable[] = createTasks('task', 3, command => execution.push(command)); - - parallel(tasks).execute(mockBuildConfig).then(() => { - expect(execution).toEqual([ - 'executing task 0', - 'executing task 1', - 'executing task 2', - 'complete task 0', - 'complete task 1', - 'complete task 2' - ]); - done(); - }).catch(error => done(error)); + const tasks: IExecutable[] = createTasks('task', 3, (command) => execution.push(command)); + + parallel(tasks) + .execute(mockBuildConfig) + .then(() => { + expect(execution).toEqual([ + 'executing task 0', + 'executing task 1', + 'executing task 2', + 'complete task 0', + 'complete task 1', + 'complete task 2', + ]); + done(); + }) + .catch((error) => done(error)); }); it('can mix in serial sets of tasks', (done) => { const execution: string[] = []; - const serial1Tasks: IExecutable = serial(createTasks('serial set 1 -', 2, command => execution.push(command))); - const parallelTasks: IExecutable = parallel(createTasks('parallel', 2, command => execution.push(command))); - const serial2Tasks: IExecutable = serial(createTasks('serial set 2 -', 2, command => execution.push(command))); - - serial([ - serial1Tasks, - parallelTasks, - serial2Tasks - ]).execute(mockBuildConfig) + const serial1Tasks: IExecutable = serial( + createTasks('serial set 1 -', 2, (command) => execution.push(command)) + ); + const parallelTasks: IExecutable = parallel( + createTasks('parallel', 2, (command) => execution.push(command)) + ); + const serial2Tasks: IExecutable = serial( + createTasks('serial set 2 -', 2, (command) => execution.push(command)) + ); + + serial([serial1Tasks, parallelTasks, serial2Tasks]) + .execute(mockBuildConfig) .then(() => { expect(execution).toEqual([ 'executing serial set 1 - 0', @@ -76,34 +77,35 @@ describe('parallel', () => { 'executing serial set 2 - 0', 'complete serial set 2 - 0', 'executing serial set 2 - 1', - 'complete serial set 2 - 1' + 'complete serial set 2 - 1', ]); done(); }) - .catch(error => done(error)); + .catch((error) => done(error)); }); it('stops running serial tasks on failure', (done) => { const execution: string[] = []; - const tasks: IExecutable[] = createTasks('task', 1, command => execution.push(command)); + const tasks: IExecutable[] = createTasks('task', 1, (command) => execution.push(command)); - tasks.push(createTask('fail task', command => execution.push(command), true)); - tasks.push(createTask('should not run task', command => execution.push(command), false)); + tasks.push(createTask('fail task', (command) => execution.push(command), true)); + tasks.push(createTask('should not run task', (command) => execution.push(command), false)); - serial(tasks).execute(mockBuildConfig).then( - () => { + serial(tasks) + .execute(mockBuildConfig) + .then(() => { done('The task returned success unexpectedly.'); - }).catch((error) => { + }) + .catch((error) => { expect(error).toEqual('Failure'); //, 'Make sure the proper error is propagate'); expect(execution).toEqual([ 'executing task 0', 'complete task 0', 'executing fail task', - 'complete fail task' + 'complete fail task', ]); done(); }); - }); it('can read the current config', (done) => { @@ -116,7 +118,7 @@ describe('parallel', () => { it('can set the config', (done) => { const distFolder: string = 'testFolder'; const newConfig: Partial = { - distFolder: distFolder + distFolder: distFolder, }; setConfig(newConfig); @@ -128,28 +130,32 @@ describe('parallel', () => { function createTasks( name: string, count: number, - executionCallback: (message: string) => void): IExecutable[] { - return Array.apply(undefined, Array(count)) - .map((item, index) => createTask(name + ' ' + index, executionCallback)); + executionCallback: (message: string) => void +): IExecutable[] { + return Array.apply(undefined, Array(count)).map((item, index) => + createTask(name + ' ' + index, executionCallback) + ); } function createTask( name: string, executionCallback: (message: string) => void, - shouldFail?: boolean): IExecutable { + shouldFail?: boolean +): IExecutable { return { - execute: (buildConfig): Promise => new Promise((resolve, reject) => { - executionCallback(`executing ${name}`); - - setTimeout(() => { - executionCallback(`complete ${name}`); - - if (shouldFail) { - reject('Failure'); - } else { - resolve(); - } - }, 10); - }) + execute: (buildConfig): Promise => + new Promise((resolve, reject) => { + executionCallback(`executing ${name}`); + + setTimeout(() => { + executionCallback(`complete ${name}`); + + if (shouldFail) { + reject('Failure'); + } else { + resolve(); + } + }, 10); + }), }; } diff --git a/core-build/gulp-core-build/src/test/mockBuildConfig.ts b/core-build/gulp-core-build/src/test/mockBuildConfig.ts index 71563f935da..b1506fdb70a 100644 --- a/core-build/gulp-core-build/src/test/mockBuildConfig.ts +++ b/core-build/gulp-core-build/src/test/mockBuildConfig.ts @@ -14,5 +14,5 @@ export const mockBuildConfig: IBuildConfig = { verbose: false, production: false, args: {}, - shouldWarningsFailBuild: false + shouldWarningsFailBuild: false, }; diff --git a/core-build/gulp-core-build/src/test/other-schema-task.config.json b/core-build/gulp-core-build/src/test/other-schema-task.config.json index b5dbcabaaf8..df8dff12303 100644 --- a/core-build/gulp-core-build/src/test/other-schema-task.config.json +++ b/core-build/gulp-core-build/src/test/other-schema-task.config.json @@ -9,4 +9,4 @@ "type": "boolean" } } -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build/src/test/schema-task.config.json b/core-build/gulp-core-build/src/test/schema-task.config.json index ba382d6def6..48c61fb42e2 100644 --- a/core-build/gulp-core-build/src/test/schema-task.config.json +++ b/core-build/gulp-core-build/src/test/schema-task.config.json @@ -1,3 +1,3 @@ { "shouldDoThings": true -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build/src/test/schema-task.schema.json b/core-build/gulp-core-build/src/test/schema-task.schema.json index 449441f1f72..4967131d2af 100644 --- a/core-build/gulp-core-build/src/test/schema-task.schema.json +++ b/core-build/gulp-core-build/src/test/schema-task.schema.json @@ -13,4 +13,4 @@ "type": "boolean" } } -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build/src/utilities/FileDeletionUtility.ts b/core-build/gulp-core-build/src/utilities/FileDeletionUtility.ts index d65f67d5bdf..574feb0419e 100644 --- a/core-build/gulp-core-build/src/utilities/FileDeletionUtility.ts +++ b/core-build/gulp-core-build/src/utilities/FileDeletionUtility.ts @@ -79,4 +79,4 @@ export class FileDeletionUtility { } return true; } -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build/src/utilities/GCBTerminalProvider.ts b/core-build/gulp-core-build/src/utilities/GCBTerminalProvider.ts index da69b36c586..66993c7eff2 100644 --- a/core-build/gulp-core-build/src/utilities/GCBTerminalProvider.ts +++ b/core-build/gulp-core-build/src/utilities/GCBTerminalProvider.ts @@ -1,10 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - TerminalProviderSeverity, - ConsoleTerminalProvider -} from '@rushstack/node-core-library'; +import { TerminalProviderSeverity, ConsoleTerminalProvider } from '@rushstack/node-core-library'; import { GulpTask } from '../tasks/GulpTask'; @@ -46,4 +43,4 @@ export class GCBTerminalProvider extends ConsoleTerminalProvider { } } } -} \ No newline at end of file +} diff --git a/core-build/gulp-core-build/src/utilities/test/FileDeletionUtility.test.ts b/core-build/gulp-core-build/src/utilities/test/FileDeletionUtility.test.ts index a73479203ae..9e823a83881 100644 --- a/core-build/gulp-core-build/src/utilities/test/FileDeletionUtility.test.ts +++ b/core-build/gulp-core-build/src/utilities/test/FileDeletionUtility.test.ts @@ -12,74 +12,42 @@ describe('FileDeletionUtility', () => { }); describe('isParentDirectory', () => { it('can detect an immediate child', () => { - expect( - FileDeletionUtility.isParentDirectory('/a', '/a/b.txt') - ).toEqual(true); + expect(FileDeletionUtility.isParentDirectory('/a', '/a/b.txt')).toEqual(true); }); it('can detect a deep child', () => { - expect( - FileDeletionUtility.isParentDirectory('/a', '/a/b/c/d.txt') - ).toEqual(true); + expect(FileDeletionUtility.isParentDirectory('/a', '/a/b/c/d.txt')).toEqual(true); }); it('can detect if base path is longer', () => { - expect( - FileDeletionUtility.isParentDirectory('/a/b/c/d', '/a/b/c/d/g.txt') - ).toEqual(true); + expect(FileDeletionUtility.isParentDirectory('/a/b/c/d', '/a/b/c/d/g.txt')).toEqual(true); }); it('can detect siblings', () => { - expect( - FileDeletionUtility.isParentDirectory('/a/b', '/a/c') - ).toEqual(false); + expect(FileDeletionUtility.isParentDirectory('/a/b', '/a/c')).toEqual(false); }); it('can detect siblings with file extensions', () => { - expect( - FileDeletionUtility.isParentDirectory('/a/b/c.txt', '/a/b/d.txt') - ).toEqual(false); + expect(FileDeletionUtility.isParentDirectory('/a/b/c.txt', '/a/b/d.txt')).toEqual(false); }); it('can detect when not a parent', () => { - expect( - FileDeletionUtility.isParentDirectory('/a/b/c', '/a') - ).toEqual(false); - expect( - FileDeletionUtility.isParentDirectory('/a/b/c', '/a/b.txt') - ).toEqual(false); + expect(FileDeletionUtility.isParentDirectory('/a/b/c', '/a')).toEqual(false); + expect(FileDeletionUtility.isParentDirectory('/a/b/c', '/a/b.txt')).toEqual(false); }); it('accepts anything under the root', () => { - expect( - FileDeletionUtility.isParentDirectory('/', '/a.txt') - ).toEqual(true); - expect( - FileDeletionUtility.isParentDirectory('/', '/a/b/c/d.txt') - ).toEqual(true); + expect(FileDeletionUtility.isParentDirectory('/', '/a.txt')).toEqual(true); + expect(FileDeletionUtility.isParentDirectory('/', '/a/b/c/d.txt')).toEqual(true); }); it('it is case sensitive', () => { - expect( - FileDeletionUtility.isParentDirectory('/a', '/A/b.txt') - ).toEqual(false); - expect( - FileDeletionUtility.isParentDirectory('/a', '/a/b.txt') - ).toEqual(true); - expect( - FileDeletionUtility.isParentDirectory('/a/B/c', '/a/b/c/d.txt') - ).toEqual(false); + expect(FileDeletionUtility.isParentDirectory('/a', '/A/b.txt')).toEqual(false); + expect(FileDeletionUtility.isParentDirectory('/a', '/a/b.txt')).toEqual(true); + expect(FileDeletionUtility.isParentDirectory('/a/B/c', '/a/b/c/d.txt')).toEqual(false); }); it('it does not accept null or undefined', () => { /* eslint-disable @rushstack/no-null */ - expect( - FileDeletionUtility.isParentDirectory('', '/A/b.txt') - ).toEqual(false); - expect( - FileDeletionUtility.isParentDirectory(undefined, '/a/b.txt') - ).toEqual(false); + expect(FileDeletionUtility.isParentDirectory('', '/A/b.txt')).toEqual(false); + expect(FileDeletionUtility.isParentDirectory(undefined, '/a/b.txt')).toEqual(false); expect( FileDeletionUtility.isParentDirectory(null as any, '/a/b/c/d.txt') // eslint-disable-line @typescript-eslint/no-explicit-any ).toEqual(false); - expect( - FileDeletionUtility.isParentDirectory('/A/b.txt', '') - ).toEqual(false); - expect( - FileDeletionUtility.isParentDirectory('/a/b.txt', undefined) - ).toEqual(false); + expect(FileDeletionUtility.isParentDirectory('/A/b.txt', '')).toEqual(false); + expect(FileDeletionUtility.isParentDirectory('/a/b.txt', undefined)).toEqual(false); expect( FileDeletionUtility.isParentDirectory('/a/b/c/d.txt', null as any) // eslint-disable-line @typescript-eslint/no-explicit-any ).toEqual(false); @@ -100,15 +68,9 @@ describe('FileDeletionUtility', () => { '/c', '/c/a.txt', '/c/f/g/h/j/k/l/q', - '/d' - ]; - const expected: string[] = [ - '/a', - '/b/f/g', - '/b/f/ggg', - '/c', - '/d' + '/d', ]; + const expected: string[] = ['/a', '/b/f/g', '/b/f/ggg', '/c', '/d']; const actual: string[] = FileDeletionUtility.removeChildren(files); expect(actual).toHaveLength(expected.length); @@ -127,15 +89,13 @@ describe('FileDeletionUtility', () => { '/c', '/c/a.txt', '/c/f/g/h/j/k/l/q', - '/d' - ]; - const expected: string[] = [ - '/' + '/d', ]; + const expected: string[] = ['/']; const actual: string[] = FileDeletionUtility.removeChildren(files); expect(actual).toHaveLength(expected.length); expect(expected).toEqual(actual); }); }); -}); \ No newline at end of file +}); diff --git a/core-build/gulp-core-build/tsconfig.json b/core-build/gulp-core-build/tsconfig.json index 47e75f9f181..f81ee11ef26 100644 --- a/core-build/gulp-core-build/tsconfig.json +++ b/core-build/gulp-core-build/tsconfig.json @@ -1,8 +1,6 @@ { "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "jest" - ] + "types": ["jest"] } } diff --git a/core-build/gulp-core-build/typings-custom/glob-escape/index.d.ts b/core-build/gulp-core-build/typings-custom/glob-escape/index.d.ts index a1c89033510..cf21aa060c6 100644 --- a/core-build/gulp-core-build/typings-custom/glob-escape/index.d.ts +++ b/core-build/gulp-core-build/typings-custom/glob-escape/index.d.ts @@ -1,8 +1,7 @@ // Type definitions for glob-escape 0.0.1 // Definitions by: pgonzal -declare module "glob-escape" { - +declare module 'glob-escape' { function escapeGlob(glob: string): string; function escapeGlob(glob: string[]): string[]; diff --git a/core-build/node-library-build/.eslintrc.js b/core-build/node-library-build/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/core-build/node-library-build/.eslintrc.js +++ b/core-build/node-library-build/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/core-build/node-library-build/gulpfile.js b/core-build/node-library-build/gulpfile.js index dee27c7c4a6..b7457c2afb9 100644 --- a/core-build/node-library-build/gulpfile.js +++ b/core-build/node-library-build/gulpfile.js @@ -1,13 +1,12 @@ 'use strict'; let build = require('@microsoft/gulp-core-build'); -let { tscCmd, lintCmd, apiExtractor } = require('@microsoft/gulp-core-build-typescript') +let { tscCmd, lintCmd, apiExtractor } = require('@microsoft/gulp-core-build-typescript'); build.setConfig({ - shouldWarningsFailBuild: build.getConfig().production + shouldWarningsFailBuild: build.getConfig().production, }); build.task('default', build.serial(build.parallel(tscCmd, lintCmd), apiExtractor)); build.initialize(require('gulp')); - diff --git a/core-build/node-library-build/src/index.ts b/core-build/node-library-build/src/index.ts index 5bda754d5b7..97dd478503a 100644 --- a/core-build/node-library-build/src/index.ts +++ b/core-build/node-library-build/src/index.ts @@ -10,7 +10,7 @@ import { serial, parallel, IExecutable, - setConfig + setConfig, } from '@microsoft/gulp-core-build'; import { tscCmd, lintCmd, apiExtractor } from '@microsoft/gulp-core-build-typescript'; import { instrument, mocha } from '@microsoft/gulp-core-build-mocha'; @@ -32,10 +32,11 @@ preCopy.name = 'pre-copy'; export const postCopy: CopyTask = new CopyTask(); postCopy.name = 'post-copy'; -const PRODUCTION: boolean = process.argv.indexOf('--production') !== -1 || process.argv.indexOf('--ship') !== -1; +const PRODUCTION: boolean = + process.argv.indexOf('--production') !== -1 || process.argv.indexOf('--ship') !== -1; setConfig({ production: PRODUCTION, - shouldWarningsFailBuild: PRODUCTION + shouldWarningsFailBuild: PRODUCTION, }); const buildSubtask: IExecutable = serial( diff --git a/core-build/web-library-build/.eslintrc.js b/core-build/web-library-build/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/core-build/web-library-build/.eslintrc.js +++ b/core-build/web-library-build/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/core-build/web-library-build/src/PostProcessSourceMaps.ts b/core-build/web-library-build/src/PostProcessSourceMaps.ts index 2c1ccc53f23..a3aea17f780 100644 --- a/core-build/web-library-build/src/PostProcessSourceMaps.ts +++ b/core-build/web-library-build/src/PostProcessSourceMaps.ts @@ -11,20 +11,19 @@ export class PostProcessSourceMaps extends GulpTask { public executeTask(gulp: gulpType.Gulp): NodeJS.ReadWriteStream | void { if (this.buildConfig.args.hasOwnProperty('vscode')) { - // eslint-disable-next-line const replace = require('gulp-replace'); - return gulp.src(['dist/*!(.min).js.map']) + return gulp + .src(['dist/*!(.min).js.map']) .pipe(replace('webpack:///./', '')) .pipe(replace('webpack:////source/', '')) .pipe(replace('webpack:////src/', '')) .pipe(replace('webpack:///../~/', '../node_modules/')) .pipe(replace('"sourceRoot":""', '"sourceRoot":"/"')) .pipe(gulp.dest('dist/')); - } else { return; } } -} \ No newline at end of file +} diff --git a/core-build/web-library-build/src/index.ts b/core-build/web-library-build/src/index.ts index 4143630358b..d063d00fc40 100644 --- a/core-build/web-library-build/src/index.ts +++ b/core-build/web-library-build/src/index.ts @@ -12,7 +12,7 @@ import { task, watch, setConfig, - getConfig + getConfig, } from '@microsoft/gulp-core-build'; import { apiExtractor, tscCmd, lintCmd } from '@microsoft/gulp-core-build-typescript'; import { sass } from '@microsoft/gulp-core-build-sass'; @@ -39,16 +39,13 @@ preCopy.name = 'pre-copy'; export const postCopy: CopyTask = new CopyTask(); postCopy.name = 'post-copy'; -const sourceMatch: string[] = [ - 'src/**/*.{ts,tsx,scss,js,txt,html}', - '!src/**/*.scss.ts' -]; +const sourceMatch: string[] = ['src/**/*.{ts,tsx,scss,js,txt,html}', '!src/**/*.scss.ts']; // eslint-disable-next-line dot-notation const PRODUCTION: boolean = !!getConfig().args['production'] || !!getConfig().args['ship']; setConfig({ production: PRODUCTION, - shouldWarningsFailBuild: PRODUCTION + shouldWarningsFailBuild: PRODUCTION, }); // Define default task groups. @@ -95,13 +92,11 @@ task('generate', generateShrinkwrapTask); task('test-watch', watch(sourceMatch, testTasks)); // For watch scenarios like serve, make sure to exclude generated files from src (like *.scss.ts.) -task('serve', +task( + 'serve', serial( serve, - watch( - sourceMatch, - serial(preCopy, sass, tscCmd, postCopy, webpack, postProcessSourceMapsTask, reload) - ) + watch(sourceMatch, serial(preCopy, sass, tscCmd, postCopy, webpack, postProcessSourceMapsTask, reload)) ) ); diff --git a/libraries/debug-certificate-manager/.eslintrc.js b/libraries/debug-certificate-manager/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/libraries/debug-certificate-manager/.eslintrc.js +++ b/libraries/debug-certificate-manager/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/libraries/debug-certificate-manager/config/jest.json b/libraries/debug-certificate-manager/config/jest.json index b4a7ec97a56..902b00ea176 100644 --- a/libraries/debug-certificate-manager/config/jest.json +++ b/libraries/debug-certificate-manager/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": true -} \ No newline at end of file +} diff --git a/libraries/debug-certificate-manager/src/CertificateManager.ts b/libraries/debug-certificate-manager/src/CertificateManager.ts index a5ac4b8f42f..844333c165a 100644 --- a/libraries/debug-certificate-manager/src/CertificateManager.ts +++ b/libraries/debug-certificate-manager/src/CertificateManager.ts @@ -51,17 +51,12 @@ export class CertificateManager { * * @public */ - public ensureCertificate( - canGenerateNewCertificate: boolean, - terminal: Terminal - ): ICertificate { - + public ensureCertificate(canGenerateNewCertificate: boolean, terminal: Terminal): ICertificate { if (this._certificateStore.certificateData && this._certificateStore.keyData) { if (!this._certificateHasSubjectAltName()) { - let warningMessage: string = ( + let warningMessage: string = 'The existing development certificate is missing the subjectAltName ' + - 'property and will not work with the latest versions of some browsers. ' - ); + 'property and will not work with the latest versions of some browsers. '; if (canGenerateNewCertificate) { warningMessage += ' Attempting to untrust the certificate and generate a new one.'; @@ -82,7 +77,7 @@ export class CertificateManager { return { pemCertificate: this._certificateStore.certificateData, - pemKey: this._certificateStore.keyData + pemKey: this._certificateStore.keyData, }; } @@ -100,8 +95,10 @@ export class CertificateManager { return false; } - const winUntrustResult: child_process.SpawnSyncReturns = - child_process.spawnSync(certutilExePath, ['-user', '-delstore', 'root', serialNumber]); + const winUntrustResult: child_process.SpawnSyncReturns = child_process.spawnSync( + certutilExePath, + ['-user', '-delstore', 'root', serialNumber] + ); if (winUntrustResult.status !== 0) { terminal.writeErrorLine(`Error: ${winUntrustResult.stdout.toString()}`); @@ -114,16 +111,20 @@ export class CertificateManager { case 'darwin': terminal.writeVerboseLine('Trying to find the signature of the dev cert'); - const macFindCertificateResult: child_process.SpawnSyncReturns = - child_process.spawnSync('security', ['find-certificate', '-c', 'localhost', '-a', '-Z', macKeychain]); + const macFindCertificateResult: child_process.SpawnSyncReturns = child_process.spawnSync( + 'security', + ['find-certificate', '-c', 'localhost', '-a', '-Z', macKeychain] + ); if (macFindCertificateResult.status !== 0) { - terminal.writeErrorLine(`Error finding the dev certificate: ${macFindCertificateResult.output.join(' ')}`); + terminal.writeErrorLine( + `Error finding the dev certificate: ${macFindCertificateResult.output.join(' ')}` + ); return false; } const outputLines: string[] = macFindCertificateResult.stdout.toString().split(EOL); let found: boolean = false; - let shaHash: string = ""; + let shaHash: string = ''; for (let i: number = 0; i < outputLines.length; i++) { const line: string = outputLines[i]; const shaMatch: string[] | null = line.match(/^SHA-1 hash: (.+)$/); @@ -145,8 +146,13 @@ export class CertificateManager { terminal.writeVerboseLine(`Found the dev cert. SHA is ${shaHash}`); - const macUntrustResult: ISudoSyncResult = - runSudoSync(['security', 'delete-certificate', '-Z', shaHash, macKeychain]); + const macUntrustResult: ISudoSyncResult = runSudoSync([ + 'security', + 'delete-certificate', + '-Z', + shaHash, + macKeychain, + ]); if (macUntrustResult.code === 0) { terminal.writeVerboseLine('Successfully untrusted dev certificate.'); @@ -160,15 +166,14 @@ export class CertificateManager { // Linux + others: Have the user manually untrust the cert terminal.writeLine( 'Automatic certificate untrust is only implemented for debug-certificate-manager on Windows ' + - 'and macOS. To untrust the development certificate, remove this certificate from your trusted ' + - `root certification authorities: "${this._certificateStore.certificatePath}". The ` + - `certificate has serial number "${serialNumber}".` + 'and macOS. To untrust the development certificate, remove this certificate from your trusted ' + + `root certification authorities: "${this._certificateStore.certificatePath}". The ` + + `certificate has serial number "${serialNumber}".` ); return false; } } - private _createDevelopmentCertificate(): ICertificate { const keys: forge.pki.KeyPair = forge.pki.rsa.generateKeyPair(2048); const certificate: forge.pki.Certificate = forge.pki.createCertificate(); @@ -181,10 +186,12 @@ export class CertificateManager { // Valid for 3 years certificate.validity.notAfter.setFullYear(certificate.validity.notBefore.getFullYear() + 3); - const attrs: forge.pki.CertificateField[] = [{ - name: 'commonName', - value: 'localhost' - }]; + const attrs: forge.pki.CertificateField[] = [ + { + name: 'commonName', + value: 'localhost', + }, + ]; certificate.setSubject(attrs); certificate.setIssuer(attrs); @@ -192,23 +199,28 @@ export class CertificateManager { certificate.setExtensions([ { name: 'subjectAltName', - altNames: [{ - type: 2, // DNS - value: 'localhost' - }] + altNames: [ + { + type: 2, // DNS + value: 'localhost', + }, + ], }, { name: 'keyUsage', digitalSignature: true, keyEncipherment: true, - dataEncipherment: true - }, { + dataEncipherment: true, + }, + { name: 'extKeyUsage', - serverAuth: true - }, { + serverAuth: true, + }, + { name: 'friendlyName', - value: friendlyName - }]); + value: friendlyName, + }, + ]); // self-sign certificate certificate.sign(keys.privateKey, forge.md.sha256.create()); @@ -219,16 +231,13 @@ export class CertificateManager { return { pemCertificate: pem, - pemKey: pemKey + pemKey: pemKey, }; } private _ensureCertUtilExePath(terminal: Terminal): string | undefined { if (!_certutilExePath) { - const where: child_process.SpawnSyncReturns = child_process.spawnSync( - 'where', - ['certutil'] - ); + const where: child_process.SpawnSyncReturns = child_process.spawnSync('where', ['certutil']); const whereErr: string = where.stderr.toString(); if (whereErr) { @@ -254,23 +263,28 @@ export class CertificateManager { terminal.writeLine( 'Attempting to trust a dev certificate. This self-signed certificate only points to localhost ' + - 'and will be stored in your local user profile to be used by other instances of ' + - 'debug-certificate-manager. If you do not consent to trust this certificate, click "NO" in the dialog.' + 'and will be stored in your local user profile to be used by other instances of ' + + 'debug-certificate-manager. If you do not consent to trust this certificate, click "NO" in the dialog.' ); - const winTrustResult: child_process.SpawnSyncReturns = - child_process.spawnSync(certutilExePath, ['-user', '-addstore', 'root', certificatePath]); + const winTrustResult: child_process.SpawnSyncReturns = child_process.spawnSync( + certutilExePath, + ['-user', '-addstore', 'root', certificatePath] + ); if (winTrustResult.status !== 0) { terminal.writeErrorLine(`Error: ${winTrustResult.stdout.toString()}`); - const errorLines: string[] = winTrustResult.stdout.toString().split(EOL).map( - (line: string) => line.trim() - ); + const errorLines: string[] = winTrustResult.stdout + .toString() + .split(EOL) + .map((line: string) => line.trim()); // Not sure if this is always the status code for "cancelled" - should confirm. - if (winTrustResult.status === 2147943623 || - errorLines[errorLines.length - 1].indexOf('The operation was canceled by the user.') > 0) { + if ( + winTrustResult.status === 2147943623 || + errorLines[errorLines.length - 1].indexOf('The operation was canceled by the user.') > 0 + ) { terminal.writeLine('Certificate trust cancelled.'); } else { terminal.writeErrorLine('Certificate trust failed with an unknown error.'); @@ -286,9 +300,9 @@ export class CertificateManager { case 'darwin': terminal.writeLine( 'Attempting to trust a dev certificate. This self-signed certificate only points to localhost ' + - 'and will be stored in your local user profile to be used by other instances of ' + - 'debug-certificate-manager. If you do not consent to trust this certificate, do not enter your ' + - 'root password in the prompt.' + 'and will be stored in your local user profile to be used by other instances of ' + + 'debug-certificate-manager. If you do not consent to trust this certificate, do not enter your ' + + 'root password in the prompt.' ); const commands: string[] = [ @@ -299,7 +313,7 @@ export class CertificateManager { 'trustRoot', '-k', macKeychain, - certificatePath + certificatePath, ]; const result: ISudoSyncResult = runSudoSync(commands); @@ -307,13 +321,17 @@ export class CertificateManager { terminal.writeVerboseLine('Successfully trusted development certificate.'); return true; } else { - if (result.stderr.some((value: string) => !!value.match(/The authorization was cancelled by the user\./))) { + if ( + result.stderr.some( + (value: string) => !!value.match(/The authorization was cancelled by the user\./) + ) + ) { terminal.writeLine('Certificate trust cancelled.'); return false; } else { terminal.writeErrorLine( `Certificate trust failed with an unknown error. Exit code: ${result.code}. ` + - `Error: ${result.stderr.join(' ')}` + `Error: ${result.stderr.join(' ')}` ); return false; } @@ -323,8 +341,8 @@ export class CertificateManager { // Linux + others: Have the user manually trust the cert if they want to terminal.writeLine( 'Automatic certificate trust is only implemented for debug-certificate-manager on Windows ' + - 'and macOS. To trust the development certificate, add this certificate to your trusted root ' + - `certification authorities: "${certificatePath}".` + 'and macOS. To trust the development certificate, add this certificate to your trusted root ' + + `certification authorities: "${certificatePath}".` ); return true; } @@ -347,20 +365,16 @@ export class CertificateManager { 'Signature = "$Windows NT$"', '[Properties]', `11 = "{text}${friendlyName}"`, - '' + '', ].join(EOL); FileSystem.writeFile(friendlyNamePath, friendlyNameFile); - const commands: string[] = [ - '–repairstore', - '–user', - 'root', - serialNumber, - friendlyNamePath - ]; - const repairStoreResult: child_process.SpawnSyncReturns = - child_process.spawnSync(certutilExePath, commands); + const commands: string[] = ['–repairstore', '–user', 'root', serialNumber, friendlyNamePath]; + const repairStoreResult: child_process.SpawnSyncReturns = child_process.spawnSync( + certutilExePath, + commands + ); if (repairStoreResult.status !== 0) { terminal.writeErrorLine(`CertUtil Error: ${repairStoreResult.stdout.toString()}`); @@ -389,7 +403,7 @@ export class CertificateManager { const pemFileContents: string | undefined = generatedCertificate.pemCertificate; if (pemFileContents) { FileSystem.writeFile(tempCertificatePath, pemFileContents, { - ensureFolderExists: true + ensureFolderExists: true, }); } @@ -399,7 +413,7 @@ export class CertificateManager { // Try to set the friendly name, and warn if we can't if (!this._trySetFriendlyName(tempCertificatePath, terminal)) { - terminal.writeWarningLine('Unable to set the certificate\'s friendly name.'); + terminal.writeWarningLine("Unable to set the certificate's friendly name."); } } else { // Clear out the existing store data, if any exists @@ -418,6 +432,4 @@ export class CertificateManager { const certificate: forge.pki.Certificate = forge.pki.certificateFromPem(certificateData); return !!certificate.getExtension('subjectAltName'); } - - -} \ No newline at end of file +} diff --git a/libraries/debug-certificate-manager/src/CertificateStore.ts b/libraries/debug-certificate-manager/src/CertificateStore.ts index 6133a4087be..0473d140874 100644 --- a/libraries/debug-certificate-manager/src/CertificateStore.ts +++ b/libraries/debug-certificate-manager/src/CertificateStore.ts @@ -23,7 +23,7 @@ export class CertificateStore { const unresolvedUserFolder: string = homedir(); this._userProfilePath = path.resolve(unresolvedUserFolder); if (!FileSystem.exists(this._userProfilePath)) { - throw new Error('Unable to determine the current user\'s home directory'); + throw new Error("Unable to determine the current user's home directory"); } this._serveDataPath = path.join(this._userProfilePath, '.rushstack'); diff --git a/libraries/debug-certificate-manager/src/index.ts b/libraries/debug-certificate-manager/src/index.ts index 0d695fd51ef..dfe85732fa9 100644 --- a/libraries/debug-certificate-manager/src/index.ts +++ b/libraries/debug-certificate-manager/src/index.ts @@ -16,8 +16,5 @@ * @packageDocumentation */ -export { - ICertificate, - CertificateManager -} from './CertificateManager'; -export { CertificateStore } from './CertificateStore'; \ No newline at end of file +export { ICertificate, CertificateManager } from './CertificateManager'; +export { CertificateStore } from './CertificateStore'; diff --git a/libraries/debug-certificate-manager/src/sudoSync.ts b/libraries/debug-certificate-manager/src/sudoSync.ts index 68c13ce444b..e93ada44514 100644 --- a/libraries/debug-certificate-manager/src/sudoSync.ts +++ b/libraries/debug-certificate-manager/src/sudoSync.ts @@ -14,13 +14,10 @@ export interface ISudoSyncResult { } export function runSudoSync(params: string[]): ISudoSyncResult { - const sudoResult: child_process.ChildProcess = sudo( - params, - { - cachePassword: false, - prompt: 'Enter your password: ' - } - ); + const sudoResult: child_process.ChildProcess = sudo(params, { + cachePassword: false, + prompt: 'Enter your password: ', + }); const stderr: string[] = []; sudoResult.stderr.on('data', (data: Buffer) => { @@ -45,4 +42,4 @@ export function runSudoSync(params: string[]): ISudoSyncResult { } return { code, stdout, stderr }; -} \ No newline at end of file +} diff --git a/libraries/debug-certificate-manager/src/test/index.test.ts b/libraries/debug-certificate-manager/src/test/index.test.ts index 8b88f37ddbe..de97063f68b 100644 --- a/libraries/debug-certificate-manager/src/test/index.test.ts +++ b/libraries/debug-certificate-manager/src/test/index.test.ts @@ -11,7 +11,7 @@ test('Verify CertificateStore store is created.', () => { }); test('Verify CertificateManger provides ensure and untrust methods', () => { - const certificateManger: CertificateManager = new CertificateManager; + const certificateManger: CertificateManager = new CertificateManager(); expect(certificateManger).toHaveProperty('ensureCertificate'); expect(certificateManger).toHaveProperty('untrustCertificate'); -}); \ No newline at end of file +}); diff --git a/libraries/debug-certificate-manager/tsconfig.json b/libraries/debug-certificate-manager/tsconfig.json index 824a88b71e5..46bc07fdda9 100644 --- a/libraries/debug-certificate-manager/tsconfig.json +++ b/libraries/debug-certificate-manager/tsconfig.json @@ -2,9 +2,6 @@ "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "jest", - "node" - ] + "types": ["jest", "node"] } } diff --git a/libraries/load-themed-styles/.eslintrc.js b/libraries/load-themed-styles/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/libraries/load-themed-styles/.eslintrc.js +++ b/libraries/load-themed-styles/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/libraries/load-themed-styles/config/jest.json b/libraries/load-themed-styles/config/jest.json index b4a7ec97a56..902b00ea176 100644 --- a/libraries/load-themed-styles/config/jest.json +++ b/libraries/load-themed-styles/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": true -} \ No newline at end of file +} diff --git a/libraries/load-themed-styles/gulpfile.js b/libraries/load-themed-styles/gulpfile.js index efaca7428df..ff83fe8e6ea 100644 --- a/libraries/load-themed-styles/gulpfile.js +++ b/libraries/load-themed-styles/gulpfile.js @@ -9,34 +9,21 @@ const tscAmdTask = new build.TscCmdTask(); tscAmdTask.name = 'tsc-amd'; tscAmdTask.cleanMatch = [path.join(__dirname, 'lib-amd')]; tscAmdTask.setConfig({ - customArgs: [ - '--outDir', './lib-amd', - '--module', 'amd' - ] + customArgs: ['--outDir', './lib-amd', '--module', 'amd'], }); const tscEsnextTask = new build.TscCmdTask(); tscEsnextTask.name = 'tsc-es6'; tscEsnextTask.cleanMatch = [path.join(__dirname, 'lib-es6')]; tscEsnextTask.setConfig({ - customArgs: [ - '--outDir', './lib-es6', - '--module', 'esnext' - ] + customArgs: ['--outDir', './lib-es6', '--module', 'esnext'], }); -build.defaultTasks = build.task( - 'default', - build.parallel( - build.defaultTasks, - tscAmdTask, - tscEsnextTask - ) -); +build.defaultTasks = build.task('default', build.parallel(build.defaultTasks, tscAmdTask, tscEsnextTask)); build.setConfig({ libAMDFolder: 'lib-amd', - libES6Folder: 'lib-es6' + libES6Folder: 'lib-es6', }); build.initialize(require('gulp')); diff --git a/libraries/load-themed-styles/src/index.ts b/libraries/load-themed-styles/src/index.ts index ef348edc102..00ff5d097e6 100644 --- a/libraries/load-themed-styles/src/index.ts +++ b/libraries/load-themed-styles/src/index.ts @@ -52,8 +52,8 @@ interface IRunState { interface IThemeState { theme: ITheme | undefined; lastStyleElement: IExtendedHtmlStyleElement; - registeredStyles: IStyleRecord[]; // records of already registered non-themable styles - registeredThemableStyles: IStyleRecord[]; // records of already registered themable styles + registeredStyles: IStyleRecord[]; // records of already registered non-themable styles + registeredThemableStyles: IStyleRecord[]; // records of already registered themable styles loadStyles: ((processedStyles: string, rawStyles?: string | ThemableArray) => void) | undefined; perf: IMeasurement; runState: IRunState; @@ -85,7 +85,7 @@ interface IThemableArrayResolveResult { */ export const enum Mode { sync, - async + async, } /** @@ -98,12 +98,12 @@ export const enum ClearStyleOptions { /** only non-themable styles will be cleared */ onlyNonThemable = 2, /** both themable and non-themable styles will be cleared */ - all = 3 + all = 3, } // Store the theming state in __themeState__ global scope for reuse in the case of duplicate // load-themed-styles hosted on the page. -const _root: any = (typeof window === 'undefined') ? global : window; // eslint-disable-line @typescript-eslint/no-explicit-any +const _root: any = typeof window === 'undefined' ? global : window; // eslint-disable-line @typescript-eslint/no-explicit-any // Nonce string to inject into script tag if one provided. This is used in CSP (Content Security Policy). const _styleNonce: string = _root && _root.CSPSettings && _root.CSPSettings.nonce; @@ -115,8 +115,8 @@ const _themeState: IThemeState = initializeThemeState(); */ const _themeTokenRegex: RegExp = /[\'\"]\[theme:\s*(\w+)\s*(?:\,\s*default:\s*([\\"\']?[\.\,\(\)\#\-\s\w]*[\.\,\(\)\#\-\w][\"\']?))?\s*\][\'\"]/g; -const now: () => number = - () => (typeof performance !== 'undefined' && !!performance.now) ? performance.now() : Date.now(); +const now: () => number = () => + typeof performance !== 'undefined' && !!performance.now ? performance.now() : Date.now(); function measure(func: () => void): void { const start: number = now(); @@ -132,27 +132,27 @@ function initializeThemeState(): IThemeState { let state: IThemeState = _root.__themeState__ || { theme: undefined, lastStyleElement: undefined, - registeredStyles: [] + registeredStyles: [], }; if (!state.runState) { state = { - ...(state), + ...state, perf: { count: 0, - duration: 0 + duration: 0, }, runState: { flushTimer: 0, mode: Mode.sync, - buffer: [] - } + buffer: [], + }, }; } if (!state.registeredThemableStyles) { state = { - ...(state), - registeredThemableStyles: [] + ...state, + registeredThemableStyles: [], }; } _root.__themeState__ = state; @@ -168,11 +168,7 @@ function initializeThemeState(): IThemeState { export function loadStyles(styles: string | ThemableArray, loadAsync: boolean = false): void { measure(() => { const styleParts: ThemableArray = Array.isArray(styles) ? styles : splitStyles(styles); - const { - mode, - buffer, - flushTimer - } = _themeState.runState; + const { mode, buffer, flushTimer } = _themeState.runState; if (loadAsync || mode === Mode.async) { buffer.push(styleParts); if (!flushTimer) { @@ -237,7 +233,7 @@ function applyThemableStyles(stylesArray: ThemableArray, styleRecord?: IStyleRec if (_themeState.loadStyles) { _themeState.loadStyles(resolveThemableArray(stylesArray).styleString, stylesArray); } else { - registerStyles(stylesArray); + registerStyles(stylesArray); } } @@ -271,7 +267,7 @@ export function clearStyles(option: ClearStyleOptions = ClearStyleOptions.all): function clearStylesInternal(records: IStyleRecord[]): void { records.forEach((styleRecord: IStyleRecord) => { - const styleElement: HTMLStyleElement = styleRecord && styleRecord.styleElement as HTMLStyleElement; + const styleElement: HTMLStyleElement = styleRecord && (styleRecord.styleElement as HTMLStyleElement); if (styleElement && styleElement.parentElement) { styleElement.parentElement.removeChild(styleElement); } @@ -315,30 +311,39 @@ function resolveThemableArray(splitStyleArray: ThemableArray): IThemableArrayRes let themable: boolean = false; // Resolve the array of theming instructions to an array of strings. // Then join the array to produce the final CSS string. - const resolvedArray: (string | undefined)[] = (splitStyleArray || []).map((currentValue: IThemingInstruction) => { - const themeSlot: string | undefined = currentValue.theme; - if (themeSlot) { - themable = true; - // A theming annotation. Resolve it. - const themedValue: string | undefined = theme ? theme[themeSlot] : undefined; - const defaultValue: string = currentValue.defaultValue || 'inherit'; - - // Warn to console if we hit an unthemed value even when themes are provided, but only if "DEBUG" is true. - // Allow the themedValue to be undefined to explicitly request the default value. - if (theme && !themedValue && console && !(themeSlot in theme) && typeof DEBUG !== 'undefined' && DEBUG) { - console.warn(`Theming value not provided for "${themeSlot}". Falling back to "${defaultValue}".`); + const resolvedArray: (string | undefined)[] = (splitStyleArray || []).map( + (currentValue: IThemingInstruction) => { + const themeSlot: string | undefined = currentValue.theme; + if (themeSlot) { + themable = true; + // A theming annotation. Resolve it. + const themedValue: string | undefined = theme ? theme[themeSlot] : undefined; + const defaultValue: string = currentValue.defaultValue || 'inherit'; + + // Warn to console if we hit an unthemed value even when themes are provided, but only if "DEBUG" is true. + // Allow the themedValue to be undefined to explicitly request the default value. + if ( + theme && + !themedValue && + console && + !(themeSlot in theme) && + typeof DEBUG !== 'undefined' && + DEBUG + ) { + console.warn(`Theming value not provided for "${themeSlot}". Falling back to "${defaultValue}".`); + } + + return themedValue || defaultValue; + } else { + // A non-themable string. Preserve it. + return currentValue.rawString; } - - return themedValue || defaultValue; - } else { - // A non-themable string. Preserve it. - return currentValue.rawString; } - }); + ); return { styleString: resolvedArray.join(''), - themable: themable + themable: themable, }; } @@ -355,13 +360,13 @@ export function splitStyles(styles: string): ThemableArray { const matchIndex: number = tokenMatch.index; if (matchIndex > pos) { result.push({ - rawString: styles.substring(pos, matchIndex) + rawString: styles.substring(pos, matchIndex), }); } result.push({ theme: tokenMatch[1], - defaultValue: tokenMatch[2] // May be undefined + defaultValue: tokenMatch[2], // May be undefined }); // index of the first character after the current match @@ -370,7 +375,7 @@ export function splitStyles(styles: string): ThemableArray { // Push the rest of the string after the last match. result.push({ - rawString: styles.substring(pos) + rawString: styles.substring(pos), }); } @@ -389,10 +394,7 @@ function registerStyles(styleArray: ThemableArray): void { } const head: HTMLHeadElement = document.getElementsByTagName('head')[0]; const styleElement: HTMLStyleElement = document.createElement('style'); - const { - styleString, - themable - } = resolveThemableArray(styleArray); + const { styleString, themable } = resolveThemableArray(styleArray); styleElement.setAttribute('data-load-themed-styles', 'true'); if (_styleNonce) { @@ -402,16 +404,16 @@ function registerStyles(styleArray: ThemableArray): void { _themeState.perf.count++; head.appendChild(styleElement); - const ev: ICustomEvent<{ newStyle: HTMLStyleElement}> = document.createEvent('HTMLEvents'); + const ev: ICustomEvent<{ newStyle: HTMLStyleElement }> = document.createEvent('HTMLEvents'); ev.initEvent('styleinsert', true /* bubbleEvent */, false /* cancelable */); ev.args = { - newStyle: styleElement + newStyle: styleElement, }; document.dispatchEvent(ev); const record: IStyleRecord = { styleElement: styleElement, - themableStyle: styleArray + themableStyle: styleArray, }; if (themable) { diff --git a/libraries/load-themed-styles/src/test/index.test.ts b/libraries/load-themed-styles/src/test/index.test.ts index 8610f7c274d..508aba7ee46 100644 --- a/libraries/load-themed-styles/src/test/index.test.ts +++ b/libraries/load-themed-styles/src/test/index.test.ts @@ -4,7 +4,7 @@ import { splitStyles, loadStyles, configureLoadStyles, - IThemingInstruction + IThemingInstruction, } from './../index'; describe('detokenize', () => { @@ -24,7 +24,7 @@ describe('detokenize', () => { it('respects theme', () => { loadTheme({ - color: 'red' + color: 'red', }); try { @@ -45,23 +45,27 @@ describe('detokenize', () => { }); it('splits non-themable CSS', () => { - const cssString: string = '.sampleClass\n{\n color: #FF0000;\n}\n'; - const arr: IThemingInstruction[] = splitStyles(cssString); - expect(arr).toHaveLength(1); - expect(arr[0].rawString).toEqual(cssString); + const cssString: string = '.sampleClass\n{\n color: #FF0000;\n}\n'; + const arr: IThemingInstruction[] = splitStyles(cssString); + expect(arr).toHaveLength(1); + expect(arr[0].rawString).toEqual(cssString); }); it('splits themable CSS', () => { - const arr: IThemingInstruction[] = splitStyles('.firstClass { color: "[theme: firstColor ]";}\n' + - ' .secondClass { color: "[theme:secondColor, default: #AAA]";}\n .coach { color: #333; }'); - expect(arr).toHaveLength(5); - for (let i: number = 0; i < arr.length; i++) { - if (i % 2 === 0) { // even index should be a string component - expect(typeof arr[i].rawString).toEqual('string'); - } else { // odd index should be a theme instruction object - expect(typeof arr[i].theme).toEqual('string'); - } + const arr: IThemingInstruction[] = splitStyles( + '.firstClass { color: "[theme: firstColor ]";}\n' + + ' .secondClass { color: "[theme:secondColor, default: #AAA]";}\n .coach { color: #333; }' + ); + expect(arr).toHaveLength(5); + for (let i: number = 0; i < arr.length; i++) { + if (i % 2 === 0) { + // even index should be a string component + expect(typeof arr[i].rawString).toEqual('string'); + } else { + // odd index should be a theme instruction object + expect(typeof arr[i].theme).toEqual('string'); } + } }); it('passes the styles to loadStyles override callback', () => { diff --git a/libraries/load-themed-styles/tsconfig.json b/libraries/load-themed-styles/tsconfig.json index 3f04f8c7ee4..7b054559646 100644 --- a/libraries/load-themed-styles/tsconfig.json +++ b/libraries/load-themed-styles/tsconfig.json @@ -2,9 +2,6 @@ "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-web.json", "compilerOptions": { "module": "commonjs", - "types": [ - "webpack-env", - "jest" - ] + "types": ["webpack-env", "jest"] } } diff --git a/libraries/node-core-library/.eslintrc.js b/libraries/node-core-library/.eslintrc.js index 8195b92f6b2..0469b222dfe 100644 --- a/libraries/node-core-library/.eslintrc.js +++ b/libraries/node-core-library/.eslintrc.js @@ -1,10 +1,10 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, // TODO: Remove this once "tsdoc/syntax" is enabled by default - rules: { "tsdoc/syntax": "error" } + rules: { 'tsdoc/syntax': 'error' }, }; diff --git a/libraries/node-core-library/config/jest.json b/libraries/node-core-library/config/jest.json index b4a7ec97a56..902b00ea176 100644 --- a/libraries/node-core-library/config/jest.json +++ b/libraries/node-core-library/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": true -} \ No newline at end of file +} diff --git a/libraries/node-core-library/src/Constants.ts b/libraries/node-core-library/src/Constants.ts index a8a8535b774..cd9aac328f8 100644 --- a/libraries/node-core-library/src/Constants.ts +++ b/libraries/node-core-library/src/Constants.ts @@ -10,7 +10,7 @@ export const enum FileConstants { /** * "package.json" - the configuration file that defines an NPM package */ - PackageJson = 'package.json' + PackageJson = 'package.json', } /** @@ -27,5 +27,5 @@ export const enum FolderConstants { /** * "node_modules" - the folder where package managers install their files */ - NodeModules = 'node_modules' + NodeModules = 'node_modules', } diff --git a/libraries/node-core-library/src/Executable.ts b/libraries/node-core-library/src/Executable.ts index 226d4c01e33..80ed43eec19 100644 --- a/libraries/node-core-library/src/Executable.ts +++ b/libraries/node-core-library/src/Executable.ts @@ -12,9 +12,14 @@ import { PosixModeBits } from './PosixModeBits'; * Typings for one of the streams inside IExecutableSpawnSyncOptions.stdio. * @public */ -export type ExecutableStdioStreamMapping = 'pipe' | 'ignore' | 'inherit' - | NodeJS.WritableStream | NodeJS.ReadableStream - | number | undefined; +export type ExecutableStdioStreamMapping = + | 'pipe' + | 'ignore' + | 'inherit' + | NodeJS.WritableStream + | NodeJS.ReadableStream + | number + | undefined; /** * Typings for IExecutableSpawnSyncOptions.stdio. @@ -139,11 +144,13 @@ export class Executable { * wants binary output or a non-default text encoding, we will introduce a separate API function * with a name like "spawnWithBufferSync". */ - public static spawnSync(filename: string, args: string[], options?: IExecutableSpawnSyncOptions): - child_process.SpawnSyncReturns { - + public static spawnSync( + filename: string, + args: string[], + options?: IExecutableSpawnSyncOptions + ): child_process.SpawnSyncReturns { if (!options) { - options = { }; + options = {}; } const context: IExecutableContext = Executable._getExecutableContext(options); @@ -166,7 +173,7 @@ export class Executable { encoding: 'utf8', // NOTE: This is always false, because Rushell is recommended instead of relying on the OS shell. - shell: false + shell: false, } as child_process.SpawnSyncOptionsWithStringEncoding; // PROBLEM: Given an "args" array of strings that may contain special characters (e.g. spaces, @@ -185,8 +192,7 @@ export class Executable { // http://www.windowsinspired.com/understanding-the-command-line-string-and-arguments-received-by-a-windows-program/ // http://www.windowsinspired.com/how-a-windows-programs-splits-its-command-line-into-individual-arguments/ - const environment: NodeJS.ProcessEnv = options && options.environment - || process.env; + const environment: NodeJS.ProcessEnv = (options && options.environment) || process.env; const fileExtension: string = path.extname(resolvedPath); if (os.platform() === 'win32') { @@ -206,8 +212,10 @@ export class Executable { shellPath = Executable.tryResolve('cmd.exe'); } if (!shellPath) { - throw new Error(`Unable to execute "${path.basename(resolvedPath)}" ` - + `because CMD.exe was not found in the PATH`); + throw new Error( + `Unable to execute "${path.basename(resolvedPath)}" ` + + `because CMD.exe was not found in the PATH` + ); } const shellArgs: string[] = []; @@ -226,7 +234,9 @@ export class Executable { return child_process.spawnSync(shellPath, shellArgs, spawnOptions); } default: - throw new Error(`Cannot execute "${path.basename(resolvedPath)}" because the file type is not supported`); + throw new Error( + `Cannot execute "${path.basename(resolvedPath)}" because the file type is not supported` + ); } } @@ -250,16 +260,18 @@ export class Executable { * @returns the absolute path of the executable, or undefined if it was not found */ public static tryResolve(filename: string, options?: IExecutableResolveOptions): string | undefined { - return Executable._tryResolve(filename, options || { }, Executable._getExecutableContext(options)); + return Executable._tryResolve(filename, options || {}, Executable._getExecutableContext(options)); } - private static _tryResolve(filename: string, options: IExecutableResolveOptions, - context: IExecutableContext): string | undefined { - + private static _tryResolve( + filename: string, + options: IExecutableResolveOptions, + context: IExecutableContext + ): string | undefined { // NOTE: Since "filename" cannot contain command-line arguments, the "/" here // must be interpreted as a path delimiter - const hasPathSeparators: boolean = filename.indexOf('/') >= 0 - || (os.platform() === 'win32' && filename.indexOf('\\') >= 0); + const hasPathSeparators: boolean = + filename.indexOf('/') >= 0 || (os.platform() === 'win32' && filename.indexOf('\\') >= 0); // Are there any path separators? if (hasPathSeparators) { @@ -283,7 +295,10 @@ export class Executable { } } - private static _tryResolveFileExtension(resolvedPath: string, context: IExecutableContext): string | undefined { + private static _tryResolveFileExtension( + resolvedPath: string, + context: IExecutableContext + ): string | undefined { if (Executable._canExecute(resolvedPath, context)) { return resolvedPath; } @@ -321,7 +336,6 @@ export class Executable { if (path.extname(filePath) === '') { return false; } - } else { // For Unix, check whether any of the POSIX execute bits are set try { @@ -343,7 +357,6 @@ export class Executable { * based on the PATH environment variable. */ private static _getSearchFolders(context: IExecutableContext): string[] { - const pathList: string = context.environment.PATH || ''; const folders: string[] = []; @@ -383,7 +396,7 @@ export class Executable { private static _getExecutableContext(options: IExecutableResolveOptions | undefined): IExecutableContext { if (!options) { - options = { }; + options = {}; } const environment: NodeJS.ProcessEnv = options.environment || process.env; @@ -414,7 +427,7 @@ export class Executable { return { environment, currentWorkingDirectory, - windowsExecutableExtensions + windowsExecutableExtensions, }; } @@ -448,8 +461,10 @@ export class Executable { // We could work around that by adding double carets, but in general there // is no way to predict how many times the variable will get expanded. // Thus, there is no generally reliable way to pass these characters. - throw new Error(`The command line argument ${JSON.stringify(arg)} contains a` - + ` special character ${JSON.stringify(match[0])} that cannot be escaped for the Windows shell`); + throw new Error( + `The command line argument ${JSON.stringify(arg)} contains a` + + ` special character ${JSON.stringify(match[0])} that cannot be escaped for the Windows shell` + ); } } } diff --git a/libraries/node-core-library/src/FileSystem.ts b/libraries/node-core-library/src/FileSystem.ts index 5e82f0afac9..b10ab960f77 100644 --- a/libraries/node-core-library/src/FileSystem.ts +++ b/libraries/node-core-library/src/FileSystem.ts @@ -148,14 +148,17 @@ export const enum AlreadyExistsBehavior { /** * If the destination object exists, skip it and continue the operation. */ - Ignore = 'ignore' + Ignore = 'ignore', } /** * Callback function type for {@link IFileSystemCopyFilesAsyncOptions.filter} * @public */ -export type FileSystemCopyFilesAsyncFilter = (sourcePath: string, destinationPath: string) => Promise; +export type FileSystemCopyFilesAsyncFilter = ( + sourcePath: string, + destinationPath: string +) => Promise; /** * Callback function type for {@link IFileSystemCopyFilesOptions.filter} @@ -215,7 +218,7 @@ export interface IFileSystemCopyFilesOptions extends IFileSystemCopyFilesAsyncOp /** * The options for {@link FileSystem.deleteFile} * @public -*/ + */ export interface IFileSystemDeleteFileOptions { /** * If true, will throw an exception if the file did not exist before `deleteFile()` was called. @@ -261,38 +264,38 @@ export interface IFileSystemCreateLinkOptions { const MOVE_DEFAULT_OPTIONS: Partial = { overwrite: true, - ensureFolderExists: false + ensureFolderExists: false, }; const READ_FOLDER_DEFAULT_OPTIONS: Partial = { - absolutePaths: false + absolutePaths: false, }; const WRITE_FILE_DEFAULT_OPTIONS: Partial = { ensureFolderExists: false, convertLineEndings: undefined, - encoding: Encoding.Utf8 + encoding: Encoding.Utf8, }; const APPEND_TO_FILE_DEFAULT_OPTIONS: Partial = { - ...WRITE_FILE_DEFAULT_OPTIONS + ...WRITE_FILE_DEFAULT_OPTIONS, }; const READ_FILE_DEFAULT_OPTIONS: Partial = { encoding: Encoding.Utf8, - convertLineEndings: undefined + convertLineEndings: undefined, }; const COPY_FILE_DEFAULT_OPTIONS: Partial = { - alreadyExistsBehavior: AlreadyExistsBehavior.Overwrite + alreadyExistsBehavior: AlreadyExistsBehavior.Overwrite, }; const COPY_FILES_DEFAULT_OPTIONS: Partial = { - alreadyExistsBehavior: AlreadyExistsBehavior.Overwrite + alreadyExistsBehavior: AlreadyExistsBehavior.Overwrite, }; const DELETE_FILE_DEFAULT_OPTIONS: Partial = { - throwIfNotExists: false + throwIfNotExists: false, }; /** @@ -378,7 +381,6 @@ export class FileSystem { }); } - /** * Changes the permissions (i.e. file mode bits) for a filesystem object. * Behind the scenes it uses `fs.chmodSync()`. @@ -433,19 +435,19 @@ export class FileSystem { * @param modeBits - POSIX-style file mode bits specified using the {@link PosixModeBits} enum */ public static formatPosixModeBits(modeBits: PosixModeBits): string { - let result: string = '-'; // (later we may add support for additional states such as S_IFDIR or S_ISUID) + let result: string = '-'; // (later we may add support for additional states such as S_IFDIR or S_ISUID) - result += (modeBits & PosixModeBits.UserRead) ? 'r' : '-'; - result += (modeBits & PosixModeBits.UserWrite) ? 'w' : '-'; - result += (modeBits & PosixModeBits.UserExecute) ? 'x' : '-'; + result += modeBits & PosixModeBits.UserRead ? 'r' : '-'; + result += modeBits & PosixModeBits.UserWrite ? 'w' : '-'; + result += modeBits & PosixModeBits.UserExecute ? 'x' : '-'; - result += (modeBits & PosixModeBits.GroupRead) ? 'r' : '-'; - result += (modeBits & PosixModeBits.GroupWrite) ? 'w' : '-'; - result += (modeBits & PosixModeBits.GroupExecute) ? 'x' : '-'; + result += modeBits & PosixModeBits.GroupRead ? 'r' : '-'; + result += modeBits & PosixModeBits.GroupWrite ? 'w' : '-'; + result += modeBits & PosixModeBits.GroupExecute ? 'x' : '-'; - result += (modeBits & PosixModeBits.OthersRead) ? 'r' : '-'; - result += (modeBits & PosixModeBits.OthersWrite) ? 'w' : '-'; - result += (modeBits & PosixModeBits.OthersExecute) ? 'x' : '-'; + result += modeBits & PosixModeBits.OthersRead ? 'r' : '-'; + result += modeBits & PosixModeBits.OthersWrite ? 'w' : '-'; + result += modeBits & PosixModeBits.OthersExecute ? 'x' : '-'; return result; } @@ -458,7 +460,7 @@ export class FileSystem { FileSystem._wrapException(() => { options = { ...MOVE_DEFAULT_OPTIONS, - ...options + ...options, }; try { @@ -486,7 +488,7 @@ export class FileSystem { await FileSystem._wrapExceptionAsync(async () => { options = { ...MOVE_DEFAULT_OPTIONS, - ...options + ...options, }; try { @@ -543,13 +545,13 @@ export class FileSystem { return FileSystem._wrapException(() => { options = { ...READ_FOLDER_DEFAULT_OPTIONS, - ...options + ...options, }; // @todo: Update this to use Node 10's `withFileTypes: true` option when we drop support for Node 8 const fileNames: string[] = fsx.readdirSync(folderPath); if (options.absolutePaths) { - return fileNames.map(fileName => nodeJsPath.resolve(folderPath, fileName)); + return fileNames.map((fileName) => nodeJsPath.resolve(folderPath, fileName)); } else { return fileNames; } @@ -559,17 +561,20 @@ export class FileSystem { /** * An async version of {@link FileSystem.readFolder}. */ - public static async readFolderAsync(folderPath: string, options?: IFileSystemReadFolderOptions): Promise { + public static async readFolderAsync( + folderPath: string, + options?: IFileSystemReadFolderOptions + ): Promise { return await FileSystem._wrapExceptionAsync(async () => { options = { ...READ_FOLDER_DEFAULT_OPTIONS, - ...options + ...options, }; // @todo: Update this to use Node 10's `withFileTypes: true` option when we drop support for Node 8 const fileNames: string[] = await fsx.readdir(folderPath); if (options.absolutePaths) { - return fileNames.map(fileName => nodeJsPath.resolve(folderPath, fileName)); + return fileNames.map((fileName) => nodeJsPath.resolve(folderPath, fileName)); } else { return fileNames; } @@ -634,11 +639,15 @@ export class FileSystem { * @param contents - The text that should be written to the file. * @param options - Optional settings that can change the behavior. Type: `IWriteFileOptions` */ - public static writeFile(filePath: string, contents: string | Buffer, options?: IFileSystemWriteFileOptions): void { + public static writeFile( + filePath: string, + contents: string | Buffer, + options?: IFileSystemWriteFileOptions + ): void { FileSystem._wrapException(() => { options = { ...WRITE_FILE_DEFAULT_OPTIONS, - ...options + ...options, }; if (options.convertLineEndings) { @@ -666,11 +675,15 @@ export class FileSystem { /** * An async version of {@link FileSystem.writeFile}. */ - public static async writeFileAsync(filePath: string, contents: string | Buffer, options?: IFileSystemWriteFileOptions): Promise { + public static async writeFileAsync( + filePath: string, + contents: string | Buffer, + options?: IFileSystemWriteFileOptions + ): Promise { await FileSystem._wrapExceptionAsync(async () => { options = { ...WRITE_FILE_DEFAULT_OPTIONS, - ...options + ...options, }; if (options.convertLineEndings) { @@ -704,11 +717,15 @@ export class FileSystem { * @param contents - The text that should be written to the file. * @param options - Optional settings that can change the behavior. Type: `IWriteFileOptions` */ - public static appendToFile(filePath: string, contents: string | Buffer, options?: IFileSystemWriteFileOptions): void { + public static appendToFile( + filePath: string, + contents: string | Buffer, + options?: IFileSystemWriteFileOptions + ): void { FileSystem._wrapException(() => { options = { ...APPEND_TO_FILE_DEFAULT_OPTIONS, - ...options + ...options, }; if (options.convertLineEndings) { @@ -736,11 +753,15 @@ export class FileSystem { /** * An async version of {@link FileSystem.appendToFile}. */ - public static async appendToFileAsync(filePath: string, contents: string | Buffer, options?: IFileSystemWriteFileOptions): Promise { + public static async appendToFileAsync( + filePath: string, + contents: string | Buffer, + options?: IFileSystemWriteFileOptions + ): Promise { await FileSystem._wrapExceptionAsync(async () => { options = { ...APPEND_TO_FILE_DEFAULT_OPTIONS, - ...options + ...options, }; if (options.convertLineEndings) { @@ -775,7 +796,7 @@ export class FileSystem { return FileSystem._wrapException(() => { options = { ...READ_FILE_DEFAULT_OPTIONS, - ...options + ...options, }; let contents: string = FileSystem.readFileToBuffer(filePath).toString(options.encoding); @@ -794,7 +815,7 @@ export class FileSystem { return await FileSystem._wrapExceptionAsync(async () => { options = { ...READ_FILE_DEFAULT_OPTIONS, - ...options + ...options, }; let contents: string = (await FileSystem.readFileToBufferAsync(filePath)).toString(options.encoding); @@ -839,18 +860,19 @@ export class FileSystem { public static copyFile(options: IFileSystemCopyFileOptions): void { options = { ...COPY_FILE_DEFAULT_OPTIONS, - ...options + ...options, }; if (FileSystem.getStatistics(options.sourcePath).isDirectory()) { - throw new Error('The specified path refers to a folder; this operation expects a file object:\n' - + options.sourcePath); + throw new Error( + 'The specified path refers to a folder; this operation expects a file object:\n' + options.sourcePath + ); } FileSystem._wrapException(() => { fsx.copySync(options.sourcePath, options.destinationPath, { errorOnExist: options.alreadyExistsBehavior === AlreadyExistsBehavior.Error, - overwrite: options.alreadyExistsBehavior === AlreadyExistsBehavior.Overwrite + overwrite: options.alreadyExistsBehavior === AlreadyExistsBehavior.Overwrite, }); }); } @@ -861,18 +883,19 @@ export class FileSystem { public static async copyFileAsync(options: IFileSystemCopyFileOptions): Promise { options = { ...COPY_FILE_DEFAULT_OPTIONS, - ...options + ...options, }; if (FileSystem.getStatistics(options.sourcePath).isDirectory()) { - throw new Error('The specified path refers to a folder; this operation expects a file object:\n' - + options.sourcePath); + throw new Error( + 'The specified path refers to a folder; this operation expects a file object:\n' + options.sourcePath + ); } await FileSystem._wrapExceptionAsync(() => { return fsx.copy(options.sourcePath, options.destinationPath, { errorOnExist: options.alreadyExistsBehavior === AlreadyExistsBehavior.Error, - overwrite: options.alreadyExistsBehavior === AlreadyExistsBehavior.Overwrite + overwrite: options.alreadyExistsBehavior === AlreadyExistsBehavior.Overwrite, }); }); } @@ -890,7 +913,7 @@ export class FileSystem { public static copyFiles(options: IFileSystemCopyFilesOptions): void { options = { ...COPY_FILES_DEFAULT_OPTIONS, - ...options + ...options, }; FileSystem._wrapException(() => { @@ -899,7 +922,7 @@ export class FileSystem { errorOnExist: options.alreadyExistsBehavior === AlreadyExistsBehavior.Error, overwrite: options.alreadyExistsBehavior === AlreadyExistsBehavior.Overwrite, preserveTimestamps: !!options.preserveTimestamps, - filter: options.filter + filter: options.filter, }); }); } @@ -910,7 +933,7 @@ export class FileSystem { public static async copyFilesAsync(options: IFileSystemCopyFilesOptions): Promise { options = { ...COPY_FILES_DEFAULT_OPTIONS, - ...options + ...options, }; await FileSystem._wrapExceptionAsync(async () => { @@ -919,7 +942,7 @@ export class FileSystem { errorOnExist: options.alreadyExistsBehavior === AlreadyExistsBehavior.Error, overwrite: options.alreadyExistsBehavior === AlreadyExistsBehavior.Overwrite, preserveTimestamps: !!options.preserveTimestamps, - filter: options.filter + filter: options.filter, }); }); } @@ -934,7 +957,7 @@ export class FileSystem { FileSystem._wrapException(() => { options = { ...DELETE_FILE_DEFAULT_OPTIONS, - ...options + ...options, }; try { @@ -950,11 +973,14 @@ export class FileSystem { /** * An async version of {@link FileSystem.deleteFile}. */ - public static async deleteFileAsync(filePath: string, options?: IFileSystemDeleteFileOptions): Promise { + public static async deleteFileAsync( + filePath: string, + options?: IFileSystemDeleteFileOptions + ): Promise { await FileSystem._wrapExceptionAsync(async () => { options = { ...DELETE_FILE_DEFAULT_OPTIONS, - ...options + ...options, }; try { @@ -1130,14 +1156,14 @@ export class FileSystem { * Returns true if the error provided indicates the file does not exist. */ public static isFileDoesNotExistError(error: Error): boolean { - return FileSystem.isErrnoException(error) && (error.code === 'ENOENT'); + return FileSystem.isErrnoException(error) && error.code === 'ENOENT'; } /** * Returns true if the error provided indicates the folder does not exist. */ public static isFolderDoesNotExistError(error: Error): boolean { - return FileSystem.isErrnoException(error) && (error.code === 'ENOTDIR'); + return FileSystem.isErrnoException(error) && error.code === 'ENOTDIR'; } /** @@ -1173,9 +1199,11 @@ export class FileSystem { private static _updateErrorMessage(error: Error): void { if (FileSystem.isErrnoException(error)) { - if (FileSystem.isFileDoesNotExistError(error)) { // eslint-disable-line @typescript-eslint/no-use-before-define + if (FileSystem.isFileDoesNotExistError(error)) { + // eslint-disable-line @typescript-eslint/no-use-before-define error.message = `File does not exist: ${error.path}\n${error.message}`; - } else if (FileSystem.isFolderDoesNotExistError(error)) { // eslint-disable-line @typescript-eslint/no-use-before-define + } else if (FileSystem.isFolderDoesNotExistError(error)) { + // eslint-disable-line @typescript-eslint/no-use-before-define error.message = `Folder does not exist: ${error.path}\n${error.message}`; } } diff --git a/libraries/node-core-library/src/FileWriter.ts b/libraries/node-core-library/src/FileWriter.ts index cfbb1ef1715..a2767582581 100644 --- a/libraries/node-core-library/src/FileWriter.ts +++ b/libraries/node-core-library/src/FileWriter.ts @@ -62,11 +62,9 @@ export class FileWriter { flags = { append: false, exclusive: false, - ...flags + ...flags, }; - return [flags.append ? 'a' : 'w', - flags.exclusive ? 'x' : ''] - .join('') as NodeFileFlags; + return [flags.append ? 'a' : 'w', flags.exclusive ? 'x' : ''].join('') as NodeFileFlags; } /** @@ -93,4 +91,4 @@ export class FileWriter { fsx.closeSync(fd); } } -} \ No newline at end of file +} diff --git a/libraries/node-core-library/src/IPackageJson.ts b/libraries/node-core-library/src/IPackageJson.ts index 34021606b06..e84116168c0 100644 --- a/libraries/node-core-library/src/IPackageJson.ts +++ b/libraries/node-core-library/src/IPackageJson.ts @@ -38,16 +38,16 @@ export interface IPackageJsonScriptTable { * * However, NodeJS relaxes this requirement for its `require()` API. The * {@link https://nodejs.org/dist/latest-v10.x/docs/api/modules.html#modules_folders_as_modules - * | "Folders as Modules" section} from the NodeJS documentation gives an example of a package.json file - * that has only the `name` and `main` fields. NodeJS does not consider the `version` field during resolution, - * so it can be omitted. Some libraries do this. - * - * Use the `INodePackageJson` interface when loading such files. Use `IPackageJson` for package.json files - * that are installed from an NPM registry, or are otherwise known to have a `version` field. - * - * @public - */ - export interface INodePackageJson { + * | "Folders as Modules" section} from the NodeJS documentation gives an example of a package.json file + * that has only the `name` and `main` fields. NodeJS does not consider the `version` field during resolution, + * so it can be omitted. Some libraries do this. + * + * Use the `INodePackageJson` interface when loading such files. Use `IPackageJson` for package.json files + * that are installed from an NPM registry, or are otherwise known to have a `version` field. + * + * @public + */ +export interface INodePackageJson { /** * The name of the package. */ diff --git a/libraries/node-core-library/src/InternalError.ts b/libraries/node-core-library/src/InternalError.ts index c1bb063c4e8..c315f8f947f 100644 --- a/libraries/node-core-library/src/InternalError.ts +++ b/libraries/node-core-library/src/InternalError.ts @@ -51,8 +51,10 @@ export class InternalError extends Error { } private static _formatMessage(unformattedMessage: string): string { - return `Internal Error: ${unformattedMessage}\n\nYou have encountered a software defect. Please consider` - + ` reporting the issue to the maintainers of this application.`; + return ( + `Internal Error: ${unformattedMessage}\n\nYou have encountered a software defect. Please consider` + + ` reporting the issue to the maintainers of this application.` + ); } /** @override */ diff --git a/libraries/node-core-library/src/JsonFile.ts b/libraries/node-core-library/src/JsonFile.ts index d94ed9e2fcd..0b22ab8cfd6 100644 --- a/libraries/node-core-library/src/JsonFile.ts +++ b/libraries/node-core-library/src/JsonFile.ts @@ -4,15 +4,8 @@ import * as os from 'os'; import * as jju from 'jju'; -import { - JsonSchema, - IJsonSchemaErrorInfo, - IJsonSchemaValidateOptions -} from './JsonSchema'; -import { - Text, - NewlineKind -} from './Text'; +import { JsonSchema, IJsonSchemaErrorInfo, IJsonSchemaValidateOptions } from './JsonSchema'; +import { Text, NewlineKind } from './Text'; import { FileSystem } from './FileSystem'; /** @@ -198,7 +191,7 @@ export class JsonFile { options?: IJsonFileStringifyOptions ): string { if (!options) { - options = { }; + options = {}; } JsonFile.validateNoUndefinedMembers(newJsonObject); @@ -209,12 +202,12 @@ export class JsonFile { // NOTE: We don't use mode=json here because comments aren't allowed by strict JSON stringified = jju.update(previousJson, newJsonObject, { mode: 'cjson', - indent: 2 + indent: 2, }); } else if (options.prettyFormatting) { stringified = jju.stringify(newJsonObject, { mode: 'json', - indent: 2 + indent: 2, }); } else { stringified = JSON.stringify(newJsonObject, undefined, 2); @@ -239,7 +232,7 @@ export class JsonFile { */ public static save(jsonObject: JsonObject, jsonFilename: string, options?: IJsonFileSaveOptions): boolean { if (!options) { - options = { }; + options = {}; } // Do we need to read the previous file contents? @@ -272,7 +265,7 @@ export class JsonFile { } FileSystem.writeFile(jsonFilename, newBuffer.toString(DEFAULT_ENCODING), { - ensureFolderExists: options.ensureFolderExists + ensureFolderExists: options.ensureFolderExists, }); // TEST CODE: Used to verify that onlyIfChanged isn't broken by a hidden transformation during saving. @@ -291,9 +284,13 @@ export class JsonFile { /** * An async version of {@link JsonFile.loadAndValidateWithCallback}. */ - public static async saveAsync(jsonObject: JsonObject, jsonFilename: string, options?: IJsonFileSaveOptions): Promise { + public static async saveAsync( + jsonObject: JsonObject, + jsonFilename: string, + options?: IJsonFileSaveOptions + ): Promise { if (!options) { - options = { }; + options = {}; } // Do we need to read the previous file contents? @@ -326,7 +323,7 @@ export class JsonFile { } await FileSystem.writeFileAsync(jsonFilename, newBuffer.toString(DEFAULT_ENCODING), { - ensureFolderExists: options.ensureFolderExists + ensureFolderExists: options.ensureFolderExists, }); // TEST CODE: Used to verify that onlyIfChanged isn't broken by a hidden transformation during saving. @@ -392,7 +389,8 @@ export class JsonFile { // Convert this: A path: "C:\file" // To this: A path: \"C:\\file\" - const escapedKey: string = key.replace(/[\\]/g, '\\\\') // escape backslashes + const escapedKey: string = key + .replace(/[\\]/g, '\\\\') // escape backslashes .replace(/["]/g, '\\'); // escape quotes result += `["${escapedKey}"]`; } diff --git a/libraries/node-core-library/src/JsonSchema.ts b/libraries/node-core-library/src/JsonSchema.ts index 2ec7434daef..1533797190e 100644 --- a/libraries/node-core-library/src/JsonSchema.ts +++ b/libraries/node-core-library/src/JsonSchema.ts @@ -74,7 +74,7 @@ export class JsonSchema { private _validator: Validator | undefined = undefined; private _schemaObject: JsonObject | undefined = undefined; - private constructor() { } + private constructor() {} /** * Registers a JsonSchema that will be loaded from a file on disk. @@ -111,9 +111,12 @@ export class JsonSchema { return schema; } - private static _collectDependentSchemas(collectedSchemas: JsonSchema[], dependentSchemas: JsonSchema[], - seenObjects: Set, seenIds: Set): void { - + private static _collectDependentSchemas( + collectedSchemas: JsonSchema[], + dependentSchemas: JsonSchema[], + seenObjects: Set, + seenIds: Set + ): void { for (const dependentSchema of dependentSchemas) { // It's okay for the same schema to appear multiple times in the tree, but we only process it once if (seenObjects.has(dependentSchema)) { @@ -123,20 +126,27 @@ export class JsonSchema { const schemaId: string = dependentSchema._ensureLoaded(); if (schemaId === '') { - throw new Error(`This schema ${dependentSchema.shortName} cannot be referenced` - + ' because is missing the "id" field'); + throw new Error( + `This schema ${dependentSchema.shortName} cannot be referenced` + + ' because is missing the "id" field' + ); } if (seenIds.has(schemaId)) { - throw new Error(`This schema ${dependentSchema.shortName} has the same "id" as` - + ' another schema in this set'); + throw new Error( + `This schema ${dependentSchema.shortName} has the same "id" as` + ' another schema in this set' + ); } seenIds.add(schemaId); collectedSchemas.push(dependentSchema); - JsonSchema._collectDependentSchemas(collectedSchemas, dependentSchema._dependentSchemas, - seenObjects, seenIds); + JsonSchema._collectDependentSchemas( + collectedSchemas, + dependentSchema._dependentSchemas, + seenObjects, + seenIds + ); } } @@ -150,18 +160,19 @@ export class JsonSchema { /** * Used by _formatErrorDetails. */ - private static _formatErrorDetailsHelper(errorDetails: Validator.SchemaErrorDetail[], indent: string, - buffer: string): string { + private static _formatErrorDetailsHelper( + errorDetails: Validator.SchemaErrorDetail[], + indent: string, + buffer: string + ): string { for (const errorDetail of errorDetails) { - buffer += os.EOL + indent + `Error: ${errorDetail.path}`; if (errorDetail.description) { const MAX_LENGTH: number = 40; let truncatedDescription: string = errorDetail.description.trim(); if (truncatedDescription.length > MAX_LENGTH) { - truncatedDescription = truncatedDescription.substr(0, MAX_LENGTH - 3) - + '...'; + truncatedDescription = truncatedDescription.substr(0, MAX_LENGTH - 3) + '...'; } buffer += ` (${truncatedDescription})`; @@ -210,22 +221,15 @@ export class JsonSchema { const newValidator: Validator = new Validator({ breakOnFirstError: false, noTypeless: true, - noExtraKeywords: true + noExtraKeywords: true, }); const anythingSchema: JsonObject = { - 'type': [ - 'array', - 'boolean', - 'integer', - 'number', - 'object', - 'string' - ] + type: ['array', 'boolean', 'integer', 'number', 'object', 'string'], }; // eslint-disable-next-line @typescript-eslint/no-explicit-any - (newValidator as any).setRemoteReference('http://json-schema.org/draft-04/schema', anythingSchema); + (newValidator as any).setRemoteReference('http://json-schema.org/draft-04/schema', anythingSchema); const collectedSchemas: JsonSchema[] = []; const seenObjects: Set = new Set(); @@ -237,8 +241,11 @@ export class JsonSchema { // to make sure that circular references will fail to validate. for (const collectedSchema of collectedSchemas) { if (!newValidator.validateSchema(collectedSchema._schemaObject)) { - throw new Error(`Failed to validate schema "${collectedSchema.shortName}":` + os.EOL - + JsonSchema._formatErrorDetails(newValidator.getLastErrors())); + throw new Error( + `Failed to validate schema "${collectedSchema.shortName}":` + + os.EOL + + JsonSchema._formatErrorDetails(newValidator.getLastErrors()) + ); } } @@ -254,13 +261,16 @@ export class JsonSchema { * if not applicable * @param options - Other options that control the validation */ - public validateObject(jsonObject: JsonObject, filenameForErrors: string, options?: IJsonSchemaValidateOptions): void { + public validateObject( + jsonObject: JsonObject, + filenameForErrors: string, + options?: IJsonSchemaValidateOptions + ): void { this.validateObjectWithCallback(jsonObject, (errorInfo: IJsonSchemaErrorInfo) => { - const prefix: string = (options && options.customErrorHeader) ? options.customErrorHeader - : 'JSON validation failed:'; + const prefix: string = + options && options.customErrorHeader ? options.customErrorHeader : 'JSON validation failed:'; - throw new Error(prefix + os.EOL + - filenameForErrors + os.EOL + errorInfo.details); + throw new Error(prefix + os.EOL + filenameForErrors + os.EOL + errorInfo.details); }); } @@ -268,16 +278,17 @@ export class JsonSchema { * Validates the specified JSON object against this JSON schema. If the validation fails, * a callback is called for each validation error. */ - public validateObjectWithCallback(jsonObject: JsonObject, - errorCallback: (errorInfo: IJsonSchemaErrorInfo) => void): void { - + public validateObjectWithCallback( + jsonObject: JsonObject, + errorCallback: (errorInfo: IJsonSchemaErrorInfo) => void + ): void { this.ensureCompiled(); if (!this._validator!.validate(jsonObject, this._schemaObject)) { const errorDetails: string = JsonSchema._formatErrorDetails(this._validator!.getLastErrors()); const args: IJsonSchemaErrorInfo = { - details: errorDetails + details: errorDetails, }; errorCallback(args); } diff --git a/libraries/node-core-library/src/LegacyAdapters.ts b/libraries/node-core-library/src/LegacyAdapters.ts index 9a2b69145be..818c6705103 100644 --- a/libraries/node-core-library/src/LegacyAdapters.ts +++ b/libraries/node-core-library/src/LegacyAdapters.ts @@ -72,9 +72,9 @@ export class LegacyAdapters { fn(arg1, arg2, arg3, arg4, cb); } else if (arg1 !== undefined && arg2 !== undefined && arg3 !== undefined) { fn(arg1, arg2, arg3, cb); - } else if (arg1 !== undefined && arg2 !== undefined ) { + } else if (arg1 !== undefined && arg2 !== undefined) { fn(arg1, arg2, cb); - } else if (arg1 !== undefined ) { + } else if (arg1 !== undefined) { fn(arg1, cb); } else { fn(cb); @@ -88,7 +88,8 @@ export class LegacyAdapters { /** * Normalizes an object into an `Error` object. */ - public static scrubError(error: Error | string | any): Error { // eslint-disable-line @typescript-eslint/no-explicit-any + public static scrubError(error: Error | string | any): Error { + // eslint-disable-line @typescript-eslint/no-explicit-any if (error instanceof Error) { return error; } else if (typeof error === 'string') { diff --git a/libraries/node-core-library/src/LockFile.ts b/libraries/node-core-library/src/LockFile.ts index 3f6ded6734c..1d67e3632c9 100644 --- a/libraries/node-core-library/src/LockFile.ts +++ b/libraries/node-core-library/src/LockFile.ts @@ -22,7 +22,7 @@ const procStatStartTimePos: number = 22; * @param stat - The contents of a linux /proc/[pid]/stat file. * @returns The process start time in jiffies, or undefined if stat has an unexpected format. */ -export function getProcessStartTimeFromProcStat (stat: string): string | undefined { +export function getProcessStartTimeFromProcStat(stat: string): string | undefined { // Parse the value at position procStatStartTimePos. // We cannot just split stat on spaces, because value 2 may contain spaces. // For example, when running the following Shell commands: @@ -36,10 +36,11 @@ export function getProcessStartTimeFromProcStat (stat: string): string | undefin // trimRight to remove the trailing line terminator. let values: string[] = stat.trimRight().split(' '); let i: number = values.length - 1; - while (i >= 0 && + while ( + i >= 0 && // charAt returns an empty string if the index is out of bounds. values[i].charAt(values[i].length - 1) !== ')' - ) { + ) { i -= 1; } // i is the index of the last part of the second value (but i need not be 1). @@ -80,7 +81,7 @@ export function getProcessStartTime(pid: number): string | undefined { } const psResult: child_process.SpawnSyncReturns = child_process.spawnSync('ps', args, { - encoding: 'utf8' + encoding: 'utf8', }); const psStdout: string = psResult.stdout; @@ -90,7 +91,7 @@ export function getProcessStartTime(pid: number): string | undefined { // zero bytes are written to stdout. if (psResult.status !== 0 && !psStdout && process.platform === 'linux') { // Try to read /proc/[pid]/stat and get the value at position procStatStartTimePos. - let stat: undefined|string; + let stat: undefined | string; try { stat = FileSystem.readFile(`/proc/${pidString}/stat`); } catch (error) { @@ -102,10 +103,12 @@ export function getProcessStartTime(pid: number): string | undefined { return undefined; } if (stat !== undefined) { - const startTimeJiffies: string|undefined = getProcessStartTimeFromProcStat(stat); + const startTimeJiffies: string | undefined = getProcessStartTimeFromProcStat(stat); if (startTimeJiffies === undefined) { - throw new Error(`Could not retrieve the start time of process ${pidString} from the OS because the ` - + `contents of /proc/${pidString}/stat have an unexpected format`); + throw new Error( + `Could not retrieve the start time of process ${pidString} from the OS because the ` + + `contents of /proc/${pidString}/stat have an unexpected format` + ); } return startTimeJiffies; } @@ -155,10 +158,16 @@ export class LockFile { /** * Returns the path to the lockfile, should it be created successfully. */ - public static getLockFilePath(resourceDir: string, resourceName: string, pid: number = process.pid): string { + public static getLockFilePath( + resourceDir: string, + resourceName: string, + pid: number = process.pid + ): string { if (!resourceName.match(/^[a-zA-Z0-9][a-zA-Z0-9-.]+[a-zA-Z0-9]$/)) { - throw new Error(`The resource name "${resourceName}" is invalid.` - + ` It must be an alphanumberic string with only "-" or "." It must start with an alphanumeric character.`); + throw new Error( + `The resource name "${resourceName}" is invalid.` + + ` It must be an alphanumberic string with only "-" or "." It must start with an alphanumeric character.` + ); } if (process.platform === 'win32') { @@ -202,8 +211,10 @@ export class LockFile { if (lock) { return Promise.resolve(lock); } - if (maxWaitMs && (Date.now() > startTime + maxWaitMs)) { - return Promise.reject(new Error(`Exceeded maximum wait time to acquire lock for resource "${resourceName}"`)); + if (maxWaitMs && Date.now() > startTime + maxWaitMs) { + return Promise.reject( + new Error(`Exceeded maximum wait time to acquire lock for resource "${resourceName}"`) + ); } return LockFile._sleepForMs(interval).then(() => { @@ -262,10 +273,11 @@ export class LockFile { let match: RegExpMatchArray | null; let otherPid: string; for (const fileInFolder of files) { - if ((match = fileInFolder.match(lockFileRegExp)) - && (match[1] === resourceName) - && ((otherPid = match[2]) !== pid.toString())) { - + if ( + (match = fileInFolder.match(lockFileRegExp)) && + match[1] === resourceName && + (otherPid = match[2]) !== pid.toString() + ) { // we found at least one lockfile hanging around that isn't ours const fileInFolderPath: string = path.join(resourceDir, fileInFolder); dirtyWhenAcquired = true; @@ -295,8 +307,11 @@ export class LockFile { // will hold it // console.log(`Ignoring lock for pid ${otherPid} because its lockfile is newer than ours.`); continue; - } else if (otherBirthtimeMs - currentBirthTimeMs < 0 // it was created before us AND - && otherBirthtimeMs - currentBirthTimeMs > -1000) { // it was created less than a second before + } else if ( + otherBirthtimeMs - currentBirthTimeMs < 0 && // it was created before us AND + otherBirthtimeMs - currentBirthTimeMs > -1000 + ) { + // it was created less than a second before // conservatively be unable to keep the lock return undefined; @@ -420,4 +435,4 @@ export class LockFile { public get isReleased(): boolean { return this._fileWriter === undefined; } -} \ No newline at end of file +} diff --git a/libraries/node-core-library/src/PackageJsonLookup.ts b/libraries/node-core-library/src/PackageJsonLookup.ts index 2ea4a427a66..6d2a56ddef0 100644 --- a/libraries/node-core-library/src/PackageJsonLookup.ts +++ b/libraries/node-core-library/src/PackageJsonLookup.ts @@ -29,7 +29,9 @@ export interface IPackageJsonLookupParameters { * @public */ export class PackageJsonLookup { - private static _loadOwnPackageJsonLookup: PackageJsonLookup = new PackageJsonLookup({ loadExtraFields: true }); + private static _loadOwnPackageJsonLookup: PackageJsonLookup = new PackageJsonLookup({ + loadExtraFields: true, + }); private _loadExtraFields: boolean = false; @@ -74,22 +76,28 @@ export class PackageJsonLookup { * loading, an exception will be thrown instead. */ public static loadOwnPackageJson(dirnameOfCaller: string): IPackageJson { - const packageJson: IPackageJson | undefined = PackageJsonLookup._loadOwnPackageJsonLookup - .tryLoadPackageJsonFor(dirnameOfCaller); + const packageJson: + | IPackageJson + | undefined = PackageJsonLookup._loadOwnPackageJsonLookup.tryLoadPackageJsonFor(dirnameOfCaller); if (packageJson === undefined) { - throw new Error(`PackageJsonLookup.loadOwnPackageJson() failed to find the caller's package.json.` - + ` The __dirname was: ${dirnameOfCaller}`); + throw new Error( + `PackageJsonLookup.loadOwnPackageJson() failed to find the caller's package.json.` + + ` The __dirname was: ${dirnameOfCaller}` + ); } if (packageJson.version !== undefined) { return packageJson as IPackageJson; } - const errorPath: string = PackageJsonLookup._loadOwnPackageJsonLookup.tryGetPackageJsonFilePathFor(dirnameOfCaller) - || 'package.json'; - throw new Error(`PackageJsonLookup.loadOwnPackageJson() failed because the "version" field is missing in` - + ` ${errorPath}`); + const errorPath: string = + PackageJsonLookup._loadOwnPackageJsonLookup.tryGetPackageJsonFilePathFor(dirnameOfCaller) || + 'package.json'; + throw new Error( + `PackageJsonLookup.loadOwnPackageJson() failed because the "version" field is missing in` + + ` ${errorPath}` + ); } /** @@ -202,8 +210,7 @@ export class PackageJsonLookup { const packageJson: INodePackageJson = this.loadNodePackageJson(jsonFilename); if (!packageJson.version) { - throw new Error(`Error reading "${jsonFilename}":\n ` - + 'The required field "version" was not found'); + throw new Error(`Error reading "${jsonFilename}":\n ` + 'The required field "version" was not found'); } return packageJson as IPackageJson; @@ -230,14 +237,13 @@ export class PackageJsonLookup { // Make sure this is really a package.json file. CommonJS has fairly strict requirements, // but NPM only requires "name" and "version" if (!loadedPackageJson.name) { - throw new Error(`Error reading "${jsonFilename}":\n ` - + 'The required field "name" was not found'); + throw new Error(`Error reading "${jsonFilename}":\n ` + 'The required field "name" was not found'); } if (this._loadExtraFields) { packageJson = loadedPackageJson; } else { - packageJson = { } as IPackageJson; + packageJson = {} as IPackageJson; // Unless "loadExtraFields" was requested, copy over the essential fields only packageJson.bin = loadedPackageJson.bin; @@ -284,7 +290,7 @@ export class PackageJsonLookup { // We reached the root directory without finding a package.json file, // so cache the negative result this._packageFolderCache.set(resolvedFileOrFolderPath, undefined); - return undefined; // no match + return undefined; // no match } // Recurse upwards, caching every step along the way diff --git a/libraries/node-core-library/src/PackageName.ts b/libraries/node-core-library/src/PackageName.ts index bb614019d3a..1f2d99cf786 100644 --- a/libraries/node-core-library/src/PackageName.ts +++ b/libraries/node-core-library/src/PackageName.ts @@ -78,7 +78,7 @@ export class PackageNameParser { private readonly _options: IPackageNameParserOptions; - public constructor(options: IPackageNameParserOptions = { }) { + public constructor(options: IPackageNameParserOptions = {}) { this._options = { ...options }; } @@ -95,7 +95,7 @@ export class PackageNameParser { const result: IParsedPackageNameOrError = { scope: '', unscopedName: '', - error: '' + error: '', }; let input: string = packageName; @@ -147,8 +147,8 @@ export class PackageNameParser { } // Convert "@scope/unscoped-name" --> "scopeunscoped-name" - const nameWithoutScopeSymbols: string = (result.scope ? result.scope.slice(1, -1) : '') - + result.unscopedName; + const nameWithoutScopeSymbols: string = + (result.scope ? result.scope.slice(1, -1) : '') + result.unscopedName; if (!this._options.allowUpperCase) { // "New packages must not have uppercase letters in the name." @@ -164,7 +164,8 @@ export class PackageNameParser { // "The name ends up being part of a URL, an argument on the command line, and a folder name. // Therefore, the name can't contain any non-URL-safe characters" const match: RegExpMatchArray | null = nameWithoutScopeSymbols.match( - PackageNameParser._invalidNameCharactersRegExp); + PackageNameParser._invalidNameCharactersRegExp + ); if (match) { result.error = `The package name "${packageName}" contains an invalid character: "${match[0]}"`; return result; @@ -276,7 +277,7 @@ export class PackageName { /** {@inheritDoc PackageNameParser.parse} */ public static parse(packageName: string): IParsedPackageName { - return this._parser.parse(packageName); + return this._parser.parse(packageName); } /** {@inheritDoc PackageNameParser.getScope} */ diff --git a/libraries/node-core-library/src/PosixModeBits.ts b/libraries/node-core-library/src/PosixModeBits.ts index cd4129674da..d4a38e6ae23 100644 --- a/libraries/node-core-library/src/PosixModeBits.ts +++ b/libraries/node-core-library/src/PosixModeBits.ts @@ -90,5 +90,5 @@ export const enum PosixModeBits { /** * An alias combining OthersExecute, GroupExecute, and UserExecute permission bits. */ - AllExecute = OthersExecute | GroupExecute | UserExecute + AllExecute = OthersExecute | GroupExecute | UserExecute, } diff --git a/libraries/node-core-library/src/ProtectableMapView.ts b/libraries/node-core-library/src/ProtectableMapView.ts index b4f13e0ae1f..f7a0babc1da 100644 --- a/libraries/node-core-library/src/ProtectableMapView.ts +++ b/libraries/node-core-library/src/ProtectableMapView.ts @@ -21,21 +21,24 @@ export class ProtectableMapView extends Map { this._parameters = parameters; } - public clear(): void { // override + public clear(): void { + // override if (this._parameters.onClear) { this._parameters.onClear(this._owner); } super.clear(); } - public delete(key: K): boolean { // override + public delete(key: K): boolean { + // override if (this._parameters.onDelete) { this._parameters.onDelete(this._owner, key); } return super.delete(key); } - public set(key: K, value: V): this { // override + public set(key: K, value: V): this { + // override let modifiedValue: V = value; if (this._parameters.onSet) { modifiedValue = this._parameters.onSet(this._owner, key, modifiedValue); diff --git a/libraries/node-core-library/src/Sort.ts b/libraries/node-core-library/src/Sort.ts index 7212a9fc3eb..878a9b7e1ee 100644 --- a/libraries/node-core-library/src/Sort.ts +++ b/libraries/node-core-library/src/Sort.ts @@ -45,10 +45,12 @@ export class Sort { } // Null is smaller than anything except undefined - if (x === null) { // eslint-disable-line @rushstack/no-null + if (x === null) { + // eslint-disable-line @rushstack/no-null return -1; } - if (y === null) { // eslint-disable-line @rushstack/no-null + if (y === null) { + // eslint-disable-line @rushstack/no-null return 1; } @@ -76,8 +78,11 @@ export class Sort { * ``` */ // eslint-disable-next-line @typescript-eslint/no-explicit-any - public static sortBy(array: T[], keySelector: (element: T) => any, comparer: (x: any, y: any) => number - = Sort.compareByValue): void { + public static sortBy( + array: T[], + keySelector: (element: T) => any, + comparer: (x: any, y: any) => number = Sort.compareByValue + ): void { LegacyAdapters.sortStable(array, (x, y) => comparer(keySelector(x), keySelector(y))); } @@ -107,9 +112,11 @@ export class Sort { * ``` */ // eslint-disable-next-line @typescript-eslint/no-explicit-any - public static isSortedBy(array: T[], keySelector: (element: T) => any, comparer: (x: any, y: any) => number - = Sort.compareByValue): boolean { - + public static isSortedBy( + array: T[], + keySelector: (element: T) => any, + comparer: (x: any, y: any) => number = Sort.compareByValue + ): boolean { let previousKey: T | undefined = undefined; for (const element of array) { const key: T = keySelector(element); @@ -137,15 +144,18 @@ export class Sort { * ``` */ // eslint-disable-next-line @typescript-eslint/no-explicit-any - public static sortMapKeys(map: Map, keyComparer: (x: K, y: K) => number = Sort.compareByValue): void { + public static sortMapKeys( + map: Map, + keyComparer: (x: K, y: K) => number = Sort.compareByValue + ): void { const pairs: [K, V][] = Array.from(map.entries()); // Sorting a map is expensive, so first check whether it's already sorted. - if (Sort.isSortedBy(pairs, x => x[0], keyComparer)) { + if (Sort.isSortedBy(pairs, (x) => x[0], keyComparer)) { return; } - Sort.sortBy(pairs, x => x[0], keyComparer); + Sort.sortBy(pairs, (x) => x[0], keyComparer); map.clear(); for (const pair of pairs) { map.set(pair[0], pair[1]); @@ -168,9 +178,11 @@ export class Sort { * ``` */ // eslint-disable-next-line @typescript-eslint/no-explicit-any - public static sortSetBy(set: Set, keySelector: (element: T) => any, - keyComparer: (x: T, y: T) => number = Sort.compareByValue): void { - + public static sortSetBy( + set: Set, + keySelector: (element: T) => any, + keyComparer: (x: T, y: T) => number = Sort.compareByValue + ): void { const array: T[] = Array.from(set); // Sorting a set is expensive, so first check whether it's already sorted. diff --git a/libraries/node-core-library/src/Terminal/Colors.ts b/libraries/node-core-library/src/Terminal/Colors.ts index efcb815875b..b42a8264a2c 100644 --- a/libraries/node-core-library/src/Terminal/Colors.ts +++ b/libraries/node-core-library/src/Terminal/Colors.ts @@ -13,7 +13,7 @@ export interface IColorableSequence { } export const eolSequence: IColorableSequence = { - isEol: true + isEol: true, } as IColorableSequence; /** @@ -29,7 +29,7 @@ export enum ColorValue { Magenta, Cyan, White, - Gray + Gray, } /** @@ -42,7 +42,7 @@ export enum TextAttribute { Underline, Blink, InvertColor, - Hidden + Hidden, } /** @@ -58,126 +58,126 @@ export class Colors { public static black(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - foregroundColor: ColorValue.Black + foregroundColor: ColorValue.Black, }; } public static red(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - foregroundColor: ColorValue.Red + foregroundColor: ColorValue.Red, }; } public static green(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - foregroundColor: ColorValue.Green + foregroundColor: ColorValue.Green, }; } public static yellow(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - foregroundColor: ColorValue.Yellow + foregroundColor: ColorValue.Yellow, }; } public static blue(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - foregroundColor: ColorValue.Blue + foregroundColor: ColorValue.Blue, }; } public static magenta(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - foregroundColor: ColorValue.Magenta + foregroundColor: ColorValue.Magenta, }; } public static cyan(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - foregroundColor: ColorValue.Cyan + foregroundColor: ColorValue.Cyan, }; } public static white(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - foregroundColor: ColorValue.White + foregroundColor: ColorValue.White, }; } public static gray(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - foregroundColor: ColorValue.Gray + foregroundColor: ColorValue.Gray, }; } public static blackBackground(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - backgroundColor: ColorValue.Black + backgroundColor: ColorValue.Black, }; } public static redBackground(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - backgroundColor: ColorValue.Red + backgroundColor: ColorValue.Red, }; } public static greenBackground(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - backgroundColor: ColorValue.Green + backgroundColor: ColorValue.Green, }; } public static yellowBackground(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - backgroundColor: ColorValue.Yellow + backgroundColor: ColorValue.Yellow, }; } public static blueBackground(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - backgroundColor: ColorValue.Blue + backgroundColor: ColorValue.Blue, }; } public static magentaBackground(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - backgroundColor: ColorValue.Magenta + backgroundColor: ColorValue.Magenta, }; } public static cyanBackground(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - backgroundColor: ColorValue.Cyan + backgroundColor: ColorValue.Cyan, }; } public static whiteBackground(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - backgroundColor: ColorValue.White + backgroundColor: ColorValue.White, }; } public static grayBackground(text: string | IColorableSequence): IColorableSequence { return { ...Colors._normalizeStringOrColorableSequence(text), - backgroundColor: ColorValue.Gray + backgroundColor: ColorValue.Gray, }; } @@ -214,14 +214,17 @@ export class Colors { public static _normalizeStringOrColorableSequence(value: string | IColorableSequence): IColorableSequence { if (typeof value === 'string') { return { - text: value + text: value, }; } else { return value; } } - private static _applyTextAttribute(text: string | IColorableSequence, attribute: TextAttribute): IColorableSequence { + private static _applyTextAttribute( + text: string | IColorableSequence, + attribute: TextAttribute + ): IColorableSequence { const sequence: IColorableSequence = Colors._normalizeStringOrColorableSequence(text); if (!sequence.textAttributes) { sequence.textAttributes = []; diff --git a/libraries/node-core-library/src/Terminal/ITerminalProvider.ts b/libraries/node-core-library/src/Terminal/ITerminalProvider.ts index 5d3add0ac27..d59ab9cec75 100644 --- a/libraries/node-core-library/src/Terminal/ITerminalProvider.ts +++ b/libraries/node-core-library/src/Terminal/ITerminalProvider.ts @@ -5,7 +5,7 @@ export enum TerminalProviderSeverity { log, warning, error, - verbose + verbose, } /** diff --git a/libraries/node-core-library/src/Terminal/Terminal.ts b/libraries/node-core-library/src/Terminal/Terminal.ts index 85f8260e223..43bb98a11f9 100644 --- a/libraries/node-core-library/src/Terminal/Terminal.ts +++ b/libraries/node-core-library/src/Terminal/Terminal.ts @@ -1,17 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - ITerminalProvider, - TerminalProviderSeverity -} from './ITerminalProvider'; -import { - IColorableSequence, - ColorValue, - Colors, - eolSequence, - TextAttribute -} from './Colors'; +import { ITerminalProvider, TerminalProviderSeverity } from './ITerminalProvider'; +import { IColorableSequence, ColorValue, Colors, eolSequence, TextAttribute } from './Colors'; /** * This class facilitates writing to a console. @@ -67,7 +58,7 @@ export class Terminal { messageParts.map( (part): IColorableSequence => ({ ...Colors._normalizeStringOrColorableSequence(part), - foregroundColor: ColorValue.Yellow + foregroundColor: ColorValue.Yellow, }) ), TerminalProviderSeverity.warning @@ -86,10 +77,10 @@ export class Terminal { ...messageParts.map( (part): IColorableSequence => ({ ...Colors._normalizeStringOrColorableSequence(part), - foregroundColor: ColorValue.Yellow + foregroundColor: ColorValue.Yellow, }) ), - eolSequence + eolSequence, ], TerminalProviderSeverity.warning ); @@ -106,7 +97,7 @@ export class Terminal { messageParts.map( (part): IColorableSequence => ({ ...Colors._normalizeStringOrColorableSequence(part), - foregroundColor: ColorValue.Red + foregroundColor: ColorValue.Red, }) ), TerminalProviderSeverity.error @@ -125,10 +116,10 @@ export class Terminal { ...messageParts.map( (part): IColorableSequence => ({ ...Colors._normalizeStringOrColorableSequence(part), - foregroundColor: ColorValue.Red + foregroundColor: ColorValue.Red, }) ), - eolSequence + eolSequence, ], TerminalProviderSeverity.error ); @@ -186,7 +177,10 @@ export class Terminal { }); } - private _serializeFormattableTextSegments(segments: (string | IColorableSequence)[], withColor: boolean): string[] { + private _serializeFormattableTextSegments( + segments: (string | IColorableSequence)[], + withColor: boolean + ): string[] { const lines: string[] = []; let segmentsToJoin: string[] = []; let lastSegmentWasEol: boolean = false; @@ -197,7 +191,6 @@ export class Terminal { lines.push(segmentsToJoin.join('')); segmentsToJoin = []; } else { - if (withColor) { const startColorCodes: number[] = []; const endColorCodes: number[] = []; @@ -357,22 +350,14 @@ export class Terminal { for (let j: number = 0; j < startColorCodes.length; j++) { const code: number = startColorCodes[j]; - segmentsToJoin.push(...[ - '\u001b[', - code.toString(), - 'm' - ]); + segmentsToJoin.push(...['\u001b[', code.toString(), 'm']); } segmentsToJoin.push(segment.text); for (let j: number = endColorCodes.length - 1; j >= 0; j--) { const code: number = endColorCodes[j]; - segmentsToJoin.push(...[ - '\u001b[', - code.toString(), - 'm' - ]); + segmentsToJoin.push(...['\u001b[', code.toString(), 'm']); } } else { segmentsToJoin.push(segment.text); diff --git a/libraries/node-core-library/src/Terminal/test/Terminal.test.ts b/libraries/node-core-library/src/Terminal/test/Terminal.test.ts index b0bd0247dbd..0a8bf34a4b1 100644 --- a/libraries/node-core-library/src/Terminal/test/Terminal.test.ts +++ b/libraries/node-core-library/src/Terminal/test/Terminal.test.ts @@ -13,7 +13,7 @@ function verifyProvider(): void { log: provider.getOutput(), warning: provider.getWarningOutput(), error: provider.getErrorOutput(), - verbose: provider.getVerbose() + verbose: provider.getVerbose(), }).toMatchSnapshot(); } @@ -127,7 +127,12 @@ describe('01 color enabled', () => { }); test('05 writes a messages with colors interspersed with non-colored messages', () => { - terminal.writeWarningLine('message 1', Colors.green('message 2'), 'message 3', Colors.red('message 4')); + terminal.writeWarningLine( + 'message 1', + Colors.green('message 2'), + 'message 3', + Colors.red('message 4') + ); verifyProvider(); }); }); @@ -235,7 +240,12 @@ describe('01 color enabled', () => { }); test('05 writes a messages with colors interspersed with non-colored messages', () => { - terminal.writeVerboseLine('message 1', Colors.green('message 2'), 'message 3', Colors.red('message 4')); + terminal.writeVerboseLine( + 'message 1', + Colors.green('message 2'), + 'message 3', + Colors.red('message 4') + ); verifyProvider(); }); }); @@ -395,7 +405,12 @@ describe('02 color disabled', () => { }); test('05 writes a messages with colors interspersed with non-colored messages', () => { - terminal.writeWarningLine('message 1', Colors.green('message 2'), 'message 3', Colors.red('message 4')); + terminal.writeWarningLine( + 'message 1', + Colors.green('message 2'), + 'message 3', + Colors.red('message 4') + ); verifyProvider(); }); }); @@ -503,7 +518,12 @@ describe('02 color disabled', () => { }); test('05 writes a messages with colors interspersed with non-colored messages', () => { - terminal.writeVerboseLine('message 1', Colors.green('message 2'), 'message 3', Colors.red('message 4')); + terminal.writeVerboseLine( + 'message 1', + Colors.green('message 2'), + 'message 3', + Colors.red('message 4') + ); verifyProvider(); }); }); diff --git a/libraries/node-core-library/src/Terminal/test/createColorGrid.ts b/libraries/node-core-library/src/Terminal/test/createColorGrid.ts index bb1d01a5e47..c62a08656d4 100644 --- a/libraries/node-core-library/src/Terminal/test/createColorGrid.ts +++ b/libraries/node-core-library/src/Terminal/test/createColorGrid.ts @@ -5,10 +5,7 @@ * This file is a little program that prints all of the colors to the console */ -import { - Colors, - IColorableSequence -} from '../../index'; +import { Colors, IColorableSequence } from '../../index'; export function createColorGrid( attributeFunction?: (text: string | IColorableSequence) => IColorableSequence @@ -23,7 +20,7 @@ export function createColorGrid( Colors.yellow, Colors.green, Colors.cyan, - Colors.blue + Colors.blue, ]; const backgroundFunctions: ((text: string | IColorableSequence) => IColorableSequence)[] = [ @@ -36,7 +33,7 @@ export function createColorGrid( Colors.yellowBackground, Colors.greenBackground, Colors.cyanBackground, - Colors.blueBackground + Colors.blueBackground, ]; const lines: IColorableSequence[][] = []; diff --git a/libraries/node-core-library/src/Terminal/test/write-colors.ts b/libraries/node-core-library/src/Terminal/test/write-colors.ts index 72006c25b5e..74a6b86ae5a 100644 --- a/libraries/node-core-library/src/Terminal/test/write-colors.ts +++ b/libraries/node-core-library/src/Terminal/test/write-colors.ts @@ -7,10 +7,7 @@ * Run this program with `node write-colors.js` */ -import { - Terminal, - ConsoleTerminalProvider -} from '../../index'; +import { Terminal, ConsoleTerminalProvider } from '../../index'; import { createColorGrid } from './createColorGrid'; import { Colors, IColorableSequence } from '../Colors'; diff --git a/libraries/node-core-library/src/Text.ts b/libraries/node-core-library/src/Text.ts index a7099c52d3e..04492edd4b7 100644 --- a/libraries/node-core-library/src/Text.ts +++ b/libraries/node-core-library/src/Text.ts @@ -8,7 +8,7 @@ import * as os from 'os'; * @public */ export const enum Encoding { - Utf8 = 'utf8' + Utf8 = 'utf8', } /** @@ -32,7 +32,7 @@ export const enum NewlineKind { /** * Default newline type for this operating system (`os.EOL`). */ - OsDefault = 'os' + OsDefault = 'os', } /** @@ -79,7 +79,7 @@ export class Text { * Converts all newlines in the provided string to use the specified newline type. */ public static convertTo(input: string, newlineKind: NewlineKind): string { - const newline: string = newlineKind === NewlineKind.OsDefault ? os.EOL : newlineKind as string; + const newline: string = newlineKind === NewlineKind.OsDefault ? os.EOL : (newlineKind as string); return input.replace(Text._newLineRegEx, newline); } diff --git a/libraries/node-core-library/src/index.ts b/libraries/node-core-library/src/index.ts index be87db4d101..de0187275cb 100644 --- a/libraries/node-core-library/src/index.ts +++ b/libraries/node-core-library/src/index.ts @@ -7,64 +7,42 @@ * @packageDocumentation */ -export { - FileConstants, - FolderConstants -} from './Constants'; +export { FileConstants, FolderConstants } from './Constants'; export { ExecutableStdioStreamMapping, ExecutableStdioMapping, IExecutableResolveOptions, IExecutableSpawnSyncOptions, - Executable + Executable, } from './Executable'; export { INodePackageJson, IPackageJson, IPackageJsonDependencyTable, - IPackageJsonScriptTable + IPackageJsonScriptTable, } from './IPackageJson'; export { InternalError } from './InternalError'; -export { - JsonObject, - JsonFile, - IJsonFileSaveOptions, - IJsonFileStringifyOptions -} from './JsonFile'; +export { JsonObject, JsonFile, IJsonFileSaveOptions, IJsonFileStringifyOptions } from './JsonFile'; export { JsonSchema, IJsonSchemaErrorInfo, IJsonSchemaValidateOptions, - IJsonSchemaFromFileOptions + IJsonSchemaFromFileOptions, } from './JsonSchema'; -export { - LockFile -} from './LockFile'; -export { - MapExtensions -} from './MapExtensions'; +export { LockFile } from './LockFile'; +export { MapExtensions } from './MapExtensions'; export { PosixModeBits } from './PosixModeBits'; -export { - ProtectableMap, - IProtectableMapParameters -} from './ProtectableMap'; -export { - IPackageJsonLookupParameters, - PackageJsonLookup -} from './PackageJsonLookup'; +export { ProtectableMap, IProtectableMapParameters } from './ProtectableMap'; +export { IPackageJsonLookupParameters, PackageJsonLookup } from './PackageJsonLookup'; export { PackageName, PackageNameParser, IPackageNameParserOptions, IParsedPackageName, - IParsedPackageNameOrError + IParsedPackageNameOrError, } from './PackageName'; export { Path } from './Path'; -export { - Encoding, - Text, - NewlineKind -} from './Text'; +export { Encoding, Text, NewlineKind } from './Text'; export { Sort } from './Sort'; export { AlreadyExistsBehavior, @@ -83,30 +61,11 @@ export { FileSystemCopyFilesAsyncFilter, FileSystemCopyFilesFilter, } from './FileSystem'; -export { - FileWriter, - IFileWriterFlags -} from './FileWriter'; -export { - LegacyAdapters, - LegacyCallback -} from './LegacyAdapters'; +export { FileWriter, IFileWriterFlags } from './FileWriter'; +export { LegacyAdapters, LegacyCallback } from './LegacyAdapters'; export { StringBuilder, IStringBuilder } from './StringBuilder'; export { Terminal } from './Terminal/Terminal'; -export { - Colors, - IColorableSequence, - ColorValue, - TextAttribute -} from './Terminal/Colors'; -export { - ITerminalProvider, - TerminalProviderSeverity -} from './Terminal/ITerminalProvider'; -export { - ConsoleTerminalProvider, - IConsoleTerminalProviderOptions -} from './Terminal/ConsoleTerminalProvider'; -export { - StringBufferTerminalProvider -} from './Terminal/StringBufferTerminalProvider'; +export { Colors, IColorableSequence, ColorValue, TextAttribute } from './Terminal/Colors'; +export { ITerminalProvider, TerminalProviderSeverity } from './Terminal/ITerminalProvider'; +export { ConsoleTerminalProvider, IConsoleTerminalProviderOptions } from './Terminal/ConsoleTerminalProvider'; +export { StringBufferTerminalProvider } from './Terminal/StringBufferTerminalProvider'; diff --git a/libraries/node-core-library/src/test/Executable.test.ts b/libraries/node-core-library/src/test/Executable.test.ts index 5bb59c717a0..821b97439bf 100644 --- a/libraries/node-core-library/src/test/Executable.test.ts +++ b/libraries/node-core-library/src/test/Executable.test.ts @@ -24,12 +24,12 @@ if (os.platform() === 'win32') { path.join(executableFolder, 'skipped'), path.join(executableFolder, 'success'), path.join(executableFolder, 'fail'), - path.dirname(process.execPath) // the folder where node.exe can be found + path.dirname(process.execPath), // the folder where node.exe can be found ].join(path.delimiter), PATHEXT: '.COM;.EXE;.BAT;.CMD;.VBS', - TEST_VAR: '123' + TEST_VAR: '123', }; } else { environment = { @@ -41,17 +41,17 @@ if (os.platform() === 'win32') { // These are needed because our example script needs to find bash '/usr/local/bin', '/usr/bin', - '/bin' + '/bin', ].join(path.delimiter), - TEST_VAR: '123' + TEST_VAR: '123', }; } const options: IExecutableSpawnSyncOptions = { environment: environment, currentWorkingDirectory: executableFolder, - stdio: 'pipe' + stdio: 'pipe', }; beforeAll(() => { @@ -62,28 +62,35 @@ beforeAll(() => { // it completely impractical to store POSIX file permissions in a cross-platform Git repo. // So instead we set them before the test runs, and then revert them after the test completes. if (os.platform() !== 'win32') { - FileSystem.changePosixModeBits(path.join(executableFolder, 'success', 'npm-binary-wrapper'), - PosixModeBits.AllRead | PosixModeBits.AllWrite | PosixModeBits.AllExecute); - FileSystem.changePosixModeBits(path.join(executableFolder, 'success', 'bash-script.sh'), - PosixModeBits.AllRead | PosixModeBits.AllWrite | PosixModeBits.AllExecute); + FileSystem.changePosixModeBits( + path.join(executableFolder, 'success', 'npm-binary-wrapper'), + PosixModeBits.AllRead | PosixModeBits.AllWrite | PosixModeBits.AllExecute + ); + FileSystem.changePosixModeBits( + path.join(executableFolder, 'success', 'bash-script.sh'), + PosixModeBits.AllRead | PosixModeBits.AllWrite | PosixModeBits.AllExecute + ); } }); afterAll(() => { // Revert the permissions to the defaults if (os.platform() !== 'win32') { - FileSystem.changePosixModeBits(path.join(executableFolder, 'success', 'npm-binary-wrapper'), - PosixModeBits.AllRead | PosixModeBits.AllWrite); - FileSystem.changePosixModeBits(path.join(executableFolder, 'success', 'bash-script.sh'), - PosixModeBits.AllRead | PosixModeBits.AllWrite); + FileSystem.changePosixModeBits( + path.join(executableFolder, 'success', 'npm-binary-wrapper'), + PosixModeBits.AllRead | PosixModeBits.AllWrite + ); + FileSystem.changePosixModeBits( + path.join(executableFolder, 'success', 'bash-script.sh'), + PosixModeBits.AllRead | PosixModeBits.AllWrite + ); } }); test('Executable.tryResolve() pathless', () => { const resolved: string | undefined = Executable.tryResolve('npm-binary-wrapper', options); expect(resolved).toBeDefined(); - const resolvedRelative: string = Text.replaceAll(path.relative(executableFolder, resolved!), - '\\', '/'); + const resolvedRelative: string = Text.replaceAll(path.relative(executableFolder, resolved!), '\\', '/'); if (os.platform() === 'win32') { // On Windows, we should find npm-binary-wrapper.cmd instead of npm-binary-wrapper @@ -103,15 +110,21 @@ test('Executable.tryResolve() with path', () => { }); function executeNpmBinaryWrapper(args: string[]): string[] { - const result: child_process.SpawnSyncReturns - = Executable.spawnSync('npm-binary-wrapper', args, options); + const result: child_process.SpawnSyncReturns = Executable.spawnSync( + 'npm-binary-wrapper', + args, + options + ); expect(result.error).toBeUndefined(); expect(result.stderr).toBeDefined(); expect(result.stderr.toString()).toEqual(''); expect(result.stdout).toBeDefined(); - const outputLines: string[] = result.stdout.toString().split(/[\r\n]+/g).map(x => x.trim()); + const outputLines: string[] = result.stdout + .toString() + .split(/[\r\n]+/g) + .map((x) => x.trim()); let lineIndex: number = 0; if (os.platform() === 'win32') { @@ -120,17 +133,17 @@ function executeNpmBinaryWrapper(args: string[]): string[] { expect(outputLines[lineIndex++]).toEqual('Executing npm-binary-wrapper with args:'); } // console.log('npm-binary-wrapper.cmd ARGS: ' + outputLines[lineIndex]); - ++lineIndex; // skip npm-binary-wrapper's args + ++lineIndex; // skip npm-binary-wrapper's args expect(outputLines[lineIndex++]).toEqual('Executing javascript-file.js with args:'); const stringifiedArgv: string = outputLines[lineIndex++]; - expect(stringifiedArgv.substr(0, 2)).toEqual('[\"'); + expect(stringifiedArgv.substr(0, 2)).toEqual('["'); const argv: string[] = JSON.parse(stringifiedArgv); // Discard the first two array entries whose path is nondeterministic - argv.shift(); // the path to node.exe - argv.shift(); // the path to javascript-file.js + argv.shift(); // the path to node.exe + argv.shift(); // the path to javascript-file.js return argv; } @@ -151,8 +164,8 @@ test('Executable.spawnSync("npm-binary-wrapper") edge cases 2', () => { const args: string[] = [ // Characters that are impossible to escape for cmd.exe: // %^&|<> newline - '~!@#$*()_+`={}[]\:";\'?,./', - '~!@#$*()_+`={}[]\:";\'?,./' + '~!@#$*()_+`={}[]:";\'?,./', + '~!@#$*()_+`={}[]:";\'?,./', ]; expect(executeNpmBinaryWrapper(args)).toEqual(args); }); @@ -162,19 +175,25 @@ test('Executable.spawnSync("npm-binary-wrapper") edge cases 2', () => { const args: string[] = [ // Characters that are impossible to escape for cmd.exe: // %^&|<> newline - '~!@#$*()_+`={}[]\:";\'?,./', - '~!@#$*()_+`={}[]\:";\'?,./' + '~!@#$*()_+`={}[]:";\'?,./', + '~!@#$*()_+`={}[]:";\'?,./', ]; expect(executeNpmBinaryWrapper(args)).toEqual(args); }); test('Executable.spawnSync("npm-binary-wrapper") bad characters', () => { if (os.platform() === 'win32') { - expect(() => { executeNpmBinaryWrapper(['abc%123']); }) - .toThrowError('The command line argument "abc%123" contains a special character "%"' - + ' that cannot be escaped for the Windows shell'); - expect(() => { executeNpmBinaryWrapper(['abc<>123']); }) - .toThrowError('The command line argument "abc<>123" contains a special character "<"' - + ' that cannot be escaped for the Windows shell'); + expect(() => { + executeNpmBinaryWrapper(['abc%123']); + }).toThrowError( + 'The command line argument "abc%123" contains a special character "%"' + + ' that cannot be escaped for the Windows shell' + ); + expect(() => { + executeNpmBinaryWrapper(['abc<>123']); + }).toThrowError( + 'The command line argument "abc<>123" contains a special character "<"' + + ' that cannot be escaped for the Windows shell' + ); } }); diff --git a/libraries/node-core-library/src/test/JsonSchema.test.ts b/libraries/node-core-library/src/test/JsonSchema.test.ts index 08a56589e4b..987f176eac9 100644 --- a/libraries/node-core-library/src/test/JsonSchema.test.ts +++ b/libraries/node-core-library/src/test/JsonSchema.test.ts @@ -6,8 +6,7 @@ import { JsonFile, JsonObject } from '../JsonFile'; import { JsonSchema, IJsonSchemaErrorInfo } from '../JsonSchema'; function normalize(text: string): string { - return text.replace(/[\r\n ]+/g, ' ') - .trim(); + return text.replace(/[\r\n ]+/g, ' ').trim(); } describe('JsonSchema', () => { @@ -18,16 +17,10 @@ describe('JsonSchema', () => { test('loadAndValidate successfully validates a JSON file', () => { const jsonPath: string = path.resolve(path.join(__dirname, './test-data/test.json')); const jsonObject: JsonObject = JsonFile.loadAndValidate(jsonPath, schema); - expect(jsonObject).toMatchObject( - { - 'exampleString': 'This is a string', - 'exampleArray': [ - 'apple', - 'banana', - 'coconut' - ] - } - ); + expect(jsonObject).toMatchObject({ + exampleString: 'This is a string', + exampleArray: ['apple', 'banana', 'coconut'], + }); }); test('validateObjectWithCallback successfully reports a compound validation error', () => { diff --git a/libraries/node-core-library/src/test/LockFile.test.ts b/libraries/node-core-library/src/test/LockFile.test.ts index 1d482b7a72c..15146ce01f4 100644 --- a/libraries/node-core-library/src/test/LockFile.test.ts +++ b/libraries/node-core-library/src/test/LockFile.test.ts @@ -50,7 +50,7 @@ describe('LockFile', () => { }); describe('getProcessStartTimeFromProcStat', () => { - function createStatOutput (value2: string, n: number): string { + function createStatOutput(value2: string, n: number): string { let statOutput: string = `0 ${value2} S`; for (let i: number = 0; i < n; i++) { statOutput += ' 0'; @@ -60,34 +60,37 @@ describe('LockFile', () => { test('returns undefined if too few values are contained in /proc/[pid]/stat (1)', () => { const stat: string = createStatOutput('(bash)', 1); - const ret: string|undefined = getProcessStartTimeFromProcStat(stat); + const ret: string | undefined = getProcessStartTimeFromProcStat(stat); expect(ret).toBeUndefined(); }); test('returns undefined if too few values are contained in /proc/[pid]/stat (2)', () => { const stat: string = createStatOutput('(bash)', 0); - const ret: string|undefined = getProcessStartTimeFromProcStat(stat); + const ret: string | undefined = getProcessStartTimeFromProcStat(stat); expect(ret).toBeUndefined(); }); test('returns the correct start time if the second value in /proc/[pid]/stat contains spaces', () => { let stat: string = createStatOutput('(bash 2)', 18); const value22: string = '12345'; stat += ` ${value22}`; - const ret: string|undefined = getProcessStartTimeFromProcStat(stat); - expect(ret).toEqual(value22); - }); - test('returns the correct start time if there are 22 values in /proc/[pid]/stat, including a trailing line ' - + 'terminator', () => { - let stat: string = createStatOutput('(bash)', 18); - const value22: string = '12345'; - stat += ` ${value22}\n`; - const ret: string|undefined = getProcessStartTimeFromProcStat(stat); + const ret: string | undefined = getProcessStartTimeFromProcStat(stat); expect(ret).toEqual(value22); }); + test( + 'returns the correct start time if there are 22 values in /proc/[pid]/stat, including a trailing line ' + + 'terminator', + () => { + let stat: string = createStatOutput('(bash)', 18); + const value22: string = '12345'; + stat += ` ${value22}\n`; + const ret: string | undefined = getProcessStartTimeFromProcStat(stat); + expect(ret).toEqual(value22); + } + ); test('returns the correct start time if the second value in /proc/[pid]/stat does not contain spaces', () => { let stat: string = createStatOutput('(bash)', 18); const value22: string = '12345'; stat += ` ${value22}`; - const ret: string|undefined = getProcessStartTimeFromProcStat(stat); + const ret: string | undefined = getProcessStartTimeFromProcStat(stat); expect(ret).toEqual(value22); }); }); @@ -96,17 +99,13 @@ describe('LockFile', () => { describe('Linux and Mac', () => { describe('getLockFilePath()', () => { test('returns a resolved path containing the pid', () => { - expect( - path.join(process.cwd(), `test#${process.pid}.lock`) - ).toEqual( + expect(path.join(process.cwd(), `test#${process.pid}.lock`)).toEqual( LockFile.getLockFilePath('./', 'test') ); }); test('allows for overridden pid', () => { - expect( - path.join(process.cwd(), `test#99.lock`) - ).toEqual( + expect(path.join(process.cwd(), `test#99.lock`)).toEqual( LockFile.getLockFilePath('./', 'test', 99) ); }); @@ -160,7 +159,7 @@ describe('LockFile', () => { lockFileHandle.close(); FileSystem.updateTimes(otherPidLockFileName, { accessedTime: 10000, - modifiedTime: 10000 + modifiedTime: 10000, }); const lock: LockFile | undefined = LockFile.tryAcquire(testFolder, resourceName); @@ -173,20 +172,12 @@ describe('LockFile', () => { if (process.platform === 'win32') { describe('getLockFilePath()', () => { - test('returns a resolved path that doesn\'t contain', () => { - expect( - path.join(process.cwd(), `test.lock`) - ).toEqual( - LockFile.getLockFilePath('./', 'test') - ); + test("returns a resolved path that doesn't contain", () => { + expect(path.join(process.cwd(), `test.lock`)).toEqual(LockFile.getLockFilePath('./', 'test')); }); test('ignores pid that is passed in', () => { - expect( - path.join(process.cwd(), `test.lock`) - ).toEqual( - LockFile.getLockFilePath('./', 'test', 99) - ); + expect(path.join(process.cwd(), `test.lock`)).toEqual(LockFile.getLockFilePath('./', 'test', 99)); }); }); @@ -259,4 +250,4 @@ describe('LockFile', () => { }).toThrow(); }); } -}); \ No newline at end of file +}); diff --git a/libraries/node-core-library/src/test/PackageJsonLookup.test.ts b/libraries/node-core-library/src/test/PackageJsonLookup.test.ts index 92861e8f2ed..b324dede985 100644 --- a/libraries/node-core-library/src/test/PackageJsonLookup.test.ts +++ b/libraries/node-core-library/src/test/PackageJsonLookup.test.ts @@ -7,9 +7,7 @@ import { IPackageJson, INodePackageJson } from '../IPackageJson'; import { FileConstants } from '../Constants'; describe('PackageJsonLookup', () => { - describe('basic tests', () => { - test('', () => { expect(PackageJsonLookup.loadOwnPackageJson(__dirname).name).toEqual('@rushstack/node-core-library'); }); @@ -31,7 +29,9 @@ describe('PackageJsonLookup', () => { test('tryLoadNodePackageJsonFor() test package with no version', () => { const packageJsonLookup: PackageJsonLookup = new PackageJsonLookup(); const sourceFilePath: string = path.join(__dirname, './test-data/example-package-no-version'); - const packageJson: INodePackageJson | undefined = packageJsonLookup.tryLoadNodePackageJsonFor(sourceFilePath); + const packageJson: INodePackageJson | undefined = packageJsonLookup.tryLoadNodePackageJsonFor( + sourceFilePath + ); expect(packageJson).toBeDefined(); if (packageJson) { expect(packageJson.name).toEqual('example-package'); diff --git a/libraries/node-core-library/src/test/PackageName.test.ts b/libraries/node-core-library/src/test/PackageName.test.ts index 311c11ef64f..691bd9c9322 100644 --- a/libraries/node-core-library/src/test/PackageName.test.ts +++ b/libraries/node-core-library/src/test/PackageName.test.ts @@ -5,7 +5,6 @@ import { PackageName } from '../PackageName'; describe('PackageName', () => { describe('Test', () => { - test('isValidName() positive test', () => { expect(PackageName.isValidName('@microsoft/example-package')).toEqual(true); }); @@ -15,111 +14,74 @@ describe('PackageName', () => { }); test('tryParse() tests', () => { - expect( - PackageName.tryParse('@microsoft/example-package') - ).toEqual( - { - scope: '@microsoft', - unscopedName: 'example-package', - error: '' - } - ); - - expect( - PackageName.tryParse('') - ).toEqual( - { - scope: '', - unscopedName: '', - error: 'The package name must not be empty' - } - ); + expect(PackageName.tryParse('@microsoft/example-package')).toEqual({ + scope: '@microsoft', + unscopedName: 'example-package', + error: '', + }); + + expect(PackageName.tryParse('')).toEqual({ + scope: '', + unscopedName: '', + error: 'The package name must not be empty', + }); expect( PackageName.tryParse(undefined as any) // eslint-disable-line @typescript-eslint/no-explicit-any - ).toEqual( - { - scope: '', - unscopedName: '', - error: 'The package name must not be null or undefined' - } - ); - - expect( - PackageName.tryParse('@microsoft') - ).toEqual( - { - scope: '@microsoft', - unscopedName: '', - error: 'Error parsing "@microsoft": The scope must be followed by a slash' - } - ); - - expect( - PackageName.tryParse('@/example-package') - ).toEqual( - { - scope: '@', - unscopedName: 'example-package', - error: 'Error parsing "@/example-package": The scope name cannot be empty' - } - ); - - expect( - PackageName.tryParse('@Microsoft/example-package') - ).toEqual( - { - scope: '@Microsoft', - unscopedName: 'example-package', - error: 'The package scope "@Microsoft" must not contain upper case characters' - } - ); - - expect( - PackageName.tryParse('@micro!soft/example-package') - ).toEqual( - { - scope: '@micro!soft', - unscopedName: 'example-package', - error: 'The package name "@micro!soft/example-package" contains an invalid character: \"!\"' - } - ); - - expect( - PackageName.tryParse('@microsoft/node-co~re-library') - ).toEqual( - { - scope: '@microsoft', - unscopedName: 'node-co~re-library', - error: 'The package name "@microsoft/node-co~re-library" contains an invalid character: \"~\"' - } - ); - - expect( - PackageName.tryParse('@microsoft/example-package/path') - ).toEqual( - { - scope: '@microsoft', - unscopedName: 'example-package/path', - error: 'The package name "@microsoft/example-package/path" contains an invalid character: \"/\"' - } - ); - + ).toEqual({ + scope: '', + unscopedName: '', + error: 'The package name must not be null or undefined', + }); + + expect(PackageName.tryParse('@microsoft')).toEqual({ + scope: '@microsoft', + unscopedName: '', + error: 'Error parsing "@microsoft": The scope must be followed by a slash', + }); + + expect(PackageName.tryParse('@/example-package')).toEqual({ + scope: '@', + unscopedName: 'example-package', + error: 'Error parsing "@/example-package": The scope name cannot be empty', + }); + + expect(PackageName.tryParse('@Microsoft/example-package')).toEqual({ + scope: '@Microsoft', + unscopedName: 'example-package', + error: 'The package scope "@Microsoft" must not contain upper case characters', + }); + + expect(PackageName.tryParse('@micro!soft/example-package')).toEqual({ + scope: '@micro!soft', + unscopedName: 'example-package', + error: 'The package name "@micro!soft/example-package" contains an invalid character: "!"', + }); + + expect(PackageName.tryParse('@microsoft/node-co~re-library')).toEqual({ + scope: '@microsoft', + unscopedName: 'node-co~re-library', + error: 'The package name "@microsoft/node-co~re-library" contains an invalid character: "~"', + }); + + expect(PackageName.tryParse('@microsoft/example-package/path')).toEqual({ + scope: '@microsoft', + unscopedName: 'example-package/path', + error: 'The package name "@microsoft/example-package/path" contains an invalid character: "/"', + }); }); }); test('parse() test', () => { - expect( - () => { PackageName.parse('@'); } - ).toThrowError('The scope must be followed by a slash'); + expect(() => { + PackageName.parse('@'); + }).toThrowError('The scope must be followed by a slash'); }); test('combineParts() tests', () => { - expect(PackageName.combineParts('@microsoft', 'example-package')) - .toEqual('@microsoft/example-package'); + expect(PackageName.combineParts('@microsoft', 'example-package')).toEqual('@microsoft/example-package'); - expect(PackageName.combineParts('', 'example-package')) - .toEqual('example-package'); + expect(PackageName.combineParts('', 'example-package')).toEqual('example-package'); }); test('combineParts() errors', () => { diff --git a/libraries/node-core-library/src/test/Path.test.ts b/libraries/node-core-library/src/test/Path.test.ts index eccc499cd36..7943b3df79c 100644 --- a/libraries/node-core-library/src/test/Path.test.ts +++ b/libraries/node-core-library/src/test/Path.test.ts @@ -6,7 +6,6 @@ import { Path } from '../Path'; describe('Path', () => { describe('Test', () => { - if (os.platform() === 'win32') { test('Windows paths', () => { expect(Path.isUnder('C:\\a\\b.txt', 'C:\\a')).toEqual(true); diff --git a/libraries/node-core-library/src/test/ProtectableMap.test.ts b/libraries/node-core-library/src/test/ProtectableMap.test.ts index b3c7058e38a..ca3c3e5643b 100644 --- a/libraries/node-core-library/src/test/ProtectableMap.test.ts +++ b/libraries/node-core-library/src/test/ProtectableMap.test.ts @@ -27,7 +27,7 @@ class ExampleApi { // If the provided value is negative, clamp it to zero: return Math.max(value, 0); - } + }, }); } @@ -79,5 +79,4 @@ describe('ProtectableMap', () => { exampleApi.studentAgesByName.set('Jane', 23); }).toThrowError('The key must be all upper case: Jane'); }); - }); diff --git a/libraries/node-core-library/src/test/Sort.test.ts b/libraries/node-core-library/src/test/Sort.test.ts index 0aaf22a7449..fd5aafef2e6 100644 --- a/libraries/node-core-library/src/test/Sort.test.ts +++ b/libraries/node-core-library/src/test/Sort.test.ts @@ -5,7 +5,7 @@ import { Sort } from '../Sort'; test('Sort.compareByValue', () => { const array: number[] = [3, 6, 2]; - array.sort(Sort.compareByValue); // [2, 3, 6] + array.sort(Sort.compareByValue); // [2, 3, 6] }); test('Sort.compareByValue cases', () => { @@ -17,9 +17,15 @@ test('Sort.compareByValue cases', () => { const y: unknown = values[j]; let relation: string = '?'; switch (Sort.compareByValue(x, y)) { - case -1: relation = '<'; break; - case 0: relation = '='; break; - case 1: relation = '>'; break; + case -1: + relation = '<'; + break; + case 0: + relation = '='; + break; + case 1: + relation = '>'; + break; } results.push(`${x} ${relation} ${y}`); } @@ -28,13 +34,13 @@ test('Sort.compareByValue cases', () => { }); test('Sort.sortBy', () => { - const array: string[] = [ 'aaa', 'bb', 'c' ]; - Sort.sortBy(array, x => x.length); // [ 'c', 'bb', 'aaa' ] + const array: string[] = ['aaa', 'bb', 'c']; + Sort.sortBy(array, (x) => x.length); // [ 'c', 'bb', 'aaa' ] }); test('Sort.isSortedBy', () => { - const array: string[] = [ 'a', 'bb', 'ccc' ]; - Sort.isSortedBy(array, x => x.length); // true + const array: string[] = ['a', 'bb', 'ccc']; + Sort.isSortedBy(array, (x) => x.length); // true }); test('Sort.sortMapKeys', () => { @@ -51,7 +57,7 @@ test('Sort.sortSetBy', () => { set.add('aaa'); set.add('bb'); set.add('c'); - Sort.sortSetBy(set, x => x.length); + Sort.sortSetBy(set, (x) => x.length); expect(Array.from(set)).toEqual(['c', 'bb', 'aaa']); }); diff --git a/libraries/node-core-library/src/test/Text.test.ts b/libraries/node-core-library/src/test/Text.test.ts index e6e16b6c569..7032a425bbd 100644 --- a/libraries/node-core-library/src/test/Text.test.ts +++ b/libraries/node-core-library/src/test/Text.test.ts @@ -5,49 +5,49 @@ import { Text } from '../Text'; describe('Text', () => { describe('padEnd', () => { - test('Throws an exception if the padding character isn\'t a single character', () => { + test("Throws an exception if the padding character isn't a single character", () => { expect(() => Text.padEnd('123', 1, '')).toThrow(); expect(() => Text.padEnd('123', 1, ' ')).toThrow(); }); - test('Doesn\'t change the string if it\'s already at or greater than the minimum length', () => { - expect(Text.padEnd('12345', 5)).toEqual( '12345'); + test("Doesn't change the string if it's already at or greater than the minimum length", () => { + expect(Text.padEnd('12345', 5)).toEqual('12345'); expect(Text.padEnd('123456', 5)).toEqual('123456'); - expect(Text.padEnd('12345', 5, '0')).toEqual( '12345'); + expect(Text.padEnd('12345', 5, '0')).toEqual('12345'); expect(Text.padEnd('123456', 5, '0')).toEqual('123456'); }); test('Appends the default character (spaces) to the end of a string', () => { - expect(Text.padEnd('', 5)).toEqual( ' '); + expect(Text.padEnd('', 5)).toEqual(' '); expect(Text.padEnd('123', 5)).toEqual('123 '); }); test('Appends the characters to the end of a string', () => { - expect(Text.padEnd('', 5, '0')).toEqual( '00000'); + expect(Text.padEnd('', 5, '0')).toEqual('00000'); expect(Text.padEnd('123', 5, '0')).toEqual('12300'); }); }); describe('padStart', () => { - test('Throws an exception if the padding character isn\'t a single character', () => { + test("Throws an exception if the padding character isn't a single character", () => { expect(() => Text.padStart('123', 1, '')).toThrow(); expect(() => Text.padStart('123', 1, ' ')).toThrow(); }); - test('Doesn\'t change the string if it\'s already at or greater than the minimum length', () => { - expect(Text.padStart('12345', 5)).toEqual( '12345'); + test("Doesn't change the string if it's already at or greater than the minimum length", () => { + expect(Text.padStart('12345', 5)).toEqual('12345'); expect(Text.padStart('123456', 5)).toEqual('123456'); - expect(Text.padStart('12345', 5, '0')).toEqual( '12345'); + expect(Text.padStart('12345', 5, '0')).toEqual('12345'); expect(Text.padStart('123456', 5, '0')).toEqual('123456'); }); test('Appends the default character (spaces) to the end of a string', () => { - expect(Text.padStart('', 5)).toEqual( ' '); + expect(Text.padStart('', 5)).toEqual(' '); expect(Text.padStart('123', 5)).toEqual(' 123'); }); test('Appends the characters to the end of a string', () => { - expect(Text.padStart('', 5, '0')).toEqual( '00000'); + expect(Text.padStart('', 5, '0')).toEqual('00000'); expect(Text.padStart('123', 5, '0')).toEqual('00123'); }); }); @@ -57,19 +57,19 @@ describe('Text', () => { expect(() => Text.truncateWithEllipsis('123', -1)).toThrow(); }); - test('Doesn\'t change the string if it\'s already shorter than the maximum length', () => { - expect(Text.truncateWithEllipsis('', 2)).toEqual( ''); - expect(Text.truncateWithEllipsis('1', 2)).toEqual( '1'); - expect(Text.truncateWithEllipsis('12', 2)).toEqual( '12'); + test("Doesn't change the string if it's already shorter than the maximum length", () => { + expect(Text.truncateWithEllipsis('', 2)).toEqual(''); + expect(Text.truncateWithEllipsis('1', 2)).toEqual('1'); + expect(Text.truncateWithEllipsis('12', 2)).toEqual('12'); - expect(Text.truncateWithEllipsis('123', 5)).toEqual( '123'); - expect(Text.truncateWithEllipsis('1234', 5)).toEqual( '1234'); + expect(Text.truncateWithEllipsis('123', 5)).toEqual('123'); + expect(Text.truncateWithEllipsis('1234', 5)).toEqual('1234'); }); test('Truncates strings', () => { - expect(Text.truncateWithEllipsis('123', 0)).toEqual( ''); - expect(Text.truncateWithEllipsis('123', 2)).toEqual( '12'); - expect(Text.truncateWithEllipsis('12345', 5)).toEqual( '12345'); + expect(Text.truncateWithEllipsis('123', 0)).toEqual(''); + expect(Text.truncateWithEllipsis('123', 2)).toEqual('12'); + expect(Text.truncateWithEllipsis('12345', 5)).toEqual('12345'); expect(Text.truncateWithEllipsis('123456', 5)).toEqual('12...'); }); }); diff --git a/libraries/node-core-library/src/test/test-data/example-package-no-version/package.json b/libraries/node-core-library/src/test/test-data/example-package-no-version/package.json index ef5a1f3ad2e..5bd28c0d0b8 100644 --- a/libraries/node-core-library/src/test/test-data/example-package-no-version/package.json +++ b/libraries/node-core-library/src/test/test-data/example-package-no-version/package.json @@ -1,4 +1,4 @@ { "name": "example-package", "nonstandardField": 123 -} \ No newline at end of file +} diff --git a/libraries/node-core-library/src/test/test-data/example-package/package.json b/libraries/node-core-library/src/test/test-data/example-package/package.json index 58fce8e1943..4c2845e9fb4 100644 --- a/libraries/node-core-library/src/test/test-data/example-package/package.json +++ b/libraries/node-core-library/src/test/test-data/example-package/package.json @@ -2,4 +2,4 @@ "name": "example-package", "version": "1.0.0", "nonstandardField": 123 -} \ No newline at end of file +} diff --git a/libraries/node-core-library/src/test/test-data/executable/success/javascript-file.js b/libraries/node-core-library/src/test/test-data/executable/success/javascript-file.js index bea88b7cc80..eb013d61af3 100644 --- a/libraries/node-core-library/src/test/test-data/executable/success/javascript-file.js +++ b/libraries/node-core-library/src/test/test-data/executable/success/javascript-file.js @@ -2,4 +2,3 @@ console.log('Executing javascript-file.js with args:'); // Print the command line arguments: console.log(JSON.stringify(process.argv)); - diff --git a/libraries/node-core-library/src/test/test-data/test-schema.json b/libraries/node-core-library/src/test/test-data/test-schema.json index cbf8b76bd2d..9bcce6a4888 100644 --- a/libraries/node-core-library/src/test/test-data/test-schema.json +++ b/libraries/node-core-library/src/test/test-data/test-schema.json @@ -13,7 +13,7 @@ } }, "additionalProperties": false, - "required": [ "field1" ] + "required": ["field1"] }, "type2": { "description": "Description for type2", @@ -29,7 +29,7 @@ } }, "additionalProperties": false, - "required": [ "field2", "field3" ] + "required": ["field2", "field3"] } }, @@ -46,12 +46,9 @@ "exampleOneOf": { "description": "Description for exampleOneOf - this is a very long description to show in an error message", "type": "object", - "oneOf": [ - { "$ref": "#/definitions/type1" }, - { "$ref": "#/definitions/type2" } - ] + "oneOf": [{ "$ref": "#/definitions/type1" }, { "$ref": "#/definitions/type2" }] } }, "additionalProperties": false, - "required": [ "exampleString", "exampleArray" ] + "required": ["exampleString", "exampleArray"] } diff --git a/libraries/node-core-library/src/test/test-data/test.json b/libraries/node-core-library/src/test/test-data/test.json index 7ffb7142ca8..0d0cafa9b9b 100644 --- a/libraries/node-core-library/src/test/test-data/test.json +++ b/libraries/node-core-library/src/test/test-data/test.json @@ -1,8 +1,4 @@ { "exampleString": "This is a string", - "exampleArray": [ - "apple", - "banana", - "coconut" - ] + "exampleArray": ["apple", "banana", "coconut"] } diff --git a/libraries/node-core-library/src/test/test-data/test2.json b/libraries/node-core-library/src/test/test-data/test2.json index 5a0eeeaa2de..3f5d37c1c31 100644 --- a/libraries/node-core-library/src/test/test-data/test2.json +++ b/libraries/node-core-library/src/test/test-data/test2.json @@ -1,10 +1,6 @@ { "exampleString": "This is a string", - "exampleArray": [ - "apple", - "banana", - "coconut" - ], + "exampleArray": ["apple", "banana", "coconut"], "exampleOneOf": { "field2": "blah" } diff --git a/libraries/node-core-library/tsconfig.json b/libraries/node-core-library/tsconfig.json index 824a88b71e5..46bc07fdda9 100644 --- a/libraries/node-core-library/tsconfig.json +++ b/libraries/node-core-library/tsconfig.json @@ -2,9 +2,6 @@ "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "jest", - "node" - ] + "types": ["jest", "node"] } } diff --git a/libraries/package-deps-hash/.eslintrc.js b/libraries/package-deps-hash/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/libraries/package-deps-hash/.eslintrc.js +++ b/libraries/package-deps-hash/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/libraries/package-deps-hash/config/jest.json b/libraries/package-deps-hash/config/jest.json index b4a7ec97a56..902b00ea176 100644 --- a/libraries/package-deps-hash/config/jest.json +++ b/libraries/package-deps-hash/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": true -} \ No newline at end of file +} diff --git a/libraries/package-deps-hash/src/getPackageDeps.ts b/libraries/package-deps-hash/src/getPackageDeps.ts index c485d7ed4f9..2684f525622 100644 --- a/libraries/package-deps-hash/src/getPackageDeps.ts +++ b/libraries/package-deps-hash/src/getPackageDeps.ts @@ -19,8 +19,7 @@ export function parseGitLsTree(output: string): Map { const gitRegex: RegExp = /([0-9]{6})\s(blob|commit)\s([a-f0-9]{40})\s*(.*)/; // Note: The output of git ls-tree uses \n newlines regardless of OS. - output.split('\n').forEach(line => { - + output.split('\n').forEach((line) => { if (line) { // Take everything after the "100644 blob", which is just the hash and filename const matches: RegExpMatchArray | null = line.match(gitRegex); @@ -29,7 +28,6 @@ export function parseGitLsTree(output: string): Map { const filename: string = matches[4]; changes.set(filename, hash); - } else { throw new Error(`Cannot parse git ls-tree input: "${line}"`); } @@ -47,10 +45,10 @@ export function parseGitStatus(output: string, packagePath: string): Map = new Map(); /* - * Typically, output will look something like: - * M temp_modules/rush-package-deps-hash/package.json - * D package-deps-hash/src/index.ts - */ + * Typically, output will look something like: + * M temp_modules/rush-package-deps-hash/package.json + * D package-deps-hash/src/index.ts + */ // If there was an issue with `git ls-tree`, or there are no current changes, processOutputBlocks[1] // will be empty or undefined @@ -62,19 +60,22 @@ export function parseGitStatus(output: string, packagePath: string): Map { + .forEach((line) => { /* - * changeType is in the format of "XY" where "X" is the status of the file in the index and "Y" is the status of - * the file in the working tree. Some example statuses: - * - 'D' == deletion - * - 'M' == modification - * - 'A' == addition - * - '??' == untracked - * - 'R' == rename - * - 'RM' == rename with modifications - * filenames == path to the file, or files in the case of files that have been renamed - */ - const [changeType, ...filenames]: string[] = line.trim().split(' ').filter((linePart) => !!linePart); + * changeType is in the format of "XY" where "X" is the status of the file in the index and "Y" is the status of + * the file in the working tree. Some example statuses: + * - 'D' == deletion + * - 'M' == modification + * - 'A' == addition + * - '??' == untracked + * - 'R' == rename + * - 'RM' == rename with modifications + * filenames == path to the file, or files in the case of files that have been renamed + */ + const [changeType, ...filenames]: string[] = line + .trim() + .split(' ') + .filter((linePart) => !!linePart); if (changeType && filenames && filenames.length > 0) { // We always care about the last filename in the filenames array. In the case of non-rename changes, @@ -112,7 +113,9 @@ export function getGitHashForFiles(filesToHash: string[], packagePath: string): const hashes: string[] = hashStdout.split('\n'); if (hashes.length !== filesToHash.length) { - throw new Error(`Passed ${filesToHash.length} file paths to Git to hash, but received ${hashes.length} hashes.`); + throw new Error( + `Passed ${filesToHash.length} file paths to Git to hash, but received ${hashes.length} hashes.` + ); } for (let i: number = 0; i < hashes.length; i++) { @@ -120,7 +123,6 @@ export function getGitHashForFiles(filesToHash: string[], packagePath: string): const filePath: string = filesToHash[i]; changes.set(filePath, hash); } - } return changes; @@ -134,7 +136,7 @@ export function gitLsTree(path: string): string { 'git', ['ls-tree', 'HEAD', '-r'], { - currentWorkingDirectory: path + currentWorkingDirectory: path, } ); @@ -153,7 +155,7 @@ export function gitStatus(path: string): string { 'git', ['status', '-s', '-u', '.'], { - currentWorkingDirectory: path + currentWorkingDirectory: path, } ); @@ -178,11 +180,13 @@ export function getPackageDeps(packagePath: string = process.cwd(), excludedPath const excludedHashes: { [key: string]: boolean } = {}; if (excludedPaths) { - excludedPaths.forEach((path) => { excludedHashes[path] = true }); + excludedPaths.forEach((path) => { + excludedHashes[path] = true; + }); } const changes: IPackageDeps = { - files: {} + files: {}, }; const gitLsOutput: string = gitLsTree(packagePath); @@ -196,8 +200,7 @@ export function getPackageDeps(packagePath: string = process.cwd(), excludedPath // Update the checked in hashes with the current repo status const gitStatusOutput: string = gitStatus(packagePath); - const currentlyChangedFiles: Map = - parseGitStatus(gitStatusOutput, packagePath); + const currentlyChangedFiles: Map = parseGitStatus(gitStatusOutput, packagePath); const filesToHash: string[] = []; currentlyChangedFiles.forEach((changeType: string, filename: string) => { diff --git a/libraries/package-deps-hash/src/index.ts b/libraries/package-deps-hash/src/index.ts index 827f1a3b28f..f541c4606aa 100644 --- a/libraries/package-deps-hash/src/index.ts +++ b/libraries/package-deps-hash/src/index.ts @@ -13,8 +13,5 @@ * @packageDocumentation */ -export { - getPackageDeps, - getGitHashForFiles -} from './getPackageDeps'; +export { getPackageDeps, getGitHashForFiles } from './getPackageDeps'; export { IPackageDeps } from './IPackageDeps'; diff --git a/libraries/package-deps-hash/src/test/getPackageDeps.test.ts b/libraries/package-deps-hash/src/test/getPackageDeps.test.ts index 914c8957c94..f53e4076422 100644 --- a/libraries/package-deps-hash/src/test/getPackageDeps.test.ts +++ b/libraries/package-deps-hash/src/test/getPackageDeps.test.ts @@ -6,14 +6,9 @@ import { IPackageDeps } from '../IPackageDeps'; import * as path from 'path'; import { execSync } from 'child_process'; -import { - FileSystem, - FileConstants -} from '@rushstack/node-core-library'; +import { FileSystem, FileConstants } from '@rushstack/node-core-library'; -const SOURCE_PATH: string = path.join(__dirname).replace( - path.join('lib', 'test'), - path.join('src', 'test')); +const SOURCE_PATH: string = path.join(__dirname).replace(path.join('lib', 'test'), path.join('src', 'test')); const TEST_PROJECT_PATH: string = path.join(SOURCE_PATH, 'testProject'); const NESTED_TEST_PROJECT_PATH: string = path.join(SOURCE_PATH, 'nestedTestProject'); @@ -66,19 +61,19 @@ describe('parseGitLsTree', () => { }); describe('getPackageDeps', () => { - it('can parse committed file', (done) => { const results: IPackageDeps = getPackageDeps(TEST_PROJECT_PATH); try { const expectedFiles: { [key: string]: string } = { 'file1.txt': 'c7b2f707ac99ca522f965210a7b6b0b109863f34', - [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9' + [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9', }; const filePaths: string[] = Object.keys(results.files).sort(); - filePaths.forEach(filePath => (expect(results.files[filePath]).toEqual(expectedFiles[filePath]))); - - } catch (e) { return done(e); } + filePaths.forEach((filePath) => expect(results.files[filePath]).toEqual(expectedFiles[filePath])); + } catch (e) { + return done(e); + } done(); }); @@ -88,12 +83,14 @@ describe('getPackageDeps', () => { try { const expectedFiles: { [key: string]: string } = { 'src/file 1.txt': 'c7b2f707ac99ca522f965210a7b6b0b109863f34', - [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9' + [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9', }; const filePaths: string[] = Object.keys(results.files).sort(); - filePaths.forEach(filePath => (expect(results.files[filePath]).toEqual(expectedFiles[filePath]))); - } catch (e) { return done(e); } + filePaths.forEach((filePath) => expect(results.files[filePath]).toEqual(expectedFiles[filePath])); + } catch (e) { + return done(e); + } done(); }); @@ -113,18 +110,16 @@ describe('getPackageDeps', () => { const expectedFiles: { [key: string]: string } = { 'a.txt': '2e65efe2a145dda7ee51d1741299f848e5bf752e', 'file1.txt': 'c7b2f707ac99ca522f965210a7b6b0b109863f34', - [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9' + [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9', }; const filePaths: string[] = Object.keys(results.files).sort(); - filePaths.forEach(filePath => (expect(results.files[filePath]).toEqual(expectedFiles[filePath]))); - + filePaths.forEach((filePath) => expect(results.files[filePath]).toEqual(expectedFiles[filePath])); } catch (e) { return _done(e); } _done(); - }); it('can handle adding two files', (done) => { @@ -146,12 +141,11 @@ describe('getPackageDeps', () => { 'a.txt': '2e65efe2a145dda7ee51d1741299f848e5bf752e', 'b.txt': '2e65efe2a145dda7ee51d1741299f848e5bf752e', 'file1.txt': 'c7b2f707ac99ca522f965210a7b6b0b109863f34', - [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9' + [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9', }; const filePaths: string[] = Object.keys(results.files).sort(); - filePaths.forEach(filePath => (expect(results.files[filePath]).toEqual(expectedFiles[filePath]))); - + filePaths.forEach((filePath) => expect(results.files[filePath]).toEqual(expectedFiles[filePath])); } catch (e) { return _done(e); } @@ -165,19 +159,18 @@ describe('getPackageDeps', () => { FileSystem.deleteFile(testFilePath); function _done(e?: Error): void { - execSync(`git checkout ${ testFilePath }`, { stdio: 'ignore' }); + execSync(`git checkout ${testFilePath}`, { stdio: 'ignore' }); done(e); } const results: IPackageDeps = getPackageDeps(TEST_PROJECT_PATH); try { const expectedFiles: { [key: string]: string } = { - [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9' + [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9', }; const filePaths: string[] = Object.keys(results.files).sort(); - filePaths.forEach(filePath => (expect(results.files[filePath]).toEqual(expectedFiles[filePath]))); - + filePaths.forEach((filePath) => expect(results.files[filePath]).toEqual(expectedFiles[filePath])); } catch (e) { return _done(e); } @@ -199,12 +192,11 @@ describe('getPackageDeps', () => { try { const expectedFiles: { [key: string]: string } = { 'file1.txt': 'f2ba8f84ab5c1bce84a7b441cb1959cfc7093b7f', - [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9' + [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9', }; const filePaths: string[] = Object.keys(results.files).sort(); - filePaths.forEach(filePath => (expect(results.files[filePath]).toEqual(expectedFiles[filePath]))); - + filePaths.forEach((filePath) => expect(results.files[filePath]).toEqual(expectedFiles[filePath])); } catch (e) { return _done(e); } @@ -216,13 +208,14 @@ describe('getPackageDeps', () => { const results: IPackageDeps = getPackageDeps(TEST_PROJECT_PATH, ['file1.txt']); try { const expectedFiles: { [key: string]: string } = { - [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9' + [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9', }; const filePaths: string[] = Object.keys(results.files).sort(); - filePaths.forEach(filePath => (expect(results.files[filePath]).toEqual(expectedFiles[filePath]))); - - } catch (e) { return done(e); } + filePaths.forEach((filePath) => expect(results.files[filePath]).toEqual(expectedFiles[filePath])); + } catch (e) { + return done(e); + } done(); }); @@ -241,19 +234,17 @@ describe('getPackageDeps', () => { try { const expectedFiles: { [key: string]: string } = { 'file1.txt': 'c7b2f707ac99ca522f965210a7b6b0b109863f34', - [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9' + [FileConstants.PackageJson]: '33703d582243a41bdebff8ee7dd046a01fc054b9', }; const filePaths: string[] = Object.keys(results.files).sort(); expect(filePaths).toHaveLength(Object.keys(expectedFiles).length); - filePaths.forEach(filePath => (expect(results.files[filePath]).toEqual(expectedFiles[filePath]))); - + filePaths.forEach((filePath) => expect(results.files[filePath]).toEqual(expectedFiles[filePath])); } catch (e) { return _done(e); } _done(); }); - }); diff --git a/libraries/package-deps-hash/src/test/nestedTestProject/package.json b/libraries/package-deps-hash/src/test/nestedTestProject/package.json index 33703d58224..18a1e415e56 100644 --- a/libraries/package-deps-hash/src/test/nestedTestProject/package.json +++ b/libraries/package-deps-hash/src/test/nestedTestProject/package.json @@ -1,3 +1,3 @@ { "dependencies": {} -} \ No newline at end of file +} diff --git a/libraries/package-deps-hash/src/test/testProject/package.json b/libraries/package-deps-hash/src/test/testProject/package.json index 33703d58224..18a1e415e56 100644 --- a/libraries/package-deps-hash/src/test/testProject/package.json +++ b/libraries/package-deps-hash/src/test/testProject/package.json @@ -1,3 +1,3 @@ { "dependencies": {} -} \ No newline at end of file +} diff --git a/libraries/package-deps-hash/tsconfig.json b/libraries/package-deps-hash/tsconfig.json index 76f0d945025..8f1cbebe335 100644 --- a/libraries/package-deps-hash/tsconfig.json +++ b/libraries/package-deps-hash/tsconfig.json @@ -1,9 +1,6 @@ { "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "jest", - "node" - ] + "types": ["jest", "node"] } } diff --git a/libraries/rushell/.eslintrc.js b/libraries/rushell/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/libraries/rushell/.eslintrc.js +++ b/libraries/rushell/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/libraries/rushell/config/jest.json b/libraries/rushell/config/jest.json index b4a7ec97a56..902b00ea176 100644 --- a/libraries/rushell/config/jest.json +++ b/libraries/rushell/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": true -} \ No newline at end of file +} diff --git a/libraries/rushell/src/AstNode.ts b/libraries/rushell/src/AstNode.ts index 0f6d054bb91..8412778e928 100644 --- a/libraries/rushell/src/AstNode.ts +++ b/libraries/rushell/src/AstNode.ts @@ -11,7 +11,7 @@ export const enum AstKind { Command = 'Command', CompoundWord = 'CompoundWord', VariableExpansion = 'VariableExpansion', - Text = 'Text' + Text = 'Text', } /** diff --git a/libraries/rushell/src/ParseError.ts b/libraries/rushell/src/ParseError.ts index 8d340ccf21f..5bdd7f9d1d6 100644 --- a/libraries/rushell/src/ParseError.ts +++ b/libraries/rushell/src/ParseError.ts @@ -59,5 +59,4 @@ export class ParseError extends Error { } return message; } - } diff --git a/libraries/rushell/src/Parser.ts b/libraries/rushell/src/Parser.ts index a073dddce7f..041055aa884 100644 --- a/libraries/rushell/src/Parser.ts +++ b/libraries/rushell/src/Parser.ts @@ -3,13 +3,7 @@ import { ParseError } from './ParseError'; import { Tokenizer, Token, TokenKind } from './Tokenizer'; -import { - AstNode, - AstScript, - AstCommand, - AstCompoundWord, - AstText -} from './AstNode'; +import { AstNode, AstScript, AstCommand, AstCompoundWord, AstText } from './AstNode'; export class Parser { private readonly _tokenizer: Tokenizer; diff --git a/libraries/rushell/src/Rushell.ts b/libraries/rushell/src/Rushell.ts index 77a447026e1..02322ef357f 100644 --- a/libraries/rushell/src/Rushell.ts +++ b/libraries/rushell/src/Rushell.ts @@ -26,7 +26,6 @@ export interface IRushellExecuteResult { */ export class Rushell { public execute(script: string): IRushellExecuteResult { - const tokenizer: Tokenizer = new Tokenizer(script); const parser: Parser = new Parser(tokenizer); const astScript: AstScript = parser.parse(); @@ -37,7 +36,7 @@ export class Rushell { private _evaluateNode(astNode: AstNode): IRushellExecuteResult { switch (astNode.kind) { case AstKind.CompoundWord: - return { value: astNode.parts.map(x => this._evaluateNode(x).value).join('') }; + return { value: astNode.parts.map((x) => this._evaluateNode(x).value).join('') }; case AstKind.Text: return { value: astNode.token!.range.toString() }; case AstKind.Script: @@ -65,7 +64,7 @@ export class Rushell { } const commandPath: string = commandPathResult.value; - const commandArgs: string[] = commandArgResults.map(x => x.value); + const commandArgs: string[] = commandArgResults.map((x) => x.value); const result: child_process.SpawnSyncReturns = Executable.spawnSync(commandPath, commandArgs); diff --git a/libraries/rushell/src/TextRange.ts b/libraries/rushell/src/TextRange.ts index 068707196f7..b4fdc239884 100644 --- a/libraries/rushell/src/TextRange.ts +++ b/libraries/rushell/src/TextRange.ts @@ -143,12 +143,14 @@ export class TextRange { const current: string = this.buffer[currentIndex]; ++currentIndex; - if (current === '\r') { // CR + if (current === '\r') { + // CR // Ignore '\r' and assume it will always have an accompanying '\n' continue; } - if (current === '\n') { // LF + if (current === '\n') { + // LF ++line; column = 1; } else { diff --git a/libraries/rushell/src/Tokenizer.ts b/libraries/rushell/src/Tokenizer.ts index 381e337cac7..d75f64a5e29 100644 --- a/libraries/rushell/src/Tokenizer.ts +++ b/libraries/rushell/src/Tokenizer.ts @@ -30,7 +30,7 @@ export enum TokenKind { DollarVariable, // The end of the input string - EndOfInput + EndOfInput, } export class Token { @@ -66,7 +66,7 @@ export class Tokenizer { private _currentIndex: number; public constructor(input: TextRange | string) { - if (typeof(input) === 'string') { + if (typeof input === 'string') { this.input = TextRange.fromString(input); } else { this.input = input; @@ -128,12 +128,16 @@ export class Tokenizer { let c: string | undefined = this._peekCharacter(); while (c !== '"') { if (c === undefined) { - throw new ParseError('The double-quoted string is missing the ending quote', - input.getNewRange(startIndex, this._currentIndex)); + throw new ParseError( + 'The double-quoted string is missing the ending quote', + input.getNewRange(startIndex, this._currentIndex) + ); } if (c === '\r' || c === '\n') { - throw new ParseError('Newlines are not supported inside strings', - input.getNewRange(this._currentIndex, this._currentIndex + 1)); + throw new ParseError( + 'Newlines are not supported inside strings', + input.getNewRange(this._currentIndex, this._currentIndex + 1) + ); } // NOTE: POSIX says that backslash acts as an escape character inside a double-quoted string @@ -147,8 +151,10 @@ export class Tokenizer { if (c === '\\') { this._readCharacter(); // discard the backslash if (this._peekCharacter() === undefined) { - throw new ParseError('A backslash must be followed by another character', - input.getNewRange(this._currentIndex, this._currentIndex + 1)); + throw new ParseError( + 'A backslash must be followed by another character', + input.getNewRange(this._currentIndex, this._currentIndex + 1) + ); } // Add the escaped character text += this._readCharacter(); @@ -171,8 +177,10 @@ export class Tokenizer { if (c === '\\') { this._readCharacter(); // discard the backslash if (this._peekCharacter() === undefined) { - throw new ParseError('A backslash must be followed by another character', - input.getNewRange(this._currentIndex, this._currentIndex + 1)); + throw new ParseError( + 'A backslash must be followed by another character', + input.getNewRange(this._currentIndex, this._currentIndex + 1) + ); } // Add the escaped character text += this._readCharacter(); @@ -192,8 +200,10 @@ export class Tokenizer { let name: string = this._readCharacter() || ''; if (!startVariableCharacterRegExp.test(name)) { - throw new ParseError('The "$" symbol must be followed by a letter or underscore', - input.getNewRange(startIndex, this._currentIndex)); + throw new ParseError( + 'The "$" symbol must be followed by a letter or underscore', + input.getNewRange(startIndex, this._currentIndex) + ); } let c: string | undefined = this._peekCharacter(); diff --git a/libraries/rushell/src/index.ts b/libraries/rushell/src/index.ts index 289e0ab64b2..489e6956444 100644 --- a/libraries/rushell/src/index.ts +++ b/libraries/rushell/src/index.ts @@ -7,7 +7,4 @@ * @packageDocumentation */ -export { - Rushell, - IRushellExecuteResult -} from './Rushell'; +export { Rushell, IRushellExecuteResult } from './Rushell'; diff --git a/libraries/rushell/src/test/Parser.test.ts b/libraries/rushell/src/test/Parser.test.ts index 7130532bf3b..37ba71e0df8 100644 --- a/libraries/rushell/src/test/Parser.test.ts +++ b/libraries/rushell/src/test/Parser.test.ts @@ -6,10 +6,7 @@ import { Parser } from '../Parser'; import { AstScript } from '../AstNode'; function escape(s: string): string { - return s.replace(/\n/g, '[n]') - .replace(/\r/g, '[r]') - .replace(/\t/g, '[t]') - .replace(/\\/g, '[b]'); + return s.replace(/\n/g, '[n]').replace(/\r/g, '[r]').replace(/\t/g, '[t]').replace(/\\/g, '[b]'); } function matchSnapshot(input: string): void { @@ -18,7 +15,7 @@ function matchSnapshot(input: string): void { const result: AstScript = parser.parse(); expect({ input: escape(tokenizer.input.toString()), - tree: '\n' + result.getDump() + tree: '\n' + result.getDump(), }).toMatchSnapshot(); } @@ -33,7 +30,7 @@ function matchErrorSnapshot(input: string): void { } expect({ input: escape(tokenizer.input.toString()), - reportedError: error + reportedError: error, }).toMatchSnapshot(); } diff --git a/libraries/rushell/src/test/TextRange.test.ts b/libraries/rushell/src/test/TextRange.test.ts index d46fe0988fb..8c31c7dcaf8 100644 --- a/libraries/rushell/src/test/TextRange.test.ts +++ b/libraries/rushell/src/test/TextRange.test.ts @@ -4,17 +4,15 @@ import { TextRange } from '../TextRange'; function escape(s: string): string { - return s.replace(/\n/g, '[n]') - .replace(/\r/g, '[r]') - .replace(/\t/g, '[t]'); + return s.replace(/\n/g, '[n]').replace(/\r/g, '[r]').replace(/\t/g, '[t]'); } function matchSnapshot(textRange: TextRange): void { for (let i: number = -1; i <= textRange.end + 1; ++i) { - // Show the current character const c: string = escape(textRange.buffer.substr(Math.max(i, 0), 1)) - .replace(/\n/g, '[n]').replace(/\r/g, '[r]'); + .replace(/\n/g, '[n]') + .replace(/\r/g, '[r]'); // Show the next 10 characters of context const context: string = escape(textRange.buffer.substr(Math.max(i, 0), 10)); @@ -23,7 +21,7 @@ function matchSnapshot(textRange: TextRange): void { c: c, context: context, i: i, - location: textRange.getLocation(i) + location: textRange.getLocation(i), }).toMatchSnapshot(); } } @@ -38,13 +36,15 @@ test('construction scenarios', () => { }); test('getLocation() basic', () => { - const textRange: TextRange = TextRange.fromString([ - 'L1', - 'L2', - '', // (line 3 is blank) - 'L4', - 'L5+CR\rL5+CRLF\r\nL6+LFCR\n\rL7' - ].join('\n')); + const textRange: TextRange = TextRange.fromString( + [ + 'L1', + 'L2', + '', // (line 3 is blank) + 'L4', + 'L5+CR\rL5+CRLF\r\nL6+LFCR\n\rL7', + ].join('\n') + ); matchSnapshot(textRange); }); diff --git a/libraries/rushell/src/test/Tokenizer.test.ts b/libraries/rushell/src/test/Tokenizer.test.ts index 41251c1b742..ec84a2cc381 100644 --- a/libraries/rushell/src/test/Tokenizer.test.ts +++ b/libraries/rushell/src/test/Tokenizer.test.ts @@ -4,10 +4,7 @@ import { Tokenizer, TokenKind, Token } from '../Tokenizer'; function escape(s: string): string { - return s.replace(/\n/g, '[n]') - .replace(/\r/g, '[r]') - .replace(/\t/g, '[t]') - .replace(/\\/g, '[b]'); + return s.replace(/\n/g, '[n]').replace(/\r/g, '[r]').replace(/\t/g, '[t]').replace(/\\/g, '[b]'); } function tokenize(input: string): Token[] { @@ -18,21 +15,17 @@ function tokenize(input: string): Token[] { function matchSnapshot(input: string): void { const tokenizer: Tokenizer = new Tokenizer(input); - const reportedTokens: { kind: string, value: string }[] = tokenizer.readTokens().map( - token => { - return { - kind: TokenKind[token.kind], - value: escape(token.toString()) - }; - } - ); + const reportedTokens: { kind: string; value: string }[] = tokenizer.readTokens().map((token) => { + return { + kind: TokenKind[token.kind], + value: escape(token.toString()), + }; + }); - expect( - { - input: escape(tokenizer.input.toString()), - tokens: reportedTokens - } - ).toMatchSnapshot(); + expect({ + input: escape(tokenizer.input.toString()), + tokens: reportedTokens, + }).toMatchSnapshot(); } test('00: empty inputs', () => { diff --git a/libraries/rushell/tsconfig.json b/libraries/rushell/tsconfig.json index 76f0d945025..8f1cbebe335 100644 --- a/libraries/rushell/tsconfig.json +++ b/libraries/rushell/tsconfig.json @@ -1,9 +1,6 @@ { "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "jest", - "node" - ] + "types": ["jest", "node"] } } diff --git a/libraries/stream-collator/.eslintrc.js b/libraries/stream-collator/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/libraries/stream-collator/.eslintrc.js +++ b/libraries/stream-collator/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/libraries/stream-collator/config/jest.json b/libraries/stream-collator/config/jest.json index b4a7ec97a56..902b00ea176 100644 --- a/libraries/stream-collator/config/jest.json +++ b/libraries/stream-collator/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": true -} \ No newline at end of file +} diff --git a/libraries/stream-collator/src/Interleaver.ts b/libraries/stream-collator/src/Interleaver.ts index ce917be6ca4..f0bd1ae07d5 100644 --- a/libraries/stream-collator/src/Interleaver.ts +++ b/libraries/stream-collator/src/Interleaver.ts @@ -10,18 +10,18 @@ import * as os from 'os'; * @public */ export interface ITaskWriter { - write(data: string): void; // Writes a string to the buffer - writeLine(data: string): void; // Writes a string with a newline character at the end + write(data: string): void; // Writes a string to the buffer + writeLine(data: string): void; // Writes a string with a newline character at the end writeError(data: string): void; // Writes an error to the stderr stream - getStdOutput(): string; // Returns standard output buffer as a string - getStdError(): string; // Returns standard error buffer as a string - close(): void; // Closes the stream and marks the simultaneous process as completed + getStdOutput(): string; // Returns standard output buffer as a string + getStdError(): string; // Returns standard error buffer as a string + close(): void; // Closes the stream and marks the simultaneous process as completed } enum TaskWriterState { Open = 1, ClosedUnwritten = 2, - Written = 3 + Written = 3, } interface ITaskWriterInfo { @@ -33,7 +33,7 @@ interface ITaskWriterInfo { enum ITaskOutputStream { stdout = 1, - stderr = 2 + stderr = 2, } /** @@ -46,7 +46,7 @@ export class Interleaver { private static _activeTask: string = undefined; private static _stdout: { write: (text: string) => void } = process.stdout; - private constructor() { } + private constructor() {} /** * Resets the default output stream @@ -68,7 +68,7 @@ export class Interleaver { quietMode: quietMode, state: TaskWriterState.Open, stderr: [], - stdout: [] + stdout: [], }); if (this._activeTask === undefined) { @@ -81,7 +81,7 @@ export class Interleaver { getStdOutput: (): string => this._getTaskOutput(taskName), write: (data: string): void => this._writeTaskOutput(taskName, data), writeError: (data: string): void => this._writeTaskOutput(taskName, data, ITaskOutputStream.stderr), - writeLine: (data: string): void => this._writeTaskOutput(taskName, data + os.EOL) + writeLine: (data: string): void => this._writeTaskOutput(taskName, data + os.EOL), }; } @@ -96,14 +96,16 @@ export class Interleaver { /** * Adds the text to the task's buffer, and writes it to the console if it is the active task */ - private static _writeTaskOutput(taskName: string, data: string, - stream: ITaskOutputStream = ITaskOutputStream.stdout): void { - + private static _writeTaskOutput( + taskName: string, + data: string, + stream: ITaskOutputStream = ITaskOutputStream.stdout + ): void { const taskInfo: ITaskWriterInfo = this._tasks.get(taskName); if (!taskInfo || taskInfo.state !== TaskWriterState.Open) { throw new Error('The task is not registered or has been completed and written.'); } - const outputBuffer: string[] = (stream === ITaskOutputStream.stderr ? taskInfo.stderr : taskInfo.stdout); + const outputBuffer: string[] = stream === ITaskOutputStream.stderr ? taskInfo.stderr : taskInfo.stdout; if (!this._activeTask) { this._activeTask = taskName; @@ -124,7 +126,10 @@ export class Interleaver { /** * Returns the current value of the task's buffer */ - private static _getTaskOutput(taskName: string, stream: ITaskOutputStream = ITaskOutputStream.stdout): string { + private static _getTaskOutput( + taskName: string, + stream: ITaskOutputStream = ITaskOutputStream.stdout + ): string { const taskInfo: ITaskWriterInfo = this._tasks.get(taskName); return (stream === ITaskOutputStream.stdout ? taskInfo.stdout : taskInfo.stderr).join(''); } diff --git a/libraries/stream-collator/src/index.ts b/libraries/stream-collator/src/index.ts index 36f5cad362b..54fcf60880c 100644 --- a/libraries/stream-collator/src/index.ts +++ b/libraries/stream-collator/src/index.ts @@ -13,7 +13,4 @@ * @packageDocumentation */ -export { - Interleaver, - ITaskWriter -} from './Interleaver'; +export { Interleaver, ITaskWriter } from './Interleaver'; diff --git a/libraries/stream-collator/src/test/Interleaver.test.ts b/libraries/stream-collator/src/test/Interleaver.test.ts index 1d1d5f0455c..a8895373336 100644 --- a/libraries/stream-collator/src/test/Interleaver.test.ts +++ b/libraries/stream-collator/src/test/Interleaver.test.ts @@ -38,8 +38,12 @@ describe('Interleaver tests', () => { it('should not let you register two tasks with the same name', () => { const taskName: string = 'Hello World'; - expect(() => { Interleaver.registerTask(taskName); }).not.toThrow(); - expect(() => { Interleaver.registerTask(taskName); }).toThrow(); + expect(() => { + Interleaver.registerTask(taskName); + }).not.toThrow(); + expect(() => { + Interleaver.registerTask(taskName); + }).toThrow(); }); it('should not let you close a task twice', () => { @@ -53,7 +57,9 @@ describe('Interleaver tests', () => { const taskName: string = 'Hello World'; const task: ITaskWriter = Interleaver.registerTask(taskName); task.close(); - expect(() => { task.write('1'); }).toThrow(); + expect(() => { + task.write('1'); + }).toThrow(); }); }); @@ -78,7 +84,6 @@ describe('Interleaver tests', () => { expect(taskA.getStdOutput()).toEqual(''); expect(taskA.getStdError()).toEqual(error); - }); }); diff --git a/libraries/stream-collator/tsconfig.json b/libraries/stream-collator/tsconfig.json index f1746911fcf..e6d9347a115 100644 --- a/libraries/stream-collator/tsconfig.json +++ b/libraries/stream-collator/tsconfig.json @@ -2,9 +2,6 @@ "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { "strictNullChecks": false, - "types": [ - "node", - "jest" - ] + "types": ["node", "jest"] } } diff --git a/libraries/ts-command-line/.eslintrc.js b/libraries/ts-command-line/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/libraries/ts-command-line/.eslintrc.js +++ b/libraries/ts-command-line/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/libraries/ts-command-line/config/jest.json b/libraries/ts-command-line/config/jest.json index b4a7ec97a56..902b00ea176 100644 --- a/libraries/ts-command-line/config/jest.json +++ b/libraries/ts-command-line/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": true -} \ No newline at end of file +} diff --git a/libraries/ts-command-line/src/index.ts b/libraries/ts-command-line/src/index.ts index efb88d89364..0b3c246d11b 100644 --- a/libraries/ts-command-line/src/index.ts +++ b/libraries/ts-command-line/src/index.ts @@ -7,10 +7,7 @@ * @packageDocumentation */ -export { - CommandLineAction, - ICommandLineActionOptions -} from './providers/CommandLineAction'; +export { CommandLineAction, ICommandLineActionOptions } from './providers/CommandLineAction'; export { IBaseCommandLineDefinition, @@ -20,13 +17,13 @@ export { ICommandLineStringListDefinition, ICommandLineIntegerDefinition, ICommandLineChoiceDefinition, - ICommandLineRemainderDefinition + ICommandLineRemainderDefinition, } from './parameters/CommandLineDefinition'; export { CommandLineParameterKind, CommandLineParameter, - CommandLineParameterWithArgument + CommandLineParameterWithArgument, } from './parameters/BaseClasses'; export { CommandLineFlagParameter } from './parameters/CommandLineFlagParameter'; @@ -38,18 +35,11 @@ export { CommandLineRemainder } from './parameters/CommandLineRemainder'; export { CommandLineParameterProvider, - ICommandLineParserData as _ICommandLineParserData + ICommandLineParserData as _ICommandLineParserData, } from './providers/CommandLineParameterProvider'; -export { - ICommandLineParserOptions, - CommandLineParser -} from './providers/CommandLineParser'; +export { ICommandLineParserOptions, CommandLineParser } from './providers/CommandLineParser'; -export { - DynamicCommandLineAction -} from './providers/DynamicCommandLineAction'; +export { DynamicCommandLineAction } from './providers/DynamicCommandLineAction'; -export { - DynamicCommandLineParser -} from './providers/DynamicCommandLineParser'; +export { DynamicCommandLineParser } from './providers/DynamicCommandLineParser'; diff --git a/libraries/ts-command-line/src/parameters/BaseClasses.ts b/libraries/ts-command-line/src/parameters/BaseClasses.ts index 2d0830e58b8..ddeced41749 100644 --- a/libraries/ts-command-line/src/parameters/BaseClasses.ts +++ b/libraries/ts-command-line/src/parameters/BaseClasses.ts @@ -1,10 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - IBaseCommandLineDefinition, - IBaseCommandLineDefinitionWithArgument -} from './CommandLineDefinition'; +import { IBaseCommandLineDefinition, IBaseCommandLineDefinitionWithArgument } from './CommandLineDefinition'; /** * Identifies the kind of a CommandLineParameter. @@ -20,7 +17,7 @@ export enum CommandLineParameterKind { /** Indicates a CommandLineStringParameter */ String, /** Indicates a CommandLineStringListParameter */ - StringList + StringList, } /** @@ -70,14 +67,18 @@ export abstract class CommandLineParameter { this.environmentVariable = definition.environmentVariable; if (!CommandLineParameter._longNameRegExp.test(this.longName)) { - throw new Error(`Invalid name: "${this.longName}". The parameter long name must be` - + ` lower-case and use dash delimiters (e.g. "--do-a-thing")`); + throw new Error( + `Invalid name: "${this.longName}". The parameter long name must be` + + ` lower-case and use dash delimiters (e.g. "--do-a-thing")` + ); } if (this.shortName) { if (!CommandLineParameter._shortNameRegExp.test(this.shortName)) { - throw new Error(`Invalid name: "${this.shortName}". The parameter short name must be` - + ` a dash followed by a single upper-case or lower-case letter (e.g. "-a")`); + throw new Error( + `Invalid name: "${this.shortName}". The parameter short name must be` + + ` a dash followed by a single upper-case or lower-case letter (e.g. "-a")` + ); } } @@ -85,13 +86,17 @@ export abstract class CommandLineParameter { if (this.required) { // TODO: This constraint is imposed only because argparse enforces "required" parameters, but // it does not know about ts-command-line environment variable mappings. We should fix this. - throw new Error(`An "environmentVariable" cannot be specified for "${this.longName}"` - + ` because it is a required parameter`); + throw new Error( + `An "environmentVariable" cannot be specified for "${this.longName}"` + + ` because it is a required parameter` + ); } if (!CommandLineParameter._environmentVariableRegExp.test(this.environmentVariable)) { - throw new Error(`Invalid environment variable name: "${this.environmentVariable}". The name must` - + ` consist only of upper-case letters, numbers, and underscores. It may not start with a number.`); + throw new Error( + `Invalid environment variable name: "${this.environmentVariable}". The name must` + + ` consist only of upper-case letters, numbers, and underscores. It may not start with a number.` + ); } } } @@ -106,10 +111,14 @@ export abstract class CommandLineParameter { * Returns additional text used by the help formatter. * @internal */ - public _getSupplementaryNotes(supplementaryNotes: string[]): void { // virtual + public _getSupplementaryNotes(supplementaryNotes: string[]): void { + // virtual if (this.environmentVariable !== undefined) { - supplementaryNotes.push('This parameter may alternatively be specified via the ' + this.environmentVariable - + ' environment variable.'); + supplementaryNotes.push( + 'This parameter may alternatively be specified via the ' + + this.environmentVariable + + ' environment variable.' + ); } } @@ -136,9 +145,9 @@ export abstract class CommandLineParameter { /** * Internal usage only. Used to report unexpected output from the argparse library. */ - protected reportInvalidData(data: any): never { // eslint-disable-line @typescript-eslint/no-explicit-any - throw new Error(`Unexpected data object for parameter "${this.longName}": ` - + JSON.stringify(data)); + protected reportInvalidData(data: any): never { + // eslint-disable-line @typescript-eslint/no-explicit-any + throw new Error(`Unexpected data object for parameter "${this.longName}": ` + JSON.stringify(data)); } protected validateDefaultValue(hasDefaultValue: boolean): void { @@ -148,8 +157,9 @@ export abstract class CommandLineParameter { // It would be confusing to allow a default value that sometimes allows the "required" parameter // to be omitted. If you sometimes don't have a suitable default value, then the better approach // is to throw a custom error explaining why the parameter is required in that case. - throw new Error(`A default value cannot be specified for "${this.longName}"` - + ` because it is a "required" parameter`); + throw new Error( + `A default value cannot be specified for "${this.longName}"` + ` because it is a "required" parameter` + ); } } } @@ -174,22 +184,24 @@ export abstract class CommandLineParameterWithArgument extends CommandLineParame super(definition); if (definition.argumentName === '') { - throw new Error('The argument name cannot be an empty string. (For the default name, specify undefined.)'); + throw new Error( + 'The argument name cannot be an empty string. (For the default name, specify undefined.)' + ); } if (definition.argumentName.toUpperCase() !== definition.argumentName) { - throw new Error(`Invalid name: "${definition.argumentName}". The argument name must be all upper case.`); + throw new Error( + `Invalid name: "${definition.argumentName}". The argument name must be all upper case.` + ); } const match: RegExpMatchArray | null = definition.argumentName.match( - CommandLineParameterWithArgument._invalidArgumentNameRegExp); + CommandLineParameterWithArgument._invalidArgumentNameRegExp + ); if (match) { - throw new Error(`The argument name "${definition.argumentName}" contains an invalid character "${match[0]}".` - + ` Only upper-case letters, numbers, and underscores are allowed.`); + throw new Error( + `The argument name "${definition.argumentName}" contains an invalid character "${match[0]}".` + + ` Only upper-case letters, numbers, and underscores are allowed.` + ); } this.argumentName = definition.argumentName; } } - - - - - diff --git a/libraries/ts-command-line/src/parameters/CommandLineChoiceParameter.ts b/libraries/ts-command-line/src/parameters/CommandLineChoiceParameter.ts index aa18bd7b863..93f380b1ad3 100644 --- a/libraries/ts-command-line/src/parameters/CommandLineChoiceParameter.ts +++ b/libraries/ts-command-line/src/parameters/CommandLineChoiceParameter.ts @@ -22,11 +22,15 @@ export class CommandLineChoiceParameter extends CommandLineParameter { super(definition); if (definition.alternatives.length < 1) { - throw new Error(`When defining a choice parameter, the alternatives list must contain at least one value.`); + throw new Error( + `When defining a choice parameter, the alternatives list must contain at least one value.` + ); } if (definition.defaultValue && definition.alternatives.indexOf(definition.defaultValue) === -1) { - throw new Error(`The specified default value "${definition.defaultValue}"` - + ` is not one of the available options: ${definition.alternatives.toString()}`); + throw new Error( + `The specified default value "${definition.defaultValue}"` + + ` is not one of the available options: ${definition.alternatives.toString()}` + ); } this.alternatives = definition.alternatives; @@ -44,7 +48,8 @@ export class CommandLineChoiceParameter extends CommandLineParameter { * @internal */ // eslint-disable-next-line @typescript-eslint/no-explicit-any - public _setValue(data: any): void { // abstract + public _setValue(data: any): void { + // abstract if (data !== null && data !== undefined) { if (typeof data !== 'string') { this.reportInvalidData(data); @@ -59,8 +64,10 @@ export class CommandLineChoiceParameter extends CommandLineParameter { if (environmentValue !== undefined && environmentValue !== '') { if (this.alternatives.indexOf(environmentValue) < 0) { const choices: string = '"' + this.alternatives.join('", "') + '"'; - throw new Error(`Invalid value "${environmentValue}" for the environment variable` - + ` ${this.environmentVariable}. Valid choices are: ${choices}`); + throw new Error( + `Invalid value "${environmentValue}" for the environment variable` + + ` ${this.environmentVariable}. Valid choices are: ${choices}` + ); } this._value = environmentValue; return; @@ -79,7 +86,8 @@ export class CommandLineChoiceParameter extends CommandLineParameter { * {@inheritDoc CommandLineParameter._getSupplementaryNotes} * @internal */ - public _getSupplementaryNotes(supplementaryNotes: string[]): void { // virtual + public _getSupplementaryNotes(supplementaryNotes: string[]): void { + // virtual super._getSupplementaryNotes(supplementaryNotes); if (this.defaultValue !== undefined) { supplementaryNotes.push(`The default value is "${this.defaultValue}".`); @@ -104,4 +112,4 @@ export class CommandLineChoiceParameter extends CommandLineParameter { argList.push(this.value); } } -} \ No newline at end of file +} diff --git a/libraries/ts-command-line/src/parameters/CommandLineDefinition.ts b/libraries/ts-command-line/src/parameters/CommandLineDefinition.ts index 485474f78ab..012a342cb01 100644 --- a/libraries/ts-command-line/src/parameters/CommandLineDefinition.ts +++ b/libraries/ts-command-line/src/parameters/CommandLineDefinition.ts @@ -108,7 +108,7 @@ export interface ICommandLineChoiceDefinition extends IBaseCommandLineDefinition * * @public */ -export interface ICommandLineFlagDefinition extends IBaseCommandLineDefinition { } +export interface ICommandLineFlagDefinition extends IBaseCommandLineDefinition {} /** * For use with {@link CommandLineParameterProvider.defineIntegerParameter}, @@ -148,7 +148,7 @@ export interface ICommandLineStringDefinition extends IBaseCommandLineDefinition * * @public */ -export interface ICommandLineStringListDefinition extends IBaseCommandLineDefinitionWithArgument { } +export interface ICommandLineStringListDefinition extends IBaseCommandLineDefinitionWithArgument {} /** * For use with {@link CommandLineParameterProvider.defineCommandLineRemainder}, diff --git a/libraries/ts-command-line/src/parameters/CommandLineFlagParameter.ts b/libraries/ts-command-line/src/parameters/CommandLineFlagParameter.ts index e54d2c8dd33..1311228f5c0 100644 --- a/libraries/ts-command-line/src/parameters/CommandLineFlagParameter.ts +++ b/libraries/ts-command-line/src/parameters/CommandLineFlagParameter.ts @@ -26,7 +26,8 @@ export class CommandLineFlagParameter extends CommandLineParameter { * @internal */ // eslint-disable-next-line @typescript-eslint/no-explicit-any - public _setValue(data: any): void { // abstract + public _setValue(data: any): void { + // abstract if (data !== null && data !== undefined) { if (typeof data !== 'boolean') { this.reportInvalidData(data); @@ -46,8 +47,10 @@ export class CommandLineFlagParameter extends CommandLineParameter { const environmentValue: string | undefined = process.env[this.environmentVariable]; if (environmentValue !== undefined && environmentValue !== '') { if (environmentValue !== '0' && environmentValue !== '1') { - throw new Error(`Invalid value "${environmentValue}" for the environment variable` - + ` ${this.environmentVariable}. Valid choices are 0 or 1.`); + throw new Error( + `Invalid value "${environmentValue}" for the environment variable` + + ` ${this.environmentVariable}. Valid choices are 0 or 1.` + ); } this._value = environmentValue === '1'; return; diff --git a/libraries/ts-command-line/src/parameters/CommandLineIntegerParameter.ts b/libraries/ts-command-line/src/parameters/CommandLineIntegerParameter.ts index 739f9c76f57..f2ce3bca1a8 100644 --- a/libraries/ts-command-line/src/parameters/CommandLineIntegerParameter.ts +++ b/libraries/ts-command-line/src/parameters/CommandLineIntegerParameter.ts @@ -31,7 +31,8 @@ export class CommandLineIntegerParameter extends CommandLineParameterWithArgumen * @internal */ // eslint-disable-next-line @typescript-eslint/no-explicit-any - public _setValue(data: any): void { // abstract + public _setValue(data: any): void { + // abstract if (data !== null && data !== undefined) { if (typeof data !== 'number') { this.reportInvalidData(data); @@ -46,8 +47,10 @@ export class CommandLineIntegerParameter extends CommandLineParameterWithArgumen if (environmentValue !== undefined && environmentValue !== '') { const parsed: number = parseInt(environmentValue, 10); if (isNaN(parsed) || environmentValue.indexOf('.') >= 0) { - throw new Error(`Invalid value "${environmentValue}" for the environment variable` - + ` ${this.environmentVariable}. It must be an integer value.`); + throw new Error( + `Invalid value "${environmentValue}" for the environment variable` + + ` ${this.environmentVariable}. It must be an integer value.` + ); } this._value = parsed; return; @@ -66,7 +69,8 @@ export class CommandLineIntegerParameter extends CommandLineParameterWithArgumen * {@inheritDoc CommandLineParameter._getSupplementaryNotes} * @internal */ - public _getSupplementaryNotes(supplementaryNotes: string[]): void { // virtual + public _getSupplementaryNotes(supplementaryNotes: string[]): void { + // virtual super._getSupplementaryNotes(supplementaryNotes); if (this.defaultValue !== undefined) { supplementaryNotes.push(`The default value is ${this.defaultValue}.`); diff --git a/libraries/ts-command-line/src/parameters/CommandLineRemainder.ts b/libraries/ts-command-line/src/parameters/CommandLineRemainder.ts index ea207730654..d9bf4c07bc3 100644 --- a/libraries/ts-command-line/src/parameters/CommandLineRemainder.ts +++ b/libraries/ts-command-line/src/parameters/CommandLineRemainder.ts @@ -34,8 +34,9 @@ export class CommandLineRemainder { * @internal */ // eslint-disable-next-line @typescript-eslint/no-explicit-any - public _setValue(data: any): void { // abstract - if (!Array.isArray(data) || !data.every(x => typeof x === 'string')) { + public _setValue(data: any): void { + // abstract + if (!Array.isArray(data) || !data.every((x) => typeof x === 'string')) { throw new Error(`Unexpected data object for remainder: ` + JSON.stringify(data)); } diff --git a/libraries/ts-command-line/src/parameters/CommandLineStringListParameter.ts b/libraries/ts-command-line/src/parameters/CommandLineStringListParameter.ts index 53fd4401dad..19966171782 100644 --- a/libraries/ts-command-line/src/parameters/CommandLineStringListParameter.ts +++ b/libraries/ts-command-line/src/parameters/CommandLineStringListParameter.ts @@ -26,13 +26,14 @@ export class CommandLineStringListParameter extends CommandLineParameterWithArgu * @internal */ // eslint-disable-next-line @typescript-eslint/no-explicit-any - public _setValue(data: any): void { // abstract + public _setValue(data: any): void { + // abstract if (data !== null && data !== undefined) { if (!Array.isArray(data)) { this.reportInvalidData(data); } for (const arrayItem of data) { - if (typeof(arrayItem) !== 'string') { + if (typeof arrayItem !== 'string') { this.reportInvalidData(data); } } @@ -57,20 +58,29 @@ export class CommandLineStringListParameter extends CommandLineParameterWithArgu // than a custom delimiter. try { const parsedJson: unknown = JSON.parse(environmentValue); - if (!Array.isArray(parsedJson) - || !parsedJson.every(x => typeof x === 'string' || typeof x === "boolean" || typeof x === "number")) { - throw new Error(`The ${environmentValue} environment variable value must be a JSON ` - + ` array containing only strings, numbers, and booleans.`); + if ( + !Array.isArray(parsedJson) || + !parsedJson.every( + (x) => typeof x === 'string' || typeof x === 'boolean' || typeof x === 'number' + ) + ) { + throw new Error( + `The ${environmentValue} environment variable value must be a JSON ` + + ` array containing only strings, numbers, and booleans.` + ); } - this._values = parsedJson.map(x => x.toString()); + this._values = parsedJson.map((x) => x.toString()); } catch (ex) { - throw new Error(`The ${environmentValue} environment variable value looks like a JSON array` - + ` but failed to parse: ` + ex.message); + throw new Error( + `The ${environmentValue} environment variable value looks like a JSON array` + + ` but failed to parse: ` + + ex.message + ); } } else { // As a shorthand, a single value may be specified without JSON encoding, as long as it does not // start with the "[" character. - this._values = [ environmentValue ]; + this._values = [environmentValue]; } return; @@ -102,4 +112,4 @@ export class CommandLineStringListParameter extends CommandLineParameterWithArgu } } } -} \ No newline at end of file +} diff --git a/libraries/ts-command-line/src/parameters/CommandLineStringParameter.ts b/libraries/ts-command-line/src/parameters/CommandLineStringParameter.ts index bb9aeafcee5..93041c4a9c1 100644 --- a/libraries/ts-command-line/src/parameters/CommandLineStringParameter.ts +++ b/libraries/ts-command-line/src/parameters/CommandLineStringParameter.ts @@ -32,7 +32,8 @@ export class CommandLineStringParameter extends CommandLineParameterWithArgument * @internal */ // eslint-disable-next-line @typescript-eslint/no-explicit-any - public _setValue(data: any): void { // abstract + public _setValue(data: any): void { + // abstract if (data !== null && data !== undefined) { if (typeof data !== 'string') { this.reportInvalidData(data); @@ -64,7 +65,8 @@ export class CommandLineStringParameter extends CommandLineParameterWithArgument * {@inheritDoc CommandLineParameter._getSupplementaryNotes} * @internal */ - public _getSupplementaryNotes(supplementaryNotes: string[]): void { // virtual + public _getSupplementaryNotes(supplementaryNotes: string[]): void { + // virtual super._getSupplementaryNotes(supplementaryNotes); if (this.defaultValue !== undefined) { if (this.defaultValue.length < 160) { @@ -91,5 +93,4 @@ export class CommandLineStringParameter extends CommandLineParameterWithArgument argList.push(this.value); } } - } diff --git a/libraries/ts-command-line/src/providers/CommandLineAction.ts b/libraries/ts-command-line/src/providers/CommandLineAction.ts index b1a35eb9250..3ab75622ffa 100644 --- a/libraries/ts-command-line/src/providers/CommandLineAction.ts +++ b/libraries/ts-command-line/src/providers/CommandLineAction.ts @@ -60,8 +60,10 @@ export abstract class CommandLineAction extends CommandLineParameterProvider { super(); if (!CommandLineAction._actionNameRegExp.test(options.actionName)) { - throw new Error(`Invalid action name "${options.actionName}". ` - + `The name must be comprised of lower-case words optionally separated by hyphens or colons.`); + throw new Error( + `Invalid action name "${options.actionName}". ` + + `The name must be comprised of lower-case words optionally separated by hyphens or colons.` + ); } this.actionName = options.actionName; @@ -78,7 +80,7 @@ export abstract class CommandLineAction extends CommandLineParameterProvider { public _buildParser(actionsSubParser: argparse.SubParser): void { this._argumentParser = actionsSubParser.addParser(this.actionName, { help: this.summary, - description: this.documentation + description: this.documentation, }); this.onDefineParameters(); @@ -104,7 +106,8 @@ export abstract class CommandLineAction extends CommandLineParameterProvider { * {@inheritDoc CommandLineParameterProvider._getArgumentParser} * @internal */ - protected _getArgumentParser(): argparse.ArgumentParser { // override + protected _getArgumentParser(): argparse.ArgumentParser { + // override 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'); diff --git a/libraries/ts-command-line/src/providers/CommandLineParameterProvider.ts b/libraries/ts-command-line/src/providers/CommandLineParameterProvider.ts index 4341eea6f81..25e0d8d06b2 100644 --- a/libraries/ts-command-line/src/providers/CommandLineParameterProvider.ts +++ b/libraries/ts-command-line/src/providers/CommandLineParameterProvider.ts @@ -8,7 +8,7 @@ import { ICommandLineStringListDefinition, ICommandLineIntegerDefinition, ICommandLineChoiceDefinition, - ICommandLineRemainderDefinition + ICommandLineRemainderDefinition, } from '../parameters/CommandLineDefinition'; import { CommandLineParameter, @@ -175,7 +175,9 @@ export abstract class CommandLineParameterProvider { * example-tool --add file1.txt --add file2.txt --add file3.txt * ``` */ - public defineStringListParameter(definition: ICommandLineStringListDefinition): CommandLineStringListParameter { + public defineStringListParameter( + definition: ICommandLineStringListDefinition + ): CommandLineStringListParameter { const parameter: CommandLineStringListParameter = new CommandLineStringListParameter(definition); this._defineParameter(parameter); return parameter; @@ -205,7 +207,7 @@ export abstract class CommandLineParameterProvider { const argparseOptions: argparse.ArgumentOptions = { help: this._remainder.description, nargs: argparse.Const.REMAINDER, - metavar: '"..."' + metavar: '"..."', }; this._getArgumentParser().addArgument(argparse.Const.REMAINDER, argparseOptions); @@ -258,24 +260,29 @@ export abstract class CommandLineParameterProvider { return 'key_' + (CommandLineParameterProvider._keyCounter++).toString(); } - private _getParameter(parameterLongName: string, - expectedKind: CommandLineParameterKind): T { - + private _getParameter( + parameterLongName: string, + expectedKind: CommandLineParameterKind + ): T { const parameter: CommandLineParameter | undefined = this._parametersByLongName.get(parameterLongName); if (!parameter) { throw new Error(`The parameter "${parameterLongName}" is not defined`); } if (parameter.kind !== expectedKind) { - throw new Error(`The parameter "${parameterLongName}" is of type "${CommandLineParameterKind[parameter.kind]}"` - + ` whereas the caller was expecting "${CommandLineParameterKind[expectedKind]}".`); + throw new Error( + `The parameter "${parameterLongName}" is of type "${CommandLineParameterKind[parameter.kind]}"` + + ` whereas the caller was expecting "${CommandLineParameterKind[expectedKind]}".` + ); } return parameter as T; } private _defineParameter(parameter: CommandLineParameter): void { if (this._remainder) { - throw new Error('defineCommandLineRemainder() was already called for this provider;' - + ' no further parameters can be defined'); + throw new Error( + 'defineCommandLineRemainder() was already called for this provider;' + + ' no further parameters can be defined' + ); } const names: string[] = []; @@ -305,7 +312,7 @@ export abstract class CommandLineParameterProvider { help: finalDescription, dest: parameter._parserKey, metavar: (parameter as CommandLineParameterWithArgument).argumentName || undefined, - required: parameter.required + required: parameter.required, }; switch (parameter.kind) { diff --git a/libraries/ts-command-line/src/providers/CommandLineParser.ts b/libraries/ts-command-line/src/providers/CommandLineParser.ts index 81425907ba7..cbfe6784f2d 100644 --- a/libraries/ts-command-line/src/providers/CommandLineParser.ts +++ b/libraries/ts-command-line/src/providers/CommandLineParser.ts @@ -6,7 +6,7 @@ import * as colors from 'colors'; import { CommandLineAction } from './CommandLineAction'; import { CommandLineParameterProvider, ICommandLineParserData } from './CommandLineParameterProvider'; -import { CommandLineParserExitError, CustomArgumentParser} from './CommandLineParserExitError'; +import { CommandLineParserExitError, CustomArgumentParser } from './CommandLineParserExitError'; /** * Options for the {@link CommandLineParser} constructor. @@ -60,14 +60,15 @@ export abstract class CommandLineParser extends CommandLineParameterProvider { this._options = options; this._actions = []; - this._actionsByName = new Map(); + this._actionsByName = new Map(); this._argumentParser = new CustomArgumentParser({ addHelp: true, prog: this._options.toolFilename, description: this._options.toolDescription, - epilog: colors.bold('For detailed help about a specific command, use:' - + ` ${this._options.toolFilename} -h`) + epilog: colors.bold( + 'For detailed help about a specific command, use:' + ` ${this._options.toolFilename} -h` + ), }); this.onDefineParameters(); @@ -87,7 +88,7 @@ export abstract class CommandLineParser extends CommandLineParameterProvider { if (!this._actionsSubParser) { this._actionsSubParser = this._argumentParser.addSubparsers({ metavar: '', - dest: 'action' + dest: 'action', }); } @@ -134,27 +135,29 @@ export abstract class CommandLineParser extends CommandLineParameterProvider { * the process.argv will be used */ public execute(args?: string[]): Promise { - return this.executeWithoutErrorHandling(args).then(() => { - return true; - }).catch((err) => { - if (err instanceof CommandLineParserExitError) { - // executeWithoutErrorHandling() handles the successful cases, - // so here we can assume err has a nonzero exit code - if (err.message) { - console.error(err.message); - } - if (!process.exitCode) { - process.exitCode = err.exitCode; - } - } else { - const message: string = (err.message || 'An unknown error occurred').trim(); - console.error(colors.red('Error: ' + message)); - if (!process.exitCode) { - process.exitCode = 1; + return this.executeWithoutErrorHandling(args) + .then(() => { + return true; + }) + .catch((err) => { + if (err instanceof CommandLineParserExitError) { + // executeWithoutErrorHandling() handles the successful cases, + // so here we can assume err has a nonzero exit code + if (err.message) { + console.error(err.message); + } + if (!process.exitCode) { + process.exitCode = err.exitCode; + } + } else { + const message: string = (err.message || 'An unknown error occurred').trim(); + console.error(colors.red('Error: ' + message)); + if (!process.exitCode) { + process.exitCode = 1; + } } - } - return false; - }); + return false; + }); } /** @@ -193,7 +196,7 @@ export abstract class CommandLineParser extends CommandLineParameterProvider { } } if (this.actions.length > 0 && !this.selectedAction) { - const actions: string[] = this.actions.map(x => x.actionName); + const actions: string[] = this.actions.map((x) => x.actionName); throw new Error(`An action must be specified (${actions.join(', ')})`); } @@ -223,7 +226,8 @@ export abstract class CommandLineParser extends CommandLineParameterProvider { * {@inheritDoc CommandLineParameterProvider._getArgumentParser} * @internal */ - protected _getArgumentParser(): argparse.ArgumentParser { // override + protected _getArgumentParser(): argparse.ArgumentParser { + // override return this._argumentParser; } diff --git a/libraries/ts-command-line/src/providers/CommandLineParserExitError.ts b/libraries/ts-command-line/src/providers/CommandLineParserExitError.ts index 9f600a91201..6c0bd9bf130 100644 --- a/libraries/ts-command-line/src/providers/CommandLineParserExitError.ts +++ b/libraries/ts-command-line/src/providers/CommandLineParserExitError.ts @@ -20,11 +20,13 @@ export class CommandLineParserExitError extends Error { } export class CustomArgumentParser extends argparse.ArgumentParser { - public exit(status: number, message: string): void { // override + public exit(status: number, message: string): void { + // override throw new CommandLineParserExitError(status, message); } - public error(err: Error | string): void { // override + public error(err: Error | string): void { + // override // Ensure the ParserExitError bubbles up to the top without any special processing if (err instanceof CommandLineParserExitError) { throw err; @@ -32,4 +34,4 @@ export class CustomArgumentParser extends argparse.ArgumentParser { super.error(err); } -} \ No newline at end of file +} diff --git a/libraries/ts-command-line/src/providers/DynamicCommandLineAction.ts b/libraries/ts-command-line/src/providers/DynamicCommandLineAction.ts index c888baa0509..d1143c17580 100644 --- a/libraries/ts-command-line/src/providers/DynamicCommandLineAction.ts +++ b/libraries/ts-command-line/src/providers/DynamicCommandLineAction.ts @@ -7,11 +7,13 @@ import { CommandLineAction } from './CommandLineAction'; * @public */ export class DynamicCommandLineAction extends CommandLineAction { - protected onDefineParameters(): void { // abstract + protected onDefineParameters(): void { + // abstract // (handled by the external code) } - protected onExecute(): Promise { // abstract + protected onExecute(): Promise { + // abstract // (handled by the external code) return Promise.resolve(); } diff --git a/libraries/ts-command-line/src/providers/DynamicCommandLineParser.ts b/libraries/ts-command-line/src/providers/DynamicCommandLineParser.ts index 3e9fe4adac1..b115c00aa86 100644 --- a/libraries/ts-command-line/src/providers/DynamicCommandLineParser.ts +++ b/libraries/ts-command-line/src/providers/DynamicCommandLineParser.ts @@ -7,6 +7,7 @@ import { CommandLineParser } from './CommandLineParser'; * @public */ export class DynamicCommandLineParser extends CommandLineParser { - protected onDefineParameters(): void { // abstract + protected onDefineParameters(): void { + // abstract } } diff --git a/libraries/ts-command-line/src/test/ActionlessParser.test.ts b/libraries/ts-command-line/src/test/ActionlessParser.test.ts index 3b5e594115a..6b8ee5156e6 100644 --- a/libraries/ts-command-line/src/test/ActionlessParser.test.ts +++ b/libraries/ts-command-line/src/test/ActionlessParser.test.ts @@ -9,20 +9,19 @@ class TestCommandLine extends CommandLineParser { public constructor() { super({ toolFilename: 'example', - toolDescription: 'An example project' + toolDescription: 'An example project', }); } protected onDefineParameters(): void { this.flag = this.defineFlagParameter({ parameterLongName: '--flag', - description: 'The flag' + description: 'The flag', }); } } describe('Actionless CommandLineParser', () => { - it('parses a flag', () => { const commandLineParser: TestCommandLine = new TestCommandLine(); @@ -36,7 +35,7 @@ describe('Actionless CommandLineParser', () => { const commandLineParser: TestCommandLine = new TestCommandLine(); commandLineParser.defineCommandLineRemainder({ - description: 'remainder description' + description: 'remainder description', }); return commandLineParser.execute(['--flag', 'the', 'remaining', 'args']).then(() => { @@ -45,5 +44,4 @@ describe('Actionless CommandLineParser', () => { expect(commandLineParser.remainder!.values).toEqual(['the', 'remaining', 'args']); }); }); - }); diff --git a/libraries/ts-command-line/src/test/CommandLineParameter.test.ts b/libraries/ts-command-line/src/test/CommandLineParameter.test.ts index b922031cdca..40a9ed168b7 100644 --- a/libraries/ts-command-line/src/test/CommandLineParameter.test.ts +++ b/libraries/ts-command-line/src/test/CommandLineParameter.test.ts @@ -6,22 +6,20 @@ import * as colors from 'colors'; import { CommandLineAction, CommandLineParser, DynamicCommandLineParser, DynamicCommandLineAction } from '..'; function createParser(): DynamicCommandLineParser { - const commandLineParser: DynamicCommandLineParser = new DynamicCommandLineParser( - { - toolFilename: 'example', - toolDescription: 'An example project' - } - ); + const commandLineParser: DynamicCommandLineParser = new DynamicCommandLineParser({ + toolFilename: 'example', + toolDescription: 'An example project', + }); commandLineParser.defineFlagParameter({ parameterLongName: '--global-flag', parameterShortName: '-g', - description: 'A flag that affects all actions' + description: 'A flag that affects all actions', }); const action: DynamicCommandLineAction = new DynamicCommandLineAction({ actionName: 'do:the-job', summary: 'does the job', - documentation: 'a longer description' + documentation: 'a longer description', }); commandLineParser.addAction(action); @@ -30,15 +28,15 @@ function createParser(): DynamicCommandLineParser { parameterLongName: '--choice', parameterShortName: '-c', description: 'A choice', - alternatives: [ 'one', 'two', 'three', 'default' ], - environmentVariable: 'ENV_CHOICE' + alternatives: ['one', 'two', 'three', 'default'], + environmentVariable: 'ENV_CHOICE', }); action.defineChoiceParameter({ parameterLongName: '--choice-with-default', description: 'A choice with a default. This description ends with a "quoted word"', - alternatives: [ 'one', 'two', 'three', 'default' ], + alternatives: ['one', 'two', 'three', 'default'], environmentVariable: 'ENV_CHOICE2', - defaultValue: 'default' + defaultValue: 'default', }); // Flag @@ -46,7 +44,7 @@ function createParser(): DynamicCommandLineParser { parameterLongName: '--flag', parameterShortName: '-f', description: 'A flag', - environmentVariable: 'ENV_FLAG' + environmentVariable: 'ENV_FLAG', }); // Integer @@ -55,14 +53,14 @@ function createParser(): DynamicCommandLineParser { parameterShortName: '-i', description: 'An integer', argumentName: 'NUMBER', - environmentVariable: 'ENV_INTEGER' + environmentVariable: 'ENV_INTEGER', }); action.defineIntegerParameter({ parameterLongName: '--integer-with-default', description: 'An integer with a default', argumentName: 'NUMBER', environmentVariable: 'ENV_INTEGER2', - defaultValue: 123 + defaultValue: 123, }); action.defineIntegerParameter({ parameterLongName: '--integer-required', @@ -70,7 +68,7 @@ function createParser(): DynamicCommandLineParser { argumentName: 'NUMBER', // Not yet supported // environmentVariable: 'ENV_INTEGER_REQUIRED', - required: true + required: true, }); // String @@ -79,14 +77,14 @@ function createParser(): DynamicCommandLineParser { parameterShortName: '-s', description: 'A string', argumentName: 'TEXT', - environmentVariable: 'ENV_STRING' + environmentVariable: 'ENV_STRING', }); action.defineStringParameter({ parameterLongName: '--string-with-default', description: 'A string with a default', argumentName: 'TEXT', environmentVariable: 'ENV_STRING2', - defaultValue: '123' + defaultValue: '123', }); // String List @@ -95,7 +93,7 @@ function createParser(): DynamicCommandLineParser { parameterShortName: '-l', description: 'This parameter be specified multiple times to make a list of strings', argumentName: 'LIST_ITEM', - environmentVariable: 'ENV_STRING_LIST' + environmentVariable: 'ENV_STRING_LIST', }); return commandLineParser; } @@ -120,7 +118,7 @@ const snapshotPropertyNames: string[] = [ 'environmentVariable', 'required', 'defaultValue', - 'values' + 'values', ]; describe('CommandLineParameter', () => { @@ -143,13 +141,19 @@ describe('CommandLineParameter', () => { const args: string[] = [ '--global-flag', 'do:the-job', - '--choice', 'two', + '--choice', + 'two', '--flag', - '--integer', '123', - '--integer-required', '321', - '--string', 'hello', - '--string-list', 'first', - '--string-list', 'second' + '--integer', + '123', + '--integer-required', + '321', + '--string', + 'hello', + '--string-list', + 'first', + '--string-list', + 'second', ]; return commandLineParser.execute(args).then(() => { @@ -160,22 +164,13 @@ describe('CommandLineParameter', () => { snapshotPropertyNames ); - expectPropertiesToMatchSnapshot( - action.getChoiceParameter('--choice'), - snapshotPropertyNames - ); + expectPropertiesToMatchSnapshot(action.getChoiceParameter('--choice'), snapshotPropertyNames); expectPropertiesToMatchSnapshot( action.getChoiceParameter('--choice-with-default'), snapshotPropertyNames ); - expectPropertiesToMatchSnapshot( - action.getFlagParameter('--flag'), - snapshotPropertyNames - ); - expectPropertiesToMatchSnapshot( - action.getIntegerParameter('--integer'), - snapshotPropertyNames - ); + expectPropertiesToMatchSnapshot(action.getFlagParameter('--flag'), snapshotPropertyNames); + expectPropertiesToMatchSnapshot(action.getIntegerParameter('--integer'), snapshotPropertyNames); expectPropertiesToMatchSnapshot( action.getIntegerParameter('--integer-with-default'), snapshotPropertyNames @@ -184,18 +179,12 @@ describe('CommandLineParameter', () => { action.getIntegerParameter('--integer-required'), snapshotPropertyNames ); - expectPropertiesToMatchSnapshot( - action.getStringParameter('--string'), - snapshotPropertyNames - ); + expectPropertiesToMatchSnapshot(action.getStringParameter('--string'), snapshotPropertyNames); expectPropertiesToMatchSnapshot( action.getStringParameter('--string-with-default'), snapshotPropertyNames ); - expectPropertiesToMatchSnapshot( - action.getStringListParameter('--string-list'), - snapshotPropertyNames - ); + expectPropertiesToMatchSnapshot(action.getStringListParameter('--string-list'), snapshotPropertyNames); const copiedArgs: string[] = []; for (const parameter of action.parameters) { @@ -209,7 +198,7 @@ describe('CommandLineParameter', () => { it('parses an input with NO parameters', () => { const commandLineParser: CommandLineParser = createParser(); const action: CommandLineAction = commandLineParser.getAction('do:the-job'); - const args: string[] = [ 'do:the-job', '--integer-required', '123']; + const args: string[] = ['do:the-job', '--integer-required', '123']; return commandLineParser.execute(args).then(() => { expect(commandLineParser.selectedAction).toBe(action); @@ -219,22 +208,13 @@ describe('CommandLineParameter', () => { snapshotPropertyNames ); - expectPropertiesToMatchSnapshot( - action.getChoiceParameter('--choice'), - snapshotPropertyNames - ); + expectPropertiesToMatchSnapshot(action.getChoiceParameter('--choice'), snapshotPropertyNames); expectPropertiesToMatchSnapshot( action.getChoiceParameter('--choice-with-default'), snapshotPropertyNames ); - expectPropertiesToMatchSnapshot( - action.getFlagParameter('--flag'), - snapshotPropertyNames - ); - expectPropertiesToMatchSnapshot( - action.getIntegerParameter('--integer'), - snapshotPropertyNames - ); + expectPropertiesToMatchSnapshot(action.getFlagParameter('--flag'), snapshotPropertyNames); + expectPropertiesToMatchSnapshot(action.getIntegerParameter('--integer'), snapshotPropertyNames); expectPropertiesToMatchSnapshot( action.getIntegerParameter('--integer-with-default'), snapshotPropertyNames @@ -243,18 +223,12 @@ describe('CommandLineParameter', () => { action.getIntegerParameter('--integer-required'), snapshotPropertyNames ); - expectPropertiesToMatchSnapshot( - action.getStringParameter('--string'), - snapshotPropertyNames - ); + expectPropertiesToMatchSnapshot(action.getStringParameter('--string'), snapshotPropertyNames); expectPropertiesToMatchSnapshot( action.getStringParameter('--string-with-default'), snapshotPropertyNames ); - expectPropertiesToMatchSnapshot( - action.getStringListParameter('--string-list'), - snapshotPropertyNames - ); + expectPropertiesToMatchSnapshot(action.getStringListParameter('--string-list'), snapshotPropertyNames); const copiedArgs: string[] = []; for (const parameter of action.parameters) { @@ -273,10 +247,10 @@ describe('CommandLineParameter', () => { parameterLongName: '--json-string-list', description: 'Test JSON parsing', argumentName: 'LIST_ITEM', - environmentVariable: 'ENV_JSON_STRING_LIST' + environmentVariable: 'ENV_JSON_STRING_LIST', }); - const args: string[] = [ 'do:the-job', '--integer-required', '1' ]; + const args: string[] = ['do:the-job', '--integer-required', '1']; process.env.ENV_CHOICE = 'one'; process.env.ENV_CHOICE2 = 'two'; diff --git a/libraries/ts-command-line/src/test/CommandLineParser.test.ts b/libraries/ts-command-line/src/test/CommandLineParser.test.ts index b88ceeac39d..5331252c265 100644 --- a/libraries/ts-command-line/src/test/CommandLineParser.test.ts +++ b/libraries/ts-command-line/src/test/CommandLineParser.test.ts @@ -11,7 +11,7 @@ class TestAction extends CommandLineAction { super({ actionName: 'do:the-job', summary: 'does the job', - documentation: 'a longer description' + documentation: 'a longer description', }); } @@ -24,7 +24,7 @@ class TestAction extends CommandLineAction { protected onDefineParameters(): void { this._flag = this.defineFlagParameter({ parameterLongName: '--flag', - description: 'The flag' + description: 'The flag', }); } } @@ -33,7 +33,7 @@ class TestCommandLine extends CommandLineParser { public constructor() { super({ toolFilename: 'example', - toolDescription: 'An example project' + toolDescription: 'An example project', }); this.addAction(new TestAction()); @@ -45,7 +45,6 @@ class TestCommandLine extends CommandLineParser { } describe('CommandLineParser', () => { - it('executes an action', () => { const commandLineParser: TestCommandLine = new TestCommandLine(); @@ -57,5 +56,4 @@ describe('CommandLineParser', () => { expect(action.done).toBe(true); }); }); - }); diff --git a/libraries/ts-command-line/src/test/CommandLineRemainder.test.ts b/libraries/ts-command-line/src/test/CommandLineRemainder.test.ts index ca07ba2142c..d51f0175868 100644 --- a/libraries/ts-command-line/src/test/CommandLineRemainder.test.ts +++ b/libraries/ts-command-line/src/test/CommandLineRemainder.test.ts @@ -9,33 +9,31 @@ import { DynamicCommandLineParser } from '../providers/DynamicCommandLineParser' import { DynamicCommandLineAction } from '../providers/DynamicCommandLineAction'; function createParser(): DynamicCommandLineParser { - const commandLineParser: DynamicCommandLineParser = new DynamicCommandLineParser( - { - toolFilename: 'example', - toolDescription: 'An example project' - } - ); + const commandLineParser: DynamicCommandLineParser = new DynamicCommandLineParser({ + toolFilename: 'example', + toolDescription: 'An example project', + }); commandLineParser.defineFlagParameter({ parameterLongName: '--verbose', - description: 'A flag that affects all actions' + description: 'A flag that affects all actions', }); const action: DynamicCommandLineAction = new DynamicCommandLineAction({ actionName: 'run', summary: 'does the job', - documentation: 'a longer description' + documentation: 'a longer description', }); commandLineParser.addAction(action); action.defineStringParameter({ parameterLongName: '--title', description: 'A string', - argumentName: 'TEXT' + argumentName: 'TEXT', }); // Although this is defined BEFORE the parameter, but it should still capture the end action.defineCommandLineRemainder({ - description: 'The action remainder' + description: 'The action remainder', }); return commandLineParser; @@ -57,7 +55,7 @@ describe('CommandLineRemainder', () => { it('parses an action input with remainder', () => { const commandLineParser: CommandLineParser = createParser(); const action: CommandLineAction = commandLineParser.getAction('run'); - const args: string[] = [ 'run', '--title', 'The title', 'the', 'remaining', 'args']; + const args: string[] = ['run', '--title', 'The title', 'the', 'remaining', 'args']; return commandLineParser.execute(args).then(() => { expect(commandLineParser.selectedAction).toBe(action); @@ -74,5 +72,4 @@ describe('CommandLineRemainder', () => { expect(copiedArgs).toMatchSnapshot(); }); }); - }); diff --git a/libraries/ts-command-line/src/test/DynamicCommandLineParser.test.ts b/libraries/ts-command-line/src/test/DynamicCommandLineParser.test.ts index 3a2b4c9e8a0..8fa32522a19 100644 --- a/libraries/ts-command-line/src/test/DynamicCommandLineParser.test.ts +++ b/libraries/ts-command-line/src/test/DynamicCommandLineParser.test.ts @@ -4,24 +4,21 @@ import { DynamicCommandLineParser, DynamicCommandLineAction, CommandLineFlagParameter } from '..'; describe('DynamicCommandLineParser', () => { - it('parses an action', () => { - const commandLineParser: DynamicCommandLineParser = new DynamicCommandLineParser( - { - toolFilename: 'example', - toolDescription: 'An example project' - } - ); + const commandLineParser: DynamicCommandLineParser = new DynamicCommandLineParser({ + toolFilename: 'example', + toolDescription: 'An example project', + }); const action: DynamicCommandLineAction = new DynamicCommandLineAction({ actionName: 'do:the-job', summary: 'does the job', - documentation: 'a longer description' + documentation: 'a longer description', }); commandLineParser.addAction(action); action.defineFlagParameter({ parameterLongName: '--flag', - description: 'The flag' + description: 'The flag', }); return commandLineParser.execute(['do:the-job', '--flag']).then(() => { diff --git a/libraries/ts-command-line/tsconfig.json b/libraries/ts-command-line/tsconfig.json index 824a88b71e5..46bc07fdda9 100644 --- a/libraries/ts-command-line/tsconfig.json +++ b/libraries/ts-command-line/tsconfig.json @@ -2,9 +2,6 @@ "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "jest", - "node" - ] + "types": ["jest", "node"] } } diff --git a/libraries/typings-generator/.eslintrc.js b/libraries/typings-generator/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/libraries/typings-generator/.eslintrc.js +++ b/libraries/typings-generator/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/libraries/typings-generator/src/StringValuesTypingsGenerator.ts b/libraries/typings-generator/src/StringValuesTypingsGenerator.ts index 3919b520c5f..6c7a64b91f0 100644 --- a/libraries/typings-generator/src/StringValuesTypingsGenerator.ts +++ b/libraries/typings-generator/src/StringValuesTypingsGenerator.ts @@ -3,10 +3,7 @@ import { EOL } from 'os'; -import { - ITypingsGeneratorOptions, - TypingsGenerator -} from './TypingsGenerator'; +import { ITypingsGeneratorOptions, TypingsGenerator } from './TypingsGenerator'; /** * @public @@ -43,14 +40,15 @@ export class StringValuesTypingsGenerator extends TypingsGenerator { super({ ...options, parseAndGenerateTypings: (fileContents: string, filePath: string) => { - const stringValueTypings: IStringValueTypings = options.parseAndGenerateTypings(fileContents, filePath); + const stringValueTypings: IStringValueTypings = options.parseAndGenerateTypings( + fileContents, + filePath + ); const outputLines: string[] = []; let indent: string = ''; if (options.exportAsDefault) { - outputLines.push( - `export interface ${EXPORT_AS_DEFAULT_INTERFACE_NAME} {` - ); + outputLines.push(`export interface ${EXPORT_AS_DEFAULT_INTERFACE_NAME} {`); indent = ' '; } @@ -67,15 +65,9 @@ export class StringValuesTypingsGenerator extends TypingsGenerator { } if (options.exportAsDefault) { - outputLines.push( - `${indent}${exportName}: string;`, - '' - ); + outputLines.push(`${indent}${exportName}: string;`, ''); } else { - outputLines.push( - `export declare const ${exportName}: string;`, - '' - ); + outputLines.push(`export declare const ${exportName}: string;`, ''); } } @@ -89,7 +81,7 @@ export class StringValuesTypingsGenerator extends TypingsGenerator { } return outputLines.join(EOL); - } + }, }); } } diff --git a/libraries/typings-generator/src/TypingsGenerator.ts b/libraries/typings-generator/src/TypingsGenerator.ts index 959ade6d5fa..a9b63d7ac4d 100644 --- a/libraries/typings-generator/src/TypingsGenerator.ts +++ b/libraries/typings-generator/src/TypingsGenerator.ts @@ -6,7 +6,7 @@ import { Terminal, ConsoleTerminalProvider, Path, - NewlineKind + NewlineKind, } from '@rushstack/node-core-library'; import * as glob from 'glob'; import * as path from 'path'; @@ -35,7 +35,7 @@ export class TypingsGenerator { public constructor(options: ITypingsGeneratorOptions) { this._options = { - ...options + ...options, }; if (!this._options.generatedTsFolder) { @@ -72,20 +72,19 @@ export class TypingsGenerator { public generateTypings(): void { FileSystem.ensureEmptyFolder(this._options.generatedTsFolder); - const filesToIgnore: Set = new Set((this._options.filesToIgnore!).map((fileToIgnore) => { - return path.resolve(this._options.srcFolder, fileToIgnore); - })); - - const filePaths: string[] = glob.sync( - path.join('**', `*+(${this._options.fileExtensions.join('|')})`), - { - cwd: this._options.srcFolder, - absolute: true, - nosort: true, - nodir: true - } + const filesToIgnore: Set = new Set( + this._options.filesToIgnore!.map((fileToIgnore) => { + return path.resolve(this._options.srcFolder, fileToIgnore); + }) ); + const filePaths: string[] = glob.sync(path.join('**', `*+(${this._options.fileExtensions.join('|')})`), { + cwd: this._options.srcFolder, + absolute: true, + nosort: true, + nodir: true, + }); + for (let filePath of filePaths) { filePath = path.resolve(this._options.srcFolder, filePath); @@ -105,7 +104,9 @@ export class TypingsGenerator { const watcher: chokidar.FSWatcher = chokidar.watch( this._options.fileExtensions.map((fileExtension) => path.join(globBase, `*${fileExtension}`)) ); - const boundGenerateTypingsFunction: (filePath: string) => void = this._parseFileAndGenerateTypings.bind(this); + const boundGenerateTypingsFunction: (filePath: string) => void = this._parseFileAndGenerateTypings.bind( + this + ); watcher.on('add', boundGenerateTypingsFunction); watcher.on('change', boundGenerateTypingsFunction); watcher.on('unlink', (filePath) => { @@ -123,15 +124,13 @@ export class TypingsGenerator { const prefixedTypingsData: string = [ '// This file was generated by a tool. Modifying it will produce unexpected behavior', '', - typingsData + typingsData, ].join(EOL); - FileSystem.writeFile( - generatedTsFilePath, - prefixedTypingsData, - { ensureFolderExists: true, convertLineEndings: NewlineKind.OsDefault } - ); - + FileSystem.writeFile(generatedTsFilePath, prefixedTypingsData, { + ensureFolderExists: true, + convertLineEndings: NewlineKind.OsDefault, + }); } catch (e) { this._options.terminal!.writeError( `Error occurred parsing and generating typings for file "${locFilePath}": ${e}` diff --git a/libraries/typings-generator/src/index.ts b/libraries/typings-generator/src/index.ts index b28052933b4..b01e103822a 100644 --- a/libraries/typings-generator/src/index.ts +++ b/libraries/typings-generator/src/index.ts @@ -1,14 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export { - ITypingsGeneratorOptions, - TypingsGenerator -} from './TypingsGenerator'; +export { ITypingsGeneratorOptions, TypingsGenerator } from './TypingsGenerator'; export { IStringValueTyping, IStringValueTypings, IStringValuesTypingsGeneratorOptions, - StringValuesTypingsGenerator + StringValuesTypingsGenerator, } from './StringValuesTypingsGenerator'; diff --git a/repo-scripts/doc-plugin-rush-stack/.eslintrc.js b/repo-scripts/doc-plugin-rush-stack/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/repo-scripts/doc-plugin-rush-stack/.eslintrc.js +++ b/repo-scripts/doc-plugin-rush-stack/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/repo-scripts/doc-plugin-rush-stack/src/RushStackFeature.ts b/repo-scripts/doc-plugin-rush-stack/src/RushStackFeature.ts index 07307dd6c36..136aeb50ac8 100644 --- a/repo-scripts/doc-plugin-rush-stack/src/RushStackFeature.ts +++ b/repo-scripts/doc-plugin-rush-stack/src/RushStackFeature.ts @@ -8,7 +8,7 @@ import { ApiItem } from '@microsoft/api-extractor-model'; import { MarkdownDocumenterFeature, IMarkdownDocumenterFeatureOnBeforeWritePageArgs, - IMarkdownDocumenterFeatureOnFinishedArgs + IMarkdownDocumenterFeatureOnFinishedArgs, } from '@microsoft/api-documenter'; interface INavigationNode { @@ -35,7 +35,7 @@ export class RushStackFeature extends MarkdownDocumenterFeature { 'navigation_source: api_nav', 'improve_this_button: false', '---', - '' + '', ].join('\n'); eventArgs.pageContent = header + eventArgs.pageContent; @@ -47,9 +47,9 @@ export class RushStackFeature extends MarkdownDocumenterFeature { api_nav: [ { title: 'API Reference', - url: '/pages/api/' - } - ] + url: '/pages/api/', + }, + ], }; this._buildNavigation(navigationFile.api_nav, this.context.apiModel); @@ -64,7 +64,9 @@ export class RushStackFeature extends MarkdownDocumenterFeature { if (this._apiItemsWithPages.has(apiItem)) { const newNode: INavigationNode = { title: apiItem.displayName, - url: path.posix.join('/pages/api/', this.context.documenter.getLinkForApiItem(apiItem)!).replace(/\.md$/, '') + url: path.posix + .join('/pages/api/', this.context.documenter.getLinkForApiItem(apiItem)!) + .replace(/\.md$/, ''), }; parentNodes.push(newNode); diff --git a/repo-scripts/doc-plugin-rush-stack/src/index.ts b/repo-scripts/doc-plugin-rush-stack/src/index.ts index 682e121ef88..e3899db1b29 100644 --- a/repo-scripts/doc-plugin-rush-stack/src/index.ts +++ b/repo-scripts/doc-plugin-rush-stack/src/index.ts @@ -10,7 +10,7 @@ export const apiDocumenterPluginManifest: IApiDocumenterPluginManifest = { { featureName: 'rush-stack-markdown-documenter', kind: 'MarkdownDocumenterFeature', - subclass: RushStackFeature - } - ] + subclass: RushStackFeature, + }, + ], }; diff --git a/repo-scripts/doc-plugin-rush-stack/tsconfig.json b/repo-scripts/doc-plugin-rush-stack/tsconfig.json index 0085de105f6..51c71c4bdec 100644 --- a/repo-scripts/doc-plugin-rush-stack/tsconfig.json +++ b/repo-scripts/doc-plugin-rush-stack/tsconfig.json @@ -2,8 +2,6 @@ "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "node" - ] + "types": ["node"] } } diff --git a/repo-scripts/generate-api-docs/api-documenter.json b/repo-scripts/generate-api-docs/api-documenter.json index 4847e0e9e26..a7d702a36c7 100644 --- a/repo-scripts/generate-api-docs/api-documenter.json +++ b/repo-scripts/generate-api-docs/api-documenter.json @@ -4,7 +4,7 @@ "plugins": [ { "packageName": "doc-plugin-rush-stack", - "enabledFeatureNames": [ "rush-stack-markdown-documenter" ] + "enabledFeatureNames": ["rush-stack-markdown-documenter"] } ] } diff --git a/repo-scripts/repo-toolbox/.eslintrc.js b/repo-scripts/repo-toolbox/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/repo-scripts/repo-toolbox/.eslintrc.js +++ b/repo-scripts/repo-toolbox/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/repo-scripts/repo-toolbox/src/ReadmeAction.ts b/repo-scripts/repo-toolbox/src/ReadmeAction.ts index c708a03eaf9..abd4a94c6de 100644 --- a/repo-scripts/repo-toolbox/src/ReadmeAction.ts +++ b/repo-scripts/repo-toolbox/src/ReadmeAction.ts @@ -11,7 +11,7 @@ export class ReadmeAction extends CommandLineAction { super({ actionName: 'readme', summary: 'Generates README.md project table based on rush.json inventory', - documentation: 'Use this to update the repo\'s README.md' + documentation: "Use this to update the repo's README.md", }); } @@ -19,20 +19,20 @@ export class ReadmeAction extends CommandLineAction { return project.shouldPublish || !!project.versionPolicyName; } - protected onExecute(): Promise { // abstract + protected onExecute(): Promise { + // abstract const rushConfiguration: RushConfiguration = RushConfiguration.loadFromDefaultLocation(); const builder: StringBuilder = new StringBuilder(); const orderedProjects: RushConfigurationProject[] = [...rushConfiguration.projects]; - Sort.sortBy(orderedProjects, x => x.projectRelativeFolder); + Sort.sortBy(orderedProjects, (x) => x.projectRelativeFolder); builder.append('## Published Packages\n\n'); builder.append('\n\n'); builder.append('| Folder | Version | Changelog | Package |\n'); builder.append('| ------ | ------- | --------- | ------- |\n'); - for (const project of orderedProjects.filter(x => ReadmeAction._isPublished(x))) { - + for (const project of orderedProjects.filter((x) => ReadmeAction._isPublished(x))) { // Example: // // | [/apps/api-extractor](./apps/api-extractor/) @@ -43,8 +43,8 @@ export class ReadmeAction extends CommandLineAction { // | const scopedName: string = project.packageName; // "@microsoft/api-extractor" - const folderPath: string = project.projectRelativeFolder; // "apps/api-extractor" - let escapedScopedName: string = scopedName; // "%40microsoft%2Fapi-extractor" + const folderPath: string = project.projectRelativeFolder; // "apps/api-extractor" + let escapedScopedName: string = scopedName; // "%40microsoft%2Fapi-extractor" escapedScopedName = Text.replaceAll(escapedScopedName, '/', '%2F'); escapedScopedName = Text.replaceAll(escapedScopedName, '@', '%40'); @@ -53,8 +53,10 @@ export class ReadmeAction extends CommandLineAction { // | [![npm version](https://badge.fury.io/js/%40microsoft%2Fapi-extractor.svg // )](https://badge.fury.io/js/%40microsoft%2Fapi-extractor) - builder.append(`| [![npm version](https://badge.fury.io/js/${escapedScopedName}.svg)]` - + `(https://badge.fury.io/js/${escapedScopedName}) `); + builder.append( + `| [![npm version](https://badge.fury.io/js/${escapedScopedName}.svg)]` + + `(https://badge.fury.io/js/${escapedScopedName}) ` + ); let hasChangeLog: boolean = true; if (project.versionPolicy instanceof LockStepVersionPolicy) { @@ -82,8 +84,8 @@ export class ReadmeAction extends CommandLineAction { builder.append('\n\n'); builder.append('| Folder | Description |\n'); builder.append('| ------ | -----------|\n'); - for (const project of orderedProjects.filter(x => !ReadmeAction._isPublished(x))) { - const folderPath: string = project.projectRelativeFolder; // "apps/api-extractor" + for (const project of orderedProjects.filter((x) => !ReadmeAction._isPublished(x))) { + const folderPath: string = project.projectRelativeFolder; // "apps/api-extractor" // | [/apps/api-extractor](./apps/api-extractor/) builder.append(`| [/${folderPath}](./${folderPath}/) `); @@ -105,6 +107,7 @@ export class ReadmeAction extends CommandLineAction { return Promise.resolve(); } - protected onDefineParameters(): void { // abstract + protected onDefineParameters(): void { + // abstract } } diff --git a/repo-scripts/repo-toolbox/src/ToolboxCommandLine.ts b/repo-scripts/repo-toolbox/src/ToolboxCommandLine.ts index a6a32c68d92..475fba7ec82 100644 --- a/repo-scripts/repo-toolbox/src/ToolboxCommandLine.ts +++ b/repo-scripts/repo-toolbox/src/ToolboxCommandLine.ts @@ -1,26 +1,25 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See the @microsoft/rush package's LICENSE file for license information. -import { - CommandLineParser -} from '@rushstack/ts-command-line'; +import { CommandLineParser } from '@rushstack/ts-command-line'; import { ReadmeAction } from './ReadmeAction'; export class ToolboxCommandLine extends CommandLineParser { - public constructor() { super({ toolFilename: 'toolbox', - toolDescription: 'Used to execute various operations specific to this repo' + toolDescription: 'Used to execute various operations specific to this repo', }); this.addAction(new ReadmeAction()); } - protected onDefineParameters(): void { // abstract + protected onDefineParameters(): void { + // abstract } - protected onExecute(): Promise { // override + protected onExecute(): Promise { + // override return super.onExecute(); } -} \ No newline at end of file +} diff --git a/repo-scripts/repo-toolbox/tsconfig.json b/repo-scripts/repo-toolbox/tsconfig.json index 0085de105f6..51c71c4bdec 100644 --- a/repo-scripts/repo-toolbox/tsconfig.json +++ b/repo-scripts/repo-toolbox/tsconfig.json @@ -2,8 +2,6 @@ "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "node" - ] + "types": ["node"] } } diff --git a/repo-scripts/tombstone/postinstall.js b/repo-scripts/tombstone/postinstall.js index 5e406648d42..47f3b5a5a7c 100644 --- a/repo-scripts/tombstone/postinstall.js +++ b/repo-scripts/tombstone/postinstall.js @@ -1,11 +1,9 @@ - function writeErrorInRed(message) { console.error(''); console.error('\u001b[31m' + message + '\u001b[39m'); } -writeErrorInRed( -`* * * * * * * * * * * * * THIS PACKAGE WAS RENAMED! * * * * * * * * * * * * * *`); +writeErrorInRed(`* * * * * * * * * * * * * THIS PACKAGE WAS RENAMED! * * * * * * * * * * * * * *`); console.error(` IMPORTANT: This package has moved under the "@rushstack" NPM scope. @@ -15,10 +13,8 @@ NEW NAME: @rushstack/node-core-library (3.19.4) The new package's CHANGELOG.md preserves version history from before the rename. The new package starts with a SemVer PATCH increment, since no code has changed. -To learn about the Rush Stack project, please visit https://rushstack.io/` -); +To learn about the Rush Stack project, please visit https://rushstack.io/`); -writeErrorInRed( -`* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n`); +writeErrorInRed(`* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n`); process.exit(1); diff --git a/rush.json b/rush.json index 4802b9fc6e8..c7676ca01ec 100644 --- a/rush.json +++ b/rush.json @@ -64,7 +64,6 @@ */ "strictPeerDependencies": true, - /** * Configures the strategy used to select versions during installation. * @@ -95,7 +94,7 @@ * * The default value is false. */ - "preventManualShrinkwrapChanges": true + "preventManualShrinkwrapChanges": true }, /** @@ -109,16 +108,16 @@ "nodeSupportedVersionRange": ">=8.9.4 <9.0.0 || >=10.13.0 <11.0.0 || >=12.13.0 <13.0.0 || >=14.0.0 <15.0.0", /** - * Odd-numbered major versions of Node.js are experimental. Even-numbered releases - * spend six months in a stabilization period before the first Long Term Support (LTS) version. - * For example, 8.9.0 was the first LTS version of Node.js 8. Pre-LTS versions are not recommended - * for production usage because they frequently have bugs. They may cause Rush itself - * to malfunction. - * - * Rush normally prints a warning if it detects a pre-LTS Node.js version. If you are testing - * pre-LTS versions in preparation for supporting the first LTS version, you can use this setting - * to disable Rush's warning. - */ + * Odd-numbered major versions of Node.js are experimental. Even-numbered releases + * spend six months in a stabilization period before the first Long Term Support (LTS) version. + * For example, 8.9.0 was the first LTS version of Node.js 8. Pre-LTS versions are not recommended + * for production usage because they frequently have bugs. They may cause Rush itself + * to malfunction. + * + * Rush normally prints a warning if it detects a pre-LTS Node.js version. If you are testing + * pre-LTS versions in preparation for supporting the first LTS version, you can use this setting + * to disable Rush's warning. + */ // "suppressNodeLtsWarning": false, /** @@ -181,8 +180,8 @@ * or you could just have a single category called "default". */ "reviewCategories": [ - "libraries", // library projects that ship - "tests", // non-shipping test projects + "libraries", // library projects that ship + "tests" // non-shipping test projects ], /** @@ -191,7 +190,7 @@ * if the underlying package was already approved, this would imply that the typings * are also approved. */ - "ignoredNpmScopes": [ "@types" ] + "ignoredNpmScopes": ["@types"] }, /** @@ -210,16 +209,14 @@ * IMPORTANT: Because these are regular expressions encoded as JSON string literals, * RegExp escapes need two backspashes, and ordinary periods should be "\\.". */ - "allowedEmailRegExps": [ - "[^@]+@users\\.noreply\\.github\\.com" - ], + "allowedEmailRegExps": ["[^@]+@users\\.noreply\\.github\\.com"], /** * When Rush reports that the address is malformed, the notice can include an example * of a recommended email. Make sure it conforms to one of the allowedEmailRegExps * expressions. */ - "sampleEmail": "mrexample@users.noreply.github.com", + "sampleEmail": "mrexample@users.noreply.github.com" /** * The commit message to use when committing changes during 'rush publish'. @@ -247,7 +244,7 @@ * your PR branch, and in this situation "rush change" will also automatically invoke "git fetch" * to retrieve the latest activity for the remote master branch. */ - "url": "https://github.com/microsoft/rushstack.git" + "url": "https://github.com/microsoft/rushstack.git" /** * The default branch name. This tells "rush change" which remote branch to compare against. @@ -400,20 +397,14 @@ "projectFolder": "apps/api-extractor", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/api-extractor-model", "projectFolder": "apps/api-extractor-model", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/api-documenter", @@ -616,20 +607,14 @@ "projectFolder": "core-build/gulp-core-build", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/gulp-core-build-mocha", "projectFolder": "core-build/gulp-core-build-mocha", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/gulp-core-build-sass", @@ -648,10 +633,7 @@ "projectFolder": "core-build/gulp-core-build-typescript", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/gulp-core-build-webpack", @@ -690,10 +672,7 @@ "projectFolder": "libraries/node-core-library", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@rushstack/package-deps-hash", @@ -718,10 +697,7 @@ "projectFolder": "libraries/ts-command-line", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@rushstack/typings-generator", @@ -762,130 +738,91 @@ "projectFolder": "stack/eslint-plugin", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/rush-stack-compiler-2.4", - "projectFolder": "stack/rush-stack-compiler-2.4", + "projectFolder": "stack/rush-stack-compiler-2.4", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/rush-stack-compiler-2.7", - "projectFolder": "stack/rush-stack-compiler-2.7", + "projectFolder": "stack/rush-stack-compiler-2.7", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/rush-stack-compiler-2.8", "projectFolder": "stack/rush-stack-compiler-2.8", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/rush-stack-compiler-2.9", "projectFolder": "stack/rush-stack-compiler-2.9", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/rush-stack-compiler-3.0", "projectFolder": "stack/rush-stack-compiler-3.0", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/rush-stack-compiler-3.1", "projectFolder": "stack/rush-stack-compiler-3.1", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/rush-stack-compiler-3.2", "projectFolder": "stack/rush-stack-compiler-3.2", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/rush-stack-compiler-3.3", "projectFolder": "stack/rush-stack-compiler-3.3", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/rush-stack-compiler-3.4", "projectFolder": "stack/rush-stack-compiler-3.4", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/rush-stack-compiler-3.5", "projectFolder": "stack/rush-stack-compiler-3.5", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/rush-stack-compiler-3.6", "projectFolder": "stack/rush-stack-compiler-3.6", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/rush-stack-compiler-3.7", "projectFolder": "stack/rush-stack-compiler-3.7", "reviewCategory": "libraries", "shouldPublish": true, - "cyclicDependencyProjects": [ - "@microsoft/node-library-build", - "@microsoft/rush-stack-compiler-3.5" - ] + "cyclicDependencyProjects": ["@microsoft/node-library-build", "@microsoft/rush-stack-compiler-3.5"] }, { "packageName": "@microsoft/rush-stack-compiler-shared", diff --git a/stack/eslint-config/index.js b/stack/eslint-config/index.js index 59e856ae331..3ed4a0e7a8a 100644 --- a/stack/eslint-config/index.js +++ b/stack/eslint-config/index.js @@ -3,41 +3,41 @@ module.exports = { // Disable the parser by default - parser: "", + parser: '', plugins: [ - "@rushstack/eslint-plugin", - "@typescript-eslint/eslint-plugin", - "eslint-plugin-promise", - "eslint-plugin-security", - "eslint-plugin-tsdoc" + '@rushstack/eslint-plugin', + '@typescript-eslint/eslint-plugin', + 'eslint-plugin-promise', + 'eslint-plugin-security', + 'eslint-plugin-tsdoc', ], overrides: [ { // Declare an override that applies to TypeScript files only - "files": [ "*.ts", "*.tsx" ], - parser: "@typescript-eslint/parser", + files: ['*.ts', '*.tsx'], + parser: '@typescript-eslint/parser', parserOptions: { // The "project" path is resolved relative to parserOptions.tsconfigRootDir. // Your local .eslintrc.js must specify that parserOptions.tsconfigRootDir=__dirname. - project: "./tsconfig.json", + project: './tsconfig.json', // Allow parsing of newer ECMAScript constructs used in TypeScript source code. Although tsconfig.json // may allow only a small subset of ES2018 features, this liberal setting ensures that ESLint will correctly // parse whatever is encountered. ecmaVersion: 2018, - sourceType: "module" + sourceType: 'module', }, rules: { // The @rushstack rules are documented in the package README: // https://www.npmjs.com/package/@rushstack/eslint-plugin - "@rushstack/no-null": "error", + '@rushstack/no-null': 'error', // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json - "@typescript-eslint/adjacent-overload-signatures": "error", + '@typescript-eslint/adjacent-overload-signatures': 'error', // RATIONALE: We require "string[]" (instead of "Array") because it is idiomatic TypeScript. // We require "ReadonlyArray" (instead of "readonly string[]") because, although @@ -45,69 +45,69 @@ module.exports = { // It can be expensive to upgrade a large code base to use the latest compiler, so our // lint rules should not require usage of bleeding edge language features. In the future // when TypeScript 3 is obsolete, we'll change this rule to require "readonly string[]". - "@typescript-eslint/array-type": [ - "error", + '@typescript-eslint/array-type': [ + 'error', { - default: "array", - readonly: "generic" - } + default: 'array', + readonly: 'generic', + }, ], // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json // // CONFIGURATION: By default, these are banned: String, Boolean, Number, Object, Symbol - "@typescript-eslint/ban-types": [ - "error", + '@typescript-eslint/ban-types': [ + 'error', { types: { String: { message: "Use 'string' instead", - fixWith: "string" + fixWith: 'string', }, Boolean: { message: "Use 'boolean' instead", - fixWith: "boolean" + fixWith: 'boolean', }, Number: { message: "Use 'number' instead", - fixWith: "number" + fixWith: 'number', }, Object: { - message: "Use 'object' instead, or else define a proper TypeScript type:" + message: "Use 'object' instead, or else define a proper TypeScript type:", }, Symbol: { message: "Use 'symbol' instead", - fixWith: "symbol" - } - } - } + fixWith: 'symbol', + }, + }, + }, ], // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json - "@typescript-eslint/camelcase": [ - "error", + '@typescript-eslint/camelcase': [ + 'error', { // This is a special exception for naming patterns that use an underscore to separate two camel-cased // parts. Example: "checkBox1_onChanged" or "_checkBox1_onChanged" - allow: [ "^_?[a-z][a-z0-9]*([A-Z][a-z]?[a-z0-9]*)*_[a-z][a-z0-9]*([A-Z][a-z]?[a-z0-9]*)*$" ] - } + allow: ['^_?[a-z][a-z0-9]*([A-Z][a-z]?[a-z0-9]*)*_[a-z][a-z0-9]*([A-Z][a-z]?[a-z0-9]*)*$'], + }, ], // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json - "@typescript-eslint/class-name-casing": [ - "error", + '@typescript-eslint/class-name-casing': [ + 'error', { - "allowUnderscorePrefix": true - } + allowUnderscorePrefix: true, + }, ], // RATIONALE: We require "x as number" instead of "x" to avoid conflicts with JSX. - "@typescript-eslint/consistent-type-assertions": "error", + '@typescript-eslint/consistent-type-assertions': 'error', // RATIONALE: We prefer "interface IBlah { x: number }" over "type Blah = { x: number }" // because code is more readable when it is built from stereotypical forms // (interfaces, enums, functions, etc.) instead of freeform type algebra. - "@typescript-eslint/consistent-type-definitions": "error", + '@typescript-eslint/consistent-type-definitions': 'error', // RATIONALE: Code is more readable when the type of every variable is immediately obvious. // Even if the compiler may be able to infer a type, this inference will be unavailable @@ -115,8 +115,8 @@ module.exports = { // but writing code is a much less important activity than reading it. // // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json - "@typescript-eslint/explicit-function-return-type": [ - "error", + '@typescript-eslint/explicit-function-return-type': [ + 'error', { allowExpressions: true, allowTypedFunctionExpressions: true, @@ -125,7 +125,7 @@ module.exports = { ], // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json - "@typescript-eslint/explicit-member-accessibility": "error", + '@typescript-eslint/explicit-member-accessibility': 'error', // RATIONALE: It is very common for a class to implement an interface of the same name. // For example, the Widget class may implement the IWidget interface. The "I" prefix @@ -134,19 +134,19 @@ module.exports = { // objects, here the "I" prefix also helps by avoiding spurious conflicts with classes // by the same name. // - "@typescript-eslint/interface-name-prefix": [ - "error", + '@typescript-eslint/interface-name-prefix': [ + 'error', { - "prefixWithI": "always", - "allowUnderscorePrefix": true - } + prefixWithI: 'always', + allowUnderscorePrefix: true, + }, ], // RATIONALE: Requiring private members to be prefixed with an underscore prevents accidental access // by scripts that are coded in plain JavaScript and cannot see the TypeScript visibility // declarations. Also, using underscore prefixes allows the private field to be exposed // by a public getter/setter with the same name (but omitting the underscore). - "@typescript-eslint/member-naming": ["error", { "private": "^_" }], + '@typescript-eslint/member-naming': ['error', { private: '^_' }], // RATIONALE: Object-oriented programming organizes code into "classes" that associate // data structures (the class's fields) and the operations performed on those @@ -157,20 +157,16 @@ module.exports = { // or static/instance, because these designations tend to change as code evolves, and // reordering methods produces spurious diffs that make PRs hard to read. For classes // with lots of methods, alphabetization is probably a more useful secondary ordering. - "@typescript-eslint/member-ordering": [ - "error", + '@typescript-eslint/member-ordering': [ + 'error', { - "default": "never", - "classes": [ - "field", - "constructor", - "method" - ] - } + default: 'never', + classes: ['field', 'constructor', 'method'], + }, ], // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json - "@typescript-eslint/no-array-constructor": "error", + '@typescript-eslint/no-array-constructor': 'error', // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json // @@ -178,20 +174,20 @@ module.exports = { // This rule should be suppressed only in very special cases such as JSON.stringify() // where the type really can be anything. Even if the type is flexible, another type // may be more appropriate such as "unknown", "{}", or "Record". - "@typescript-eslint/no-explicit-any": "error", + '@typescript-eslint/no-explicit-any': 'error', // RATIONALE: The #1 rule of promises is that every promise chain must be terminated by a catch() // handler. Thus wherever a Promise arises, the code must either append a catch handler, // or else return the object to a caller (who assumes this responsibility). Unterminated // promise chains are a serious issue. Besides causing errors to be silently ignored, // they can also cause a NodeJS process to terminate unexpectedly. - "@typescript-eslint/no-floating-promises": "error", + '@typescript-eslint/no-floating-promises': 'error', // RATIONALE: Catches a common coding mistake. - "@typescript-eslint/no-for-in-array": "error", + '@typescript-eslint/no-for-in-array': 'error', // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json - "@typescript-eslint/no-misused-new": "error", + '@typescript-eslint/no-misused-new': 'error', // RATIONALE: The "namespace" keyword is not recommended for organizing code because JavaScript lacks // a "using" statement to traverse namespaces. Nested namespaces prevent certain bundler @@ -205,15 +201,15 @@ module.exports = { // dependencies are tracked more conscientiously. // // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json - "@typescript-eslint/no-namespace": [ - "error", + '@typescript-eslint/no-namespace': [ + 'error', { // Discourage "namespace" in .ts and .tsx files - "allowDeclarations": false, + allowDeclarations: false, // Allow it in .d.ts files that describe legacy libraries - "allowDefinitionFiles": false - } + allowDefinitionFiles: false, + }, ], // RATIONALE: Parameter properties provide a shorthand such as "constructor(public title: string)" @@ -224,35 +220,35 @@ module.exports = { // just to save some typing. // // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json - "@typescript-eslint/no-parameter-properties": "error", + '@typescript-eslint/no-parameter-properties': 'error', // RATIONALE: When left in shipping code, unused variables often indicate a mistake. Dead code // may impact performance. // // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json - "@typescript-eslint/no-unused-vars": [ - "error", + '@typescript-eslint/no-unused-vars': [ + 'error', { - "vars": "all", + vars: 'all', // Unused function arguments often indicate a mistake in JavaScript code. However in TypeScript code, // the compiler catches most of those mistakes, and unused arguments are fairly common for type signatures // that are overriding a base class method or implementing an interface. - "args": "none" - } + args: 'none', + }, ], // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json - "@typescript-eslint/no-use-before-define": "error", + '@typescript-eslint/no-use-before-define': 'error', // RATIONALE: The require() API is generally obsolete. Use "import" instead. // // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json - "@typescript-eslint/no-var-requires": "error", + '@typescript-eslint/no-var-requires': 'error', // RATIONALE: The "module" keyword is deprecated except when describing legacy libraries. // // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json - "@typescript-eslint/prefer-namespace-keyword": "error", + '@typescript-eslint/prefer-namespace-keyword': 'error', // RATIONALE: We require explicit type annotations, even when the compiler could infer the type. // This is a controversial rule because it makes code more verbose. The reason is that @@ -265,250 +261,250 @@ module.exports = { // to reason about when its authors went through the exercise of choosing meaningful names. // // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json - "@typescript-eslint/typedef": [ - "error", + '@typescript-eslint/typedef': [ + 'error', { - "arrayDestructuring": false, - "arrowParameter": false, - "memberVariableDeclaration": true, - "parameter": true, - "objectDestructuring": false, - "propertyDeclaration": true, - "variableDeclaration": true + arrayDestructuring: false, + arrowParameter: false, + memberVariableDeclaration: true, + parameter: true, + objectDestructuring: false, + propertyDeclaration: true, + variableDeclaration: true, }, ], // RATIONALE: Catches a common coding mistake. - "accessor-pairs": "error", + 'accessor-pairs': 'error', // RATIONALE: In TypeScript, if you write x["y"] instead of x.y, it disables type checking. - "dot-notation": [ - "error", + 'dot-notation': [ + 'error', { - "allowPattern": "^_" - } + allowPattern: '^_', + }, ], // RATIONALE: Catches a common coding mistake. - "eqeqeq": "error", + eqeqeq: 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "for-direction": "error", + 'for-direction': 'error', // RATIONALE: Catches a common coding mistake. - "guard-for-in": "error", + 'guard-for-in': 'error', // RATIONALE: If you have more than 2,000 lines in a single source file, it's probably time // to split up your code. - "max-lines": ["error", { "max": 2000 }], + 'max-lines': ['error', { max: 2000 }], // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-async-promise-executor": "error", + 'no-async-promise-executor': 'error', // RATIONALE: "|" and "&" are relatively rare, and are more likely to appear as a mistake when // someone meant "||" or "&&". (But nobody types the other operators by mistake.) - "no-bitwise": [ - "error", + 'no-bitwise': [ + 'error', { allow: [ - "^", + '^', // "|", // "&", - "<<", - ">>", - ">>>", - "^=", + '<<', + '>>', + '>>>', + '^=', // "|=", //"&=", - "<<=", - ">>=", - ">>>=", - "~" - ] - } + '<<=', + '>>=', + '>>>=', + '~', + ], + }, ], // RATIONALE: Deprecated language feature. - "no-caller": "error", + 'no-caller': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-compare-neg-zero": "error", + 'no-compare-neg-zero': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-cond-assign": "error", + 'no-cond-assign': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-constant-condition": "error", + 'no-constant-condition': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-control-regex": "error", + 'no-control-regex': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-debugger": "error", + 'no-debugger': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-delete-var": "error", + 'no-delete-var': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-duplicate-case": "error", + 'no-duplicate-case': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-empty": "error", + 'no-empty': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-empty-character-class": "error", + 'no-empty-character-class': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-empty-pattern": "error", + 'no-empty-pattern': 'error', // RATIONALE: Eval is a security concern and a performance concern. - "no-eval": "error", + 'no-eval': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-ex-assign": "error", + 'no-ex-assign': 'error', // RATIONALE: System types are global and should not be tampered with in a scalable code base. // If two different libraries (or two versions of the same library) both try to modify // a type, only one of them can win. Polyfills are acceptable because they implement // a standardized interoperable contract, but polyfills are generally coded in plain // JavaScript. - "no-extend-native": "error", + 'no-extend-native': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-extra-boolean-cast": "error", + 'no-extra-boolean-cast': 'error', // RATIONALE: Catches a common coding mistake. - "no-extra-label": "error", + 'no-extra-label': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-fallthrough": "error", + 'no-fallthrough': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-func-assign": "error", + 'no-func-assign': 'error', // RATIONALE: Catches a common coding mistake. - "no-implied-eval": "error", + 'no-implied-eval': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-invalid-regexp": "error", + 'no-invalid-regexp': 'error', // RATIONALE: Catches a common coding mistake. - "no-label-var": "error", + 'no-label-var': 'error', // RATIONALE: Eliminates redundant code. - "no-lone-blocks": "error", + 'no-lone-blocks': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-misleading-character-class": "error", + 'no-misleading-character-class': 'error', // RATIONALE: Catches a common coding mistake. - "no-multi-str": "error", + 'no-multi-str': 'error', // RATIONALE: It's generally a bad practice to call "new Thing()" without assigning the result to // a variable. Either it's part of an awkward expression like "(new Thing()).doSomething()", // or else implies that the constructor is doing nontrivial computations, which is often // a poor class design. - "no-new": "error", + 'no-new': 'error', // RATIONALE: Obsolete notation that is error-prone. - "no-new-func": "error", + 'no-new-func': 'error', // RATIONALE: Obsolete notation. - "no-new-object": "error", + 'no-new-object': 'error', // RATIONALE: Obsolete notation. - "no-new-wrappers": "error", + 'no-new-wrappers': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-octal": "error", + 'no-octal': 'error', // RATIONALE: Catches a common coding mistake. - "no-octal-escape": "error", + 'no-octal-escape': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-regex-spaces": "error", + 'no-regex-spaces': 'error', // RATIONALE: Catches a common coding mistake. - "no-return-assign": "error", + 'no-return-assign': 'error', // RATIONALE: Security risk. - "no-script-url": "error", + 'no-script-url': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-self-assign": "error", + 'no-self-assign': 'error', // RATIONALE: Catches a common coding mistake. - "no-self-compare": "error", + 'no-self-compare': 'error', // RATIONALE: This avoids statements such as "while (a = next(), a && a.length);" that use // commas to create compound expressions. In general code is more readable if each // step is split onto a separate line. This also makes it easier to set breakpoints // in the debugger. - "no-sequences": "error", + 'no-sequences': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-shadow-restricted-names": "error", + 'no-shadow-restricted-names': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-sparse-arrays": "error", + 'no-sparse-arrays': 'error', // RATIONALE: Although in theory JavaScript allows any possible data type to be thrown as an exception, // such flexibility adds pointless complexity, by requiring every catch block to test // the type of the object that it receives. Whereas if catch blocks can always assume // that their object implements the "Error" contract, then the code is simpler, and // we generally get useful additional information like a call stack. - "no-throw-literal": "error", + 'no-throw-literal': 'error', // RATIONALE: Catches a common coding mistake. - "no-unmodified-loop-condition": "error", + 'no-unmodified-loop-condition': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-unsafe-finally": "error", + 'no-unsafe-finally': 'error', // RATIONALE: Catches a common coding mistake. - "no-unused-expressions": "error", + 'no-unused-expressions': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-unused-labels": "error", + 'no-unused-labels': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-useless-catch": "error", + 'no-useless-catch': 'error', // RATIONALE: Avoids a potential performance problem. - "no-useless-concat": "error", + 'no-useless-concat': 'error', // RATIONALE: The "var" keyword is deprecated because of its confusing "hoisting" behavior. // Always use "let" or "const" instead. // // STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json - "no-var": "error", + 'no-var': 'error', // RATIONALE: Generally not needed in modern code. - "no-void": "error", + 'no-void': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "no-with": "error", + 'no-with': 'error', // @typescript-eslint\eslint-plugin\dist\configs\eslint-recommended.js - "prefer-const": "error", + 'prefer-const': 'error', // RATIONALE: Catches a common coding mistake where "resolve" and "reject" are confused. - "promise/param-names": "error", + 'promise/param-names': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "require-atomic-updates": "error", + 'require-atomic-updates': 'error', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "require-yield": "error", + 'require-yield': 'error', // "Use strict" is redundant when using the TypeScript compiler. - "strict": ["error", "never"], + strict: ['error', 'never'], // We're still experimenting with this plugin, so for now it is off by default. - "tsdoc/syntax": "off", + 'tsdoc/syntax': 'off', // STANDARDIZED BY: eslint\conf\eslint-recommended.js - "use-isnan": "error", + 'use-isnan': 'error', // The "no-restricted-syntax" rule is a general purpose pattern matcher that we can use to experiment with // new rules. If a rule works well, we should convert it to a proper rule so it gets its own name @@ -519,7 +515,7 @@ module.exports = { // // "no-restricted-syntax": [ // ], - } - } - ] + }, + }, + ], }; diff --git a/stack/eslint-config/patch-eslint6.js b/stack/eslint-config/patch-eslint6.js index 65d57a30abe..86ad8ac6d25 100644 --- a/stack/eslint-config/patch-eslint6.js +++ b/stack/eslint-config/patch-eslint6.js @@ -19,17 +19,17 @@ while (!/[\\/]eslint[\\/]lib[\\/]cli-engine[\\/]config-array-factory\.js/i.test( } const eslintFolder = path.join(path.dirname(currentModule.filename), '../..'); -const configArrayFactoryPath = path.join(eslintFolder, "lib/cli-engine/config-array-factory"); +const configArrayFactoryPath = path.join(eslintFolder, 'lib/cli-engine/config-array-factory'); const ConfigArrayFactory = require(configArrayFactoryPath).ConfigArrayFactory; if (!ConfigArrayFactory.__patched) { ConfigArrayFactory.__patched = true; - const moduleResolverPath = path.join(eslintFolder, "lib/shared/relative-module-resolver"); + const moduleResolverPath = path.join(eslintFolder, 'lib/shared/relative-module-resolver'); const ModuleResolver = require(moduleResolverPath); const originalLoadPlugin = ConfigArrayFactory.prototype._loadPlugin; - ConfigArrayFactory.prototype._loadPlugin = function(name, importerPath, importerName) { + ConfigArrayFactory.prototype._loadPlugin = function (name, importerPath, importerName) { const originalResolve = ModuleResolver.resolve; try { ModuleResolver.resolve = function (moduleName, relativeToPath) { @@ -40,5 +40,5 @@ if (!ConfigArrayFactory.__patched) { } finally { ModuleResolver.resolve = originalResolve; } - } + }; } diff --git a/stack/eslint-config/react.js b/stack/eslint-config/react.js index b706a8fe955..9ae143fe3c8 100644 --- a/stack/eslint-config/react.js +++ b/stack/eslint-config/react.js @@ -2,72 +2,70 @@ // See LICENSE in the project root for license information. module.exports = { - plugins: [ - "eslint-plugin-react" - ], + plugins: ['eslint-plugin-react'], settings: { react: { - "version": "detect" - } + version: 'detect', + }, }, overrides: [ { // Declare an override that applies to TypeScript files only - "files": [ "*.ts", "*.tsx" ], + files: ['*.ts', '*.tsx'], rules: { // RATIONALE: When React components are added to an array, they generally need a "key". - "react/jsx-key": "error", + 'react/jsx-key': 'error', // RATIONALE: Catches a common coding practice that significantly impacts performance. - "react/jsx-no-bind": "error", + 'react/jsx-no-bind': 'error', // RATIONALE: Catches a common coding mistake. - "react/jsx-no-comment-textnodes": "error", + 'react/jsx-no-comment-textnodes': 'error', // RATIONALE: Security risk. - "react/jsx-no-target-blank": "error", + 'react/jsx-no-target-blank': 'error', // RATIONALE: Fixes the no-unused-vars rule to make it compatible with React - "react/jsx-uses-react": "error", + 'react/jsx-uses-react': 'error', // RATIONALE: Fixes the no-unused-vars rule to make it compatible with React - "react/jsx-uses-vars": "error", + 'react/jsx-uses-vars': 'error', // RATIONALE: Catches a common coding mistake. - "react/no-children-prop": "error", + 'react/no-children-prop': 'error', // RATIONALE: Catches a common coding mistake. - "react/no-danger-with-children": "error", + 'react/no-danger-with-children': 'error', // RATIONALE: Avoids usage of deprecated APIs. // // Note that the set of deprecated APIs is determined by the "react.version" setting. - "react/no-deprecated": "error", + 'react/no-deprecated': 'error', // RATIONALE: Catches a common coding mistake. - "react/no-direct-mutation-state": "error", + 'react/no-direct-mutation-state': 'error', // RATIONALE: Catches some common coding mistakes. - "react/no-unescaped-entities": "error", + 'react/no-unescaped-entities': 'error', // RATIONALE: Avoids a potential performance problem. - "react/no-find-dom-node": "error", + 'react/no-find-dom-node': 'error', // RATIONALE: Deprecated API. - "react/no-is-mounted": "error", + 'react/no-is-mounted': 'error', // RATIONALE: Deprecated API. - "react/no-render-return-value": "error", + 'react/no-render-return-value': 'error', // RATIONALE: Deprecated API. - "react/no-string-refs": "error", + 'react/no-string-refs': 'error', // RATIONALE: Improves syntax for some cases that are not already handled by Prettier. - "react/self-closing-comp": "error", - } - } - ] + 'react/self-closing-comp': 'error', + }, + }, + ], }; diff --git a/stack/eslint-plugin/src/index.ts b/stack/eslint-plugin/src/index.ts index b4ebfbf4183..0d47cb547ac 100644 --- a/stack/eslint-plugin/src/index.ts +++ b/stack/eslint-plugin/src/index.ts @@ -14,8 +14,8 @@ const plugin: IPlugin = { rules: { // NOTE: The actual ESLint rule name will be "@rushstack/no-null". 'no-null': noNullRule, - 'no-untyped-underscore': noUntypedUnderscoreRule - } + 'no-untyped-underscore': noUntypedUnderscoreRule, + }, }; export = plugin; diff --git a/stack/eslint-plugin/src/no-null.ts b/stack/eslint-plugin/src/no-null.ts index 076c282b2ed..8ed4b7a94ae 100644 --- a/stack/eslint-plugin/src/no-null.ts +++ b/stack/eslint-plugin/src/no-null.ts @@ -1,35 +1,31 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - TSESTree, - TSESLint -} from '@typescript-eslint/experimental-utils'; +import { TSESTree, TSESLint } from '@typescript-eslint/experimental-utils'; type MessageIds = 'error-usage-of-null'; -type Options = [ ]; +type Options = []; -const noNullRule: TSESLint.RuleModule = { +const noNullRule: TSESLint.RuleModule = { meta: { type: 'problem', messages: { 'error-usage-of-null': - 'Usage of "null" is deprecated except when received from legacy APIs; use "undefined" instead' + 'Usage of "null" is deprecated except when received from legacy APIs; use "undefined" instead', }, - schema: [ ], + schema: [], docs: { description: 'Prevent usage of JavaScript\'s "null" keyword', category: 'Stylistic Issues', - recommended: "error", - url: 'https://www.npmjs.com/package/@rushstack/eslint-plugin' - } + recommended: 'error', + url: 'https://www.npmjs.com/package/@rushstack/eslint-plugin', + }, }, create: (context: TSESLint.RuleContext) => { return { - Literal: function(node: TSESTree.Literal) { + Literal: function (node: TSESTree.Literal) { // Is it a "null" literal? if (node.value === null) { - // Does the "null" appear in a comparison such as "if (x === null)"? let isComparison: boolean = false; if (node.parent && node.parent.type === 'BinaryExpression') { @@ -41,9 +37,9 @@ const noNullRule: TSESLint.RuleModule = { context.report({ node, messageId: 'error-usage-of-null' }); } } - } + }, }; - } + }, }; export { noNullRule }; diff --git a/stack/eslint-plugin/src/no-untyped-underscore.ts b/stack/eslint-plugin/src/no-untyped-underscore.ts index 1ce349f936b..80b19b2c458 100644 --- a/stack/eslint-plugin/src/no-untyped-underscore.ts +++ b/stack/eslint-plugin/src/no-untyped-underscore.ts @@ -1,47 +1,43 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - TSESTree, - TSESLint, - ParserServices -} from '@typescript-eslint/experimental-utils'; +import { TSESTree, TSESLint, ParserServices } from '@typescript-eslint/experimental-utils'; import * as ts from 'typescript'; type MessageIds = 'error-untyped-underscore'; -type Options = [ ]; +type Options = []; -const noUntypedUnderscoreRule: TSESLint.RuleModule = { +const noUntypedUnderscoreRule: TSESLint.RuleModule = { meta: { type: 'problem', messages: { 'error-untyped-underscore': - 'This expression appears to access a private member "{{memberName}}"; ' - + 'either remove the underscore prefix or else declare a type for the containing object' + 'This expression appears to access a private member "{{memberName}}"; ' + + 'either remove the underscore prefix or else declare a type for the containing object', }, - schema: [ ], + schema: [], docs: { - description: 'Prevent TypeScript code from accessing legacy JavaScript members' - + ' whose names have an underscore prefix', + description: + 'Prevent TypeScript code from accessing legacy JavaScript members' + + ' whose names have an underscore prefix', category: 'Stylistic Issues', recommended: false, - url: 'https://www.npmjs.com/package/@rushstack/eslint-plugin' - } + url: 'https://www.npmjs.com/package/@rushstack/eslint-plugin', + }, }, create: (context: TSESLint.RuleContext) => { - const parserServices: ParserServices | undefined = context.parserServices; - if (!parserServices || - !parserServices.program || - !parserServices.esTreeNodeToTSNodeMap) { - throw new Error('This rule requires your ESLint configuration to define the "parserOptions.project"' - + ' property for "@typescript-eslint/parser".',); + if (!parserServices || !parserServices.program || !parserServices.esTreeNodeToTSNodeMap) { + throw new Error( + 'This rule requires your ESLint configuration to define the "parserOptions.project"' + + ' property for "@typescript-eslint/parser".' + ); } const typeChecker: ts.TypeChecker = parserServices.program.getTypeChecker(); return { - MemberExpression: function(node: TSESTree.MemberExpression) { + MemberExpression: function (node: TSESTree.MemberExpression) { // Is it an expression like "x.y"? // Ignore expressions such as "super.y", "this.y", and "that.y" @@ -61,7 +57,6 @@ const noUntypedUnderscoreRule: TSESLint.RuleModule = { if (node.property && node.property.type === 'Identifier') { const memberName: string = node.property.name; if (memberName && memberName[0] === '_') { - // Do we have type information for the property (e.g. "_y")? // // Examples where propertyType is defined: @@ -78,7 +73,9 @@ const noUntypedUnderscoreRule: TSESLint.RuleModule = { // let propertyType: ts.Symbol | undefined = undefined; - const memberObjectNode: ts.Node | undefined = parserServices.esTreeNodeToTSNodeMap!.get(node.object); + const memberObjectNode: ts.Node | undefined = parserServices.esTreeNodeToTSNodeMap!.get( + node.object + ); if (memberObjectNode) { const memberObjectType: ts.Type | undefined = typeChecker.getTypeAtLocation(memberObjectNode); if (memberObjectType) { @@ -92,15 +89,14 @@ const noUntypedUnderscoreRule: TSESLint.RuleModule = { context.report({ node, messageId: 'error-untyped-underscore', - data: { memberName: memberName } + data: { memberName: memberName }, }); } - } } - } + }, }; - } + }, }; export { noUntypedUnderscoreRule }; diff --git a/stack/eslint-plugin/tsconfig.json b/stack/eslint-plugin/tsconfig.json index 0085de105f6..51c71c4bdec 100644 --- a/stack/eslint-plugin/tsconfig.json +++ b/stack/eslint-plugin/tsconfig.json @@ -2,8 +2,6 @@ "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "node" - ] + "types": ["node"] } } diff --git a/stack/rush-stack-compiler-2.4/.eslintrc.js b/stack/rush-stack-compiler-2.4/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/stack/rush-stack-compiler-2.4/.eslintrc.js +++ b/stack/rush-stack-compiler-2.4/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/stack/rush-stack-compiler-2.4/gulpfile.js b/stack/rush-stack-compiler-2.4/gulpfile.js index b298091c3dc..ba4ec3edbb7 100644 --- a/stack/rush-stack-compiler-2.4/gulpfile.js +++ b/stack/rush-stack-compiler-2.4/gulpfile.js @@ -8,13 +8,31 @@ const sharedLibDir = path.join(__dirname, 'lib', 'shared'); build.preCopy.setConfig({ copyTo: { [sharedSrcDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*') + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*' + ), ], [sharedLibDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*.d.ts') - ] + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*.d.ts' + ), + ], }, - shouldFlatten: false + shouldFlatten: false, }); build.preCopy.cleanMatch = [sharedSrcDir]; diff --git a/stack/rush-stack-compiler-2.4/includes/tsconfig-base.json b/stack/rush-stack-compiler-2.4/includes/tsconfig-base.json index 38ad07b899b..da0130b1475 100644 --- a/stack/rush-stack-compiler-2.4/includes/tsconfig-base.json +++ b/stack/rush-stack-compiler-2.4/includes/tsconfig-base.json @@ -15,12 +15,6 @@ "noUnusedLocals": true, "types": [] }, - "include": [ - "../../../../src/**/*.ts", - "../../../../src/**/*.tsx" - ], - "exclude": [ - "../../../../node_modules", - "../../../../lib" - ] + "include": ["../../../../src/**/*.ts", "../../../../src/**/*.tsx"], + "exclude": ["../../../../node_modules", "../../../../lib"] } diff --git a/stack/rush-stack-compiler-2.4/includes/tsconfig-node.json b/stack/rush-stack-compiler-2.4/includes/tsconfig-node.json index 4b3023cd795..722f0b8f62a 100644 --- a/stack/rush-stack-compiler-2.4/includes/tsconfig-node.json +++ b/stack/rush-stack-compiler-2.4/includes/tsconfig-node.json @@ -5,6 +5,6 @@ "compilerOptions": { "module": "commonjs", "target": "es2017", - "lib": [ "es2017" ] + "lib": ["es2017"] } } diff --git a/stack/rush-stack-compiler-2.4/includes/tsconfig-web.json b/stack/rush-stack-compiler-2.4/includes/tsconfig-web.json index cec8cef7f99..5dd9e12e4aa 100644 --- a/stack/rush-stack-compiler-2.4/includes/tsconfig-web.json +++ b/stack/rush-stack-compiler-2.4/includes/tsconfig-web.json @@ -6,13 +6,6 @@ "module": "esnext", "moduleResolution": "node", "target": "es5", - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ] + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"] } } diff --git a/stack/rush-stack-compiler-2.4/includes/tslint.json b/stack/rush-stack-compiler-2.4/includes/tslint.json index 052770e297e..f55613b66cc 100644 --- a/stack/rush-stack-compiler-2.4/includes/tslint.json +++ b/stack/rush-stack-compiler-2.4/includes/tslint.json @@ -1,9 +1,7 @@ { "$schema": "http://json.schemastore.org/tslint", - "rulesDirectory": [ - "tslint-microsoft-contrib" - ], + "rulesDirectory": ["tslint-microsoft-contrib"], "rules": { "class-name": true, "comment-format": [true, "check-space"], @@ -43,14 +41,7 @@ "no-any": true, "no-bitwise": true, "no-consecutive-blank-lines": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], + "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], "no-constant-condition": true, "no-construct": true, "no-debugger": true, @@ -73,13 +64,7 @@ "no-with-statement": true, "no-var-keyword": true, "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], + "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"], "quotemark": [true, "single", "avoid-escape"], "prefer-const": true, "radix": true, @@ -113,13 +98,6 @@ "use-isnan": true, "use-named-parameter": true, "variable-name": [true, "check-format", "allow-leading-underscore", "ban-keywords"], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] + "whitespace": [true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type"] } } diff --git a/stack/rush-stack-compiler-2.4/tsconfig.json b/stack/rush-stack-compiler-2.4/tsconfig.json index 29a2db909ad..56aa0598ed3 100644 --- a/stack/rush-stack-compiler-2.4/tsconfig.json +++ b/stack/rush-stack-compiler-2.4/tsconfig.json @@ -4,4 +4,4 @@ "compilerOptions": { "rootDir": "src" } -} \ No newline at end of file +} diff --git a/stack/rush-stack-compiler-2.7/.eslintrc.js b/stack/rush-stack-compiler-2.7/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/stack/rush-stack-compiler-2.7/.eslintrc.js +++ b/stack/rush-stack-compiler-2.7/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/stack/rush-stack-compiler-2.7/gulpfile.js b/stack/rush-stack-compiler-2.7/gulpfile.js index b298091c3dc..ba4ec3edbb7 100644 --- a/stack/rush-stack-compiler-2.7/gulpfile.js +++ b/stack/rush-stack-compiler-2.7/gulpfile.js @@ -8,13 +8,31 @@ const sharedLibDir = path.join(__dirname, 'lib', 'shared'); build.preCopy.setConfig({ copyTo: { [sharedSrcDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*') + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*' + ), ], [sharedLibDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*.d.ts') - ] + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*.d.ts' + ), + ], }, - shouldFlatten: false + shouldFlatten: false, }); build.preCopy.cleanMatch = [sharedSrcDir]; diff --git a/stack/rush-stack-compiler-2.7/includes/tsconfig-base.json b/stack/rush-stack-compiler-2.7/includes/tsconfig-base.json index 38ad07b899b..da0130b1475 100644 --- a/stack/rush-stack-compiler-2.7/includes/tsconfig-base.json +++ b/stack/rush-stack-compiler-2.7/includes/tsconfig-base.json @@ -15,12 +15,6 @@ "noUnusedLocals": true, "types": [] }, - "include": [ - "../../../../src/**/*.ts", - "../../../../src/**/*.tsx" - ], - "exclude": [ - "../../../../node_modules", - "../../../../lib" - ] + "include": ["../../../../src/**/*.ts", "../../../../src/**/*.tsx"], + "exclude": ["../../../../node_modules", "../../../../lib"] } diff --git a/stack/rush-stack-compiler-2.7/includes/tsconfig-node.json b/stack/rush-stack-compiler-2.7/includes/tsconfig-node.json index 4b3023cd795..722f0b8f62a 100644 --- a/stack/rush-stack-compiler-2.7/includes/tsconfig-node.json +++ b/stack/rush-stack-compiler-2.7/includes/tsconfig-node.json @@ -5,6 +5,6 @@ "compilerOptions": { "module": "commonjs", "target": "es2017", - "lib": [ "es2017" ] + "lib": ["es2017"] } } diff --git a/stack/rush-stack-compiler-2.7/includes/tsconfig-web.json b/stack/rush-stack-compiler-2.7/includes/tsconfig-web.json index cec8cef7f99..5dd9e12e4aa 100644 --- a/stack/rush-stack-compiler-2.7/includes/tsconfig-web.json +++ b/stack/rush-stack-compiler-2.7/includes/tsconfig-web.json @@ -6,13 +6,6 @@ "module": "esnext", "moduleResolution": "node", "target": "es5", - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ] + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"] } } diff --git a/stack/rush-stack-compiler-2.7/includes/tslint.json b/stack/rush-stack-compiler-2.7/includes/tslint.json index 052770e297e..f55613b66cc 100644 --- a/stack/rush-stack-compiler-2.7/includes/tslint.json +++ b/stack/rush-stack-compiler-2.7/includes/tslint.json @@ -1,9 +1,7 @@ { "$schema": "http://json.schemastore.org/tslint", - "rulesDirectory": [ - "tslint-microsoft-contrib" - ], + "rulesDirectory": ["tslint-microsoft-contrib"], "rules": { "class-name": true, "comment-format": [true, "check-space"], @@ -43,14 +41,7 @@ "no-any": true, "no-bitwise": true, "no-consecutive-blank-lines": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], + "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], "no-constant-condition": true, "no-construct": true, "no-debugger": true, @@ -73,13 +64,7 @@ "no-with-statement": true, "no-var-keyword": true, "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], + "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"], "quotemark": [true, "single", "avoid-escape"], "prefer-const": true, "radix": true, @@ -113,13 +98,6 @@ "use-isnan": true, "use-named-parameter": true, "variable-name": [true, "check-format", "allow-leading-underscore", "ban-keywords"], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] + "whitespace": [true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type"] } } diff --git a/stack/rush-stack-compiler-2.7/tsconfig.json b/stack/rush-stack-compiler-2.7/tsconfig.json index 29a2db909ad..56aa0598ed3 100644 --- a/stack/rush-stack-compiler-2.7/tsconfig.json +++ b/stack/rush-stack-compiler-2.7/tsconfig.json @@ -4,4 +4,4 @@ "compilerOptions": { "rootDir": "src" } -} \ No newline at end of file +} diff --git a/stack/rush-stack-compiler-2.8/.eslintrc.js b/stack/rush-stack-compiler-2.8/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/stack/rush-stack-compiler-2.8/.eslintrc.js +++ b/stack/rush-stack-compiler-2.8/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/stack/rush-stack-compiler-2.8/gulpfile.js b/stack/rush-stack-compiler-2.8/gulpfile.js index b298091c3dc..ba4ec3edbb7 100644 --- a/stack/rush-stack-compiler-2.8/gulpfile.js +++ b/stack/rush-stack-compiler-2.8/gulpfile.js @@ -8,13 +8,31 @@ const sharedLibDir = path.join(__dirname, 'lib', 'shared'); build.preCopy.setConfig({ copyTo: { [sharedSrcDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*') + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*' + ), ], [sharedLibDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*.d.ts') - ] + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*.d.ts' + ), + ], }, - shouldFlatten: false + shouldFlatten: false, }); build.preCopy.cleanMatch = [sharedSrcDir]; diff --git a/stack/rush-stack-compiler-2.8/includes/tsconfig-base.json b/stack/rush-stack-compiler-2.8/includes/tsconfig-base.json index 38ad07b899b..da0130b1475 100644 --- a/stack/rush-stack-compiler-2.8/includes/tsconfig-base.json +++ b/stack/rush-stack-compiler-2.8/includes/tsconfig-base.json @@ -15,12 +15,6 @@ "noUnusedLocals": true, "types": [] }, - "include": [ - "../../../../src/**/*.ts", - "../../../../src/**/*.tsx" - ], - "exclude": [ - "../../../../node_modules", - "../../../../lib" - ] + "include": ["../../../../src/**/*.ts", "../../../../src/**/*.tsx"], + "exclude": ["../../../../node_modules", "../../../../lib"] } diff --git a/stack/rush-stack-compiler-2.8/includes/tsconfig-node.json b/stack/rush-stack-compiler-2.8/includes/tsconfig-node.json index 4b3023cd795..722f0b8f62a 100644 --- a/stack/rush-stack-compiler-2.8/includes/tsconfig-node.json +++ b/stack/rush-stack-compiler-2.8/includes/tsconfig-node.json @@ -5,6 +5,6 @@ "compilerOptions": { "module": "commonjs", "target": "es2017", - "lib": [ "es2017" ] + "lib": ["es2017"] } } diff --git a/stack/rush-stack-compiler-2.8/includes/tsconfig-web.json b/stack/rush-stack-compiler-2.8/includes/tsconfig-web.json index cec8cef7f99..5dd9e12e4aa 100644 --- a/stack/rush-stack-compiler-2.8/includes/tsconfig-web.json +++ b/stack/rush-stack-compiler-2.8/includes/tsconfig-web.json @@ -6,13 +6,6 @@ "module": "esnext", "moduleResolution": "node", "target": "es5", - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ] + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"] } } diff --git a/stack/rush-stack-compiler-2.8/includes/tslint.json b/stack/rush-stack-compiler-2.8/includes/tslint.json index 052770e297e..f55613b66cc 100644 --- a/stack/rush-stack-compiler-2.8/includes/tslint.json +++ b/stack/rush-stack-compiler-2.8/includes/tslint.json @@ -1,9 +1,7 @@ { "$schema": "http://json.schemastore.org/tslint", - "rulesDirectory": [ - "tslint-microsoft-contrib" - ], + "rulesDirectory": ["tslint-microsoft-contrib"], "rules": { "class-name": true, "comment-format": [true, "check-space"], @@ -43,14 +41,7 @@ "no-any": true, "no-bitwise": true, "no-consecutive-blank-lines": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], + "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], "no-constant-condition": true, "no-construct": true, "no-debugger": true, @@ -73,13 +64,7 @@ "no-with-statement": true, "no-var-keyword": true, "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], + "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"], "quotemark": [true, "single", "avoid-escape"], "prefer-const": true, "radix": true, @@ -113,13 +98,6 @@ "use-isnan": true, "use-named-parameter": true, "variable-name": [true, "check-format", "allow-leading-underscore", "ban-keywords"], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] + "whitespace": [true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type"] } } diff --git a/stack/rush-stack-compiler-2.8/tsconfig.json b/stack/rush-stack-compiler-2.8/tsconfig.json index 29a2db909ad..56aa0598ed3 100644 --- a/stack/rush-stack-compiler-2.8/tsconfig.json +++ b/stack/rush-stack-compiler-2.8/tsconfig.json @@ -4,4 +4,4 @@ "compilerOptions": { "rootDir": "src" } -} \ No newline at end of file +} diff --git a/stack/rush-stack-compiler-2.9/.eslintrc.js b/stack/rush-stack-compiler-2.9/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/stack/rush-stack-compiler-2.9/.eslintrc.js +++ b/stack/rush-stack-compiler-2.9/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/stack/rush-stack-compiler-2.9/gulpfile.js b/stack/rush-stack-compiler-2.9/gulpfile.js index b298091c3dc..ba4ec3edbb7 100644 --- a/stack/rush-stack-compiler-2.9/gulpfile.js +++ b/stack/rush-stack-compiler-2.9/gulpfile.js @@ -8,13 +8,31 @@ const sharedLibDir = path.join(__dirname, 'lib', 'shared'); build.preCopy.setConfig({ copyTo: { [sharedSrcDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*') + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*' + ), ], [sharedLibDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*.d.ts') - ] + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*.d.ts' + ), + ], }, - shouldFlatten: false + shouldFlatten: false, }); build.preCopy.cleanMatch = [sharedSrcDir]; diff --git a/stack/rush-stack-compiler-2.9/includes/tsconfig-base.json b/stack/rush-stack-compiler-2.9/includes/tsconfig-base.json index 89f92e23058..7bc3fe2ec7c 100644 --- a/stack/rush-stack-compiler-2.9/includes/tsconfig-base.json +++ b/stack/rush-stack-compiler-2.9/includes/tsconfig-base.json @@ -16,12 +16,6 @@ "noUnusedLocals": true, "types": [] }, - "include": [ - "../../../../src/**/*.ts", - "../../../../src/**/*.tsx" - ], - "exclude": [ - "../../../../node_modules", - "../../../../lib" - ] + "include": ["../../../../src/**/*.ts", "../../../../src/**/*.tsx"], + "exclude": ["../../../../node_modules", "../../../../lib"] } diff --git a/stack/rush-stack-compiler-2.9/includes/tsconfig-node.json b/stack/rush-stack-compiler-2.9/includes/tsconfig-node.json index 4b3023cd795..722f0b8f62a 100644 --- a/stack/rush-stack-compiler-2.9/includes/tsconfig-node.json +++ b/stack/rush-stack-compiler-2.9/includes/tsconfig-node.json @@ -5,6 +5,6 @@ "compilerOptions": { "module": "commonjs", "target": "es2017", - "lib": [ "es2017" ] + "lib": ["es2017"] } } diff --git a/stack/rush-stack-compiler-2.9/includes/tsconfig-web.json b/stack/rush-stack-compiler-2.9/includes/tsconfig-web.json index cec8cef7f99..5dd9e12e4aa 100644 --- a/stack/rush-stack-compiler-2.9/includes/tsconfig-web.json +++ b/stack/rush-stack-compiler-2.9/includes/tsconfig-web.json @@ -6,13 +6,6 @@ "module": "esnext", "moduleResolution": "node", "target": "es5", - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ] + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"] } } diff --git a/stack/rush-stack-compiler-2.9/includes/tslint.json b/stack/rush-stack-compiler-2.9/includes/tslint.json index 052770e297e..f55613b66cc 100644 --- a/stack/rush-stack-compiler-2.9/includes/tslint.json +++ b/stack/rush-stack-compiler-2.9/includes/tslint.json @@ -1,9 +1,7 @@ { "$schema": "http://json.schemastore.org/tslint", - "rulesDirectory": [ - "tslint-microsoft-contrib" - ], + "rulesDirectory": ["tslint-microsoft-contrib"], "rules": { "class-name": true, "comment-format": [true, "check-space"], @@ -43,14 +41,7 @@ "no-any": true, "no-bitwise": true, "no-consecutive-blank-lines": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], + "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], "no-constant-condition": true, "no-construct": true, "no-debugger": true, @@ -73,13 +64,7 @@ "no-with-statement": true, "no-var-keyword": true, "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], + "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"], "quotemark": [true, "single", "avoid-escape"], "prefer-const": true, "radix": true, @@ -113,13 +98,6 @@ "use-isnan": true, "use-named-parameter": true, "variable-name": [true, "check-format", "allow-leading-underscore", "ban-keywords"], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] + "whitespace": [true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type"] } } diff --git a/stack/rush-stack-compiler-2.9/tsconfig.json b/stack/rush-stack-compiler-2.9/tsconfig.json index 29a2db909ad..56aa0598ed3 100644 --- a/stack/rush-stack-compiler-2.9/tsconfig.json +++ b/stack/rush-stack-compiler-2.9/tsconfig.json @@ -4,4 +4,4 @@ "compilerOptions": { "rootDir": "src" } -} \ No newline at end of file +} diff --git a/stack/rush-stack-compiler-3.0/.eslintrc.js b/stack/rush-stack-compiler-3.0/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/stack/rush-stack-compiler-3.0/.eslintrc.js +++ b/stack/rush-stack-compiler-3.0/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/stack/rush-stack-compiler-3.0/gulpfile.js b/stack/rush-stack-compiler-3.0/gulpfile.js index b298091c3dc..ba4ec3edbb7 100644 --- a/stack/rush-stack-compiler-3.0/gulpfile.js +++ b/stack/rush-stack-compiler-3.0/gulpfile.js @@ -8,13 +8,31 @@ const sharedLibDir = path.join(__dirname, 'lib', 'shared'); build.preCopy.setConfig({ copyTo: { [sharedSrcDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*') + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*' + ), ], [sharedLibDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*.d.ts') - ] + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*.d.ts' + ), + ], }, - shouldFlatten: false + shouldFlatten: false, }); build.preCopy.cleanMatch = [sharedSrcDir]; diff --git a/stack/rush-stack-compiler-3.0/includes/tsconfig-base.json b/stack/rush-stack-compiler-3.0/includes/tsconfig-base.json index 89f92e23058..7bc3fe2ec7c 100644 --- a/stack/rush-stack-compiler-3.0/includes/tsconfig-base.json +++ b/stack/rush-stack-compiler-3.0/includes/tsconfig-base.json @@ -16,12 +16,6 @@ "noUnusedLocals": true, "types": [] }, - "include": [ - "../../../../src/**/*.ts", - "../../../../src/**/*.tsx" - ], - "exclude": [ - "../../../../node_modules", - "../../../../lib" - ] + "include": ["../../../../src/**/*.ts", "../../../../src/**/*.tsx"], + "exclude": ["../../../../node_modules", "../../../../lib"] } diff --git a/stack/rush-stack-compiler-3.0/includes/tsconfig-node.json b/stack/rush-stack-compiler-3.0/includes/tsconfig-node.json index 4b3023cd795..722f0b8f62a 100644 --- a/stack/rush-stack-compiler-3.0/includes/tsconfig-node.json +++ b/stack/rush-stack-compiler-3.0/includes/tsconfig-node.json @@ -5,6 +5,6 @@ "compilerOptions": { "module": "commonjs", "target": "es2017", - "lib": [ "es2017" ] + "lib": ["es2017"] } } diff --git a/stack/rush-stack-compiler-3.0/includes/tsconfig-web.json b/stack/rush-stack-compiler-3.0/includes/tsconfig-web.json index cec8cef7f99..5dd9e12e4aa 100644 --- a/stack/rush-stack-compiler-3.0/includes/tsconfig-web.json +++ b/stack/rush-stack-compiler-3.0/includes/tsconfig-web.json @@ -6,13 +6,6 @@ "module": "esnext", "moduleResolution": "node", "target": "es5", - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ] + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"] } } diff --git a/stack/rush-stack-compiler-3.0/includes/tslint.json b/stack/rush-stack-compiler-3.0/includes/tslint.json index 052770e297e..f55613b66cc 100644 --- a/stack/rush-stack-compiler-3.0/includes/tslint.json +++ b/stack/rush-stack-compiler-3.0/includes/tslint.json @@ -1,9 +1,7 @@ { "$schema": "http://json.schemastore.org/tslint", - "rulesDirectory": [ - "tslint-microsoft-contrib" - ], + "rulesDirectory": ["tslint-microsoft-contrib"], "rules": { "class-name": true, "comment-format": [true, "check-space"], @@ -43,14 +41,7 @@ "no-any": true, "no-bitwise": true, "no-consecutive-blank-lines": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], + "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], "no-constant-condition": true, "no-construct": true, "no-debugger": true, @@ -73,13 +64,7 @@ "no-with-statement": true, "no-var-keyword": true, "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], + "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"], "quotemark": [true, "single", "avoid-escape"], "prefer-const": true, "radix": true, @@ -113,13 +98,6 @@ "use-isnan": true, "use-named-parameter": true, "variable-name": [true, "check-format", "allow-leading-underscore", "ban-keywords"], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] + "whitespace": [true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type"] } } diff --git a/stack/rush-stack-compiler-3.0/tsconfig.json b/stack/rush-stack-compiler-3.0/tsconfig.json index 29a2db909ad..56aa0598ed3 100644 --- a/stack/rush-stack-compiler-3.0/tsconfig.json +++ b/stack/rush-stack-compiler-3.0/tsconfig.json @@ -4,4 +4,4 @@ "compilerOptions": { "rootDir": "src" } -} \ No newline at end of file +} diff --git a/stack/rush-stack-compiler-3.1/.eslintrc.js b/stack/rush-stack-compiler-3.1/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/stack/rush-stack-compiler-3.1/.eslintrc.js +++ b/stack/rush-stack-compiler-3.1/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/stack/rush-stack-compiler-3.1/gulpfile.js b/stack/rush-stack-compiler-3.1/gulpfile.js index b298091c3dc..ba4ec3edbb7 100644 --- a/stack/rush-stack-compiler-3.1/gulpfile.js +++ b/stack/rush-stack-compiler-3.1/gulpfile.js @@ -8,13 +8,31 @@ const sharedLibDir = path.join(__dirname, 'lib', 'shared'); build.preCopy.setConfig({ copyTo: { [sharedSrcDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*') + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*' + ), ], [sharedLibDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*.d.ts') - ] + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*.d.ts' + ), + ], }, - shouldFlatten: false + shouldFlatten: false, }); build.preCopy.cleanMatch = [sharedSrcDir]; diff --git a/stack/rush-stack-compiler-3.1/includes/tsconfig-base.json b/stack/rush-stack-compiler-3.1/includes/tsconfig-base.json index 89f92e23058..7bc3fe2ec7c 100644 --- a/stack/rush-stack-compiler-3.1/includes/tsconfig-base.json +++ b/stack/rush-stack-compiler-3.1/includes/tsconfig-base.json @@ -16,12 +16,6 @@ "noUnusedLocals": true, "types": [] }, - "include": [ - "../../../../src/**/*.ts", - "../../../../src/**/*.tsx" - ], - "exclude": [ - "../../../../node_modules", - "../../../../lib" - ] + "include": ["../../../../src/**/*.ts", "../../../../src/**/*.tsx"], + "exclude": ["../../../../node_modules", "../../../../lib"] } diff --git a/stack/rush-stack-compiler-3.1/includes/tsconfig-node.json b/stack/rush-stack-compiler-3.1/includes/tsconfig-node.json index 4b3023cd795..722f0b8f62a 100644 --- a/stack/rush-stack-compiler-3.1/includes/tsconfig-node.json +++ b/stack/rush-stack-compiler-3.1/includes/tsconfig-node.json @@ -5,6 +5,6 @@ "compilerOptions": { "module": "commonjs", "target": "es2017", - "lib": [ "es2017" ] + "lib": ["es2017"] } } diff --git a/stack/rush-stack-compiler-3.1/includes/tsconfig-web.json b/stack/rush-stack-compiler-3.1/includes/tsconfig-web.json index cec8cef7f99..5dd9e12e4aa 100644 --- a/stack/rush-stack-compiler-3.1/includes/tsconfig-web.json +++ b/stack/rush-stack-compiler-3.1/includes/tsconfig-web.json @@ -6,13 +6,6 @@ "module": "esnext", "moduleResolution": "node", "target": "es5", - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ] + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"] } } diff --git a/stack/rush-stack-compiler-3.1/includes/tslint.json b/stack/rush-stack-compiler-3.1/includes/tslint.json index 052770e297e..f55613b66cc 100644 --- a/stack/rush-stack-compiler-3.1/includes/tslint.json +++ b/stack/rush-stack-compiler-3.1/includes/tslint.json @@ -1,9 +1,7 @@ { "$schema": "http://json.schemastore.org/tslint", - "rulesDirectory": [ - "tslint-microsoft-contrib" - ], + "rulesDirectory": ["tslint-microsoft-contrib"], "rules": { "class-name": true, "comment-format": [true, "check-space"], @@ -43,14 +41,7 @@ "no-any": true, "no-bitwise": true, "no-consecutive-blank-lines": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], + "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], "no-constant-condition": true, "no-construct": true, "no-debugger": true, @@ -73,13 +64,7 @@ "no-with-statement": true, "no-var-keyword": true, "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], + "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"], "quotemark": [true, "single", "avoid-escape"], "prefer-const": true, "radix": true, @@ -113,13 +98,6 @@ "use-isnan": true, "use-named-parameter": true, "variable-name": [true, "check-format", "allow-leading-underscore", "ban-keywords"], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] + "whitespace": [true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type"] } } diff --git a/stack/rush-stack-compiler-3.1/tsconfig.json b/stack/rush-stack-compiler-3.1/tsconfig.json index 29a2db909ad..56aa0598ed3 100644 --- a/stack/rush-stack-compiler-3.1/tsconfig.json +++ b/stack/rush-stack-compiler-3.1/tsconfig.json @@ -4,4 +4,4 @@ "compilerOptions": { "rootDir": "src" } -} \ No newline at end of file +} diff --git a/stack/rush-stack-compiler-3.2/.eslintrc.js b/stack/rush-stack-compiler-3.2/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/stack/rush-stack-compiler-3.2/.eslintrc.js +++ b/stack/rush-stack-compiler-3.2/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/stack/rush-stack-compiler-3.2/gulpfile.js b/stack/rush-stack-compiler-3.2/gulpfile.js index b298091c3dc..ba4ec3edbb7 100644 --- a/stack/rush-stack-compiler-3.2/gulpfile.js +++ b/stack/rush-stack-compiler-3.2/gulpfile.js @@ -8,13 +8,31 @@ const sharedLibDir = path.join(__dirname, 'lib', 'shared'); build.preCopy.setConfig({ copyTo: { [sharedSrcDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*') + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*' + ), ], [sharedLibDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*.d.ts') - ] + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*.d.ts' + ), + ], }, - shouldFlatten: false + shouldFlatten: false, }); build.preCopy.cleanMatch = [sharedSrcDir]; diff --git a/stack/rush-stack-compiler-3.2/includes/tsconfig-base.json b/stack/rush-stack-compiler-3.2/includes/tsconfig-base.json index 89f92e23058..7bc3fe2ec7c 100644 --- a/stack/rush-stack-compiler-3.2/includes/tsconfig-base.json +++ b/stack/rush-stack-compiler-3.2/includes/tsconfig-base.json @@ -16,12 +16,6 @@ "noUnusedLocals": true, "types": [] }, - "include": [ - "../../../../src/**/*.ts", - "../../../../src/**/*.tsx" - ], - "exclude": [ - "../../../../node_modules", - "../../../../lib" - ] + "include": ["../../../../src/**/*.ts", "../../../../src/**/*.tsx"], + "exclude": ["../../../../node_modules", "../../../../lib"] } diff --git a/stack/rush-stack-compiler-3.2/includes/tsconfig-node.json b/stack/rush-stack-compiler-3.2/includes/tsconfig-node.json index 4b3023cd795..722f0b8f62a 100644 --- a/stack/rush-stack-compiler-3.2/includes/tsconfig-node.json +++ b/stack/rush-stack-compiler-3.2/includes/tsconfig-node.json @@ -5,6 +5,6 @@ "compilerOptions": { "module": "commonjs", "target": "es2017", - "lib": [ "es2017" ] + "lib": ["es2017"] } } diff --git a/stack/rush-stack-compiler-3.2/includes/tsconfig-web.json b/stack/rush-stack-compiler-3.2/includes/tsconfig-web.json index cec8cef7f99..5dd9e12e4aa 100644 --- a/stack/rush-stack-compiler-3.2/includes/tsconfig-web.json +++ b/stack/rush-stack-compiler-3.2/includes/tsconfig-web.json @@ -6,13 +6,6 @@ "module": "esnext", "moduleResolution": "node", "target": "es5", - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ] + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"] } } diff --git a/stack/rush-stack-compiler-3.2/includes/tslint.json b/stack/rush-stack-compiler-3.2/includes/tslint.json index 052770e297e..f55613b66cc 100644 --- a/stack/rush-stack-compiler-3.2/includes/tslint.json +++ b/stack/rush-stack-compiler-3.2/includes/tslint.json @@ -1,9 +1,7 @@ { "$schema": "http://json.schemastore.org/tslint", - "rulesDirectory": [ - "tslint-microsoft-contrib" - ], + "rulesDirectory": ["tslint-microsoft-contrib"], "rules": { "class-name": true, "comment-format": [true, "check-space"], @@ -43,14 +41,7 @@ "no-any": true, "no-bitwise": true, "no-consecutive-blank-lines": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], + "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], "no-constant-condition": true, "no-construct": true, "no-debugger": true, @@ -73,13 +64,7 @@ "no-with-statement": true, "no-var-keyword": true, "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], + "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"], "quotemark": [true, "single", "avoid-escape"], "prefer-const": true, "radix": true, @@ -113,13 +98,6 @@ "use-isnan": true, "use-named-parameter": true, "variable-name": [true, "check-format", "allow-leading-underscore", "ban-keywords"], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] + "whitespace": [true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type"] } } diff --git a/stack/rush-stack-compiler-3.2/tsconfig.json b/stack/rush-stack-compiler-3.2/tsconfig.json index 29a2db909ad..56aa0598ed3 100644 --- a/stack/rush-stack-compiler-3.2/tsconfig.json +++ b/stack/rush-stack-compiler-3.2/tsconfig.json @@ -4,4 +4,4 @@ "compilerOptions": { "rootDir": "src" } -} \ No newline at end of file +} diff --git a/stack/rush-stack-compiler-3.3/.eslintrc.js b/stack/rush-stack-compiler-3.3/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/stack/rush-stack-compiler-3.3/.eslintrc.js +++ b/stack/rush-stack-compiler-3.3/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/stack/rush-stack-compiler-3.3/gulpfile.js b/stack/rush-stack-compiler-3.3/gulpfile.js index b298091c3dc..ba4ec3edbb7 100644 --- a/stack/rush-stack-compiler-3.3/gulpfile.js +++ b/stack/rush-stack-compiler-3.3/gulpfile.js @@ -8,13 +8,31 @@ const sharedLibDir = path.join(__dirname, 'lib', 'shared'); build.preCopy.setConfig({ copyTo: { [sharedSrcDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*') + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*' + ), ], [sharedLibDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*.d.ts') - ] + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*.d.ts' + ), + ], }, - shouldFlatten: false + shouldFlatten: false, }); build.preCopy.cleanMatch = [sharedSrcDir]; diff --git a/stack/rush-stack-compiler-3.3/includes/tsconfig-base.json b/stack/rush-stack-compiler-3.3/includes/tsconfig-base.json index 89f92e23058..7bc3fe2ec7c 100644 --- a/stack/rush-stack-compiler-3.3/includes/tsconfig-base.json +++ b/stack/rush-stack-compiler-3.3/includes/tsconfig-base.json @@ -16,12 +16,6 @@ "noUnusedLocals": true, "types": [] }, - "include": [ - "../../../../src/**/*.ts", - "../../../../src/**/*.tsx" - ], - "exclude": [ - "../../../../node_modules", - "../../../../lib" - ] + "include": ["../../../../src/**/*.ts", "../../../../src/**/*.tsx"], + "exclude": ["../../../../node_modules", "../../../../lib"] } diff --git a/stack/rush-stack-compiler-3.3/includes/tsconfig-node.json b/stack/rush-stack-compiler-3.3/includes/tsconfig-node.json index 4b3023cd795..722f0b8f62a 100644 --- a/stack/rush-stack-compiler-3.3/includes/tsconfig-node.json +++ b/stack/rush-stack-compiler-3.3/includes/tsconfig-node.json @@ -5,6 +5,6 @@ "compilerOptions": { "module": "commonjs", "target": "es2017", - "lib": [ "es2017" ] + "lib": ["es2017"] } } diff --git a/stack/rush-stack-compiler-3.3/includes/tsconfig-web.json b/stack/rush-stack-compiler-3.3/includes/tsconfig-web.json index cec8cef7f99..5dd9e12e4aa 100644 --- a/stack/rush-stack-compiler-3.3/includes/tsconfig-web.json +++ b/stack/rush-stack-compiler-3.3/includes/tsconfig-web.json @@ -6,13 +6,6 @@ "module": "esnext", "moduleResolution": "node", "target": "es5", - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ] + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"] } } diff --git a/stack/rush-stack-compiler-3.3/includes/tslint.json b/stack/rush-stack-compiler-3.3/includes/tslint.json index 052770e297e..f55613b66cc 100644 --- a/stack/rush-stack-compiler-3.3/includes/tslint.json +++ b/stack/rush-stack-compiler-3.3/includes/tslint.json @@ -1,9 +1,7 @@ { "$schema": "http://json.schemastore.org/tslint", - "rulesDirectory": [ - "tslint-microsoft-contrib" - ], + "rulesDirectory": ["tslint-microsoft-contrib"], "rules": { "class-name": true, "comment-format": [true, "check-space"], @@ -43,14 +41,7 @@ "no-any": true, "no-bitwise": true, "no-consecutive-blank-lines": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], + "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], "no-constant-condition": true, "no-construct": true, "no-debugger": true, @@ -73,13 +64,7 @@ "no-with-statement": true, "no-var-keyword": true, "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], + "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"], "quotemark": [true, "single", "avoid-escape"], "prefer-const": true, "radix": true, @@ -113,13 +98,6 @@ "use-isnan": true, "use-named-parameter": true, "variable-name": [true, "check-format", "allow-leading-underscore", "ban-keywords"], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] + "whitespace": [true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type"] } } diff --git a/stack/rush-stack-compiler-3.3/tsconfig.json b/stack/rush-stack-compiler-3.3/tsconfig.json index 29a2db909ad..56aa0598ed3 100644 --- a/stack/rush-stack-compiler-3.3/tsconfig.json +++ b/stack/rush-stack-compiler-3.3/tsconfig.json @@ -4,4 +4,4 @@ "compilerOptions": { "rootDir": "src" } -} \ No newline at end of file +} diff --git a/stack/rush-stack-compiler-3.4/.eslintrc.js b/stack/rush-stack-compiler-3.4/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/stack/rush-stack-compiler-3.4/.eslintrc.js +++ b/stack/rush-stack-compiler-3.4/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/stack/rush-stack-compiler-3.4/gulpfile.js b/stack/rush-stack-compiler-3.4/gulpfile.js index b298091c3dc..ba4ec3edbb7 100644 --- a/stack/rush-stack-compiler-3.4/gulpfile.js +++ b/stack/rush-stack-compiler-3.4/gulpfile.js @@ -8,13 +8,31 @@ const sharedLibDir = path.join(__dirname, 'lib', 'shared'); build.preCopy.setConfig({ copyTo: { [sharedSrcDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*') + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*' + ), ], [sharedLibDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*.d.ts') - ] + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*.d.ts' + ), + ], }, - shouldFlatten: false + shouldFlatten: false, }); build.preCopy.cleanMatch = [sharedSrcDir]; diff --git a/stack/rush-stack-compiler-3.4/includes/tsconfig-base.json b/stack/rush-stack-compiler-3.4/includes/tsconfig-base.json index 89f92e23058..7bc3fe2ec7c 100644 --- a/stack/rush-stack-compiler-3.4/includes/tsconfig-base.json +++ b/stack/rush-stack-compiler-3.4/includes/tsconfig-base.json @@ -16,12 +16,6 @@ "noUnusedLocals": true, "types": [] }, - "include": [ - "../../../../src/**/*.ts", - "../../../../src/**/*.tsx" - ], - "exclude": [ - "../../../../node_modules", - "../../../../lib" - ] + "include": ["../../../../src/**/*.ts", "../../../../src/**/*.tsx"], + "exclude": ["../../../../node_modules", "../../../../lib"] } diff --git a/stack/rush-stack-compiler-3.4/includes/tsconfig-node.json b/stack/rush-stack-compiler-3.4/includes/tsconfig-node.json index 4b3023cd795..722f0b8f62a 100644 --- a/stack/rush-stack-compiler-3.4/includes/tsconfig-node.json +++ b/stack/rush-stack-compiler-3.4/includes/tsconfig-node.json @@ -5,6 +5,6 @@ "compilerOptions": { "module": "commonjs", "target": "es2017", - "lib": [ "es2017" ] + "lib": ["es2017"] } } diff --git a/stack/rush-stack-compiler-3.4/includes/tsconfig-web.json b/stack/rush-stack-compiler-3.4/includes/tsconfig-web.json index cec8cef7f99..5dd9e12e4aa 100644 --- a/stack/rush-stack-compiler-3.4/includes/tsconfig-web.json +++ b/stack/rush-stack-compiler-3.4/includes/tsconfig-web.json @@ -6,13 +6,6 @@ "module": "esnext", "moduleResolution": "node", "target": "es5", - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ] + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"] } } diff --git a/stack/rush-stack-compiler-3.4/includes/tslint.json b/stack/rush-stack-compiler-3.4/includes/tslint.json index 052770e297e..f55613b66cc 100644 --- a/stack/rush-stack-compiler-3.4/includes/tslint.json +++ b/stack/rush-stack-compiler-3.4/includes/tslint.json @@ -1,9 +1,7 @@ { "$schema": "http://json.schemastore.org/tslint", - "rulesDirectory": [ - "tslint-microsoft-contrib" - ], + "rulesDirectory": ["tslint-microsoft-contrib"], "rules": { "class-name": true, "comment-format": [true, "check-space"], @@ -43,14 +41,7 @@ "no-any": true, "no-bitwise": true, "no-consecutive-blank-lines": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], + "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], "no-constant-condition": true, "no-construct": true, "no-debugger": true, @@ -73,13 +64,7 @@ "no-with-statement": true, "no-var-keyword": true, "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], + "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"], "quotemark": [true, "single", "avoid-escape"], "prefer-const": true, "radix": true, @@ -113,13 +98,6 @@ "use-isnan": true, "use-named-parameter": true, "variable-name": [true, "check-format", "allow-leading-underscore", "ban-keywords"], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] + "whitespace": [true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type"] } } diff --git a/stack/rush-stack-compiler-3.4/tsconfig.json b/stack/rush-stack-compiler-3.4/tsconfig.json index 29a2db909ad..56aa0598ed3 100644 --- a/stack/rush-stack-compiler-3.4/tsconfig.json +++ b/stack/rush-stack-compiler-3.4/tsconfig.json @@ -4,4 +4,4 @@ "compilerOptions": { "rootDir": "src" } -} \ No newline at end of file +} diff --git a/stack/rush-stack-compiler-3.5/.eslintrc.js b/stack/rush-stack-compiler-3.5/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/stack/rush-stack-compiler-3.5/.eslintrc.js +++ b/stack/rush-stack-compiler-3.5/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/stack/rush-stack-compiler-3.5/gulpfile.js b/stack/rush-stack-compiler-3.5/gulpfile.js index b298091c3dc..ba4ec3edbb7 100644 --- a/stack/rush-stack-compiler-3.5/gulpfile.js +++ b/stack/rush-stack-compiler-3.5/gulpfile.js @@ -8,13 +8,31 @@ const sharedLibDir = path.join(__dirname, 'lib', 'shared'); build.preCopy.setConfig({ copyTo: { [sharedSrcDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*') + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*' + ), ], [sharedLibDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*.d.ts') - ] + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*.d.ts' + ), + ], }, - shouldFlatten: false + shouldFlatten: false, }); build.preCopy.cleanMatch = [sharedSrcDir]; diff --git a/stack/rush-stack-compiler-3.5/includes/tsconfig-base.json b/stack/rush-stack-compiler-3.5/includes/tsconfig-base.json index 89f92e23058..7bc3fe2ec7c 100644 --- a/stack/rush-stack-compiler-3.5/includes/tsconfig-base.json +++ b/stack/rush-stack-compiler-3.5/includes/tsconfig-base.json @@ -16,12 +16,6 @@ "noUnusedLocals": true, "types": [] }, - "include": [ - "../../../../src/**/*.ts", - "../../../../src/**/*.tsx" - ], - "exclude": [ - "../../../../node_modules", - "../../../../lib" - ] + "include": ["../../../../src/**/*.ts", "../../../../src/**/*.tsx"], + "exclude": ["../../../../node_modules", "../../../../lib"] } diff --git a/stack/rush-stack-compiler-3.5/includes/tsconfig-node.json b/stack/rush-stack-compiler-3.5/includes/tsconfig-node.json index 4b3023cd795..722f0b8f62a 100644 --- a/stack/rush-stack-compiler-3.5/includes/tsconfig-node.json +++ b/stack/rush-stack-compiler-3.5/includes/tsconfig-node.json @@ -5,6 +5,6 @@ "compilerOptions": { "module": "commonjs", "target": "es2017", - "lib": [ "es2017" ] + "lib": ["es2017"] } } diff --git a/stack/rush-stack-compiler-3.5/includes/tsconfig-web.json b/stack/rush-stack-compiler-3.5/includes/tsconfig-web.json index cec8cef7f99..5dd9e12e4aa 100644 --- a/stack/rush-stack-compiler-3.5/includes/tsconfig-web.json +++ b/stack/rush-stack-compiler-3.5/includes/tsconfig-web.json @@ -6,13 +6,6 @@ "module": "esnext", "moduleResolution": "node", "target": "es5", - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ] + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"] } } diff --git a/stack/rush-stack-compiler-3.5/includes/tslint.json b/stack/rush-stack-compiler-3.5/includes/tslint.json index 052770e297e..f55613b66cc 100644 --- a/stack/rush-stack-compiler-3.5/includes/tslint.json +++ b/stack/rush-stack-compiler-3.5/includes/tslint.json @@ -1,9 +1,7 @@ { "$schema": "http://json.schemastore.org/tslint", - "rulesDirectory": [ - "tslint-microsoft-contrib" - ], + "rulesDirectory": ["tslint-microsoft-contrib"], "rules": { "class-name": true, "comment-format": [true, "check-space"], @@ -43,14 +41,7 @@ "no-any": true, "no-bitwise": true, "no-consecutive-blank-lines": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], + "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], "no-constant-condition": true, "no-construct": true, "no-debugger": true, @@ -73,13 +64,7 @@ "no-with-statement": true, "no-var-keyword": true, "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], + "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"], "quotemark": [true, "single", "avoid-escape"], "prefer-const": true, "radix": true, @@ -113,13 +98,6 @@ "use-isnan": true, "use-named-parameter": true, "variable-name": [true, "check-format", "allow-leading-underscore", "ban-keywords"], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] + "whitespace": [true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type"] } } diff --git a/stack/rush-stack-compiler-3.5/tsconfig.json b/stack/rush-stack-compiler-3.5/tsconfig.json index 29a2db909ad..56aa0598ed3 100644 --- a/stack/rush-stack-compiler-3.5/tsconfig.json +++ b/stack/rush-stack-compiler-3.5/tsconfig.json @@ -4,4 +4,4 @@ "compilerOptions": { "rootDir": "src" } -} \ No newline at end of file +} diff --git a/stack/rush-stack-compiler-3.6/.eslintrc.js b/stack/rush-stack-compiler-3.6/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/stack/rush-stack-compiler-3.6/.eslintrc.js +++ b/stack/rush-stack-compiler-3.6/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/stack/rush-stack-compiler-3.6/gulpfile.js b/stack/rush-stack-compiler-3.6/gulpfile.js index b298091c3dc..ba4ec3edbb7 100644 --- a/stack/rush-stack-compiler-3.6/gulpfile.js +++ b/stack/rush-stack-compiler-3.6/gulpfile.js @@ -8,13 +8,31 @@ const sharedLibDir = path.join(__dirname, 'lib', 'shared'); build.preCopy.setConfig({ copyTo: { [sharedSrcDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*') + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*' + ), ], [sharedLibDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*.d.ts') - ] + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*.d.ts' + ), + ], }, - shouldFlatten: false + shouldFlatten: false, }); build.preCopy.cleanMatch = [sharedSrcDir]; diff --git a/stack/rush-stack-compiler-3.6/includes/tsconfig-base.json b/stack/rush-stack-compiler-3.6/includes/tsconfig-base.json index 89f92e23058..7bc3fe2ec7c 100644 --- a/stack/rush-stack-compiler-3.6/includes/tsconfig-base.json +++ b/stack/rush-stack-compiler-3.6/includes/tsconfig-base.json @@ -16,12 +16,6 @@ "noUnusedLocals": true, "types": [] }, - "include": [ - "../../../../src/**/*.ts", - "../../../../src/**/*.tsx" - ], - "exclude": [ - "../../../../node_modules", - "../../../../lib" - ] + "include": ["../../../../src/**/*.ts", "../../../../src/**/*.tsx"], + "exclude": ["../../../../node_modules", "../../../../lib"] } diff --git a/stack/rush-stack-compiler-3.6/includes/tsconfig-node.json b/stack/rush-stack-compiler-3.6/includes/tsconfig-node.json index 4b3023cd795..722f0b8f62a 100644 --- a/stack/rush-stack-compiler-3.6/includes/tsconfig-node.json +++ b/stack/rush-stack-compiler-3.6/includes/tsconfig-node.json @@ -5,6 +5,6 @@ "compilerOptions": { "module": "commonjs", "target": "es2017", - "lib": [ "es2017" ] + "lib": ["es2017"] } } diff --git a/stack/rush-stack-compiler-3.6/includes/tsconfig-web.json b/stack/rush-stack-compiler-3.6/includes/tsconfig-web.json index cec8cef7f99..5dd9e12e4aa 100644 --- a/stack/rush-stack-compiler-3.6/includes/tsconfig-web.json +++ b/stack/rush-stack-compiler-3.6/includes/tsconfig-web.json @@ -6,13 +6,6 @@ "module": "esnext", "moduleResolution": "node", "target": "es5", - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ] + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"] } } diff --git a/stack/rush-stack-compiler-3.6/includes/tslint.json b/stack/rush-stack-compiler-3.6/includes/tslint.json index 052770e297e..f55613b66cc 100644 --- a/stack/rush-stack-compiler-3.6/includes/tslint.json +++ b/stack/rush-stack-compiler-3.6/includes/tslint.json @@ -1,9 +1,7 @@ { "$schema": "http://json.schemastore.org/tslint", - "rulesDirectory": [ - "tslint-microsoft-contrib" - ], + "rulesDirectory": ["tslint-microsoft-contrib"], "rules": { "class-name": true, "comment-format": [true, "check-space"], @@ -43,14 +41,7 @@ "no-any": true, "no-bitwise": true, "no-consecutive-blank-lines": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], + "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], "no-constant-condition": true, "no-construct": true, "no-debugger": true, @@ -73,13 +64,7 @@ "no-with-statement": true, "no-var-keyword": true, "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], + "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"], "quotemark": [true, "single", "avoid-escape"], "prefer-const": true, "radix": true, @@ -113,13 +98,6 @@ "use-isnan": true, "use-named-parameter": true, "variable-name": [true, "check-format", "allow-leading-underscore", "ban-keywords"], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] + "whitespace": [true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type"] } } diff --git a/stack/rush-stack-compiler-3.6/tsconfig.json b/stack/rush-stack-compiler-3.6/tsconfig.json index 29a2db909ad..56aa0598ed3 100644 --- a/stack/rush-stack-compiler-3.6/tsconfig.json +++ b/stack/rush-stack-compiler-3.6/tsconfig.json @@ -4,4 +4,4 @@ "compilerOptions": { "rootDir": "src" } -} \ No newline at end of file +} diff --git a/stack/rush-stack-compiler-3.7/.eslintrc.js b/stack/rush-stack-compiler-3.7/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/stack/rush-stack-compiler-3.7/.eslintrc.js +++ b/stack/rush-stack-compiler-3.7/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/stack/rush-stack-compiler-3.7/gulpfile.js b/stack/rush-stack-compiler-3.7/gulpfile.js index b298091c3dc..ba4ec3edbb7 100644 --- a/stack/rush-stack-compiler-3.7/gulpfile.js +++ b/stack/rush-stack-compiler-3.7/gulpfile.js @@ -8,13 +8,31 @@ const sharedLibDir = path.join(__dirname, 'lib', 'shared'); build.preCopy.setConfig({ copyTo: { [sharedSrcDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*') + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*' + ), ], [sharedLibDir]: [ - path.join(__dirname, 'node_modules', '@microsoft', 'rush-stack-compiler-shared', 'src', 'shared', '**', '*.d.ts') - ] + path.join( + __dirname, + 'node_modules', + '@microsoft', + 'rush-stack-compiler-shared', + 'src', + 'shared', + '**', + '*.d.ts' + ), + ], }, - shouldFlatten: false + shouldFlatten: false, }); build.preCopy.cleanMatch = [sharedSrcDir]; diff --git a/stack/rush-stack-compiler-3.7/includes/tsconfig-base.json b/stack/rush-stack-compiler-3.7/includes/tsconfig-base.json index 89f92e23058..7bc3fe2ec7c 100644 --- a/stack/rush-stack-compiler-3.7/includes/tsconfig-base.json +++ b/stack/rush-stack-compiler-3.7/includes/tsconfig-base.json @@ -16,12 +16,6 @@ "noUnusedLocals": true, "types": [] }, - "include": [ - "../../../../src/**/*.ts", - "../../../../src/**/*.tsx" - ], - "exclude": [ - "../../../../node_modules", - "../../../../lib" - ] + "include": ["../../../../src/**/*.ts", "../../../../src/**/*.tsx"], + "exclude": ["../../../../node_modules", "../../../../lib"] } diff --git a/stack/rush-stack-compiler-3.7/includes/tsconfig-node.json b/stack/rush-stack-compiler-3.7/includes/tsconfig-node.json index 4b3023cd795..722f0b8f62a 100644 --- a/stack/rush-stack-compiler-3.7/includes/tsconfig-node.json +++ b/stack/rush-stack-compiler-3.7/includes/tsconfig-node.json @@ -5,6 +5,6 @@ "compilerOptions": { "module": "commonjs", "target": "es2017", - "lib": [ "es2017" ] + "lib": ["es2017"] } } diff --git a/stack/rush-stack-compiler-3.7/includes/tsconfig-web.json b/stack/rush-stack-compiler-3.7/includes/tsconfig-web.json index cec8cef7f99..5dd9e12e4aa 100644 --- a/stack/rush-stack-compiler-3.7/includes/tsconfig-web.json +++ b/stack/rush-stack-compiler-3.7/includes/tsconfig-web.json @@ -6,13 +6,6 @@ "module": "esnext", "moduleResolution": "node", "target": "es5", - "lib": [ - "es5", - "scripthost", - "es2015.collection", - "es2015.promise", - "es2015.iterable", - "dom" - ] + "lib": ["es5", "scripthost", "es2015.collection", "es2015.promise", "es2015.iterable", "dom"] } } diff --git a/stack/rush-stack-compiler-3.7/includes/tslint.json b/stack/rush-stack-compiler-3.7/includes/tslint.json index 052770e297e..f55613b66cc 100644 --- a/stack/rush-stack-compiler-3.7/includes/tslint.json +++ b/stack/rush-stack-compiler-3.7/includes/tslint.json @@ -1,9 +1,7 @@ { "$schema": "http://json.schemastore.org/tslint", - "rulesDirectory": [ - "tslint-microsoft-contrib" - ], + "rulesDirectory": ["tslint-microsoft-contrib"], "rules": { "class-name": true, "comment-format": [true, "check-space"], @@ -43,14 +41,7 @@ "no-any": true, "no-bitwise": true, "no-consecutive-blank-lines": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], + "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], "no-constant-condition": true, "no-construct": true, "no-debugger": true, @@ -73,13 +64,7 @@ "no-with-statement": true, "no-var-keyword": true, "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], + "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"], "quotemark": [true, "single", "avoid-escape"], "prefer-const": true, "radix": true, @@ -113,13 +98,6 @@ "use-isnan": true, "use-named-parameter": true, "variable-name": [true, "check-format", "allow-leading-underscore", "ban-keywords"], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] + "whitespace": [true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type"] } } diff --git a/stack/rush-stack-compiler-3.7/tsconfig.json b/stack/rush-stack-compiler-3.7/tsconfig.json index 29a2db909ad..56aa0598ed3 100644 --- a/stack/rush-stack-compiler-3.7/tsconfig.json +++ b/stack/rush-stack-compiler-3.7/tsconfig.json @@ -4,4 +4,4 @@ "compilerOptions": { "rootDir": "src" } -} \ No newline at end of file +} diff --git a/stack/rush-stack-compiler-shared/src/shared/ApiExtractorRunner.ts b/stack/rush-stack-compiler-shared/src/shared/ApiExtractorRunner.ts index eb863e79db0..ac385849737 100644 --- a/stack/rush-stack-compiler-shared/src/shared/ApiExtractorRunner.ts +++ b/stack/rush-stack-compiler-shared/src/shared/ApiExtractorRunner.ts @@ -3,10 +3,7 @@ import { ITerminalProvider } from '@rushstack/node-core-library'; -import { - RushStackCompilerBase, - IRushStackCompilerBaseOptions -} from './RushStackCompilerBase'; +import { RushStackCompilerBase, IRushStackCompilerBaseOptions } from './RushStackCompilerBase'; import { ApiExtractor } from './index'; import { ToolPaths } from './ToolPaths'; import { LoggingUtilities } from './LoggingUtilities'; @@ -26,14 +23,14 @@ export class ApiExtractorRunner extends RushStackCompilerBase { extractorOptions: ApiExtractor.IExtractorInvokeOptions, rootPath: string, terminalProvider: ITerminalProvider - ) // Remove in the next major version + ); // Remove in the next major version public constructor( options: IRushStackCompilerBaseOptions, extractorConfig: ApiExtractor.ExtractorConfig, extractorOptions: ApiExtractor.IExtractorInvokeOptions, rootPath: string, terminalProvider: ITerminalProvider - ) + ); public constructor( arg1: IRushStackCompilerBaseOptions | ApiExtractor.ExtractorConfig, arg2: ApiExtractor.ExtractorConfig | ApiExtractor.IExtractorInvokeOptions, @@ -120,7 +117,7 @@ export class ApiExtractorRunner extends RushStackCompilerBase { } message.handled = true; }, - typescriptCompilerFolder: ToolPaths.typescriptPackagePath + typescriptCompilerFolder: ToolPaths.typescriptPackagePath, }; // NOTE: ExtractorResult.succeeded indicates whether errors or warnings occurred, however we diff --git a/stack/rush-stack-compiler-shared/src/shared/CmdRunner.ts b/stack/rush-stack-compiler-shared/src/shared/CmdRunner.ts index 7465d4171e2..3a6fb309243 100644 --- a/stack/rush-stack-compiler-shared/src/shared/CmdRunner.ts +++ b/stack/rush-stack-compiler-shared/src/shared/CmdRunner.ts @@ -4,11 +4,7 @@ import * as childProcess from 'child_process'; import * as path from 'path'; -import { - IPackageJson, - FileSystem, - Terminal -} from '@rushstack/node-core-library'; +import { IPackageJson, FileSystem, Terminal } from '@rushstack/node-core-library'; import { StandardBuildFolders } from './StandardBuildFolders'; /** @@ -55,11 +51,7 @@ export class CmdRunner { private _options: IBaseTaskOptions; private _errorHasBeenLogged: boolean; - public constructor( - constants: StandardBuildFolders, - terminal: Terminal, - options: IBaseTaskOptions - ) { + public constructor(constants: StandardBuildFolders, terminal: Terminal, options: IBaseTaskOptions) { this._standardBuildFolders = constants; this._terminal = terminal; this._options = options; @@ -70,7 +62,7 @@ export class CmdRunner { args, onData = this._onData.bind(this), onError = this._onError.bind(this), - onClose = this._onClose.bind(this) + onClose = this._onClose.bind(this), }: IRunCmdOptions = options; const packageJson: IPackageJson | undefined = this._options.packageJson; @@ -84,10 +76,12 @@ export class CmdRunner { const binaryPath: string = path.resolve(this._options.packagePath, this._options.packageBinPath); if (!FileSystem.exists(binaryPath)) { - return Promise.reject(new Error( - `The binary is missing. This indicates that ${this._options.packageBinPath} is not ` + - 'installed correctly.' - )); + return Promise.reject( + new Error( + `The binary is missing. This indicates that ${this._options.packageBinPath} is not ` + + 'installed correctly.' + ) + ); } return new Promise((resolve: () => void, reject: (error: Error) => void) => { @@ -98,15 +92,11 @@ export class CmdRunner { } // Invoke the tool and watch for log messages - const spawnResult: childProcess.ChildProcess = childProcess.spawn( - nodePath, - [binaryPath, ...args], - { - cwd: this._standardBuildFolders.projectFolderPath, - env: process.env, - stdio: 'pipe' - } - ); + const spawnResult: childProcess.ChildProcess = childProcess.spawn(nodePath, [binaryPath, ...args], { + cwd: this._standardBuildFolders.projectFolderPath, + env: process.env, + stdio: 'pipe', + }); if (spawnResult.stdout !== null) { spawnResult.stdout.on('data', onData); @@ -129,7 +119,12 @@ export class CmdRunner { this._terminal.writeError(data.toString().trim()); } - protected _onClose(code: number, hasErrors: boolean, resolve: () => void, reject: (error: Error) => void): void { + protected _onClose( + code: number, + hasErrors: boolean, + resolve: () => void, + reject: (error: Error) => void + ): void { if (code !== 0 || hasErrors) { reject(new Error(`exited with code ${code}`)); } else { diff --git a/stack/rush-stack-compiler-shared/src/shared/EslintRunner.ts b/stack/rush-stack-compiler-shared/src/shared/EslintRunner.ts index 466e766a879..68c3c77e02d 100644 --- a/stack/rush-stack-compiler-shared/src/shared/EslintRunner.ts +++ b/stack/rush-stack-compiler-shared/src/shared/EslintRunner.ts @@ -7,10 +7,7 @@ import { ITerminalProvider } from '@rushstack/node-core-library'; import { CmdRunner } from './CmdRunner'; import { ToolPaths } from './ToolPaths'; import { ILintRunnerConfig } from './ILintRunnerConfig'; -import { - RushStackCompilerBase, - WriteFileIssueFunction -} from './RushStackCompilerBase'; +import { RushStackCompilerBase, WriteFileIssueFunction } from './RushStackCompilerBase'; interface IEslintFileResult { // Example: "/full/path/to/File.ts" @@ -30,7 +27,7 @@ interface IEslintFileResult { enum EslintSeverity { Off = 0, Warn = 1, - Error = 2 + Error = 2, } interface IEslintMessage { @@ -62,22 +59,15 @@ export class EslintRunner extends RushStackCompilerBase { public constructor(taskOptions: ILintRunnerConfig, rootPath: string, terminalProvider: ITerminalProvider) { super(taskOptions, rootPath, terminalProvider); - this._cmdRunner = new CmdRunner( - this._standardBuildFolders, - this._terminal, - { - packagePath: ToolPaths.eslintPackagePath, - packageJson: ToolPaths.eslintPackageJson, - packageBinPath: path.join('bin', 'eslint.js') - } - ); + this._cmdRunner = new CmdRunner(this._standardBuildFolders, this._terminal, { + packagePath: ToolPaths.eslintPackagePath, + packageJson: ToolPaths.eslintPackageJson, + packageBinPath: path.join('bin', 'eslint.js'), + }); } public invoke(): Promise { - const args: string[] = [ - '--format', 'json', - 'src/**/*.{ts,tsx}' - ]; + const args: string[] = ['--format', 'json', 'src/**/*.{ts,tsx}']; const stdoutBuffer: string[] = []; @@ -100,16 +90,12 @@ export class EslintRunner extends RushStackCompilerBase { ? this._taskOptions.fileError : this._taskOptions.fileWarning; for (const eslintFileResult of eslintFileResults) { - const pathFromRoot: string = path.relative(this._standardBuildFolders.projectFolderPath, - eslintFileResult.filePath); + const pathFromRoot: string = path.relative( + this._standardBuildFolders.projectFolderPath, + eslintFileResult.filePath + ); for (const message of eslintFileResult.messages) { - eslintErrorLogFn( - pathFromRoot, - message.line, - message.column, - message.ruleId, - message.message - ); + eslintErrorLogFn(pathFromRoot, message.line, message.column, message.ruleId, message.message); } } } catch (e) { @@ -124,7 +110,7 @@ export class EslintRunner extends RushStackCompilerBase { } else { resolve(); } - } + }, }); } } diff --git a/stack/rush-stack-compiler-shared/src/shared/LoggingUtilities.ts b/stack/rush-stack-compiler-shared/src/shared/LoggingUtilities.ts index cdc3376c5f5..cc57a260925 100644 --- a/stack/rush-stack-compiler-shared/src/shared/LoggingUtilities.ts +++ b/stack/rush-stack-compiler-shared/src/shared/LoggingUtilities.ts @@ -1,14 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - Terminal, - ITerminalProvider -} from '@rushstack/node-core-library'; -import { - WriteFileIssueFunction, - IRushStackCompilerBaseOptions -} from './RushStackCompilerBase'; +import { Terminal, ITerminalProvider } from '@rushstack/node-core-library'; +import { WriteFileIssueFunction, IRushStackCompilerBaseOptions } from './RushStackCompilerBase'; export class LoggingUtilities { private _terminal: Terminal; @@ -20,7 +14,7 @@ export class LoggingUtilities { public getDefaultRushStackCompilerBaseOptions(): IRushStackCompilerBaseOptions { return { fileError: this.fileError, - fileWarning: this.fileWarning + fileWarning: this.fileWarning, }; } @@ -32,7 +26,7 @@ export class LoggingUtilities { message: string ): void => { this._terminal.writeErrorLine(`${filePath}(${line},${column}): error ${errorCode}: ${message}`); - } + }; public fileWarning: WriteFileIssueFunction = ( filePath: string, @@ -42,5 +36,5 @@ export class LoggingUtilities { message: string ): void => { this._terminal.writeWarningLine(`${filePath}(${line},${column}): warning ${errorCode}: ${message}`); - } + }; } diff --git a/stack/rush-stack-compiler-shared/src/shared/ToolPackages.d.ts b/stack/rush-stack-compiler-shared/src/shared/ToolPackages.d.ts index 5e2f2cf8182..0a61d17abf9 100644 --- a/stack/rush-stack-compiler-shared/src/shared/ToolPackages.d.ts +++ b/stack/rush-stack-compiler-shared/src/shared/ToolPackages.d.ts @@ -5,8 +5,4 @@ import * as Tslint from 'tslint'; import * as Typescript from 'typescript'; import * as ApiExtractor from '@microsoft/api-extractor'; -export { - Typescript, - Tslint, - ApiExtractor -}; +export { Typescript, Tslint, ApiExtractor }; diff --git a/stack/rush-stack-compiler-shared/src/shared/TslintRunner.ts b/stack/rush-stack-compiler-shared/src/shared/TslintRunner.ts index 0c18d044cf1..84bb13e6f0c 100644 --- a/stack/rush-stack-compiler-shared/src/shared/TslintRunner.ts +++ b/stack/rush-stack-compiler-shared/src/shared/TslintRunner.ts @@ -8,15 +8,12 @@ import { CmdRunner } from './CmdRunner'; import { ToolPaths } from './ToolPaths'; import { Tslint } from './index'; import { ILintRunnerConfig } from './ILintRunnerConfig'; -import { - RushStackCompilerBase, - WriteFileIssueFunction -} from './RushStackCompilerBase'; +import { RushStackCompilerBase, WriteFileIssueFunction } from './RushStackCompilerBase'; /** * @public */ -export interface ITslintRunnerConfig extends ILintRunnerConfig { } +export interface ITslintRunnerConfig extends ILintRunnerConfig {} /** * @beta @@ -24,24 +21,21 @@ export interface ITslintRunnerConfig extends ILintRunnerConfig { } export class TslintRunner extends RushStackCompilerBase { private _cmdRunner: CmdRunner; - public constructor(taskOptions: ITslintRunnerConfig, rootPath: string, terminalProvider: ITerminalProvider) { + public constructor( + taskOptions: ITslintRunnerConfig, + rootPath: string, + terminalProvider: ITerminalProvider + ) { super(taskOptions, rootPath, terminalProvider); - this._cmdRunner = new CmdRunner( - this._standardBuildFolders, - this._terminal, - { - packagePath: ToolPaths.tslintPackagePath, - packageJson: ToolPaths.tslintPackageJson, - packageBinPath: path.join('bin', 'tslint') - } - ); + this._cmdRunner = new CmdRunner(this._standardBuildFolders, this._terminal, { + packagePath: ToolPaths.tslintPackagePath, + packageJson: ToolPaths.tslintPackageJson, + packageBinPath: path.join('bin', 'tslint'), + }); } public invoke(): Promise { - const args: string[] = [ - '--format', 'json', - '--project', this._standardBuildFolders.projectFolderPath - ]; + const args: string[] = ['--format', 'json', '--project', this._standardBuildFolders.projectFolderPath]; return this._cmdRunner.runCmd({ args: args, @@ -55,7 +49,10 @@ export class TslintRunner extends RushStackCompilerBase { try { const errors: Tslint.IRuleFailureJson[] = JSON.parse(dataStr); for (const error of errors) { - const pathFromRoot: string = path.relative(this._standardBuildFolders.projectFolderPath, error.name); + const pathFromRoot: string = path.relative( + this._standardBuildFolders.projectFolderPath, + error.name + ); tslintErrorLogFn( pathFromRoot, error.startPosition.line + 1, @@ -77,7 +74,7 @@ export class TslintRunner extends RushStackCompilerBase { } else { resolve(); } - } + }, }); } } diff --git a/stack/rush-stack-compiler-shared/src/shared/TypescriptCompiler.ts b/stack/rush-stack-compiler-shared/src/shared/TypescriptCompiler.ts index 8fb533b9eb1..34380e3424d 100644 --- a/stack/rush-stack-compiler-shared/src/shared/TypescriptCompiler.ts +++ b/stack/rush-stack-compiler-shared/src/shared/TypescriptCompiler.ts @@ -6,10 +6,7 @@ import { ITerminalProvider } from '@rushstack/node-core-library'; import { CmdRunner } from './CmdRunner'; import { ToolPaths } from './ToolPaths'; -import { - RushStackCompilerBase, - IRushStackCompilerBaseOptions -} from './RushStackCompilerBase'; +import { RushStackCompilerBase, IRushStackCompilerBaseOptions } from './RushStackCompilerBase'; import { LoggingUtilities } from './LoggingUtilities'; /** @@ -27,8 +24,12 @@ export interface ITypescriptCompilerOptions extends IRushStackCompilerBaseOption */ export class TypescriptCompiler extends RushStackCompilerBase { private _cmdRunner: CmdRunner; - public constructor(rootPath: string, terminalProvider: ITerminalProvider) // Remove in the next major version - public constructor(taskOptions: ITypescriptCompilerOptions, rootPath: string, terminalProvider: ITerminalProvider) + public constructor(rootPath: string, terminalProvider: ITerminalProvider); // Remove in the next major version + public constructor( + taskOptions: ITypescriptCompilerOptions, + rootPath: string, + terminalProvider: ITerminalProvider + ); public constructor( arg1: ITypescriptCompilerOptions | string, arg2: string | ITerminalProvider, @@ -60,15 +61,11 @@ export class TypescriptCompiler extends RushStackCompilerBase { @@ -88,7 +85,7 @@ export class TypescriptCompiler extends RushStackCompilerBase { expect(LoadThemedStylesMock.calledWithAsync).toHaveLength(2); expect(returnedModule.exports).toEqual('locals'); }); -}); \ No newline at end of file +}); diff --git a/webpack/loader-load-themed-styles/src/test/testData/MockStyle1.ts b/webpack/loader-load-themed-styles/src/test/testData/MockStyle1.ts index 90d24a1c58d..add255822a3 100644 --- a/webpack/loader-load-themed-styles/src/test/testData/MockStyle1.ts +++ b/webpack/loader-load-themed-styles/src/test/testData/MockStyle1.ts @@ -2,7 +2,10 @@ // See LICENSE in the project root for license information. // eslint-disable-next-line @typescript-eslint/no-explicit-any -const exportedObject: any = [['A', 'STYLE 1'], ['B', 'STYLE 2']]; +const exportedObject: any = [ + ['A', 'STYLE 1'], + ['B', 'STYLE 2'], +]; exportedObject.locals = 'locals'; diff --git a/webpack/loader-load-themed-styles/tsconfig.json b/webpack/loader-load-themed-styles/tsconfig.json index f594dff44cc..b1ef19d6b47 100644 --- a/webpack/loader-load-themed-styles/tsconfig.json +++ b/webpack/loader-load-themed-styles/tsconfig.json @@ -1,9 +1,6 @@ { "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "node", - "jest" - ] + "types": ["node", "jest"] } } diff --git a/webpack/loader-raw-script/.eslintrc.js b/webpack/loader-raw-script/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/webpack/loader-raw-script/.eslintrc.js +++ b/webpack/loader-raw-script/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/webpack/loader-raw-script/config/jest.json b/webpack/loader-raw-script/config/jest.json index b4a7ec97a56..902b00ea176 100644 --- a/webpack/loader-raw-script/config/jest.json +++ b/webpack/loader-raw-script/config/jest.json @@ -1,3 +1,3 @@ { "isEnabled": true -} \ No newline at end of file +} diff --git a/webpack/loader-raw-script/src/RawScriptLoader.ts b/webpack/loader-raw-script/src/RawScriptLoader.ts index 778701a76f5..d2afe6a26ed 100644 --- a/webpack/loader-raw-script/src/RawScriptLoader.ts +++ b/webpack/loader-raw-script/src/RawScriptLoader.ts @@ -5,14 +5,14 @@ import { EOL } from 'os'; const loaderFn: (content: string) => string = (content: string) => { content = content.replace(/\\/g, '\\\\'); - content = content.replace(/'/g, '\\\''); + content = content.replace(/'/g, "\\'"); content = content.replace(/\n/g, '\\n'); content = content.replace(/\r/g, '\\r'); const lines: string[] = [ '(function (global) {', ` eval('${content}');`, - '}.call(exports, (function() { return this; }())))' + '}.call(exports, (function() { return this; }())))', ]; return lines.join(EOL); diff --git a/webpack/loader-raw-script/src/test/RawScriptLoader.test.ts b/webpack/loader-raw-script/src/test/RawScriptLoader.test.ts index ae6b5fe695c..5c90c86450e 100644 --- a/webpack/loader-raw-script/src/test/RawScriptLoader.test.ts +++ b/webpack/loader-raw-script/src/test/RawScriptLoader.test.ts @@ -25,4 +25,4 @@ describe('RawScriptLoader', () => { const exports: { exportedObject: number } = eval(wrapResult(RawScriptLoader(testScript))); expect(exports.exportedObject).toEqual(123); }); -}); \ No newline at end of file +}); diff --git a/webpack/loader-raw-script/tsconfig.json b/webpack/loader-raw-script/tsconfig.json index f594dff44cc..b1ef19d6b47 100644 --- a/webpack/loader-raw-script/tsconfig.json +++ b/webpack/loader-raw-script/tsconfig.json @@ -1,9 +1,6 @@ { "extends": "./node_modules/@microsoft/rush-stack-compiler-3.5/includes/tsconfig-node.json", "compilerOptions": { - "types": [ - "node", - "jest" - ] + "types": ["node", "jest"] } } diff --git a/webpack/localization-plugin/.eslintrc.js b/webpack/localization-plugin/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/webpack/localization-plugin/.eslintrc.js +++ b/webpack/localization-plugin/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/webpack/localization-plugin/src/AssetProcessor.ts b/webpack/localization-plugin/src/AssetProcessor.ts index 7eb428dfc25..715bcc77ceb 100644 --- a/webpack/localization-plugin/src/AssetProcessor.ts +++ b/webpack/localization-plugin/src/AssetProcessor.ts @@ -64,7 +64,7 @@ export interface IProcessAssetOptionsBase { chunkHasLocalizedModules: (chunk: Webpack.compilation.Chunk) => boolean; } -export interface IProcessNonLocalizedAssetOptions extends IProcessAssetOptionsBase { } +export interface IProcessNonLocalizedAssetOptions extends IProcessAssetOptionsBase {} export interface IProcessLocalizedAssetOptions extends IProcessAssetOptionsBase { locales: Set; @@ -88,7 +88,9 @@ export const PLACEHOLDER_REGEX: RegExp = new RegExp( ); export class AssetProcessor { - public static processLocalizedAsset(options: IProcessLocalizedAssetOptions): Map { + public static processLocalizedAsset( + options: IProcessLocalizedAssetOptions + ): Map { const assetSource: string = options.asset.source(); const parsedAsset: IParseResult = AssetProcessor._parseStringToReconstructionSequence( @@ -107,7 +109,9 @@ export class AssetProcessor { const parsedAssetName: IParseResult = AssetProcessor._parseStringToReconstructionSequence( options.plugin, options.assetName, - () => { throw new Error('unsupported'); } + () => { + throw new Error('unsupported'); + } ); const reconstructedAssetName: ILocalizedReconstructionResult = AssetProcessor._reconstructLocalized( parsedAssetName.reconstructionSeries, @@ -123,26 +127,23 @@ export class AssetProcessor { newAsset.source = () => source; newAsset.size = () => size; - result.set( - locale, - { - filename: reconstructedAssetName.result.get(locale)!.source, - asset: newAsset - } - ); + result.set(locale, { + filename: reconstructedAssetName.result.get(locale)!.source, + asset: newAsset, + }); } const issues: string[] = [ ...parsedAsset.issues, ...reconstructedAsset.issues, ...parsedAssetName.issues, - ...reconstructedAssetName.issues + ...reconstructedAssetName.issues, ]; if (issues.length > 0) { - options.compilation.errors.push(Error( - `localization:\n${issues.map((issue) => ` ${issue}`).join('\n')}` - )); + options.compilation.errors.push( + Error(`localization:\n${issues.map((issue) => ` ${issue}`).join('\n')}`) + ); } return result; @@ -165,7 +166,9 @@ export class AssetProcessor { const parsedAssetName: IParseResult = AssetProcessor._parseStringToReconstructionSequence( options.plugin, options.assetName, - () => { throw new Error('unsupported'); } + () => { + throw new Error('unsupported'); + } ); const reconstructedAssetName: INonLocalizedReconstructionResult = AssetProcessor._reconstructNonLocalized( parsedAssetName.reconstructionSeries, @@ -177,13 +180,13 @@ export class AssetProcessor { ...parsedAsset.issues, ...reconstructedAsset.issues, ...parsedAssetName.issues, - ...reconstructedAssetName.issues + ...reconstructedAssetName.issues, ]; if (issues.length > 0) { - options.compilation.errors.push(Error( - `localization:\n${issues.map((issue) => ` ${issue}`).join('\n')}` - )); + options.compilation.errors.push( + Error(`localization:\n${issues.map((issue) => ` ${issue}`).join('\n')}`) + ); } const newAsset: IAsset = lodash.clone(options.asset); @@ -191,7 +194,7 @@ export class AssetProcessor { newAsset.size = () => reconstructedAsset.result.size; return { filename: reconstructedAssetName.result.source, - asset: newAsset + asset: newAsset, }; } @@ -225,7 +228,7 @@ export class AssetProcessor { } else { issues.push( `The string "${localizedElement.stringName}" in "${localizedElement.locFilePath}" is missing in ` + - `the locale ${locale}` + `the locale ${locale}` ); newValue = '-- MISSING STRING --'; @@ -248,7 +251,7 @@ export class AssetProcessor { newValue = newValue.replace(/\'/g, `${escapingCharacterSequence}u0027`); reconstruction.push(newValue); - sizeDiff += (newValue.length - localizedElement.size); + sizeDiff += newValue.length - localizedElement.size; break; } @@ -256,25 +259,22 @@ export class AssetProcessor { const dynamicElement: IDynamicReconstructionElement = element as IDynamicReconstructionElement; const newValue: string = dynamicElement.valueFn(locale, dynamicElement.token); reconstruction.push(newValue); - sizeDiff += (newValue.length - dynamicElement.size); + sizeDiff += newValue.length - dynamicElement.size; break; } } } const newAssetSource: string = reconstruction.join(''); - localizedResults.set( - locale, - { - source: newAssetSource, - size: initialSize + sizeDiff - } - ); + localizedResults.set(locale, { + source: newAssetSource, + size: initialSize + sizeDiff, + }); } return { issues, - result: localizedResults + result: localizedResults, }; } @@ -299,12 +299,12 @@ export class AssetProcessor { const localizedElement: ILocalizedReconstructionElement = element as ILocalizedReconstructionElement; issues.push( `The string "${localizedElement.stringName}" in "${localizedElement.locFilePath}" appeared in an asset ` + - 'that is not expected to contain localized resources.' + 'that is not expected to contain localized resources.' ); const newValue: string = '-- NOT EXPECTED TO BE LOCALIZED --'; reconstruction.push(newValue); - sizeDiff += (newValue.length - localizedElement.size); + sizeDiff += newValue.length - localizedElement.size; break; } @@ -312,7 +312,7 @@ export class AssetProcessor { const dynamicElement: IDynamicReconstructionElement = element as IDynamicReconstructionElement; const newValue: string = dynamicElement.valueFn(noStringsLocaleName, dynamicElement.token); reconstruction.push(newValue); - sizeDiff += (newValue.length - dynamicElement.size); + sizeDiff += newValue.length - dynamicElement.size; break; } } @@ -323,8 +323,8 @@ export class AssetProcessor { issues, result: { source: newAssetSource, - size: initialSize + sizeDiff - } + size: initialSize + sizeDiff, + }, }; } @@ -338,10 +338,11 @@ export class AssetProcessor { let lastIndex: number = 0; let regexResult: RegExpExecArray | null; - while (regexResult = PLACEHOLDER_REGEX.exec(source)) { // eslint-disable-line no-cond-assign + while ((regexResult = PLACEHOLDER_REGEX.exec(source))) { + // eslint-disable-line no-cond-assign const staticElement: IStaticReconstructionElement = { kind: 'static', - staticString: source.substring(lastIndex, regexResult.index) + staticString: source.substring(lastIndex, regexResult.index), }; reconstructionSeries.push(staticElement); @@ -355,7 +356,7 @@ export class AssetProcessor { issues.push(`Missing placeholder ${placeholder}`); const brokenLocalizedElement: IStaticReconstructionElement = { kind: 'static', - staticString: placeholder + staticString: placeholder, }; localizedReconstructionElement = brokenLocalizedElement; } else { @@ -377,7 +378,7 @@ export class AssetProcessor { kind: 'dynamic', valueFn: (locale: string) => locale, size: placeholder.length, - escapedBackslash: escapedBackslash + escapedBackslash: escapedBackslash, }; localizedReconstructionElement = dynamicElement; break; @@ -389,13 +390,13 @@ export class AssetProcessor { valueFn: jsonpFunction, size: placeholder.length, escapedBackslash: escapedBackslash, - token: token.substring(1, token.length - 1) + token: token.substring(1, token.length - 1), }; localizedReconstructionElement = dynamicElement; break; } - default:{ + default: { throw new Error(`Unexpected label ${elementLabel}`); } } @@ -406,13 +407,13 @@ export class AssetProcessor { const lastElement: IStaticReconstructionElement = { kind: 'static', - staticString: source.substr(lastIndex) + staticString: source.substr(lastIndex), }; reconstructionSeries.push(lastElement); return { issues, - reconstructionSeries + reconstructionSeries, }; } @@ -458,8 +459,10 @@ export class AssetProcessor { throw new Error('Missing locale name.'); } - return `(${JSON.stringify([locale, noStringsLocaleName])})[${JSON.stringify(chunkMapping)}[${chunkIdToken}]]`; - } + return `(${JSON.stringify([locale, noStringsLocaleName])})[${JSON.stringify( + chunkMapping + )}[${chunkIdToken}]]`; + }; } } } diff --git a/webpack/localization-plugin/src/LocFileTypingsGenerator.ts b/webpack/localization-plugin/src/LocFileTypingsGenerator.ts index 44c72aae037..609c1f0540e 100644 --- a/webpack/localization-plugin/src/LocFileTypingsGenerator.ts +++ b/webpack/localization-plugin/src/LocFileTypingsGenerator.ts @@ -1,14 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - StringValuesTypingsGenerator, - IStringValueTyping -} from '@rushstack/typings-generator'; -import { - Terminal, - NewlineKind -} from '@rushstack/node-core-library'; +import { StringValuesTypingsGenerator, IStringValueTyping } from '@rushstack/typings-generator'; +import { Terminal, NewlineKind } from '@rushstack/node-core-library'; import { ILocalizationFile } from './interfaces'; import { LocFileParser } from './utilities/LocFileParser'; @@ -40,20 +34,21 @@ export class LocFileTypingsGenerator extends StringValuesTypingsGenerator { filePath: filePath, content: fileContents, terminal: this._options.terminal!, - resxNewlineNormalization: options.resxNewlineNormalization + resxNewlineNormalization: options.resxNewlineNormalization, }); const typings: IStringValueTyping[] = []; - for (const stringName in locFileData) { // eslint-disable-line guard-for-in + for (const stringName in locFileData) { + // eslint-disable-line guard-for-in typings.push({ exportName: stringName, - comment: locFileData[stringName].comment + comment: locFileData[stringName].comment, }); } return { typings }; - } + }, }); } -} \ No newline at end of file +} diff --git a/webpack/localization-plugin/src/LocalizationPlugin.ts b/webpack/localization-plugin/src/LocalizationPlugin.ts index df9cd7b18cf..dace17ba94a 100644 --- a/webpack/localization-plugin/src/LocalizationPlugin.ts +++ b/webpack/localization-plugin/src/LocalizationPlugin.ts @@ -1,12 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - JsonFile, - FileSystem, - Terminal, - NewlineKind -} from '@rushstack/node-core-library'; +import { JsonFile, FileSystem, Terminal, NewlineKind } from '@rushstack/node-core-library'; import * as Webpack from 'webpack'; import * as path from 'path'; import * as Tapable from 'tapable'; @@ -14,7 +9,7 @@ import * as Tapable from 'tapable'; import { Constants } from './utilities/Constants'; import { IWebpackConfigurationUpdaterOptions, - WebpackConfigurationUpdater + WebpackConfigurationUpdater, } from './WebpackConfigurationUpdater'; import { ILocalizationPluginOptions, @@ -25,20 +20,13 @@ import { IPseudolocaleOptions, ILocaleElementMap, ILocalizedStrings, - IResolvedMissingTranslations + IResolvedMissingTranslations, } from './interfaces'; -import { - ILocalizedWebpackChunk -} from './webpackInterfaces'; +import { ILocalizedWebpackChunk } from './webpackInterfaces'; import { LocFileTypingsGenerator } from './LocFileTypingsGenerator'; import { Pseudolocalization } from './Pseudolocalization'; import { EntityMarker } from './utilities/EntityMarker'; -import { - IAsset, - IProcessAssetResult, - AssetProcessor, - PLACEHOLDER_REGEX -} from './AssetProcessor'; +import { IAsset, IProcessAssetResult, AssetProcessor, PLACEHOLDER_REGEX } from './AssetProcessor'; import { LocFileParser } from './utilities/LocFileParser'; /** @@ -111,13 +99,19 @@ export class LocalizationPlugin implements Webpack.Plugin { private _resolvedTranslatedStringsFromOptions: ILocalizedStrings; private _filesToIgnore: Set = new Set(); private _stringPlaceholderCounter: number = 0; - private _stringPlaceholderMap: Map = new Map(); + private _stringPlaceholderMap: Map = new Map< + string, + IStringSerialNumberData + >(); private _locales: Set = new Set(); private _passthroughLocaleName: string; private _defaultLocale: string; private _noStringsLocaleName: string; private _fillMissingTranslationStrings: boolean; - private _pseudolocalizers: Map string> = new Map string>(); + private _pseudolocalizers: Map string> = new Map< + string, + (str: string) => string + >(); private _resxNewlineNormalization: NewlineKind | undefined; /** @@ -125,7 +119,10 @@ export class LocalizationPlugin implements Webpack.Plugin { * The middle map's keys are the resolved, file names. * The innermost map's keys are the string identifiers and its values are the string values. */ - private _resolvedLocalizedStrings: Map>> = new Map>>(); + private _resolvedLocalizedStrings: Map>> = new Map< + string, + Map> + >(); public constructor(options: ILocalizationPluginOptions) { this._options = options; @@ -171,7 +168,7 @@ export class LocalizationPlugin implements Webpack.Plugin { srcFolder: this._options.typingsOptions.sourceRoot || compiler.context, generatedTsFolder: this._options.typingsOptions.generatedTsFolder, exportAsDefault: this._options.typingsOptions.exportAsDefault, - filesToIgnore: this._options.filesToIgnore + filesToIgnore: this._options.filesToIgnore, }); } else { typingsPreprocessor = undefined; @@ -182,7 +179,7 @@ export class LocalizationPlugin implements Webpack.Plugin { configuration: compiler.options, filesToIgnore: this._filesToIgnore, localeNameOrPlaceholder: Constants.LOCALE_NAME_PLACEHOLDER, - resxNewlineNormalization: this._resxNewlineNormalization + resxNewlineNormalization: this._resxNewlineNormalization, }; if (errors.length > 0 || warnings.length > 0) { @@ -194,7 +191,9 @@ export class LocalizationPlugin implements Webpack.Plugin { if (errors.length > 0) { // If there are any errors, just pass through the resources in source and don't do any // additional configuration - WebpackConfigurationUpdater.amendWebpackConfigurationForInPlaceLocFiles(webpackConfigurationUpdaterOptions); + WebpackConfigurationUpdater.amendWebpackConfigurationForInPlaceLocFiles( + webpackConfigurationUpdaterOptions + ); return; } } @@ -207,10 +206,14 @@ export class LocalizationPlugin implements Webpack.Plugin { compiler.options.plugins = []; } - compiler.options.plugins.push(new Webpack.WatchIgnorePlugin([this._options.typingsOptions!.generatedTsFolder])); + compiler.options.plugins.push( + new Webpack.WatchIgnorePlugin([this._options.typingsOptions!.generatedTsFolder]) + ); } - WebpackConfigurationUpdater.amendWebpackConfigurationForInPlaceLocFiles(webpackConfigurationUpdaterOptions); + WebpackConfigurationUpdater.amendWebpackConfigurationForInPlaceLocFiles( + webpackConfigurationUpdaterOptions + ); } else { if (typingsPreprocessor) { compiler.hooks.beforeRun.tap(PLUGIN_NAME, () => typingsPreprocessor!.generateTypings()); @@ -220,7 +223,7 @@ export class LocalizationPlugin implements Webpack.Plugin { if (errors.length === 0) { compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation: IExtendedConfiguration) => { - (compilation.mainTemplate as unknown as IExtendedMainTemplate).hooks.assetPath.tap( + ((compilation.mainTemplate as unknown) as IExtendedMainTemplate).hooks.assetPath.tap( PLUGIN_NAME, (assetPath: string, options: IAssetPathOptions) => { if ( @@ -268,16 +271,17 @@ export class LocalizationPlugin implements Webpack.Plugin { } if ( - chunksHaveAnyChildren && ( - !compilation.options.output || + chunksHaveAnyChildren && + (!compilation.options.output || !compilation.options.output.chunkFilename || - compilation.options.output.chunkFilename.indexOf(Constants.LOCALE_FILENAME_TOKEN) === -1 - ) + compilation.options.output.chunkFilename.indexOf(Constants.LOCALE_FILENAME_TOKEN) === -1) ) { - compilation.errors.push(new Error( - 'The configuration.output.chunkFilename property must be provided and must include ' + - `the ${Constants.LOCALE_FILENAME_TOKEN} placeholder` - )); + compilation.errors.push( + new Error( + 'The configuration.output.chunkFilename property must be provided and must include ' + + `the ${Constants.LOCALE_FILENAME_TOKEN} placeholder` + ) + ); return; } @@ -309,7 +313,7 @@ export class LocalizationPlugin implements Webpack.Plugin { compiler.hooks.emit.tap(PLUGIN_NAME, (compilation: Webpack.compilation.Compilation) => { const localizationStats: ILocalizationStats = { entrypoints: {}, - namedChunkGroups: {} + namedChunkGroups: {}, }; const alreadyProcessedAssets: Set = new Set(); @@ -325,7 +329,9 @@ export class LocalizationPlugin implements Webpack.Plugin { !alreadyProcessedAssets.has(chunkFilename) // Ensure this isn't a vendor chunk we've already processed ) { if (alreadyProcessedAFileInThisChunk) { - throw new Error(`Found more than one JS file in chunk "${chunk.name}". This is not expected.`); + throw new Error( + `Found more than one JS file in chunk "${chunk.name}". This is not expected.` + ); } alreadyProcessedAFileInThisChunk = true; @@ -338,12 +344,17 @@ export class LocalizationPlugin implements Webpack.Plugin { if (this._chunkHasLocalizedModules(chunk)) { processChunkJsFile((chunkFilename) => { if (chunkFilename.indexOf(Constants.LOCALE_NAME_PLACEHOLDER) === -1) { - throw new Error(`Asset ${chunkFilename} is expected to be localized, but is missing a locale placeholder`); + throw new Error( + `Asset ${chunkFilename} is expected to be localized, but is missing a locale placeholder` + ); } const asset: IAsset = compilation.assets[chunkFilename]; - const resultingAssets: Map = AssetProcessor.processLocalizedAsset({ + const resultingAssets: Map< + string, + IProcessAssetResult + > = AssetProcessor.processLocalizedAsset({ plugin: this, compilation, assetName: chunkFilename, @@ -353,7 +364,7 @@ export class LocalizationPlugin implements Webpack.Plugin { locales: this._locales, noStringsLocaleName: this._noStringsLocaleName, fillMissingTranslationStrings: this._fillMissingTranslationStrings, - defaultLocale: this._defaultLocale + defaultLocale: this._defaultLocale, }); // Delete the existing asset because it's been renamed @@ -370,13 +381,13 @@ export class LocalizationPlugin implements Webpack.Plugin { if (chunk.hasRuntime()) { // This is an entrypoint localizationStats.entrypoints[chunk.name] = { - localizedAssets: localizedChunkAssets + localizedAssets: localizedChunkAssets, }; } else { // This is a secondary chunk if (chunk.name) { localizationStats.namedChunkGroups[chunk.name] = { - localizedAssets: localizedChunkAssets + localizedAssets: localizedChunkAssets, }; } } @@ -394,7 +405,7 @@ export class LocalizationPlugin implements Webpack.Plugin { asset, chunk, noStringsLocaleName: this._noStringsLocaleName, - chunkHasLocalizedModules: this._chunkHasLocalizedModules.bind(this) + chunkHasLocalizedModules: this._chunkHasLocalizedModules.bind(this), }); // Delete the existing asset because it's been renamed @@ -415,7 +426,9 @@ export class LocalizationPlugin implements Webpack.Plugin { compiler.outputPath, this._options.localizationStats.dropPath ); - JsonFile.save(localizationStats, resolvedLocalizationStatsDropPath, { ensureFolderExists: true }); + JsonFile.save(localizationStats, resolvedLocalizationStatsDropPath, { + ensureFolderExists: true, + }); } if (this._options.localizationStats.callback) { @@ -447,14 +460,16 @@ export class LocalizationPlugin implements Webpack.Plugin { const locFileData: ILocaleFileData = this._convertLocalizationFileToLocData(localizedResourceData); this._addLocFile(this._defaultLocale, localizedResourcePath, locFileData); - const resolveLocalizedData: (localizedData: ILocaleFileData | string) => ILocaleFileData = (localizedData) => { + const resolveLocalizedData: (localizedData: ILocaleFileData | string) => ILocaleFileData = ( + localizedData + ) => { if (typeof localizedData === 'string') { additionalLoadedFilePaths.push(localizedData); const localizationFile: ILocalizationFile = LocFileParser.parseLocFile({ filePath: localizedData, content: FileSystem.readFile(localizedData), terminal: terminal, - resxNewlineNormalization: this._resxNewlineNormalization + resxNewlineNormalization: this._resxNewlineNormalization, }); return this._convertLocalizationFileToLocData(localizationFile); @@ -466,9 +481,8 @@ export class LocalizationPlugin implements Webpack.Plugin { const missingLocales: string[] = []; for (const translatedLocaleName in this._resolvedTranslatedStringsFromOptions) { if (this._resolvedTranslatedStringsFromOptions.hasOwnProperty(translatedLocaleName)) { - const translatedLocFileFromOptions: ILocaleFileData | string | undefined = ( - this._resolvedTranslatedStringsFromOptions[translatedLocaleName][localizedResourcePath] - ); + const translatedLocFileFromOptions: ILocaleFileData | string | undefined = this + ._resolvedTranslatedStringsFromOptions[translatedLocaleName][localizedResourcePath]; if (!translatedLocFileFromOptions) { missingLocales.push(translatedLocaleName); } else { @@ -492,7 +506,9 @@ export class LocalizationPlugin implements Webpack.Plugin { if (resolvedTranslatedData) { for (const resolvedLocaleName in resolvedTranslatedData) { if (resolvedTranslatedData.hasOwnProperty(resolvedLocaleName)) { - const translatedLocFileData: ILocaleFileData = resolveLocalizedData(resolvedTranslatedData[resolvedLocaleName]); + const translatedLocFileData: ILocaleFileData = resolveLocalizedData( + resolvedTranslatedData[resolvedLocaleName] + ); this._addLocFile(resolvedLocaleName, localizedResourcePath, translatedLocFileData); } } @@ -521,7 +537,11 @@ export class LocalizationPlugin implements Webpack.Plugin { return this._stringPlaceholderMap.get(serialNumber); } - private _addLocFile(localeName: string, localizedFilePath: string, localizedFileData: ILocaleFileData): void { + private _addLocFile( + localeName: string, + localizedFilePath: string, + localizedFileData: ILocaleFileData + ): void { const filesMap: Map> = this._resolvedLocalizedStrings.get(localeName)!; const stringsMap: Map = new Map(); @@ -536,16 +556,13 @@ export class LocalizationPlugin implements Webpack.Plugin { const placeholder: IStringPlaceholder = this.stringKeys.get(stringKey)!; if (!this._stringPlaceholderMap.has(placeholder.suffix)) { - this._stringPlaceholderMap.set( - placeholder.suffix, - { - values: { - [this._passthroughLocaleName]: stringName - }, - locFilePath: localizedFilePath, - stringName: stringName - } - ); + this._stringPlaceholderMap.set(placeholder.suffix, { + values: { + [this._passthroughLocaleName]: stringName, + }, + locFilePath: localizedFilePath, + stringName: stringName, + }); } this._stringPlaceholderMap.get(placeholder.suffix)!.values[localeName] = stringValue; @@ -557,16 +574,16 @@ export class LocalizationPlugin implements Webpack.Plugin { private _initializeAndValidateOptions( configuration: Webpack.Configuration, isWebpackDevServer: boolean - ): { errors: Error[], warnings: Error[] } { + ): { errors: Error[]; warnings: Error[] } { const errors: Error[] = []; const warnings: Error[] = []; function ensureValidLocaleName(localeName: string): boolean { const LOCALE_NAME_REGEX: RegExp = /[a-z-]/i; if (!localeName.match(LOCALE_NAME_REGEX)) { - errors.push(new Error( - `Invalid locale name: ${localeName}. Locale names may only contain letters and hyphens.` - )); + errors.push( + new Error(`Invalid locale name: ${localeName}. Locale names may only contain letters and hyphens.`) + ); return false; } else { return true; @@ -577,18 +594,21 @@ export class LocalizationPlugin implements Webpack.Plugin { if ( !configuration.output || !configuration.output.filename || - (typeof configuration.output.filename !== 'string') || + typeof configuration.output.filename !== 'string' || configuration.output.filename.indexOf(Constants.LOCALE_FILENAME_TOKEN) === -1 ) { - errors.push(new Error( - 'The configuration.output.filename property must be provided, must be a string, and must include ' + - `the ${Constants.LOCALE_FILENAME_TOKEN} placeholder` - )); + errors.push( + new Error( + 'The configuration.output.filename property must be provided, must be a string, and must include ' + + `the ${Constants.LOCALE_FILENAME_TOKEN} placeholder` + ) + ); } // END configuration // START options.filesToIgnore - { // eslint-disable-line no-lone-blocks + { + // eslint-disable-line no-lone-blocks for (const filePath of this._options.filesToIgnore || []) { const normalizedFilePath: string = path.resolve(configuration.context!, filePath); this._filesToIgnore.add(normalizedFilePath); @@ -602,7 +622,7 @@ export class LocalizationPlugin implements Webpack.Plugin { if (this._options.localizedData.passthroughLocale) { const { usePassthroughLocale, - passthroughLocaleName = 'passthrough' + passthroughLocaleName = 'passthrough', } = this._options.localizedData.passthroughLocale; if (usePassthroughLocale) { this._passthroughLocaleName = passthroughLocaleName; @@ -618,10 +638,12 @@ export class LocalizationPlugin implements Webpack.Plugin { for (const localeName in translatedStrings) { if (translatedStrings.hasOwnProperty(localeName)) { if (this._locales.has(localeName)) { - errors.push(Error( - `The locale "${localeName}" appears multiple times. ` + - 'There may be multiple instances with different casing.' - )); + errors.push( + Error( + `The locale "${localeName}" appears multiple times. ` + + 'There may be multiple instances with different casing.' + ) + ); return { errors, warnings }; } @@ -641,10 +663,12 @@ export class LocalizationPlugin implements Webpack.Plugin { const normalizedLocFilePath: string = path.resolve(configuration.context!, locFilePath); if (locFilePathsInLocale.has(normalizedLocFilePath)) { - errors.push(new Error( - `The localization file path "${locFilePath}" appears multiple times in locale ${localeName}. ` + - 'There may be multiple instances with different casing.' - )); + errors.push( + new Error( + `The localization file path "${locFilePath}" appears multiple times in locale ${localeName}. ` + + 'There may be multiple instances with different casing.' + ) + ); return { errors, warnings }; } @@ -655,7 +679,9 @@ export class LocalizationPlugin implements Webpack.Plugin { locFileDataFromOptions = path.resolve(configuration.context!, locFileDataFromOptions); } - this._resolvedTranslatedStringsFromOptions[localeName][normalizedLocFilePath] = locFileDataFromOptions; + this._resolvedTranslatedStringsFromOptions[localeName][ + normalizedLocFilePath + ] = locFileDataFromOptions; } } } @@ -693,19 +719,28 @@ export class LocalizationPlugin implements Webpack.Plugin { for (const pseudolocaleName in this._options.localizedData.pseudolocales) { if (this._options.localizedData.pseudolocales.hasOwnProperty(pseudolocaleName)) { if (this._defaultLocale === pseudolocaleName) { - errors.push(new Error(`A pseudolocale (${pseudolocaleName}) name is also the default locale name.`)); + errors.push( + new Error(`A pseudolocale (${pseudolocaleName}) name is also the default locale name.`) + ); return { errors, warnings }; } if (this._locales.has(pseudolocaleName)) { - errors.push(new Error( - `A pseudolocale (${pseudolocaleName}) name is also specified in the translated strings.` - )); + errors.push( + new Error( + `A pseudolocale (${pseudolocaleName}) name is also specified in the translated strings.` + ) + ); return { errors, warnings }; } - const pseudoLocaleOpts: IPseudolocaleOptions = this._options.localizedData.pseudolocales[pseudolocaleName]; - this._pseudolocalizers.set(pseudolocaleName, Pseudolocalization.getPseudolocalizer(pseudoLocaleOpts)); + const pseudoLocaleOpts: IPseudolocaleOptions = this._options.localizedData.pseudolocales[ + pseudolocaleName + ]; + this._pseudolocalizers.set( + pseudolocaleName, + Pseudolocalization.getPseudolocalizer(pseudoLocaleOpts) + ); this._locales.add(pseudolocaleName); this._resolvedLocalizedStrings.set(pseudolocaleName, new Map>()); } @@ -727,10 +762,12 @@ export class LocalizationPlugin implements Webpack.Plugin { } default: { - errors.push(new Error( - `Unexpected value "${this._options.localizedData.normalizeResxNewlines}" for option ` + - '"localizedData.normalizeResxNewlines"' - )); + errors.push( + new Error( + `Unexpected value "${this._options.localizedData.normalizeResxNewlines}" for option ` + + '"localizedData.normalizeResxNewlines"' + ) + ); break; } } @@ -760,7 +797,7 @@ export class LocalizationPlugin implements Webpack.Plugin { const suffix: string = (this._stringPlaceholderCounter++).toString(); return { value: `${Constants.STRING_PLACEHOLDER_PREFIX}_\\_${Constants.STRING_PLACEHOLDER_LABEL}_${suffix}`, - suffix: suffix + suffix: suffix, }; } diff --git a/webpack/localization-plugin/src/Pseudolocalization.ts b/webpack/localization-plugin/src/Pseudolocalization.ts index fb96df6417c..f7776f9812e 100644 --- a/webpack/localization-plugin/src/Pseudolocalization.ts +++ b/webpack/localization-plugin/src/Pseudolocalization.ts @@ -13,7 +13,7 @@ export class Pseudolocalization { pseudolocale.option = { ...pseudolocale.option, - ...options + ...options, }; return pseudolocale.str; } diff --git a/webpack/localization-plugin/src/WebpackConfigurationUpdater.ts b/webpack/localization-plugin/src/WebpackConfigurationUpdater.ts index 8ed8a854e1c..3f1b7d3e823 100644 --- a/webpack/localization-plugin/src/WebpackConfigurationUpdater.ts +++ b/webpack/localization-plugin/src/WebpackConfigurationUpdater.ts @@ -27,7 +27,7 @@ export class WebpackConfigurationUpdater { const loader: string = path.resolve(__dirname, 'loaders', 'LocLoader.js'); const loaderOptions: ILocLoaderOptions = { pluginInstance: options.pluginInstance, - resxNewlineNormalization: options.resxNewlineNormalization + resxNewlineNormalization: options.resxNewlineNormalization, }; WebpackConfigurationUpdater._addLoadersForLocFiles(options, loader, loaderOptions); @@ -37,32 +37,35 @@ export class WebpackConfigurationUpdater { WebpackConfigurationUpdater._tryUpdateSourceMapFilename(options.configuration); } - public static amendWebpackConfigurationForInPlaceLocFiles(options: IWebpackConfigurationUpdaterOptions): void { + public static amendWebpackConfigurationForInPlaceLocFiles( + options: IWebpackConfigurationUpdaterOptions + ): void { const loader: string = path.resolve(__dirname, 'loaders', 'InPlaceLocFileLoader.js'); const loaderOptions: IBaseLoaderOptions = { - resxNewlineNormalization: options.resxNewlineNormalization + resxNewlineNormalization: options.resxNewlineNormalization, }; - WebpackConfigurationUpdater._addRulesToConfiguration( - options.configuration, - [ - { - test: Constants.LOC_JSON_REGEX, - use: [{ + WebpackConfigurationUpdater._addRulesToConfiguration(options.configuration, [ + { + test: Constants.LOC_JSON_REGEX, + use: [ + { loader: loader, - options: loaderOptions - }] - }, - { - test: Constants.RESX_REGEX, - use: [{ + options: loaderOptions, + }, + ], + }, + { + test: Constants.RESX_REGEX, + use: [ + { loader: loader, - options: loaderOptions - }], - type: 'json' - } - ] - ); + options: loaderOptions, + }, + ], + type: 'json', + }, + ]); } private static _tryUpdateLocaleTokenInPublicPathPlugin(options: IWebpackConfigurationUpdaterOptions): void { @@ -99,42 +102,40 @@ export class WebpackConfigurationUpdater { loader: string, loaderOptions: IBaseLoaderOptions ): void { - WebpackConfigurationUpdater._addRulesToConfiguration( - options.configuration, - [ - { - test: { - and: [ - (filePath: string) => !options.filesToIgnore.has(filePath), - Constants.LOC_JSON_REGEX - ] - }, - use: [{ - loader: loader, - options: loaderOptions - }] + WebpackConfigurationUpdater._addRulesToConfiguration(options.configuration, [ + { + test: { + and: [(filePath: string) => !options.filesToIgnore.has(filePath), Constants.LOC_JSON_REGEX], }, - { - test: { - and: [ - (filePath: string) => !options.filesToIgnore.has(filePath), - Constants.RESX_REGEX - ] + use: [ + { + loader: loader, + options: loaderOptions, }, - use: [{ + ], + }, + { + test: { + and: [(filePath: string) => !options.filesToIgnore.has(filePath), Constants.RESX_REGEX], + }, + use: [ + { loader: loader, - options: loaderOptions - }], - type: 'json' - } - ] - ); + options: loaderOptions, + }, + ], + type: 'json', + }, + ]); } - private static _addRulesToConfiguration(configuration: Webpack.Configuration, rules: Webpack.RuleSetRule[]): void { + private static _addRulesToConfiguration( + configuration: Webpack.Configuration, + rules: Webpack.RuleSetRule[] + ): void { if (!configuration.module) { configuration.module = { - rules: [] + rules: [], }; } @@ -154,7 +155,7 @@ export class WebpackConfigurationUpdater { configuration.output.sourceMapFilename = configuration.output.sourceMapFilename.replace( FILE_TOKEN_REGEX, Constants.NO_LOCALE_SOURCE_MAP_FILENAME_TOKEN - ) + ); } } } diff --git a/webpack/localization-plugin/src/index.ts b/webpack/localization-plugin/src/index.ts index 50a99f5c2e5..7054d3e5865 100644 --- a/webpack/localization-plugin/src/index.ts +++ b/webpack/localization-plugin/src/index.ts @@ -1,10 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export { - LocalizationPlugin, - IStringPlaceholder as _IStringPlaceholder -} from './LocalizationPlugin'; +export { LocalizationPlugin, IStringPlaceholder as _IStringPlaceholder } from './LocalizationPlugin'; export { IDefaultLocaleOptions, @@ -24,19 +21,17 @@ export { IPseudolocaleOptions, IPseudolocalesOptions, IResolvedMissingTranslations, - ITypingsGenerationOptions + ITypingsGenerationOptions, } from './interfaces'; export { LocFileParser as _LocFileParser, - IParseLocFileOptions as _IParseLocFileOptions + IParseLocFileOptions as _IParseLocFileOptions, } from './utilities/LocFileParser'; -export { - ILocalizedWebpackChunk -} from './webpackInterfaces'; +export { ILocalizedWebpackChunk } from './webpackInterfaces'; export { ITypingsGeneratorOptions, - LocFileTypingsGenerator as TypingsGenerator + LocFileTypingsGenerator as TypingsGenerator, } from './LocFileTypingsGenerator'; diff --git a/webpack/localization-plugin/src/interfaces.ts b/webpack/localization-plugin/src/interfaces.ts index 290fb399678..43bf0b5ee3e 100644 --- a/webpack/localization-plugin/src/interfaces.ts +++ b/webpack/localization-plugin/src/interfaces.ts @@ -220,7 +220,7 @@ export interface ILocalizedStrings { * @public */ export interface ILocaleElementMap { - [locale: string]: string + [locale: string]: string; } /** diff --git a/webpack/localization-plugin/src/loaders/InPlaceLocFileLoader.ts b/webpack/localization-plugin/src/loaders/InPlaceLocFileLoader.ts index 2164828e4a3..2a0e7423e1d 100644 --- a/webpack/localization-plugin/src/loaders/InPlaceLocFileLoader.ts +++ b/webpack/localization-plugin/src/loaders/InPlaceLocFileLoader.ts @@ -6,30 +6,26 @@ import { Terminal } from '@rushstack/node-core-library'; import { ILocalizationFile } from '../interfaces'; import { LocFileParser } from '../utilities/LocFileParser'; -import { - loaderFactory, - IBaseLoaderOptions -} from './LoaderFactory'; +import { loaderFactory, IBaseLoaderOptions } from './LoaderFactory'; import { LoaderTerminalProvider } from '../utilities/LoaderTerminalProvider'; -export default loaderFactory( - function ( - this: loader.LoaderContext, - locFilePath: string, - content: string, - options: IBaseLoaderOptions - ) { - const locFileData: ILocalizationFile = LocFileParser.parseLocFile({ - content, - filePath: locFilePath, - terminal: new Terminal(LoaderTerminalProvider.getTerminalProviderForLoader(this)), - resxNewlineNormalization: options.resxNewlineNormalization - }); - const resultObject: { [stringName: string]: string } = {}; - for (const stringName in locFileData) { // eslint-disable-line guard-for-in - resultObject[stringName] = locFileData[stringName].value; - } - - return resultObject; +export default loaderFactory(function ( + this: loader.LoaderContext, + locFilePath: string, + content: string, + options: IBaseLoaderOptions +) { + const locFileData: ILocalizationFile = LocFileParser.parseLocFile({ + content, + filePath: locFilePath, + terminal: new Terminal(LoaderTerminalProvider.getTerminalProviderForLoader(this)), + resxNewlineNormalization: options.resxNewlineNormalization, + }); + const resultObject: { [stringName: string]: string } = {}; + for (const stringName in locFileData) { + // eslint-disable-line guard-for-in + resultObject[stringName] = locFileData[stringName].value; } -); + + return resultObject; +}); diff --git a/webpack/localization-plugin/src/loaders/LoaderFactory.ts b/webpack/localization-plugin/src/loaders/LoaderFactory.ts index 02e925fd110..2506df79a6f 100644 --- a/webpack/localization-plugin/src/loaders/LoaderFactory.ts +++ b/webpack/localization-plugin/src/loaders/LoaderFactory.ts @@ -10,7 +10,7 @@ export interface IBaseLoaderOptions { } export interface ILoaderResult { - [stringName: string]: string + [stringName: string]: string; } export function loaderFactory( @@ -20,5 +20,5 @@ export function loaderFactory( const options: TOptions = loaderUtils.getOptions(this) as TOptions; const resultObject: ILoaderResult = innerLoader.call(this, this.resourcePath, content, options); return JSON.stringify(resultObject); - } -} \ No newline at end of file + }; +} diff --git a/webpack/localization-plugin/src/loaders/LocLoader.ts b/webpack/localization-plugin/src/loaders/LocLoader.ts index d05659b90e5..22c67bd0d74 100644 --- a/webpack/localization-plugin/src/loaders/LocLoader.ts +++ b/webpack/localization-plugin/src/loaders/LocLoader.ts @@ -7,10 +7,7 @@ import { Terminal } from '@rushstack/node-core-library'; import { LocalizationPlugin } from '../LocalizationPlugin'; import { ILocalizationFile } from '../interfaces'; import { LocFileParser } from '../utilities/LocFileParser'; -import { - loaderFactory, - IBaseLoaderOptions -} from './LoaderFactory'; +import { loaderFactory, IBaseLoaderOptions } from './LoaderFactory'; import { EntityMarker } from '../utilities/EntityMarker'; import { LoaderTerminalProvider } from '../utilities/LoaderTerminalProvider'; @@ -18,42 +15,45 @@ export interface ILocLoaderOptions extends IBaseLoaderOptions { pluginInstance: LocalizationPlugin; } -export default loaderFactory( - function ( - this: loader.LoaderContext, - locFilePath: string, - content: string, - options: ILocLoaderOptions - ) { - const { pluginInstance } = options; - const terminal: Terminal = new Terminal(LoaderTerminalProvider.getTerminalProviderForLoader(this)); - const locFileData: ILocalizationFile = LocFileParser.parseLocFile({ - content, - terminal, - filePath: locFilePath, - resxNewlineNormalization: options.resxNewlineNormalization - }); - const { additionalLoadedFilePaths, errors } = pluginInstance.addDefaultLocFile(terminal, locFilePath, locFileData); - for (const additionalFile of additionalLoadedFilePaths) { - this.dependency(additionalFile); - } +export default loaderFactory(function ( + this: loader.LoaderContext, + locFilePath: string, + content: string, + options: ILocLoaderOptions +) { + const { pluginInstance } = options; + const terminal: Terminal = new Terminal(LoaderTerminalProvider.getTerminalProviderForLoader(this)); + const locFileData: ILocalizationFile = LocFileParser.parseLocFile({ + content, + terminal, + filePath: locFilePath, + resxNewlineNormalization: options.resxNewlineNormalization, + }); + const { additionalLoadedFilePaths, errors } = pluginInstance.addDefaultLocFile( + terminal, + locFilePath, + locFileData + ); + for (const additionalFile of additionalLoadedFilePaths) { + this.dependency(additionalFile); + } - for (const error of errors) { - this.emitError(error); - } + for (const error of errors) { + this.emitError(error); + } - const resultObject: { [stringName: string]: string } = {}; - for (const stringName in locFileData) { // eslint-disable-line guard-for-in - const stringKey: string = `${locFilePath}?${stringName}`; - if (pluginInstance.stringKeys.has(stringKey)) { - resultObject[stringName] = pluginInstance.stringKeys.get(stringKey)!.value; - } else { - throw new Error(`Unexpected - missing placeholder for string key "${stringKey}"`); - } + const resultObject: { [stringName: string]: string } = {}; + for (const stringName in locFileData) { + // eslint-disable-line guard-for-in + const stringKey: string = `${locFilePath}?${stringName}`; + if (pluginInstance.stringKeys.has(stringKey)) { + resultObject[stringName] = pluginInstance.stringKeys.get(stringKey)!.value; + } else { + throw new Error(`Unexpected - missing placeholder for string key "${stringKey}"`); } + } - EntityMarker.markEntity(this._module, true); + EntityMarker.markEntity(this._module, true); - return resultObject; - } -); + return resultObject; +}); diff --git a/webpack/localization-plugin/src/schemas/locJson.schema.json b/webpack/localization-plugin/src/schemas/locJson.schema.json index a322cc77b09..a407d34bf33 100644 --- a/webpack/localization-plugin/src/schemas/locJson.schema.json +++ b/webpack/localization-plugin/src/schemas/locJson.schema.json @@ -20,7 +20,7 @@ } }, "additionalProperties": false, - "required": [ "value" ] + "required": ["value"] } }, "additionalProperties": false, diff --git a/webpack/localization-plugin/src/utilities/Constants.ts b/webpack/localization-plugin/src/utilities/Constants.ts index f1b0ff06b49..a93ad7ae92f 100644 --- a/webpack/localization-plugin/src/utilities/Constants.ts +++ b/webpack/localization-plugin/src/utilities/Constants.ts @@ -2,7 +2,7 @@ // See LICENSE in the project root for license information. import * as path from 'path'; -import { JsonSchema } from "@rushstack/node-core-library"; +import { JsonSchema } from '@rushstack/node-core-library'; import * as lodash from 'lodash'; export class Constants { @@ -14,7 +14,7 @@ export class Constants { public static LOCALE_FILENAME_TOKEN_REGEX: RegExp = new RegExp( lodash.escapeRegExp(Constants.LOCALE_FILENAME_TOKEN), 'gi' - ); + ); public static NO_LOCALE_SOURCE_MAP_FILENAME_TOKEN: string = '[no-locale-file]'; public static NO_LOCALE_SOURCE_MAP_FILENAME_TOKEN_REGEX: RegExp = new RegExp( lodash.escapeRegExp(Constants.NO_LOCALE_SOURCE_MAP_FILENAME_TOKEN), diff --git a/webpack/localization-plugin/src/utilities/LoaderTerminalProvider.ts b/webpack/localization-plugin/src/utilities/LoaderTerminalProvider.ts index d582a6356d3..08fa33fddd4 100644 --- a/webpack/localization-plugin/src/utilities/LoaderTerminalProvider.ts +++ b/webpack/localization-plugin/src/utilities/LoaderTerminalProvider.ts @@ -2,10 +2,7 @@ // See LICENSE in the project root for license information. import * as webpack from 'webpack'; -import { - ITerminalProvider, - TerminalProviderSeverity -} from '@rushstack/node-core-library'; +import { ITerminalProvider, TerminalProviderSeverity } from '@rushstack/node-core-library'; export class LoaderTerminalProvider { public static getTerminalProviderForLoader(loaderContext: webpack.loader.LoaderContext): ITerminalProvider { @@ -24,7 +21,7 @@ export class LoaderTerminalProvider { break; } } - } + }, }; } -} \ No newline at end of file +} diff --git a/webpack/localization-plugin/src/utilities/LocFileParser.ts b/webpack/localization-plugin/src/utilities/LocFileParser.ts index 094cb828fcd..2ea4491a32c 100644 --- a/webpack/localization-plugin/src/utilities/LocFileParser.ts +++ b/webpack/localization-plugin/src/utilities/LocFileParser.ts @@ -1,11 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - Terminal, - NewlineKind, - JsonFile -} from '@rushstack/node-core-library'; +import { Terminal, NewlineKind, JsonFile } from '@rushstack/node-core-library'; import { ILocalizationFile } from '../interfaces'; import { ResxReader } from './ResxReader'; @@ -43,14 +39,11 @@ export class LocFileParser { let parsedFile: ILocalizationFile; if (/\.resx$/i.test(options.filePath)) { - parsedFile = ResxReader.readResxAsLocFile( - options.content, - { - terminal: options.terminal, - resxFilePath: options.filePath, - newlineNormalization: options.resxNewlineNormalization - } - ); + parsedFile = ResxReader.readResxAsLocFile(options.content, { + terminal: options.terminal, + resxFilePath: options.filePath, + newlineNormalization: options.resxNewlineNormalization, + }); } else { parsedFile = JsonFile.parseString(options.content); try { diff --git a/webpack/localization-plugin/src/utilities/ResxReader.ts b/webpack/localization-plugin/src/utilities/ResxReader.ts index 79839edf733..30d83db315b 100644 --- a/webpack/localization-plugin/src/utilities/ResxReader.ts +++ b/webpack/localization-plugin/src/utilities/ResxReader.ts @@ -1,28 +1,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -import { - FileSystem, - Terminal, - Text, - NewlineKind -} from '@rushstack/node-core-library'; -import { - XmlDocument, - XmlElement -} from 'xmldoc'; - -import { - ILocalizedString, - ILocalizationFile -} from '../interfaces'; +import { FileSystem, Terminal, Text, NewlineKind } from '@rushstack/node-core-library'; +import { XmlDocument, XmlElement } from 'xmldoc'; + +import { ILocalizedString, ILocalizationFile } from '../interfaces'; const STRING_NAME_RESX: RegExp = /^[A-z_$][A-z0-9_$]*$/; export interface IResxReaderOptions { resxFilePath: string; terminal: Terminal; - newlineNormalization: NewlineKind | undefined + newlineNormalization: NewlineKind | undefined; } interface ILoggingFunctions { @@ -36,7 +25,7 @@ interface IResxReaderOptionsInternal { resxFilePath: string; resxContents: string; loggingFunctions: ILoggingFunctions; - newlineNormalization: NewlineKind | undefined + newlineNormalization: NewlineKind | undefined; } export class ResxReader { @@ -52,31 +41,19 @@ export class ResxReader { logError: (message: string) => writeError(message), logWarning: (message: string) => writeWarning(message), logFileError: (message: string, filePath: string, line?: number, position?: number) => { - ResxReader._logWithLocation( - writeError, - message, - filePath, - line, - position - ); + ResxReader._logWithLocation(writeError, message, filePath, line, position); }, logFileWarning: (message: string, filePath: string, line?: number, position?: number) => { - ResxReader._logWithLocation( - writeWarning, - message, - filePath, - line, - position - ); - } + ResxReader._logWithLocation(writeWarning, message, filePath, line, position); + }, }; return this._readResxAsLocFileInternal({ resxFilePath: options.resxFilePath, resxContents, loggingFunctions, - newlineNormalization: options.newlineNormalization - }) + newlineNormalization: options.newlineNormalization, + }); } private static _readResxAsLocFileInternal(options: IResxReaderOptionsInternal): ILocalizationFile { @@ -105,11 +82,7 @@ export class ResxReader { childNode ); } else if (!STRING_NAME_RESX.test(stringName)) { - ResxReader._logErrorWithLocation( - options, - `Invalid string name "${stringName}"`, - childNode - ); + ResxReader._logErrorWithLocation(options, `Invalid string name "${stringName}"`, childNode); } else { if (locFile.hasOwnProperty(stringName)) { ResxReader._logErrorWithLocation( @@ -119,7 +92,10 @@ export class ResxReader { ); } - const locString: ILocalizedString | undefined = ResxReader._readDataElement(options, childNode); + const locString: ILocalizedString | undefined = ResxReader._readDataElement( + options, + childNode + ); if (locString) { locFile[stringName] = locString; @@ -165,7 +141,10 @@ export class ResxReader { return locFile; } - private static _readDataElement(options: IResxReaderOptionsInternal, dataElement: XmlElement): ILocalizedString | undefined { + private static _readDataElement( + options: IResxReaderOptionsInternal, + dataElement: XmlElement + ): ILocalizedString | undefined { let foundCommentElement: boolean = false; let foundValueElement: boolean = false; let comment: string | undefined = undefined; @@ -177,11 +156,7 @@ export class ResxReader { switch (childNode.name) { case 'value': { if (foundValueElement) { - ResxReader._logErrorWithLocation( - options, - 'Duplicate element found', - childNode - ); + ResxReader._logErrorWithLocation(options, 'Duplicate element found', childNode); } else { foundValueElement = true; value = ResxReader._readTextElement(options, childNode); @@ -195,11 +170,7 @@ export class ResxReader { case 'comment': { if (foundCommentElement) { - ResxReader._logErrorWithLocation( - options, - 'Duplicate element found', - childNode - ); + ResxReader._logErrorWithLocation(options, 'Duplicate element found', childNode); } else { foundCommentElement = true; comment = ResxReader._readTextElement(options, childNode); @@ -245,28 +216,23 @@ export class ResxReader { } if (!foundValueElement) { - ResxReader._logErrorWithLocation( - options, - 'Missing string value in element', - dataElement - ); + ResxReader._logErrorWithLocation(options, 'Missing string value in element', dataElement); } else { if (comment === undefined) { - ResxReader._logWarningWithLocation( - options, - 'Missing string comment in element', - dataElement - ); + ResxReader._logWarningWithLocation(options, 'Missing string comment in element', dataElement); } return { value: value || '', - comment + comment, }; } } - private static _readTextElement(options: IResxReaderOptionsInternal, element: XmlElement): string | undefined { + private static _readTextElement( + options: IResxReaderOptionsInternal, + element: XmlElement + ): string | undefined { let foundText: string | undefined = undefined; for (const childNode of element.children) { @@ -290,19 +256,11 @@ export class ResxReader { break; case 'element': - ResxReader._logErrorWithLocation( - options, - `Unexpected element`, - childNode - ); + ResxReader._logErrorWithLocation(options, `Unexpected element`, childNode); break; default: - ResxReader._logErrorWithLocation( - options, - `Unexpected ${element.type} child`, - element - ); + ResxReader._logErrorWithLocation(options, `Unexpected ${element.type} child`, element); break; } } @@ -316,7 +274,12 @@ export class ResxReader { element?: XmlElement | XmlDocument ): void { if (element) { - options.loggingFunctions.logFileError(message, options.resxFilePath, element.line + 1, element.column + 1); + options.loggingFunctions.logFileError( + message, + options.resxFilePath, + element.line + 1, + element.column + 1 + ); } else { options.loggingFunctions.logFileError(message, options.resxFilePath); } @@ -328,7 +291,12 @@ export class ResxReader { element?: XmlElement | XmlDocument ): void { if (element) { - options.loggingFunctions.logFileWarning(message, options.resxFilePath, element.line + 1, element.column + 1); + options.loggingFunctions.logFileWarning( + message, + options.resxFilePath, + element.line + 1, + element.column + 1 + ); } else { options.loggingFunctions.logFileWarning(message, options.resxFilePath); } diff --git a/webpack/set-webpack-public-path-plugin/.eslintrc.js b/webpack/set-webpack-public-path-plugin/.eslintrc.js index d7953bb2a36..12831538b49 100644 --- a/webpack/set-webpack-public-path-plugin/.eslintrc.js +++ b/webpack/set-webpack-public-path-plugin/.eslintrc.js @@ -1,7 +1,7 @@ // This is a workaround for https://github.com/eslint/eslint/issues/3458 -require("@rushstack/eslint-config/patch-eslint6"); +require('@rushstack/eslint-config/patch-eslint6'); module.exports = { - extends: [ "@rushstack/eslint-config" ], + extends: ['@rushstack/eslint-config'], parserOptions: { tsconfigRootDir: __dirname }, }; diff --git a/webpack/set-webpack-public-path-plugin/src/SetPublicPathPlugin.ts b/webpack/set-webpack-public-path-plugin/src/SetPublicPathPlugin.ts index 2e24433d848..08692d55661 100644 --- a/webpack/set-webpack-public-path-plugin/src/SetPublicPathPlugin.ts +++ b/webpack/set-webpack-public-path-plugin/src/SetPublicPathPlugin.ts @@ -2,23 +2,13 @@ // See LICENSE in the project root for license information. import { EOL } from 'os'; -import { - cloneDeep, - escapeRegExp -} from 'lodash'; +import { cloneDeep, escapeRegExp } from 'lodash'; import * as Webpack from 'webpack'; import * as Tapable from 'tapable'; import * as lodash from 'lodash'; -import { - IV3Compilation, - IV3Module, - IV3Chunk -} from './V3Interfaces'; -import { - IInternalOptions, - getSetPublicPathCode -} from './codeGenerator'; +import { IV3Compilation, IV3Module, IV3Chunk } from './V3Interfaces'; +import { IInternalOptions, getSetPublicPathCode } from './codeGenerator'; /** * The base options for setting the webpack public path at runtime. @@ -130,7 +120,9 @@ interface IStartupCodeOptions { const PLUGIN_NAME: string = 'set-webpack-public-path'; -const SHOULD_REPLACE_ASSET_NAME_TOKEN: unique symbol = Symbol('set-public-path-plugin-should-replace-asset-name'); +const SHOULD_REPLACE_ASSET_NAME_TOKEN: unique symbol = Symbol( + 'set-public-path-plugin-should-replace-asset-name' +); const ASSET_NAME_TOKEN: string = '-ASSET-NAME-c0ef4f86-b570-44d3-b210-4428c5b7825c'; @@ -164,13 +156,14 @@ export class SetPublicPathPlugin implements Webpack.Plugin { compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation: Webpack.compilation.Compilation) => { const v4MainTemplate: IV4MainTemplate = compilation.mainTemplate as IV4MainTemplate; v4MainTemplate.hooks.startup.tap(PLUGIN_NAME, (source: string, chunk: IV4Chunk, hash: string) => { - const assetOrChunkFound: boolean = !!this.options.skipDetection || this._detectAssetsOrChunks(chunk); + const assetOrChunkFound: boolean = + !!this.options.skipDetection || this._detectAssetsOrChunks(chunk); if (assetOrChunkFound) { return this._getStartupCode({ source, chunk, hash, - requireFn: v4MainTemplate.requireFn + requireFn: v4MainTemplate.requireFn, }); } else { return source; @@ -185,7 +178,10 @@ export class SetPublicPathPlugin implements Webpack.Plugin { for (const assetFilename of chunk.files) { let escapedAssetFilename: string; if (assetFilename.match(/\.map$/)) { - escapedAssetFilename = assetFilename.substr(0, assetFilename.length - (4 /* '.map'.length */)); // Trim the ".map" extension + escapedAssetFilename = assetFilename.substr( + 0, + assetFilename.length - 4 /* '.map'.length */ + ); // Trim the ".map" extension escapedAssetFilename = lodash.escapeRegExp(escapedAssetFilename); escapedAssetFilename = JSON.stringify(escapedAssetFilename); // source in sourcemaps is JSON-encoded escapedAssetFilename = escapedAssetFilename.substring(1, escapedAssetFilename.length - 1); // Trim the quotes from the JSON encoding @@ -197,7 +193,10 @@ export class SetPublicPathPlugin implements Webpack.Plugin { const originalAssetSource: string = asset.source(); const originalAssetSize: number = asset.size(); - const newAssetSource: string = originalAssetSource.replace(ASSET_NAME_TOKEN_REGEX, escapedAssetFilename); + const newAssetSource: string = originalAssetSource.replace( + ASSET_NAME_TOKEN_REGEX, + escapedAssetFilename + ); const sizeDifference: number = assetFilename.length - ASSET_NAME_TOKEN.length; asset.source = () => newAssetSource; asset.size = () => originalAssetSize + sizeDifference; @@ -228,7 +227,7 @@ export class SetPublicPathPlugin implements Webpack.Plugin { source, chunk, hash, - requireFn: compilation.mainTemplate.requireFn + requireFn: compilation.mainTemplate.requireFn, }); } else { return source; @@ -280,10 +279,10 @@ export class SetPublicPathPlugin implements Webpack.Plugin { return [ '// Set the webpack public path', '(function () {', - getSetPublicPathCode(moduleOptions, console.error), + getSetPublicPathCode(moduleOptions, console.error), '})();', '', - options.source + options.source, ].join(EOL); } } diff --git a/webpack/set-webpack-public-path-plugin/src/V3Interfaces.ts b/webpack/set-webpack-public-path-plugin/src/V3Interfaces.ts index b6722b159d1..6c8656c0d27 100644 --- a/webpack/set-webpack-public-path-plugin/src/V3Interfaces.ts +++ b/webpack/set-webpack-public-path-plugin/src/V3Interfaces.ts @@ -1,8 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. -export interface IV3Asset { -} +export interface IV3Asset {} export interface IV3Chunk { chunks: IV3Chunk[]; @@ -22,4 +21,4 @@ export interface IV3MainTemplate { export interface IV3Compilation { mainTemplate: IV3MainTemplate; -} \ No newline at end of file +} diff --git a/webpack/set-webpack-public-path-plugin/src/codeGenerator.ts b/webpack/set-webpack-public-path-plugin/src/codeGenerator.ts index bfef5bbc851..a1809de5d97 100644 --- a/webpack/set-webpack-public-path-plugin/src/codeGenerator.ts +++ b/webpack/set-webpack-public-path-plugin/src/codeGenerator.ts @@ -4,9 +4,7 @@ import { EOL } from 'os'; import * as uglify from 'uglify-js'; -import { - ISetWebpackPublicPathOptions -} from './SetPublicPathPlugin'; +import { ISetWebpackPublicPathOptions } from './SetPublicPathPlugin'; /** * @public @@ -22,18 +20,21 @@ export interface IInternalOptions extends ISetWebpackPublicPathOptions { const varName: string = 'publicPath'; function joinLines(lines: string[], linePrefix?: string): string { - return lines.map((line: string) => { - if (line) { - return `${linePrefix || ''}${line}`; - } else { - return line; - } - }).join(EOL).replace(new RegExp(`${EOL}${EOL}+`, 'g'), `${EOL}${EOL}`); + return lines + .map((line: string) => { + if (line) { + return `${linePrefix || ''}${line}`; + } else { + return line; + } + }) + .join(EOL) + .replace(new RegExp(`${EOL}${EOL}+`, 'g'), `${EOL}${EOL}`); } function escapeSingleQuotes(str: string): string | undefined { if (str) { - return str.replace('\'', '\\\''); + return str.replace("'", "\\'"); } else { return undefined; } @@ -47,74 +48,70 @@ function appendSlashAndEscapeSingleQuotes(str: string): string | undefined { return escapeSingleQuotes(str); } -export function getSetPublicPathCode(options: IInternalOptions, emitWarning: (warning: string) => void): string { +export function getSetPublicPathCode( + options: IInternalOptions, + emitWarning: (warning: string) => void +): string { if (!options.webpackPublicPathVariable) { throw new Error('"webpackPublicPathVariable" option must be defined.'); } let lines: string[] = []; if (options.regexName) { - lines = [ - `var scripts = document.getElementsByTagName('script');` - ]; + lines = [`var scripts = document.getElementsByTagName('script');`]; const regexInitializationSnippet: string = `/${options.regexName}/i`; const regexVarName: string | undefined = options.regexVariable; if (options.regexVariable) { - lines.push(...[ - `var regex = (typeof ${regexVarName} !== 'undefined') ? ${regexVarName} : ${regexInitializationSnippet};` - ]); + lines.push( + ...[ + `var regex = (typeof ${regexVarName} !== 'undefined') ? ${regexVarName} : ${regexInitializationSnippet};`, + ] + ); } else { - lines.push(...[ - `var regex = ${regexInitializationSnippet};` - ]); + lines.push(...[`var regex = ${regexInitializationSnippet};`]); } - lines.push(...[ - `var ${varName};`, - '', - 'if (scripts && scripts.length) {', - ' for (var i = 0; i < scripts.length; i++) {', - ' if (!scripts[i]) continue;', - ` var path = scripts[i].getAttribute('src');`, - ' if (path && path.match(regex)) {', - ` ${varName} = path.substring(0, path.lastIndexOf('/') + 1);`, - ...(options.preferLastFoundScript ? [] : [' break;']), - ' }', - ' }', - '}', - '', - `if (!${varName}) {`, - ` for (var global in ${registryVariableName}) {`, - ' if (global && global.match(regex)) {', - ` ${varName} = global.substring(0, global.lastIndexOf('/') + 1);`, - ...(options.preferLastFoundScript ? [] : [' break;']), - ' }', - ' }', - '}' - ]); - - if (options.getPostProcessScript) { - lines.push(...[ + lines.push( + ...[ + `var ${varName};`, + '', + 'if (scripts && scripts.length) {', + ' for (var i = 0; i < scripts.length; i++) {', + ' if (!scripts[i]) continue;', + ` var path = scripts[i].getAttribute('src');`, + ' if (path && path.match(regex)) {', + ` ${varName} = path.substring(0, path.lastIndexOf('/') + 1);`, + ...(options.preferLastFoundScript ? [] : [' break;']), + ' }', + ' }', + '}', '', - `if (${varName}) {`, - ` ${options.getPostProcessScript(varName)};`, + `if (!${varName}) {`, + ` for (var global in ${registryVariableName}) {`, + ' if (global && global.match(regex)) {', + ` ${varName} = global.substring(0, global.lastIndexOf('/') + 1);`, + ...(options.preferLastFoundScript ? [] : [' break;']), + ' }', + ' }', '}', - '' - ]); + ] + ); + + if (options.getPostProcessScript) { + lines.push(...['', `if (${varName}) {`, ` ${options.getPostProcessScript(varName)};`, '}', '']); } } else { if (options.publicPath) { - lines.push(...[ - `var ${varName} = '${appendSlashAndEscapeSingleQuotes(options.publicPath)}';`, - '' - ]); + lines.push(...[`var ${varName} = '${appendSlashAndEscapeSingleQuotes(options.publicPath)}';`, '']); } else if (options.systemJs) { - lines.push(...[ - `var ${varName} = window.System ? window.System.baseURL || '' : '';`, - `if (${varName} !== '' && ${varName}.substr(-1) !== '/') ${varName} += '/';`, - '' - ]); + lines.push( + ...[ + `var ${varName} = window.System ? window.System.baseURL || '' : '';`, + `if (${varName} !== '' && ${varName}.substr(-1) !== '/') ${varName} += '/';`, + '', + ] + ); } else { emitWarning(`Neither 'publicPath' nor 'systemJs' is defined, so the public path will not be modified`); @@ -122,25 +119,15 @@ export function getSetPublicPathCode(options: IInternalOptions, emitWarning: (wa } if (options.urlPrefix && options.urlPrefix !== '') { - lines.push(...[ - `${varName} += '${appendSlashAndEscapeSingleQuotes(options.urlPrefix)}';`, - '' - ]); + lines.push(...[`${varName} += '${appendSlashAndEscapeSingleQuotes(options.urlPrefix)}';`, '']); } if (options.getPostProcessScript) { - lines.push(...[ - `if (${varName}) {`, - ` ${options.getPostProcessScript(varName)};`, - '}', - '' - ]); + lines.push(...[`if (${varName}) {`, ` ${options.getPostProcessScript(varName)};`, '}', '']); } } - lines.push( - `${options.webpackPublicPathVariable} = ${varName};` - ); + lines.push(`${options.webpackPublicPathVariable} = ${varName};`); return joinLines(lines, options.linePrefix); } @@ -165,7 +152,7 @@ export function getGlobalRegisterCode(debug: boolean = false): string { ` if (path) ${registryVariableName}[path]=true;`, ' }', '}', - '})();' + '})();', ]; const joinedScript: string = joinLines(lines); @@ -173,14 +160,11 @@ export function getGlobalRegisterCode(debug: boolean = false): string { if (debug) { return `${EOL}${joinedScript}`; } else { - const minifyOutput: uglify.MinifyOutput = uglify.minify( - joinedScript, - { - compress: { - dead_code: true - } - } - ); + const minifyOutput: uglify.MinifyOutput = uglify.minify(joinedScript, { + compress: { + dead_code: true, + }, + }); return `${EOL}${minifyOutput.code}`; } diff --git a/webpack/set-webpack-public-path-plugin/src/index.ts b/webpack/set-webpack-public-path-plugin/src/index.ts index 00e419a633b..2b2a4f58780 100644 --- a/webpack/set-webpack-public-path-plugin/src/index.ts +++ b/webpack/set-webpack-public-path-plugin/src/index.ts @@ -9,7 +9,4 @@ */ export * from './SetPublicPathPlugin'; -export { - getGlobalRegisterCode, - registryVariableName -} from './codeGenerator'; +export { getGlobalRegisterCode, registryVariableName } from './codeGenerator';