From 630f6c7fb5650211e16c878659c0122bf7ce675e Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Mon, 6 Sep 2021 20:50:03 +0200 Subject: [PATCH] feat(core): support TypeScript 4.4 Adds support for TypeScript 4.4. High-level overview of the changes made in this PR: * Bumps the various packages to `typescript@4.4.2` and `tslib@2.3.0`. * The error object in `catch` clauses is now typed as `unknown` which caused a lot of compilation errors. I've resolved it by casting either to `Error` or `any` depending on the use case. Note that I've been using `as` casts, rather than typing the object directly, because TS only allows for `any` or `unknown` to be used in the `catch` clause parameters. * TS now passes in a third argument to the `__spreadArray` call inside child class constructors. I had to update a couple of places in the runtime and ngcc to be able to pick up the calls correctly. * TS now generates code like `(0, foo)(arg1, arg2)` for imported function calls. I had to update a few of our tests to account for it. See https://github.com/microsoft/TypeScript/pull/44624. * Our `ngtsc` test setup calls the private `matchFiles` function from TS. I had to update our usage, because a new parameter was added. * There was one place where we were setting the readonly `hasTrailingComma` property. I updated the usage to pass in the value when constructing the object instead. * Some browser types were updated which meant that I had to resolve some trivial type errors. * The downlevel decorators tranform was running into an issue where the Closure synthetic comments were being emitted twice. I've worked around it by recreating the class declaration node instead of cloning it. --- .../scripts-js/lib/common/circle-ci-api.ts | 4 +-- .../scripts-js/lib/common/utils.ts | 2 +- .../lib/preview-server/build-retriever.ts | 2 +- .../dockerbuild/scripts-js/package.json | 4 +-- .../test/preview-server/utils.spec.ts | 2 +- .../dockerbuild/scripts-js/yarn.lock | 16 +++++------ .../examples/cli-builder/src/my-builder.ts | 2 +- aio/package.json | 4 +-- .../layout/doc-viewer/doc-viewer.component.ts | 3 ++- .../FirebaseRedirectSource.ts | 4 +-- aio/yarn.lock | 10 +++---- integration/BUILD.bazel | 12 ++++----- .../include-all.ts | 0 .../package.json | 4 +-- .../tsconfig.json | 0 package.json | 4 +-- .../transition_animation_engine_spec.ts | 2 +- packages/animations/package.json | 2 +- packages/bazel/package.json | 4 +-- .../common/http/testing/test/request_spec.ts | 6 ++--- packages/common/package.json | 2 +- packages/common/src/pipes/date_pipe.ts | 4 +-- packages/common/src/pipes/number_pipe.ts | 6 ++--- packages/common/upgrade/src/location_shim.ts | 2 +- .../linker/babel/src/es2015_linker_plugin.ts | 2 +- packages/compiler-cli/ngcc/main-ngcc.ts | 2 +- .../ngcc/src/execution/cluster/worker.ts | 4 +-- .../compiler-cli/ngcc/src/host/esm5_host.ts | 5 ++-- .../ngcc/src/locking/async_locker.ts | 2 +- .../lock_file_with_child_process/util.ts | 2 +- .../ngcc/src/locking/sync_locker.ts | 2 +- .../ngcc/src/packages/configuration.ts | 6 +++-- .../ngcc/src/packages/entry_point_manifest.ts | 3 ++- .../ngcc/src/rendering/source_maps.ts | 2 +- .../writing/new_entry_point_file_writer.ts | 2 +- .../test/execution/cluster/executor_spec.ts | 8 +++--- .../single_processor_executor_spec.ts | 8 +++--- .../ngcc/test/integration/ngcc_spec.ts | 24 ++++++++++------- .../ngcc/test/locking/async_locker_spec.ts | 2 +- .../ngcc/test/locking/sync_locker_spec.ts | 2 +- packages/compiler-cli/package.json | 4 +-- .../compiler-cli/src/metadata/collector.ts | 6 ++--- .../file_system/testing/src/test_helper.ts | 20 +++++++------- .../sourcemaps/src/source_file_loader.ts | 6 ++--- .../ngtsc/testing/src/mock_file_loading.ts | 2 +- packages/compiler-cli/src/perform_compile.ts | 9 ++++--- .../downlevel_decorators_transform.ts | 14 ++++------ .../compiler-cli/src/transformers/program.ts | 4 +-- .../compiler-cli/src/typescript_support.ts | 4 +-- .../test_helpers/get_compliance_tests.ts | 4 +-- packages/compiler-cli/test/test_support.ts | 2 +- .../downlevel_decorators_transform_spec.ts | 18 ++++++------- .../transformers/inline_resources_spec.ts | 6 ++--- packages/compiler/package.json | 2 +- packages/compiler/src/aot/static_reflector.ts | 7 +++-- .../src/aot/static_symbol_resolver.ts | 2 +- .../compiler/src/expression_parser/ast.ts | 6 ++--- .../compiler/src/output/output_interpreter.ts | 2 +- .../test/aot/static_reflector_spec.ts | 4 +-- packages/core/package.json | 2 +- .../migrations/static-queries/index.ts | 2 +- .../undecorated-classes-with-di/index.ts | 2 +- packages/core/src/di/injector.ts | 2 +- packages/core/src/di/r3_injector.ts | 2 +- packages/core/src/di/reflective_injector.ts | 4 +-- .../src/reflection/reflection_capabilities.ts | 4 +-- packages/core/src/view/services.ts | 2 +- .../animation/animation_integration_spec.ts | 2 +- .../test/compiler/compiler_facade_spec.ts | 10 ++++--- .../core/test/di/reflective_injector_spec.ts | 2 +- packages/core/test/di/static_injector_spec.ts | 2 +- .../change_detection_integration_spec.ts | 4 +-- packages/core/test/linker/integration_spec.ts | 19 ++++++------- packages/core/testing/src/resolvers.ts | 2 +- packages/core/testing/src/test_bed.ts | 2 +- packages/elements/package.json | 2 +- packages/forms/package.json | 2 +- .../ivy/test/legacy/mock_host.ts | 1 + .../language-service/ivy/testing/src/env.ts | 2 +- .../src/tools/src/source_file_utils.ts | 2 +- .../asset_files/asset_translation_handler.ts | 2 +- .../source_file_translation_handler.ts | 2 +- .../serialize_translation_message.ts | 2 +- packages/localize/src/translate.ts | 2 +- .../angular-in-memory-web-api/package.json | 2 +- .../src/backend-service.ts | 6 ++--- .../src/http-client-backend-service.ts | 4 +-- .../platform-browser-dynamic/package.json | 2 +- packages/platform-browser/package.json | 2 +- .../platform-browser/src/dom/dom_renderer.ts | 2 +- packages/platform-server/package.json | 2 +- .../platform-server/src/server_renderer.ts | 2 +- packages/router/package.json | 2 +- packages/router/src/router.ts | 2 +- .../testing/src/router_testing_module.ts | 4 +-- packages/service-worker/package.json | 2 +- packages/service-worker/test/comm_spec.ts | 6 ++--- packages/service-worker/worker/src/data.ts | 5 ++-- packages/service-worker/worker/src/driver.ts | 24 ++++++++--------- packages/service-worker/worker/src/idle.ts | 2 +- .../service-worker/worker/testing/events.ts | 1 + packages/upgrade/package.json | 2 +- .../src/common/src/downgrade_injectable.ts | 2 +- packages/zone.js/lib/common/events.ts | 4 +-- packages/zone.js/lib/extra/bluebird.ts | 2 +- .../zone.js/lib/zone-spec/long-stack-trace.ts | 2 +- packages/zone.js/lib/zone.ts | 2 +- packages/zone.js/package.json | 4 +-- .../test/browser/XMLHttpRequest.spec.ts | 2 +- packages/zone.js/test/browser/browser.spec.ts | 27 +++++++++++-------- packages/zone.js/test/common/zone.spec.ts | 5 ++-- packages/zone.js/test/test-util.ts | 4 +-- packages/zone.js/test/typings/package.json | 2 +- packages/zone.js/yarn.lock | 10 +++---- yarn.lock | 4 +-- 115 files changed, 269 insertions(+), 252 deletions(-) rename integration/{typings_test_ts42 => typings_test_ts44}/include-all.ts (100%) rename integration/{typings_test_ts42 => typings_test_ts44}/package.json (93%) rename integration/{typings_test_ts42 => typings_test_ts44}/tsconfig.json (100%) diff --git a/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/circle-ci-api.ts b/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/circle-ci-api.ts index c416ca4841464c..f8e28a4e5dec76 100644 --- a/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/circle-ci-api.ts +++ b/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/circle-ci-api.ts @@ -64,7 +64,7 @@ export class CircleCiApi { } return response.json(); } catch (error) { - throw new Error(`CircleCI build info request failed (${error.message})`); + throw new Error(`CircleCI build info request failed (${(error as Error).message})`); } } @@ -84,7 +84,7 @@ export class CircleCiApi { } return artifact.url; } catch (error) { - throw new Error(`CircleCI artifact URL request failed (${error.message})`); + throw new Error(`CircleCI artifact URL request failed (${(error as Error).message})`); } } } diff --git a/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/utils.ts b/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/utils.ts index 870126ba9555ff..bb9380184e74b3 100644 --- a/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/utils.ts +++ b/aio/aio-builds-setup/dockerbuild/scripts-js/lib/common/utils.ts @@ -66,7 +66,7 @@ export const getEnvVar = (name: string, isOptional = false): string => { try { throw new Error(`ERROR: Missing required environment variable '${name}'!`); } catch (error) { - console.error(error.stack); + console.error((error as Error).stack); process.exit(1); } } diff --git a/aio/aio-builds-setup/dockerbuild/scripts-js/lib/preview-server/build-retriever.ts b/aio/aio-builds-setup/dockerbuild/scripts-js/lib/preview-server/build-retriever.ts index 2c29d6cd961a33..2dff5804440493 100644 --- a/aio/aio-builds-setup/dockerbuild/scripts-js/lib/preview-server/build-retriever.ts +++ b/aio/aio-builds-setup/dockerbuild/scripts-js/lib/preview-server/build-retriever.ts @@ -65,7 +65,7 @@ export class BuildRetriever { await promisify(fs.writeFile)(outPath, buffer); } return outPath; - } catch (error) { + } catch (error: any) { this.logger.warn(error); const status = (error.type === 'max-size') ? 413 : 500; throw new PreviewServerError(status, `CircleCI artifact download failed (${error.message || error})`); diff --git a/aio/aio-builds-setup/dockerbuild/scripts-js/package.json b/aio/aio-builds-setup/dockerbuild/scripts-js/package.json index 2509ff6e57c4d3..3e2c63e536d853 100644 --- a/aio/aio-builds-setup/dockerbuild/scripts-js/package.json +++ b/aio/aio-builds-setup/dockerbuild/scripts-js/package.json @@ -33,7 +33,7 @@ "shelljs": "^0.8.4", "source-map-support": "^0.5.19", "tar-stream": "^2.1.3", - "tslib": "^2.2.0" + "tslib": "^2.3.0" }, "devDependencies": { "@types/body-parser": "^1.19.0", @@ -49,6 +49,6 @@ "supertest": "^4.0.2", "tslint": "^6.1.3", "tslint-jasmine-noSkipOrFocus": "^1.0.9", - "typescript": "~4.3.4" + "typescript": "~4.4.2" } } diff --git a/aio/aio-builds-setup/dockerbuild/scripts-js/test/preview-server/utils.spec.ts b/aio/aio-builds-setup/dockerbuild/scripts-js/test/preview-server/utils.spec.ts index 993225711cd629..5ecaca1eb487b7 100644 --- a/aio/aio-builds-setup/dockerbuild/scripts-js/test/preview-server/utils.spec.ts +++ b/aio/aio-builds-setup/dockerbuild/scripts-js/test/preview-server/utils.spec.ts @@ -37,7 +37,7 @@ describe('preview-server/utils', () => { originalUrl: 'some.domain.com/path', } as express.Request; throwRequestError(505, 'ERROR MESSAGE', request); - } catch (error) { + } catch (error: any) { caught = true; expect(error).toBeInstanceOf(PreviewServerError); expect(error.status).toEqual(505); diff --git a/aio/aio-builds-setup/dockerbuild/scripts-js/yarn.lock b/aio/aio-builds-setup/dockerbuild/scripts-js/yarn.lock index e54c0400bf404d..10f61033b9a5cc 100644 --- a/aio/aio-builds-setup/dockerbuild/scripts-js/yarn.lock +++ b/aio/aio-builds-setup/dockerbuild/scripts-js/yarn.lock @@ -2505,10 +2505,10 @@ tslib@^1.8.1: version "1.9.3" resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.9.3.tgz#d7e4dd79245d85428c4d7e4822a79917954ca286" -tslib@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.2.0.tgz#fb2c475977e35e241311ede2693cee1ec6698f5c" - integrity sha512-gS9GVHRU+RGn5KQM2rllAlR3dU6m7AcpJKdtH8gFvQiC4Otgk98XnmMU+nZenHt/+VhnBPWwgrJsyrdcw6i23w== +tslib@^2.3.0: + version "2.3.1" + resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01" + integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw== tslint-jasmine-noSkipOrFocus@^1.0.9: version "1.0.9" @@ -2563,10 +2563,10 @@ typedarray-to-buffer@^3.1.5: dependencies: is-typedarray "^1.0.0" -typescript@~4.3.4: - version "4.3.4" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.3.4.tgz#3f85b986945bcf31071decdd96cf8bfa65f9dcbc" - integrity sha512-uauPG7XZn9F/mo+7MrsRjyvbxFpzemRjKEZXS4AK83oP2KKOJPvb+9cO/gmnv8arWZvhnjVOXz7B49m1l0e9Ew== +typescript@~4.4.2: + version "4.4.2" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.4.2.tgz#6d618640d430e3569a1dfb44f7d7e600ced3ee86" + integrity sha512-gzP+t5W4hdy4c+68bfcv0t400HVJMMd2+H9B7gae1nQlBzCqvrXX+6GL/b3GAgyTH966pzrZ70/fRjwAtZksSQ== undefsafe@^2.0.2: version "2.0.2" diff --git a/aio/content/examples/cli-builder/src/my-builder.ts b/aio/content/examples/cli-builder/src/my-builder.ts index b7603078d47b9e..cb1bd856489689 100644 --- a/aio/content/examples/cli-builder/src/my-builder.ts +++ b/aio/content/examples/cli-builder/src/my-builder.ts @@ -29,7 +29,7 @@ async function copyFileBuilder( // #docregion builder return { success: false, - error: err.message, + error: (err as Error).message, }; } diff --git a/aio/package.json b/aio/package.json index 5714a8da448f7b..72fdc9c25fa5d7 100644 --- a/aio/package.json +++ b/aio/package.json @@ -100,7 +100,7 @@ "@angular/service-worker": "12.1.1", "@webcomponents/custom-elements": "1.5.0", "rxjs": "^6.6.7", - "tslib": "^2.2.0", + "tslib": "^2.3.0", "zone.js": "~0.11.4" }, "devDependencies": { @@ -177,7 +177,7 @@ "tree-kill": "^1.1.0", "ts-node": "^10.0.0", "tslint": "~6.1.3", - "typescript": "~4.3.4", + "typescript": "~4.4.2", "uglify-js": "^3.13.3", "unist-util-filter": "^2.0.3", "unist-util-source": "^3.0.0", diff --git a/aio/src/app/layout/doc-viewer/doc-viewer.component.ts b/aio/src/app/layout/doc-viewer/doc-viewer.component.ts index 039178436a57ce..e8bf28e7f9da51 100644 --- a/aio/src/app/layout/doc-viewer/doc-viewer.component.ts +++ b/aio/src/app/layout/doc-viewer/doc-viewer.component.ts @@ -294,7 +294,8 @@ async function printSwDebugInfo(): Promise { } console.log(await res.text()); } catch (err) { - console.log(`Failed to retrieve debug info from '/ngsw/state': ${err.message || err}`); + console.log('Failed to retrieve debug info from \'/ngsw/state\': ' + + (err as Error).message || err); } } diff --git a/aio/tools/firebase-test-utils/FirebaseRedirectSource.ts b/aio/tools/firebase-test-utils/FirebaseRedirectSource.ts index 94ba1196e9551b..ee2d3a3bc19ff5 100644 --- a/aio/tools/firebase-test-utils/FirebaseRedirectSource.ts +++ b/aio/tools/firebase-test-utils/FirebaseRedirectSource.ts @@ -49,7 +49,7 @@ export class FirebaseRedirectSource { return new FirebaseRedirectSource(`^${pattern}$`, restNamedGroups); } catch (err) { - throw new Error(`Error in FirebaseRedirectSource: "${glob}" - ${err.message}`); + throw new Error(`Error in FirebaseRedirectSource: "${glob}" - ${(err as Error).message}`); } } @@ -72,7 +72,7 @@ export class FirebaseRedirectSource { // capture groups. return new FirebaseRedirectSource(regex.replace(/(\(\?)P(<[^>]+>)/g, '$1$2')); } catch (err) { - throw new Error(`Error in FirebaseRedirectSource: "${regex}" - ${err.message}`); + throw new Error(`Error in FirebaseRedirectSource: "${regex}" - ${(err as Error).message}`); } } diff --git a/aio/yarn.lock b/aio/yarn.lock index c2447a3a38cf32..24ef83d27dd759 100644 --- a/aio/yarn.lock +++ b/aio/yarn.lock @@ -12711,7 +12711,7 @@ tslib@^1.10.0, tslib@^1.13.0, tslib@^1.8.1, tslib@^1.9.0: resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00" integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg== -tslib@^2.0.0, tslib@^2.0.1, tslib@^2.2.0: +tslib@^2.0.0, tslib@^2.0.1, tslib@^2.2.0, tslib@^2.3.0: version "2.3.1" resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01" integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw== @@ -12850,10 +12850,10 @@ typescript@~3.2.2: resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.2.4.tgz#c585cb952912263d915b462726ce244ba510ef3d" integrity sha512-0RNDbSdEokBeEAkgNbxJ+BLwSManFy9TeXz8uW+48j/xhEXv1ePME60olyzw2XzUqUBNAYFeJadIqAgNqIACwg== -typescript@~4.3.4: - version "4.3.5" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.3.5.tgz#4d1c37cc16e893973c45a06886b7113234f119f4" - integrity sha512-DqQgihaQ9cUrskJo9kIyW/+g0Vxsk8cDtZ52a3NGh0YNTfpUSArXSohyUGnvbPazEPLu398C0UxmKSOrPumUzA== +typescript@~4.4.2: + version "4.4.2" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.4.2.tgz#6d618640d430e3569a1dfb44f7d7e600ced3ee86" + integrity sha512-gzP+t5W4hdy4c+68bfcv0t400HVJMMd2+H9B7gae1nQlBzCqvrXX+6GL/b3GAgyTH966pzrZ70/fRjwAtZksSQ== ua-parser-js@^0.7.28: version "0.7.28" diff --git a/integration/BUILD.bazel b/integration/BUILD.bazel index 23b8b96dd871d4..0da533d5bc1433 100644 --- a/integration/BUILD.bazel +++ b/integration/BUILD.bazel @@ -95,18 +95,18 @@ INTEGRATION_TESTS = { # root @npm//typescript package. "pinned_npm_packages": ["typescript"], }, - "typings_test_ts42": { - # Special case for `typings_test_ts42` test as we want to pin - # `typescript` at version 4.2.x for that test and not link to the - # root @npm//typescript package. - "pinned_npm_packages": ["typescript"], - }, "typings_test_ts43": { # Special case for `typings_test_ts43` test as we want to pin # `typescript` at version 4.3.x for that test and not link to the # root @npm//typescript package. "pinned_npm_packages": ["typescript"], }, + "typings_test_ts44": { + # Special case for `typings_test_ts44` test as we want to pin + # `typescript` at version 4.4.x for that test and not link to the + # root @npm//typescript package. + "pinned_npm_packages": ["typescript"], + }, } [ diff --git a/integration/typings_test_ts42/include-all.ts b/integration/typings_test_ts44/include-all.ts similarity index 100% rename from integration/typings_test_ts42/include-all.ts rename to integration/typings_test_ts44/include-all.ts diff --git a/integration/typings_test_ts42/package.json b/integration/typings_test_ts44/package.json similarity index 93% rename from integration/typings_test_ts42/package.json rename to integration/typings_test_ts44/package.json index 165f586da2fac5..11b24fd1a8273e 100644 --- a/integration/typings_test_ts42/package.json +++ b/integration/typings_test_ts44/package.json @@ -1,6 +1,6 @@ { "name": "angular-integration", - "description": "Assert that users with TypeScript 4.2 can type-check an Angular application", + "description": "Assert that users with TypeScript 4.4 can type-check an Angular application", "version": "0.0.0", "license": "MIT", "dependencies": { @@ -19,7 +19,7 @@ "@angular/upgrade": "file:../../dist/packages-dist/upgrade", "@types/jasmine": "file:../../node_modules/@types/jasmine", "rxjs": "file:../../node_modules/rxjs", - "typescript": "4.2.4", + "typescript": "4.4.2", "zone.js": "file:../../dist/zone.js-dist/archive/zone.js.tgz" }, "scripts": { diff --git a/integration/typings_test_ts42/tsconfig.json b/integration/typings_test_ts44/tsconfig.json similarity index 100% rename from integration/typings_test_ts42/tsconfig.json rename to integration/typings_test_ts44/tsconfig.json diff --git a/package.json b/package.json index 13bb805cd514ba..422a14eede6304 100644 --- a/package.json +++ b/package.json @@ -147,9 +147,9 @@ "terser": "^4.4.0", "tmp": "0.2.1", "tsickle": "0.38.1", - "tslib": "^2.2.0", + "tslib": "^2.3.0", "tslint": "6.1.3", - "typescript": "~4.3.4", + "typescript": "~4.4.2", "xhr2": "0.2.1", "yargs": "^17.0.0" }, diff --git a/packages/animations/browser/test/render/transition_animation_engine_spec.ts b/packages/animations/browser/test/render/transition_animation_engine_spec.ts index 64ecbdafec372a..bc7792ae4ff3a7 100644 --- a/packages/animations/browser/test/render/transition_animation_engine_spec.ts +++ b/packages/animations/browser/test/render/transition_animation_engine_spec.ts @@ -633,7 +633,7 @@ describe('TransitionAnimationEngine', () => { try { engine.flush(); } catch (e) { - errorMessage = e.toString(); + errorMessage = (e as Error).toString(); } expect(errorMessage).toMatch(/Unable to animate due to the following errors:/); diff --git a/packages/animations/package.json b/packages/animations/package.json index e2883a8e199e75..4a2cf3a2cf3223 100644 --- a/packages/animations/package.json +++ b/packages/animations/package.json @@ -8,7 +8,7 @@ "node": "^12.14.1 || >=14.0.0" }, "dependencies": { - "tslib": "^2.2.0" + "tslib": "^2.3.0" }, "peerDependencies": { "@angular/core": "0.0.0-PLACEHOLDER" diff --git a/packages/bazel/package.json b/packages/bazel/package.json index f7853917428f25..6b84f7298aae78 100644 --- a/packages/bazel/package.json +++ b/packages/bazel/package.json @@ -26,13 +26,13 @@ "@microsoft/api-extractor": "7.18.6", "shelljs": "0.8.4", "tsickle": "^0.38.0", - "tslib": "^2.2.0" + "tslib": "^2.3.0" }, "peerDependencies": { "@angular/compiler-cli": "0.0.0-PLACEHOLDER", "@bazel/typescript": ">=1.0.0", "terser": "^4.3.1", - "typescript": ">=4.2.3 <4.4", + "typescript": ">=4.2.3 <4.5", "rollup": ">=1.20.0", "rollup-plugin-commonjs": ">=9.0.0", "rollup-plugin-node-resolve": ">=4.2.0", diff --git a/packages/common/http/testing/test/request_spec.ts b/packages/common/http/testing/test/request_spec.ts index 0f3679a2e51db5..4c468297bd2f66 100644 --- a/packages/common/http/testing/test/request_spec.ts +++ b/packages/common/http/testing/test/request_spec.ts @@ -39,7 +39,7 @@ describe('HttpClient TestRequest', () => { mock.expectOne('/some-url').flush(null); fail(); } catch (error) { - expect(error.message) + expect((error as Error).message) .toBe( 'Expected one matching request for criteria "Match URL: /some-url", found none.' + ' Requests received are: GET /some-other-url.'); @@ -61,7 +61,7 @@ describe('HttpClient TestRequest', () => { mock.expectOne('/some-url?query=world').flush(null); fail(); } catch (error) { - expect(error.message) + expect((error as Error).message) .toBe( 'Expected one matching request for criteria "Match URL: /some-url?query=world", found none.' + ' Requests received are: GET /some-url?query=hello.'); @@ -85,7 +85,7 @@ describe('HttpClient TestRequest', () => { mock.expectOne('/some-url').flush(null); fail(); } catch (error) { - expect(error.message) + expect((error as Error).message) .toBe( 'Expected one matching request for criteria "Match URL: /some-url", found none.' + ' Requests received are: GET /some-other-url?query=world, POST /and-another-url.'); diff --git a/packages/common/package.json b/packages/common/package.json index f9ad0716b0a777..c3b5f1ec34bb42 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -9,7 +9,7 @@ }, "locales": "locales", "dependencies": { - "tslib": "^2.2.0" + "tslib": "^2.3.0" }, "peerDependencies": { "@angular/core": "0.0.0-PLACEHOLDER", diff --git a/packages/common/src/pipes/date_pipe.ts b/packages/common/src/pipes/date_pipe.ts index b94e38f3102da2..61a9c22e52a786 100644 --- a/packages/common/src/pipes/date_pipe.ts +++ b/packages/common/src/pipes/date_pipe.ts @@ -16,7 +16,7 @@ import {invalidPipeArgumentError} from './invalid_pipe_argument_error'; * @description * * Formats a date value according to locale rules. - * + * * `DatePipe` is executed only when it detects a pure change to the input value. * A pure change is either a change to a primitive input value * (such as `String`, `Number`, `Boolean`, or `Symbol`), @@ -195,7 +195,7 @@ export class DatePipe implements PipeTransform { try { return formatDate(value, format, locale || this.locale, timezone); } catch (error) { - throw invalidPipeArgumentError(DatePipe, error.message); + throw invalidPipeArgumentError(DatePipe, (error as Error).message); } } } diff --git a/packages/common/src/pipes/number_pipe.ts b/packages/common/src/pipes/number_pipe.ts index 307a7b443ba2de..07f5c60b2f47f5 100644 --- a/packages/common/src/pipes/number_pipe.ts +++ b/packages/common/src/pipes/number_pipe.ts @@ -100,7 +100,7 @@ export class DecimalPipe implements PipeTransform { const num = strToNumber(value); return formatNumber(num, locale, digitsInfo); } catch (error) { - throw invalidPipeArgumentError(DecimalPipe, error.message); + throw invalidPipeArgumentError(DecimalPipe, (error as Error).message); } } } @@ -156,7 +156,7 @@ export class PercentPipe implements PipeTransform { const num = strToNumber(value); return formatPercent(num, locale, digitsInfo); } catch (error) { - throw invalidPipeArgumentError(PercentPipe, error.message); + throw invalidPipeArgumentError(PercentPipe, (error as Error).message); } } } @@ -281,7 +281,7 @@ export class CurrencyPipe implements PipeTransform { const num = strToNumber(value); return formatCurrency(num, locale, currency, currencyCode, digitsInfo); } catch (error) { - throw invalidPipeArgumentError(CurrencyPipe, error.message); + throw invalidPipeArgumentError(CurrencyPipe, (error as Error).message); } } } diff --git a/packages/common/upgrade/src/location_shim.ts b/packages/common/upgrade/src/location_shim.ts index 4e46269a06cce5..274eb00a634fe3 100644 --- a/packages/common/upgrade/src/location_shim.ts +++ b/packages/common/upgrade/src/location_shim.ts @@ -360,7 +360,7 @@ export class $locationShim { try { fn(url, state, oldUrl, oldState); } catch (e) { - err(e); + err(e as Error); } }); } diff --git a/packages/compiler-cli/linker/babel/src/es2015_linker_plugin.ts b/packages/compiler-cli/linker/babel/src/es2015_linker_plugin.ts index 11a647f0df416c..5616e55178ee6f 100644 --- a/packages/compiler-cli/linker/babel/src/es2015_linker_plugin.ts +++ b/packages/compiler-cli/linker/babel/src/es2015_linker_plugin.ts @@ -92,7 +92,7 @@ export function createEs2015LinkerPlugin({fileSystem, logger, ...options}: Linke call.replaceWith(replacement); } catch (e) { const node = isFatalLinkerError(e) ? e.node as t.Node : call.node; - throw buildCodeFrameError(call.hub.file, e.message, node); + throw buildCodeFrameError(call.hub.file, (e as Error).message, node); } } } diff --git a/packages/compiler-cli/ngcc/main-ngcc.ts b/packages/compiler-cli/ngcc/main-ngcc.ts index 352c83665ac0d0..6eabe0adf6d34a 100644 --- a/packages/compiler-cli/ngcc/main-ngcc.ts +++ b/packages/compiler-cli/ngcc/main-ngcc.ts @@ -22,7 +22,7 @@ if (require.main === module) { options.logger.debug(`Run ngcc in ${duration}s.`); } process.exitCode = 0; - } catch (e) { + } catch (e: any) { console.error(e.stack || e.message); process.exit(typeof e.code === 'number' ? e.code : 1); } diff --git a/packages/compiler-cli/ngcc/src/execution/cluster/worker.ts b/packages/compiler-cli/ngcc/src/execution/cluster/worker.ts index b74e849dbf3321..2806bc0ffd648d 100644 --- a/packages/compiler-cli/ngcc/src/execution/cluster/worker.ts +++ b/packages/compiler-cli/ngcc/src/execution/cluster/worker.ts @@ -48,7 +48,7 @@ if (require.main === module) { await startWorker(logger, createCompileFn); process.exitCode = 0; } catch (e) { - console.error(e.stack || e.message); + console.error((e as Error).stack || (e as Error).message); process.exit(1); } })(); @@ -79,7 +79,7 @@ export async function startWorker(logger: Logger, createCompileFn: CreateCompile throw new Error( `[Worker #${cluster.worker.id}] Invalid message received: ${JSON.stringify(msg)}`); } - } catch (err) { + } catch (err: any) { switch (err && err.code) { case 'ENOMEM': // Not being able to allocate enough memory is not necessarily a problem with processing diff --git a/packages/compiler-cli/ngcc/src/host/esm5_host.ts b/packages/compiler-cli/ngcc/src/host/esm5_host.ts index 0bd4fc5c81911f..6561f9dd1ea888 100644 --- a/packages/compiler-cli/ngcc/src/host/esm5_host.ts +++ b/packages/compiler-cli/ngcc/src/host/esm5_host.ts @@ -573,6 +573,7 @@ export class Esm5ReflectionHost extends Esm2015ReflectionHost { * * 1. `__spread(arguments)` * 2. `__spreadArray([], __read(arguments))` + * 3. `__spreadArray([], __read(arguments), false)` * * The tslib helpers may have been emitted inline as in the above example, or they may be read * from a namespace import. @@ -587,8 +588,8 @@ export class Esm5ReflectionHost extends Esm2015ReflectionHost { // `__spread(arguments)` return call.args.length === 1 && isArgumentsIdentifier(call.args[0]); } else if (call.helper === KnownDeclaration.TsHelperSpreadArray) { - // `__spreadArray([], __read(arguments))` - if (call.args.length !== 2) { + // `__spreadArray([], __read(arguments), false)` + if (call.args.length !== 2 && call.args.length !== 3) { return false; } diff --git a/packages/compiler-cli/ngcc/src/locking/async_locker.ts b/packages/compiler-cli/ngcc/src/locking/async_locker.ts index 7e2f1dc7aad33e..61d7a6fffee946 100644 --- a/packages/compiler-cli/ngcc/src/locking/async_locker.ts +++ b/packages/compiler-cli/ngcc/src/locking/async_locker.ts @@ -49,7 +49,7 @@ export class AsyncLocker { for (let attempts = 0; attempts < this.retryAttempts; attempts++) { try { return this.lockFile.write(); - } catch (e) { + } catch (e: any) { if (e.code !== 'EEXIST') { throw e; } diff --git a/packages/compiler-cli/ngcc/src/locking/lock_file_with_child_process/util.ts b/packages/compiler-cli/ngcc/src/locking/lock_file_with_child_process/util.ts index d4870221b245d1..a80c85a77f62a3 100644 --- a/packages/compiler-cli/ngcc/src/locking/lock_file_with_child_process/util.ts +++ b/packages/compiler-cli/ngcc/src/locking/lock_file_with_child_process/util.ts @@ -26,7 +26,7 @@ export function removeLockFile( logger.debug( `PIDs do not match (${pid} and ${lockFilePid}), so not removing ${lockFilePath}.`); } - } catch (e) { + } catch (e: any) { if (e.code === 'ENOENT') { logger.debug(`The lock-file at ${lockFilePath} was already removed.`); // File already removed so quietly exit diff --git a/packages/compiler-cli/ngcc/src/locking/sync_locker.ts b/packages/compiler-cli/ngcc/src/locking/sync_locker.ts index 54cca4d4a51593..51459fbad054a2 100644 --- a/packages/compiler-cli/ngcc/src/locking/sync_locker.ts +++ b/packages/compiler-cli/ngcc/src/locking/sync_locker.ts @@ -39,7 +39,7 @@ export class SyncLocker { protected create(): void { try { this.lockFile.write(); - } catch (e) { + } catch (e: any) { if (e.code !== 'EEXIST') { throw e; } diff --git a/packages/compiler-cli/ngcc/src/packages/configuration.ts b/packages/compiler-cli/ngcc/src/packages/configuration.ts index e699515c9ea0cb..2fd0642017f86d 100644 --- a/packages/compiler-cli/ngcc/src/packages/configuration.ts +++ b/packages/compiler-cli/ngcc/src/packages/configuration.ts @@ -340,7 +340,8 @@ export class NgccConfiguration { try { return this.evalSrcFile(configFilePath); } catch (e) { - throw new Error(`Invalid project configuration file at "${configFilePath}": ` + e.message); + throw new Error( + `Invalid project configuration file at "${configFilePath}": ` + (e as Error).message); } } else { return {packages: {}}; @@ -358,7 +359,8 @@ export class NgccConfiguration { versionRange: version || '*', }; } catch (e) { - throw new Error(`Invalid package configuration file at "${configFilePath}": ` + e.message); + throw new Error( + `Invalid package configuration file at "${configFilePath}": ` + (e as Error).message); } } else { return null; diff --git a/packages/compiler-cli/ngcc/src/packages/entry_point_manifest.ts b/packages/compiler-cli/ngcc/src/packages/entry_point_manifest.ts index 1bf23464b51e37..e708955e2a8992 100644 --- a/packages/compiler-cli/ngcc/src/packages/entry_point_manifest.ts +++ b/packages/compiler-cli/ngcc/src/packages/entry_point_manifest.ts @@ -95,7 +95,8 @@ export class EntryPointManifest { return entryPoints; } catch (e) { this.logger.warn( - `Unable to read the entry-point manifest for ${basePath}:\n`, e.stack || e.toString()); + `Unable to read the entry-point manifest for ${basePath}:\n`, + (e as Error).stack || (e as Error).toString()); return null; } } diff --git a/packages/compiler-cli/ngcc/src/rendering/source_maps.ts b/packages/compiler-cli/ngcc/src/rendering/source_maps.ts index 5091ac5ae391bf..2281286b661fa7 100644 --- a/packages/compiler-cli/ngcc/src/rendering/source_maps.ts +++ b/packages/compiler-cli/ngcc/src/rendering/source_maps.ts @@ -63,7 +63,7 @@ export function renderSourceAndMap( ]; } catch (e) { logger.error(`Error when flattening the source-map "${sourceMapPath}" for "${ - sourceFilePath}": ${e.toString()}`); + sourceFilePath}": ${(e as Error).toString()}`); return [ {path: sourceFilePath, contents: generatedContent}, {path: sourceMapPath, contents: fromObject(generatedMap).toJSON()}, diff --git a/packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts b/packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts index ea40506334d4c0..cf5cc3e05818b1 100644 --- a/packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts +++ b/packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts @@ -113,7 +113,7 @@ export class NewEntryPointFileWriter extends InPlaceFileWriter { this.fs.writeFile(newSourceMapPath, JSON.stringify(sourceMap)); } catch (e) { this.logger.warn(`Failed to process source-map at ${sourceMapPath}`); - this.logger.warn(e.message ?? e); + this.logger.warn((e as Error).message ?? e); } } } diff --git a/packages/compiler-cli/ngcc/test/execution/cluster/executor_spec.ts b/packages/compiler-cli/ngcc/test/execution/cluster/executor_spec.ts index ce79c66dcd1da5..c07daf0643b2da 100644 --- a/packages/compiler-cli/ngcc/test/execution/cluster/executor_spec.ts +++ b/packages/compiler-cli/ngcc/test/execution/cluster/executor_spec.ts @@ -86,7 +86,7 @@ runInEachFileSystem(() => { try { await executor.execute(analyzeEntryPointsSpy, createCompilerFnSpy); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(analyzeEntryPointsSpy).toHaveBeenCalledWith(); expect(createCompilerFnSpy).not.toHaveBeenCalled(); @@ -101,7 +101,7 @@ runInEachFileSystem(() => { try { await executor.execute(anyFn, anyFn); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('master runner error'); expect(lockFileLog).toEqual(['write()', 'remove()']); @@ -121,7 +121,7 @@ runInEachFileSystem(() => { try { await executor.execute(anyFn, anyFn); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('LockFile.write() error'); expect(masterRunSpy).not.toHaveBeenCalled(); @@ -141,7 +141,7 @@ runInEachFileSystem(() => { try { await executor.execute(anyFn, anyFn); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('LockFile.remove() error'); expect(lockFileLog).toEqual(['write()', 'remove()']); diff --git a/packages/compiler-cli/ngcc/test/execution/single_processor_executor_spec.ts b/packages/compiler-cli/ngcc/test/execution/single_processor_executor_spec.ts index 81ff7a1ac2e16f..5f365949654f25 100644 --- a/packages/compiler-cli/ngcc/test/execution/single_processor_executor_spec.ts +++ b/packages/compiler-cli/ngcc/test/execution/single_processor_executor_spec.ts @@ -65,7 +65,7 @@ describe('SingleProcessExecutor', () => { try { executor.execute(errorFn, createCompileFn); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('analyze error'); expect(lockFileLog).toEqual(['write()', 'remove()']); @@ -79,7 +79,7 @@ describe('SingleProcessExecutor', () => { try { executor.execute(oneTask, createErrorCompileFn); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('compile error'); expect(lockFileLog).toEqual(['write()', 'remove()']); @@ -100,7 +100,7 @@ describe('SingleProcessExecutor', () => { try { executor.execute(analyzeFn, anyFn); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('LockFile.write() error'); expect(lockFileLog).toEqual(['write()']); @@ -118,7 +118,7 @@ describe('SingleProcessExecutor', () => { try { executor.execute(noTasks, anyFn); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('LockFile.remove() error'); expect(lockFileLog).toEqual(['write()', 'remove()']); diff --git a/packages/compiler-cli/ngcc/test/integration/ngcc_spec.ts b/packages/compiler-cli/ngcc/test/integration/ngcc_spec.ts index ebc29bd5f5839f..af9704df1de266 100644 --- a/packages/compiler-cli/ngcc/test/integration/ngcc_spec.ts +++ b/packages/compiler-cli/ngcc/test/integration/ngcc_spec.ts @@ -381,7 +381,7 @@ runInEachFileSystem(() => { const jsContents = fs.readFile(_(`/node_modules/test-package/esm5/src/index.js`)); // Verify that the ES5 bundle does contain the expected downleveling syntax. - expect(jsContents).toContain('__spreadArray([], __read(arguments))'); + expect(jsContents).toContain('__spreadArray([], __read(arguments), false)'); expect(jsContents) .toContain( 'var ɵSubClass_BaseFactory; return function SubClass_Factory(t) { return (ɵSubClass_BaseFactory || (ɵSubClass_BaseFactory = ɵngcc0.ɵɵgetInheritedFactory(SubClass)))(t || SubClass); };'); @@ -420,7 +420,7 @@ runInEachFileSystem(() => { const jsContents = fs.readFile(_(`/node_modules/test-package/esm5/src/index.js`)); // Verify that the ES5 bundle does contain the expected downleveling syntax. - expect(jsContents).toContain('__spreadArray([], __read(arguments))'); + expect(jsContents).toContain('__spreadArray([], __read(arguments), false)'); expect(jsContents) .toContain( 'var ɵSubClass_BaseFactory; return function SubClass_Factory(t) { return (ɵSubClass_BaseFactory || (ɵSubClass_BaseFactory = ɵngcc0.ɵɵgetInheritedFactory(SubClass)))(t || SubClass); };'); @@ -730,10 +730,12 @@ runInEachFileSystem(() => { }); fail('should have thrown'); } catch (e) { - expect(e.message).toContain( - 'Failed to compile entry-point test-package (`esm2015` as esm2015) due to compilation errors:'); - expect(e.message).toContain('NG1010'); - expect(e.message).toContain('selector must be a string'); + const error = e as Error; + expect(error.message) + .toContain( + 'Failed to compile entry-point test-package (`esm2015` as esm2015) due to compilation errors:'); + expect(error.message).toContain('NG1010'); + expect(error.message).toContain('selector must be a string'); } }); @@ -1770,10 +1772,12 @@ runInEachFileSystem(() => { }); fail('should have thrown'); } catch (e) { - expect(e.message).toContain( - 'Failed to compile entry-point fatal-error (`es2015` as esm2015) due to compilation errors:'); - expect(e.message).toContain('NG2001'); - expect(e.message).toContain('component is missing a template'); + const error = e as Error; + expect(error.message) + .toContain( + 'Failed to compile entry-point fatal-error (`es2015` as esm2015) due to compilation errors:'); + expect(error.message).toContain('NG2001'); + expect(error.message).toContain('component is missing a template'); } }); diff --git a/packages/compiler-cli/ngcc/test/locking/async_locker_spec.ts b/packages/compiler-cli/ngcc/test/locking/async_locker_spec.ts index cfee2cfd010ad1..28812124cbbfdb 100644 --- a/packages/compiler-cli/ngcc/test/locking/async_locker_spec.ts +++ b/packages/compiler-cli/ngcc/test/locking/async_locker_spec.ts @@ -44,7 +44,7 @@ runInEachFileSystem(() => { throw new Error('ERROR'); }); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('ERROR'); expect(log).toEqual(['write()', 'fn()', 'remove()']); diff --git a/packages/compiler-cli/ngcc/test/locking/sync_locker_spec.ts b/packages/compiler-cli/ngcc/test/locking/sync_locker_spec.ts index b1445c40857ca8..d8d7952b34ea19 100644 --- a/packages/compiler-cli/ngcc/test/locking/sync_locker_spec.ts +++ b/packages/compiler-cli/ngcc/test/locking/sync_locker_spec.ts @@ -38,7 +38,7 @@ runInEachFileSystem(() => { throw new Error('ERROR'); }); } catch (e) { - error = e.message; + error = (e as Error).message; } expect(error).toEqual('ERROR'); expect(log).toEqual(['write()', 'fn()', 'remove()']); diff --git a/packages/compiler-cli/package.json b/packages/compiler-cli/package.json index a16d15ba41debe..6230aa5b6ae5ec 100644 --- a/packages/compiler-cli/package.json +++ b/packages/compiler-cli/package.json @@ -23,12 +23,12 @@ "semver": "^7.0.0", "source-map": "^0.6.1", "sourcemap-codec": "^1.4.8", - "tslib": "^2.2.0", + "tslib": "^2.3.0", "yargs": "^17.0.0" }, "peerDependencies": { "@angular/compiler": "0.0.0-PLACEHOLDER", - "typescript": ">=4.2.3 <4.4" + "typescript": ">=4.2.3 <4.5" }, "repository": { "type": "git", diff --git a/packages/compiler-cli/src/metadata/collector.ts b/packages/compiler-cli/src/metadata/collector.ts index 81510e93a8161b..74315bcef24f56 100644 --- a/packages/compiler-cli/src/metadata/collector.ts +++ b/packages/compiler-cli/src/metadata/collector.ts @@ -710,10 +710,10 @@ function validateMetadata( const {line, character} = sourceFile.getLineAndCharacterOfPosition(node.getStart()); throw new Error(`${sourceFile.fileName}:${line + 1}:${ character + 1}: Error encountered in metadata generated for exported symbol '${ - name}': \n ${e.message}`); + name}': \n ${(e as Error).message}`); } - throw new Error( - `Error encountered in metadata generated for exported symbol ${name}: \n ${e.message}`); + throw new Error(`Error encountered in metadata generated for exported symbol ${name}: \n ${ + (e as Error).message}`); } } }); diff --git a/packages/compiler-cli/src/ngtsc/file_system/testing/src/test_helper.ts b/packages/compiler-cli/src/ngtsc/file_system/testing/src/test_helper.ts index 28bd7b7bdd185e..918474b7f8021e 100644 --- a/packages/compiler-cli/src/ngtsc/file_system/testing/src/test_helper.ts +++ b/packages/compiler-cli/src/ngtsc/file_system/testing/src/test_helper.ts @@ -69,7 +69,7 @@ runInEachFileSystem.windows = (callback: (os: string) => void) => export function initMockFileSystem(os: string, cwd?: AbsoluteFsPath): MockFileSystem { const fs = createMockFileSystem(os, cwd); setFileSystem(fs); - monkeyPatchTypeScript(os, fs); + monkeyPatchTypeScript(fs); return fs; } @@ -88,11 +88,7 @@ function createMockFileSystem(os: string, cwd?: AbsoluteFsPath): MockFileSystem } } -function monkeyPatchTypeScript(os: string, fs: MockFileSystem) { - ts.sys.directoryExists = path => { - const absPath = fs.resolve(path); - return fs.exists(absPath) && fs.stat(absPath).isDirectory(); - }; +function monkeyPatchTypeScript(fs: MockFileSystem) { ts.sys.fileExists = path => { const absPath = fs.resolve(path); return fs.exists(absPath) && fs.stat(absPath).isFile(); @@ -102,6 +98,7 @@ function monkeyPatchTypeScript(os: string, fs: MockFileSystem) { ts.sys.readFile = fs.readFile.bind(fs); ts.sys.resolvePath = fs.resolve.bind(fs); ts.sys.writeFile = fs.writeFile.bind(fs); + ts.sys.directoryExists = directoryExists; ts.sys.readDirectory = readDirectory; function getDirectories(path: string): string[] { @@ -132,21 +129,26 @@ function monkeyPatchTypeScript(os: string, fs: MockFileSystem) { return fs.realpath(fs.resolve(path)); } + function directoryExists(path: string) { + const absPath = fs.resolve(path); + return fs.exists(absPath) && fs.stat(absPath).isDirectory(); + } + // Rather than completely re-implementing we are using the `ts.matchFiles` function, // which is internal to the `ts` namespace. const tsMatchFiles: ( path: string, extensions: ReadonlyArray|undefined, excludes: ReadonlyArray|undefined, includes: ReadonlyArray|undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number|undefined, - getFileSystemEntries: (path: string) => FileSystemEntries, - realpath: (path: string) => string) => string[] = (ts as any).matchFiles; + getFileSystemEntries: (path: string) => FileSystemEntries, realpath: (path: string) => string, + directoryExists: (path: string) => boolean) => string[] = (ts as any).matchFiles; function readDirectory( path: string, extensions?: ReadonlyArray, excludes?: ReadonlyArray, includes?: ReadonlyArray, depth?: number): string[] { return tsMatchFiles( path, extensions, excludes, includes, fs.isCaseSensitive(), fs.pwd(), depth, - getFileSystemEntries, realPath); + getFileSystemEntries, realPath, directoryExists); } } diff --git a/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file_loader.ts b/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file_loader.ts index bb6721cc12c34a..a24413f9794242 100644 --- a/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file_loader.ts +++ b/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file_loader.ts @@ -111,7 +111,7 @@ export class SourceFileLoader { return new SourceFile(sourcePath, contents, sourceMapInfo, sources, this.fs); } catch (e) { this.logger.warn( - `Unable to fully load ${sourcePath} for source-map flattening: ${e.message}`); + `Unable to fully load ${sourcePath} for source-map flattening: ${(e as Error).message}`); return null; } finally { // We are finished with this recursion so revert the paths being tracked @@ -166,8 +166,8 @@ export class SourceFileLoader { origin: ContentOrigin.FileSystem, }; } catch (e) { - this.logger.warn( - `Unable to fully load ${sourcePath} for source-map flattening: ${e.message}`); + this.logger.warn(`Unable to fully load ${sourcePath} for source-map flattening: ${ + (e as Error).message}`); return null; } } diff --git a/packages/compiler-cli/src/ngtsc/testing/src/mock_file_loading.ts b/packages/compiler-cli/src/ngtsc/testing/src/mock_file_loading.ts index 63c86058b42400..437daac37b4611 100644 --- a/packages/compiler-cli/src/ngtsc/testing/src/mock_file_loading.ts +++ b/packages/compiler-cli/src/ngtsc/testing/src/mock_file_loading.ts @@ -132,7 +132,7 @@ export function loadTestDirectory( fs.writeFile(targetPath, readFileSync(srcPath, 'utf-8')); } } catch (e) { - console.warn(`Failed to add ${srcPath} to the mock file-system: ${e.message}`); + console.warn(`Failed to add ${srcPath} to the mock file-system: ${(e as Error).message}`); } }); } diff --git a/packages/compiler-cli/src/perform_compile.ts b/packages/compiler-cli/src/perform_compile.ts index f84f0e8ab934ca..e1635f7614bf1e 100644 --- a/packages/compiler-cli/src/perform_compile.ts +++ b/packages/compiler-cli/src/perform_compile.ts @@ -206,7 +206,7 @@ export function readConfiguration( } catch (e) { const errors: ts.Diagnostic[] = [{ category: ts.DiagnosticCategory.Error, - messageText: e.stack, + messageText: (e as Error).stack || '', file: undefined, start: undefined, length: undefined, @@ -335,14 +335,15 @@ export function performCompilation({ } return {diagnostics: allDiagnostics, program}; } catch (e) { + const error = e as Error; let errMsg: string; let code: number; - if (isSyntaxError(e)) { + if (isSyntaxError(error)) { // don't report the stack for syntax errors as they are well known errors. - errMsg = e.message; + errMsg = error.message; code = api.DEFAULT_ERROR_CODE; } else { - errMsg = e.stack; + errMsg = error.stack || ''; // It is not a syntax error we might have a program with unknown state, discard it. program = undefined; code = api.UNKNOWN_ERROR_CODE; diff --git a/packages/compiler-cli/src/transformers/downlevel_decorators_transform.ts b/packages/compiler-cli/src/transformers/downlevel_decorators_transform.ts index f9da5fa2f3e3e8..f27aabee8f0854 100644 --- a/packages/compiler-cli/src/transformers/downlevel_decorators_transform.ts +++ b/packages/compiler-cli/src/transformers/downlevel_decorators_transform.ts @@ -67,8 +67,7 @@ function extractMetadataFromSingleDecorator( for (const arg of call.arguments) { args.push(arg); } - const argsArrayLiteral = ts.createArrayLiteral(args); - argsArrayLiteral.elements.hasTrailingComma = true; + const argsArrayLiteral = ts.createArrayLiteral(ts.createNodeArray(args, true)); metadataProperties.push(ts.createPropertyAssignment('args', argsArrayLiteral)); } break; @@ -480,8 +479,6 @@ export function getDownlevelDecoratorsTransform( * - creates a propDecorators property */ function transformClassDeclaration(classDecl: ts.ClassDeclaration): ts.ClassDeclaration { - classDecl = ts.getMutableClone(classDecl); - const newMembers: ts.ClassElement[] = []; const decoratedProperties = new Map(); let classParameters: ParameterDecorationInfo[]|null = null; @@ -556,11 +553,10 @@ export function getDownlevelDecoratorsTransform( const members = ts.setTextRange( ts.createNodeArray(newMembers, classDecl.members.hasTrailingComma), classDecl.members); - - return ts.updateClassDeclaration( - classDecl, decoratorsToKeep.size ? Array.from(decoratorsToKeep) : undefined, - classDecl.modifiers, classDecl.name, classDecl.typeParameters, classDecl.heritageClauses, - members); + const newClassDecl = ts.createClassDeclaration( + decoratorsToKeep.size ? Array.from(decoratorsToKeep) : undefined, classDecl.modifiers, + classDecl.name, classDecl.typeParameters, classDecl.heritageClauses, members); + return ts.setTextRange(newClassDecl, classDecl); } /** diff --git a/packages/compiler-cli/src/transformers/program.ts b/packages/compiler-cli/src/transformers/program.ts index 9e32a2a9057479..021e2e3e8fdf53 100644 --- a/packages/compiler-cli/src/transformers/program.ts +++ b/packages/compiler-cli/src/transformers/program.ts @@ -725,12 +725,12 @@ class AngularCompilerProgram implements Program { } catch (e) { // TODO(tbosch): check whether we can actually have syntax errors here, // as we already parsed the metadata and templates before to create the type check block. - if (isSyntaxError(e)) { + if (isSyntaxError(e as Error)) { const genDiags: ts.Diagnostic[] = [{ file: undefined, start: undefined, length: undefined, - messageText: e.message, + messageText: (e as Error).message, category: ts.DiagnosticCategory.Error, source: SOURCE, code: DEFAULT_ERROR_CODE diff --git a/packages/compiler-cli/src/typescript_support.ts b/packages/compiler-cli/src/typescript_support.ts index 334c4bd85eba74..6507693e84a54f 100644 --- a/packages/compiler-cli/src/typescript_support.ts +++ b/packages/compiler-cli/src/typescript_support.ts @@ -15,7 +15,7 @@ import {compareVersions} from './diagnostics/typescript_version'; * Note: this check is disabled in g3, search for * `angularCompilerOptions.disableTypeScriptVersionCheck` config param value in g3. */ -const MIN_TS_VERSION = '4.2.3'; +const MIN_TS_VERSION = '4.3.2'; /** * Supremum of supported TypeScript versions @@ -25,7 +25,7 @@ const MIN_TS_VERSION = '4.2.3'; * Note: this check is disabled in g3, search for * `angularCompilerOptions.disableTypeScriptVersionCheck` config param value in g3. */ -const MAX_TS_VERSION = '4.4.0'; +const MAX_TS_VERSION = '4.5.0'; /** * The currently used version of TypeScript, which can be adjusted for testing purposes using diff --git a/packages/compiler-cli/test/compliance/test_helpers/get_compliance_tests.ts b/packages/compiler-cli/test/compliance/test_helpers/get_compliance_tests.ts index e47479470632a8..f1ecd56e4e5527 100644 --- a/packages/compiler-cli/test/compliance/test_helpers/get_compliance_tests.ts +++ b/packages/compiler-cli/test/compliance/test_helpers/get_compliance_tests.ts @@ -59,8 +59,8 @@ function loadTestCasesFile( try { return JSON.parse(fs.readFile(testCasesPath)) as {cases: TestCaseJson | TestCaseJson[]}; } catch (e) { - throw new Error( - `Failed to load test-cases at "${fs.relative(basePath, testCasesPath)}":\n ${e.message}`); + throw new Error(`Failed to load test-cases at "${fs.relative(basePath, testCasesPath)}":\n ${ + (e as Error).message}`); } } diff --git a/packages/compiler-cli/test/test_support.ts b/packages/compiler-cli/test/test_support.ts index b0464988b80dbe..5033978f448e4a 100644 --- a/packages/compiler-cli/test/test_support.ts +++ b/packages/compiler-cli/test/test_support.ts @@ -143,7 +143,7 @@ export function setupBazelTo(tmpDirPath: string) { const rxjsSource = resolveNpmTreeArtifact('rxjs', 'index.js'); const rxjsDest = path.join(nodeModulesPath, 'rxjs'); fs.symlinkSync(rxjsSource, rxjsDest, 'junction'); - } catch (e) { + } catch (e: any) { if (e.code !== 'MODULE_NOT_FOUND') throw e; } } diff --git a/packages/compiler-cli/test/transformers/downlevel_decorators_transform_spec.ts b/packages/compiler-cli/test/transformers/downlevel_decorators_transform_spec.ts index eaee4b84da1b35..f2b47391d75399 100644 --- a/packages/compiler-cli/test/transformers/downlevel_decorators_transform_spec.ts +++ b/packages/compiler-cli/test/transformers/downlevel_decorators_transform_spec.ts @@ -182,7 +182,7 @@ describe('downlevel decorator transform', () => { expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` - MyClass = tslib_1.__decorate([ + MyClass = (0, tslib_1.__decorate)([ SomeUnknownDecorator() ], MyClass); `); @@ -197,7 +197,7 @@ describe('downlevel decorator transform', () => { expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` - MyClass = tslib_1.__decorate([ + MyClass = (0, tslib_1.__decorate)([ DecoratorBuilder().customClassDecorator ], MyClass); `); @@ -231,7 +231,7 @@ describe('downlevel decorator transform', () => { expect(diagnostics.length).toBe(0); expect(output).toContain(dedent` - tslib_1.__decorate([ + (0, tslib_1.__decorate)([ SomeDecorator() ], MyDir.prototype, "disabled", void 0); `); @@ -671,8 +671,8 @@ describe('downlevel decorator transform', () => { expect(diagnostics.length).toBe(0); expect(output).not.toContain('MyService.decorators'); expect(output).toContain(dedent` - MyService = tslib_1.__decorate([ - core_1.Injectable() + MyService = (0, tslib_1.__decorate)([ + (0, core_1.Injectable)() ], MyService); `); }); @@ -697,8 +697,8 @@ describe('downlevel decorator transform', () => { MyService.ctorParameters = () => [ { type: InjectClass } ]; - MyService = tslib_1.__decorate([ - core_1.Injectable() + MyService = (0, tslib_1.__decorate)([ + (0, core_1.Injectable)() ], MyService); `); }); @@ -723,8 +723,8 @@ describe('downlevel decorator transform', () => { MyService.ctorParameters = () => [ { type: InjectClass, decorators: [{ type: core_1.Inject, args: ['test',] }] } ]; - MyService = tslib_1.__decorate([ - core_1.Injectable() + MyService = (0, tslib_1.__decorate)([ + (0, core_1.Injectable)() ], MyService); `); }); diff --git a/packages/compiler-cli/test/transformers/inline_resources_spec.ts b/packages/compiler-cli/test/transformers/inline_resources_spec.ts index 53d43bc87c1044..011bdeb46289f3 100644 --- a/packages/compiler-cli/test/transformers/inline_resources_spec.ts +++ b/packages/compiler-cli/test/transformers/inline_resources_spec.ts @@ -47,7 +47,7 @@ describe('inline resources transformer', () => { expect(actual).not.toContain('templateUrl:'); expect(actual.replace(/\s+/g, ' ')) .toContain( - 'Foo = __decorate([ core_1.Component({ template: "Some template", otherProp: 3 }) ], Foo)'); + 'Foo = __decorate([ (0, core_1.Component)({ template: "Some template", otherProp: 3 }) ], Foo)'); }); it('should allow different quotes', () => { const actual = convert(`import {Component} from '@angular/core'; @@ -172,8 +172,6 @@ function convert(source: string) { const context = new MockAotContext('/', {[baseFileName + '.ts']: source}); const host = new MockCompilerHost(context); - const sourceFile = - ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, /* setParentNodes */ true); const program = ts.createProgram( [fileName], { module: ts.ModuleKind.CommonJS, @@ -186,7 +184,7 @@ function convert(source: string) { program, {loadResource, resourceNameToFileName: (u: string) => u})] }; let result = ''; - const emitResult = program.emit( + program.emit( moduleSourceFile, (emittedFileName, data, writeByteOrderMark, onError, sourceFiles) => { if (fileName.startsWith(moduleName)) { result = data; diff --git a/packages/compiler/package.json b/packages/compiler/package.json index 1d10bf278623f1..508fa272cc43ba 100644 --- a/packages/compiler/package.json +++ b/packages/compiler/package.json @@ -8,7 +8,7 @@ "node": "^12.14.1 || >=14.0.0" }, "dependencies": { - "tslib": "^2.2.0" + "tslib": "^2.3.0" }, "repository": { "type": "git", diff --git a/packages/compiler/src/aot/static_reflector.ts b/packages/compiler/src/aot/static_reflector.ts index e2e7b1e4f1852c..cc858541c463fb 100644 --- a/packages/compiler/src/aot/static_reflector.ts +++ b/packages/compiler/src/aot/static_reflector.ts @@ -462,7 +462,6 @@ export class StaticReflector implements CompileReflector { const self = this; let scope = BindingScope.empty; const calling = new Map(); - const rootContext = context; function simplifyInContext( context: StaticSymbol, value: any, depth: number, references: number): any { @@ -826,9 +825,9 @@ export class StaticReflector implements CompileReflector { result = simplifyInContext(context, value, 0, lazy ? 1 : 0); } catch (e) { if (this.errorRecorder) { - this.reportError(e, context); + this.reportError(e as Error, context); } else { - throw formatMetadataError(e, context); + throw formatMetadataError(e as Error, context); } } if (shouldIgnore(result)) { @@ -910,7 +909,7 @@ function metadataError( return error; } -function isMetadataError(error: Error): error is MetadataError { +function isMetadataError(error: unknown): error is MetadataError { return !!(error as any)[METADATA_ERROR]; } diff --git a/packages/compiler/src/aot/static_symbol_resolver.ts b/packages/compiler/src/aot/static_symbol_resolver.ts index 4389e6c293b52c..59a4ae3c6e8028 100644 --- a/packages/compiler/src/aot/static_symbol_resolver.ts +++ b/packages/compiler/src/aot/static_symbol_resolver.ts @@ -528,7 +528,7 @@ export class StaticSymbolResolver { return this.host.moduleNameToFileName(module, containingFile); } catch (e) { console.error(`Could not resolve module '${module}' relative to file ${containingFile}`); - this.reportError(e, undefined, containingFile); + this.reportError(e as Error, undefined, containingFile); } return null; } diff --git a/packages/compiler/src/expression_parser/ast.ts b/packages/compiler/src/expression_parser/ast.ts index 3f064620249d1a..fcd7c9e8926ef2 100644 --- a/packages/compiler/src/expression_parser/ast.ts +++ b/packages/compiler/src/expression_parser/ast.ts @@ -260,9 +260,9 @@ export class Binary extends AST { export class Unary extends Binary { // Redeclare the properties that are inherited from `Binary` as `never`, as consumers should not // depend on these fields when operating on `Unary`. - override left: never; - override right: never; - override operation: never; + override left: never = null as never; + override right: never = null as never; + override operation: never = null as never; /** * Creates a unary minus expression "-x", represented as `Binary` using "0 - x". diff --git a/packages/compiler/src/output/output_interpreter.ts b/packages/compiler/src/output/output_interpreter.ts index cfcbc43c91c47c..bbfeafaae86d3d 100644 --- a/packages/compiler/src/output/output_interpreter.ts +++ b/packages/compiler/src/output/output_interpreter.ts @@ -235,7 +235,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor { } catch (e) { const childCtx = ctx.createChildWihtLocalVars(); childCtx.vars.set(CATCH_ERROR_VAR, e); - childCtx.vars.set(CATCH_STACK_VAR, e.stack); + childCtx.vars.set(CATCH_STACK_VAR, (e as Error).stack); return this.visitAllStatements(stmt.catchStmts, childCtx); } } diff --git a/packages/compiler/test/aot/static_reflector_spec.ts b/packages/compiler/test/aot/static_reflector_spec.ts index cf56450fbe4f23..ca3ddb1d26b695 100644 --- a/packages/compiler/test/aot/static_reflector_spec.ts +++ b/packages/compiler/test/aot/static_reflector_spec.ts @@ -367,7 +367,7 @@ describe('StaticReflector', () => { simplify( reflector.getStaticSymbol('/tmp/src/invalid-metadata.ts', ''), classData.decorators[0].arguments); - } catch (e) { + } catch (e: any) { expect(e.position).toBeDefined(); threw = true; } @@ -1297,7 +1297,7 @@ describe('StaticReflector', () => { function collectError(symbol: string): string { try { reflector.annotations(reflector.getStaticSymbol(fileName, symbol)); - } catch (e) { + } catch (e: any) { return e.message; } fail('Expected an exception to be thrown'); diff --git a/packages/core/package.json b/packages/core/package.json index e0b585d592e9a3..9ea40ad28a6c17 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -8,7 +8,7 @@ "node": "^12.14.1 || >=14.0.0" }, "dependencies": { - "tslib": "^2.2.0" + "tslib": "^2.3.0" }, "peerDependencies": { "rxjs": "^6.5.3 || ^7.0.0", diff --git a/packages/core/schematics/migrations/static-queries/index.ts b/packages/core/schematics/migrations/static-queries/index.ts index 06f61ec9748913..88594b286d4f6b 100644 --- a/packages/core/schematics/migrations/static-queries/index.ts +++ b/packages/core/schematics/migrations/static-queries/index.ts @@ -200,7 +200,7 @@ async function runStaticQueryMigration( logger.warn( `Could not setup migration strategy for "${project.tsconfigPath}". The ` + `following error has been reported:\n`); - logger.error(`${e.toString()}\n`); + logger.error(`${(e as Error).toString()}\n`); logger.info( 'Migration can be rerun with: "ng update @angular/core --from 7 --to 8 --migrate-only"\n'); return []; diff --git a/packages/core/schematics/migrations/undecorated-classes-with-di/index.ts b/packages/core/schematics/migrations/undecorated-classes-with-di/index.ts index 26d27102ffb1fb..2939ec7373646b 100644 --- a/packages/core/schematics/migrations/undecorated-classes-with-di/index.ts +++ b/packages/core/schematics/migrations/undecorated-classes-with-di/index.ts @@ -196,7 +196,7 @@ function gracefullyCreateProgram( return {program, compiler}; } catch (e) { logger.warn(`\n${MIGRATION_AOT_FAILURE} The following project failed: ${tsconfigPath}\n`); - logger.error(`${e.toString()}\n`); + logger.error(`${(e as Error).toString()}\n`); return null; } } diff --git a/packages/core/src/di/injector.ts b/packages/core/src/di/injector.ts index 39db0b63ca32f7..538645f0069f32 100644 --- a/packages/core/src/di/injector.ts +++ b/packages/core/src/di/injector.ts @@ -299,7 +299,7 @@ function tryResolveToken( notFoundValue: any, flags: InjectFlags): any { try { return resolveToken(token, record, records, parent, notFoundValue, flags); - } catch (e) { + } catch (e: any) { // ensure that 'e' is of type Error. if (!(e instanceof Error)) { e = new Error(e); diff --git a/packages/core/src/di/r3_injector.ts b/packages/core/src/di/r3_injector.ts index cf0de1081abb5e..b3e0812dc8757c 100644 --- a/packages/core/src/di/r3_injector.ts +++ b/packages/core/src/di/r3_injector.ts @@ -221,7 +221,7 @@ export class R3Injector { null : notFoundValue; return nextInjector.get(token, notFoundValue); - } catch (e) { + } catch (e: any) { if (e.name === 'NullInjectorError') { const path: any[] = e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || []; path.unshift(stringify(token)); diff --git a/packages/core/src/di/reflective_injector.ts b/packages/core/src/di/reflective_injector.ts index 171a92a16c2c2c..703241f7681593 100644 --- a/packages/core/src/di/reflective_injector.ts +++ b/packages/core/src/di/reflective_injector.ts @@ -360,7 +360,7 @@ export class ReflectiveInjector_ implements ReflectiveInjector { try { deps = ResolvedReflectiveFactory.dependencies.map(dep => this._getByReflectiveDependency(dep)); - } catch (e) { + } catch (e: any) { if (e.addKey) { e.addKey(this, provider.key); } @@ -371,7 +371,7 @@ export class ReflectiveInjector_ implements ReflectiveInjector { try { obj = factory(...deps); } catch (e) { - throw instantiationError(this, e, e.stack, provider.key); + throw instantiationError(this, e, (e as Error).stack, provider.key); } return obj; diff --git a/packages/core/src/reflection/reflection_capabilities.ts b/packages/core/src/reflection/reflection_capabilities.ts index c4ad36405b4526..744f3053810e50 100644 --- a/packages/core/src/reflection/reflection_capabilities.ts +++ b/packages/core/src/reflection/reflection_capabilities.ts @@ -43,13 +43,13 @@ import {GetterFn, MethodFn, SetterFn} from './types'; * or downleveled to ES5 with `downlevelIteration` for TypeScript >= 4.2: * ``` * function MyClass() { - * var _this = _super.apply(this, __spreadArray([], __read(arguments))) || this; + * var _this = _super.apply(this, __spreadArray([], __read(arguments), false)) || this; * ``` * * More details can be found in: https://github.com/angular/angular/issues/38453. */ export const ES5_DELEGATE_CTOR = - /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*(arguments|(?:[^()]+\(\[\],)?[^()]+\(arguments\))\)/; + /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*(arguments|(?:[^()]+\(\[\],)?[^()]+\(arguments\).*)\)/; /** Regular expression that detects ES2015 classes which extend from other classes. */ export const ES2015_INHERITED_CLASS = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{/; /** diff --git a/packages/core/src/view/services.ts b/packages/core/src/view/services.ts index d62efa68eae7ba..cd309f312cb933 100644 --- a/packages/core/src/view/services.ts +++ b/packages/core/src/view/services.ts @@ -644,7 +644,7 @@ function callWithDebugContext(action: DebugAction, fn: any, self: any, args: any _currentAction = oldAction; return result; } catch (e) { - if (isViewDebugError(e) || !_currentView) { + if (isViewDebugError(e as Error) || !_currentView) { throw e; } throw viewWrappedDebugError(e, getCurrentDebugContext()!); diff --git a/packages/core/test/animation/animation_integration_spec.ts b/packages/core/test/animation/animation_integration_spec.ts index 99338410d525a8..d5c8251d21c018 100644 --- a/packages/core/test/animation/animation_integration_spec.ts +++ b/packages/core/test/animation/animation_integration_spec.ts @@ -3731,7 +3731,7 @@ describe('animation tests', function() { try { fixture.detectChanges(); } catch (e) { - errorMsg = e.message; + errorMsg = (e as Error).message; } expect(errorMsg).toMatch(/@foo has failed due to:/); diff --git a/packages/core/test/compiler/compiler_facade_spec.ts b/packages/core/test/compiler/compiler_facade_spec.ts index 6878c86442e510..399a3301a206fe 100644 --- a/packages/core/test/compiler/compiler_facade_spec.ts +++ b/packages/core/test/compiler/compiler_facade_spec.ts @@ -20,8 +20,9 @@ describe('getCompilerFacade', () => { getCompilerFacade({usage: JitCompilerUsage.Decorator, kind: 'directive', type: TestClass}); fail('Error expected as compiler facade is not available'); } catch (e) { - expect(e.message).toEqual( - `The directive 'TestClass' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available. + expect((e as Error).message) + .toEqual( + `The directive 'TestClass' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available. JIT compilation is discouraged for production use-cases! Consider using AOT mode instead. Alternatively, the JIT compiler should be loaded by bootstrapping using '@angular/platform-browser-dynamic' or '@angular/platform-server', @@ -35,8 +36,9 @@ or manually provide the compiler with 'import "@angular/compiler";' before boots {usage: JitCompilerUsage.PartialDeclaration, kind: 'directive', type: TestClass}); fail('Error expected as compiler facade is not available'); } catch (e) { - expect(e.message).toEqual( - `The directive 'TestClass' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available. + expect((e as Error).message) + .toEqual( + `The directive 'TestClass' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available. The directive is part of a library that has been partially compiled. However, the Angular Linker has not processed the library such that JIT compilation is used as fallback. diff --git a/packages/core/test/di/reflective_injector_spec.ts b/packages/core/test/di/reflective_injector_spec.ts index d06e7ac5379d34..4fb0ad7afc3df0 100644 --- a/packages/core/test/di/reflective_injector_spec.ts +++ b/packages/core/test/di/reflective_injector_spec.ts @@ -300,7 +300,7 @@ describe(`injector`, () => { try { injector.get(Car); throw 'Must throw'; - } catch (e) { + } catch (e: any) { expect(e.message).toContain( `Error during instantiation of Engine! (${stringify(Car)} -> Engine)`); expect(getOriginalError(e) instanceof Error).toBeTruthy(); diff --git a/packages/core/test/di/static_injector_spec.ts b/packages/core/test/di/static_injector_spec.ts index 5098e088147e7a..37135b94ff7fb0 100644 --- a/packages/core/test/di/static_injector_spec.ts +++ b/packages/core/test/di/static_injector_spec.ts @@ -316,7 +316,7 @@ function factoryFn(a: any) {} try { injector.get(Car); throw 'Must throw'; - } catch (e) { + } catch (e: any) { expect(e).toBe(error); expect(e.message).toContain( `StaticInjectorError[${stringify(Car)} -> Engine]: \n MyError`); diff --git a/packages/core/test/linker/change_detection_integration_spec.ts b/packages/core/test/linker/change_detection_integration_spec.ts index 2144e9e21f5f17..f6fc57ccb2f8a2 100644 --- a/packages/core/test/linker/change_detection_integration_spec.ts +++ b/packages/core/test/linker/change_detection_integration_spec.ts @@ -816,7 +816,7 @@ describe(`ChangeDetection`, () => { try { ctx.detectChanges(false); } catch (e) { - expect(e.message).toBe('Boom!'); + expect((e as Error).message).toBe('Boom!'); errored = true; } expect(errored).toBe(true); @@ -828,7 +828,7 @@ describe(`ChangeDetection`, () => { try { ctx.detectChanges(false); } catch (e) { - expect(e.message).toBe('Boom!'); + expect((e as Error).message).toBe('Boom!'); throw new Error('Second detectChanges() should not have called ngOnInit.'); } expect(directiveLog.filter(['ngOnInit'])).toEqual([]); diff --git a/packages/core/test/linker/integration_spec.ts b/packages/core/test/linker/integration_spec.ts index 11ee3e15a320a3..3615da637db1ca 100644 --- a/packages/core/test/linker/integration_spec.ts +++ b/packages/core/test/linker/integration_spec.ts @@ -1516,8 +1516,8 @@ function declareTests(config?: {useJit: boolean}) { try { TestBed.createComponent(ComponentWithoutView); } catch (e) { - expect(e.message).toContain( - `No template specified for component ${stringify(ComponentWithoutView)}`); + expect((e as Error).message) + .toContain(`No template specified for component ${stringify(ComponentWithoutView)}`); } }); @@ -1534,7 +1534,7 @@ function declareTests(config?: {useJit: boolean}) { TestBed.createComponent(MyComp); throw 'Should throw'; } catch (e) { - const c = getDebugContext(e); + const c = getDebugContext(e as Error); expect(c.componentRenderElement.nodeName.toUpperCase()).toEqual('DIV'); expect((c.injector).get).toBeTruthy(); } @@ -1550,7 +1550,7 @@ function declareTests(config?: {useJit: boolean}) { fixture.detectChanges(); throw 'Should throw'; } catch (e) { - const c = getDebugContext(e); + const c = getDebugContext(e as Error); expect(c.renderNode.nodeName.toUpperCase()).toEqual('INPUT'); expect(c.componentRenderElement.nodeName.toUpperCase()).toEqual('DIV'); expect((c.injector).get).toBeTruthy(); @@ -1570,7 +1570,7 @@ function declareTests(config?: {useJit: boolean}) { fixture.detectChanges(); throw 'Should throw'; } catch (e) { - const c = getDebugContext(e); + const c = getDebugContext(e as Error); expect(c.renderNode).toBeTruthy(); } }); @@ -1799,8 +1799,9 @@ function declareTests(config?: {useJit: boolean}) { TestBed.createComponent(MyComp); throw 'Should throw'; } catch (e) { - expect(e.message).toMatch( - /Template parse errors:\nCan't bind to 'unknown' since it isn't a known property of 'div'. \("
\]unknown="{{ctxProp}}"><\/div>"\): .*MyComp.html@0:5/); + expect((e as Error).message) + .toMatch( + /Template parse errors:\nCan't bind to 'unknown' since it isn't a known property of 'div'. \("
\]unknown="{{ctxProp}}"><\/div>"\): .*MyComp.html@0:5/); } }); @@ -1828,8 +1829,8 @@ function declareTests(config?: {useJit: boolean}) { fixture.detectChanges(); throw 'Should throw'; } catch (e) { - expect(e.message).toMatch( - /Can't bind to 'ngForIn' since it isn't a known property of 'div'./); + expect((e as Error).message) + .toMatch(/Can't bind to 'ngForIn' since it isn't a known property of 'div'./); } }); diff --git a/packages/core/testing/src/resolvers.ts b/packages/core/testing/src/resolvers.ts index ec58e2cb0d13ea..053e58ee811df0 100644 --- a/packages/core/testing/src/resolvers.ts +++ b/packages/core/testing/src/resolvers.ts @@ -57,7 +57,7 @@ abstract class OverrideResolver implements Resolver { const isKnownType = annotation instanceof Directive || annotation instanceof Component || annotation instanceof Pipe || annotation instanceof NgModule; if (isKnownType) { - return annotation instanceof this.type ? annotation : null; + return annotation instanceof this.type ? annotation as T : null; } } return null; diff --git a/packages/core/testing/src/test_bed.ts b/packages/core/testing/src/test_bed.ts index 61c4a0535774d0..19e273653d62b4 100644 --- a/packages/core/testing/src/test_bed.ts +++ b/packages/core/testing/src/test_bed.ts @@ -423,7 +423,7 @@ export class TestBedViewEngine implements TestBed { this._moduleFactory = this._compiler.compileModuleAndAllComponentsSync(moduleType).ngModuleFactory; } catch (e) { - const errorCompType = this._compiler.getComponentFromError(e); + const errorCompType = this._compiler.getComponentFromError(e as Error); if (errorCompType) { throw new Error( `This test module uses the component ${ diff --git a/packages/elements/package.json b/packages/elements/package.json index 3da5fa0277ae9a..234b5450e4ea3f 100644 --- a/packages/elements/package.json +++ b/packages/elements/package.json @@ -8,7 +8,7 @@ "node": "^12.14.1 || >=14.0.0" }, "dependencies": { - "tslib": "^2.2.0" + "tslib": "^2.3.0" }, "peerDependencies": { "@angular/core": "0.0.0-PLACEHOLDER", diff --git a/packages/forms/package.json b/packages/forms/package.json index 33cb036b42ff2d..00e3f68ba40567 100644 --- a/packages/forms/package.json +++ b/packages/forms/package.json @@ -8,7 +8,7 @@ "node": "^12.14.1 || >=14.0.0" }, "dependencies": { - "tslib": "^2.2.0" + "tslib": "^2.3.0" }, "peerDependencies": { "@angular/core": "0.0.0-PLACEHOLDER", diff --git a/packages/language-service/ivy/test/legacy/mock_host.ts b/packages/language-service/ivy/test/legacy/mock_host.ts index 4b97e42b1a1cd5..fc92342dcaf46b 100644 --- a/packages/language-service/ivy/test/legacy/mock_host.ts +++ b/packages/language-service/ivy/test/legacy/mock_host.ts @@ -154,6 +154,7 @@ export function setup() { useSingleInferredProject: true, useInferredProjectPerProjectRoot: true, typingsInstaller: ts.server.nullTypingsInstaller, + session: undefined }); // Opening APP_COMPONENT forces a new ConfiguredProject to be created based // on the tsconfig.json in the test project. diff --git a/packages/language-service/ivy/testing/src/env.ts b/packages/language-service/ivy/testing/src/env.ts index 482c81334cb9b0..cefca71637a501 100644 --- a/packages/language-service/ivy/testing/src/env.ts +++ b/packages/language-service/ivy/testing/src/env.ts @@ -36,7 +36,7 @@ export class LanguageServiceTestEnv { cancellationToken: ts.server.nullCancellationToken, host, typingsInstaller: ts.server.nullTypingsInstaller, - + session: undefined, useInferredProjectPerProjectRoot: true, useSingleInferredProject: true, }); diff --git a/packages/localize/src/tools/src/source_file_utils.ts b/packages/localize/src/tools/src/source_file_utils.ts index 4d225659879989..eeaad8cba93a84 100644 --- a/packages/localize/src/tools/src/source_file_utils.ts +++ b/packages/localize/src/tools/src/source_file_utils.ts @@ -383,7 +383,7 @@ export function translate( substitutions ]; } else { - diagnostics.error(e.message); + diagnostics.error((e as Error).message); return [messageParts, substitutions]; } } diff --git a/packages/localize/src/tools/src/translate/asset_files/asset_translation_handler.ts b/packages/localize/src/tools/src/translate/asset_files/asset_translation_handler.ts index 3b0ddeec70a08c..6e327c9d3be71d 100644 --- a/packages/localize/src/tools/src/translate/asset_files/asset_translation_handler.ts +++ b/packages/localize/src/tools/src/translate/asset_files/asset_translation_handler.ts @@ -42,7 +42,7 @@ export class AssetTranslationHandler implements TranslationHandler { this.fs.ensureDir(this.fs.dirname(outputPath)); this.fs.writeFile(outputPath, contents); } catch (e) { - diagnostics.error(e.message); + diagnostics.error((e as Error).message); } } } diff --git a/packages/localize/src/tools/src/translate/source_files/source_file_translation_handler.ts b/packages/localize/src/tools/src/translate/source_files/source_file_translation_handler.ts index 8c71aed038f9b2..2626bcc03020ed 100644 --- a/packages/localize/src/tools/src/translate/source_files/source_file_translation_handler.ts +++ b/packages/localize/src/tools/src/translate/source_files/source_file_translation_handler.ts @@ -104,7 +104,7 @@ export class SourceFileTranslationHandler implements TranslationHandler { this.fs.ensureDir(this.fs.dirname(outputPath)); this.fs.writeFile(outputPath, contents); } catch (e) { - diagnostics.error(e.message); + diagnostics.error((e as Error).message); } } } diff --git a/packages/localize/src/tools/src/translate/translation_files/translation_parsers/serialize_translation_message.ts b/packages/localize/src/tools/src/translate/translation_files/translation_parsers/serialize_translation_message.ts index df247b1801fd27..9b5b11569fef54 100644 --- a/packages/localize/src/tools/src/translate/translation_files/translation_parsers/serialize_translation_message.ts +++ b/packages/localize/src/tools/src/translate/translation_files/translation_parsers/serialize_translation_message.ts @@ -27,6 +27,6 @@ export function serializeTranslationMessage(element: Element, config: MessageSer const translation = serializer.serialize(rootNodes); return {translation, parseErrors, serializeErrors: []}; } catch (e) { - return {translation: null, parseErrors, serializeErrors: [e]}; + return {translation: null, parseErrors, serializeErrors: [e as ParseError]}; } } diff --git a/packages/localize/src/translate.ts b/packages/localize/src/translate.ts index 838df1aeddec35..2d018d0a6ccab5 100644 --- a/packages/localize/src/translate.ts +++ b/packages/localize/src/translate.ts @@ -93,7 +93,7 @@ export function translate(messageParts: TemplateStringsArray, substitutions: rea try { return _translate($localize.TRANSLATIONS, messageParts, substitutions); } catch (e) { - console.warn(e.message); + console.warn((e as Error).message); return [messageParts, substitutions]; } } diff --git a/packages/misc/angular-in-memory-web-api/package.json b/packages/misc/angular-in-memory-web-api/package.json index d0621050f69cfc..f5440c984a7b0a 100644 --- a/packages/misc/angular-in-memory-web-api/package.json +++ b/packages/misc/angular-in-memory-web-api/package.json @@ -10,7 +10,7 @@ "rxjs": "^6.5.3 || ^7.0.0" }, "dependencies": { - "tslib": "^2.2.0" + "tslib": "^2.3.0" }, "repository": { "type": "git", diff --git a/packages/misc/angular-in-memory-web-api/src/backend-service.ts b/packages/misc/angular-in-memory-web-api/src/backend-service.ts index 71a62384ead62e..234bad8e0b4d4e 100644 --- a/packages/misc/angular-in-memory-web-api/src/backend-service.ts +++ b/packages/misc/angular-in-memory-web-api/src/backend-service.ts @@ -320,7 +320,7 @@ export abstract class BackendService { try { resOptions = resOptionsFactory(); } catch (error) { - const err = error.message || error; + const err = (error as Error).message || error; resOptions = this.createErrorResponseOptions('', STATUS.INTERNAL_SERVER_ERROR, `${err}`); } @@ -550,7 +550,7 @@ export abstract class BackendService { const resourceUrl = urlRoot + apiBase + collectionName + '/'; return {apiBase, collectionName, id, query, resourceUrl}; } catch (err) { - const msg = `unable to parse url '${url}'; original error: ${err.message}`; + const msg = `unable to parse url '${url}'; original error: ${(err as Error).message}`; throw new Error(msg); } } @@ -565,7 +565,7 @@ export abstract class BackendService { try { item.id = id || this.genId(collection, collectionName); } catch (err) { - const emsg: string = err.message || ''; + const emsg: string = (err as Error).message || ''; if (/id type is non-numeric/.test(emsg)) { return this.createErrorResponseOptions(url, STATUS.UNPROCESSABLE_ENTRY, emsg); } else { diff --git a/packages/misc/angular-in-memory-web-api/src/http-client-backend-service.ts b/packages/misc/angular-in-memory-web-api/src/http-client-backend-service.ts index 92701755bf5e37..6b0ff1a69df63e 100644 --- a/packages/misc/angular-in-memory-web-api/src/http-client-backend-service.ts +++ b/packages/misc/angular-in-memory-web-api/src/http-client-backend-service.ts @@ -57,7 +57,7 @@ export class HttpClientBackendService extends BackendService implements HttpBack return this.handleRequest(req); } catch (error) { - const err = error.message || error; + const err = (error as Error).message || error; const resOptions = this.createErrorResponseOptions(req.url, STATUS.INTERNAL_SERVER_ERROR, `${err}`); return this.createResponse$(() => resOptions); @@ -94,7 +94,7 @@ export class HttpClientBackendService extends BackendService implements HttpBack try { return new HttpXhrBackend(this.xhrFactory); } catch (ex) { - ex.message = 'Cannot create passThru404 backend; ' + (ex.message || ''); + (ex as Error).message = 'Cannot create passThru404 backend; ' + ((ex as Error).message || ''); throw ex; } } diff --git a/packages/platform-browser-dynamic/package.json b/packages/platform-browser-dynamic/package.json index 28262e2e04b254..d31945f1fafcca 100644 --- a/packages/platform-browser-dynamic/package.json +++ b/packages/platform-browser-dynamic/package.json @@ -8,7 +8,7 @@ "node": "^12.14.1 || >=14.0.0" }, "dependencies": { - "tslib": "^2.2.0" + "tslib": "^2.3.0" }, "peerDependencies": { "@angular/core": "0.0.0-PLACEHOLDER", diff --git a/packages/platform-browser/package.json b/packages/platform-browser/package.json index 53a8b4ab90d968..7cc028de0d92c0 100644 --- a/packages/platform-browser/package.json +++ b/packages/platform-browser/package.json @@ -8,7 +8,7 @@ "node": "^12.14.1 || >=14.0.0" }, "dependencies": { - "tslib": "^2.2.0" + "tslib": "^2.3.0" }, "peerDependencies": { "@angular/animations": "0.0.0-PLACEHOLDER", diff --git a/packages/platform-browser/src/dom/dom_renderer.ts b/packages/platform-browser/src/dom/dom_renderer.ts index 02db420b5fcfaa..8a747fade67ca2 100644 --- a/packages/platform-browser/src/dom/dom_renderer.ts +++ b/packages/platform-browser/src/dom/dom_renderer.ts @@ -140,7 +140,7 @@ class DefaultDomRenderer2 implements Renderer2 { destroy(): void {} - destroyNode: null; + destroyNode = null; createElement(name: string, namespace?: string): any { if (namespace) { diff --git a/packages/platform-server/package.json b/packages/platform-server/package.json index bea2f098624629..039370bc60a8dc 100644 --- a/packages/platform-server/package.json +++ b/packages/platform-server/package.json @@ -17,7 +17,7 @@ }, "dependencies": { "domino": "^2.1.2", - "tslib": "^2.2.0", + "tslib": "^2.3.0", "xhr2": "^0.2.0" }, "repository": { diff --git a/packages/platform-server/src/server_renderer.ts b/packages/platform-server/src/server_renderer.ts index c24b8a426a1942..bab4c2e595d1b1 100644 --- a/packages/platform-server/src/server_renderer.ts +++ b/packages/platform-server/src/server_renderer.ts @@ -67,7 +67,7 @@ class DefaultServerRenderer2 implements Renderer2 { destroy(): void {} - destroyNode: null; + destroyNode = null; createElement(name: string, namespace?: string, debugInfo?: any): any { if (namespace) { diff --git a/packages/router/package.json b/packages/router/package.json index 30e91c1a5a5b32..d9fb4656b2245a 100644 --- a/packages/router/package.json +++ b/packages/router/package.json @@ -21,7 +21,7 @@ }, "homepage": "https://github.com/angular/angular/tree/master/packages/router", "dependencies": { - "tslib": "^2.2.0" + "tslib": "^2.3.0" }, "peerDependencies": { "@angular/core": "0.0.0-PLACEHOLDER", diff --git a/packages/router/src/router.ts b/packages/router/src/router.ts index c087670acfa182..032ca9252d4d45 100644 --- a/packages/router/src/router.ts +++ b/packages/router/src/router.ts @@ -1310,7 +1310,7 @@ export class Router { try { urlTree = this.urlSerializer.parse(url); } catch (e) { - urlTree = this.malformedUriErrorHandler(e, this.urlSerializer, url); + urlTree = this.malformedUriErrorHandler(e as Error, this.urlSerializer, url); } return urlTree; } diff --git a/packages/router/testing/src/router_testing_module.ts b/packages/router/testing/src/router_testing_module.ts index a1ee2b000d67c8..f7994bf0dba18f 100644 --- a/packages/router/testing/src/router_testing_module.ts +++ b/packages/router/testing/src/router_testing_module.ts @@ -47,7 +47,7 @@ export class SpyNgModuleFactoryLoader implements NgModuleFactoryLoader { /** * @docsNotRequired */ - private _stubbedModules: {[path: string]: Promise>} = {}; + private _stubbedModules: {[path: string]: Promise>|undefined} = {}; /** * @docsNotRequired @@ -71,7 +71,7 @@ export class SpyNgModuleFactoryLoader implements NgModuleFactoryLoader { load(path: string): Promise> { if (this._stubbedModules[path]) { - return this._stubbedModules[path]; + return this._stubbedModules[path]!; } else { return Promise.reject(new Error(`Cannot find module ${path}`)); } diff --git a/packages/service-worker/package.json b/packages/service-worker/package.json index 002df0f1665eff..3a42c3a680ade9 100644 --- a/packages/service-worker/package.json +++ b/packages/service-worker/package.json @@ -8,7 +8,7 @@ "node": "^12.14.1 || >=14.0.0" }, "dependencies": { - "tslib": "^2.2.0" + "tslib": "^2.3.0" }, "peerDependencies": { "@angular/core": "0.0.0-PLACEHOLDER", diff --git a/packages/service-worker/test/comm_spec.ts b/packages/service-worker/test/comm_spec.ts index 34b6bcc586588d..97bdf9257125a1 100644 --- a/packages/service-worker/test/comm_spec.ts +++ b/packages/service-worker/test/comm_spec.ts @@ -213,7 +213,7 @@ import {MockPushManager, MockPushSubscription, MockServiceWorkerContainer, MockS await push.unsubscribe(); throw new Error('`unsubscribe()` should fail'); } catch (err) { - expect(err.message).toBe('Not subscribed to push notifications.'); + expect((err as Error).message).toBe('Not subscribed to push notifications.'); } }); @@ -234,7 +234,7 @@ import {MockPushManager, MockPushSubscription, MockServiceWorkerContainer, MockS await push.unsubscribe(); throw new Error('`unsubscribe()` should fail'); } catch (err) { - expect(err.message).toBe('foo'); + expect((err as Error).message).toBe('foo'); } }); @@ -246,7 +246,7 @@ import {MockPushManager, MockPushSubscription, MockServiceWorkerContainer, MockS await push.unsubscribe(); throw new Error('`unsubscribe()` should fail'); } catch (err) { - expect(err.message).toBe('Unsubscribe failed!'); + expect((err as Error).message).toBe('Unsubscribe failed!'); } }); diff --git a/packages/service-worker/worker/src/data.ts b/packages/service-worker/worker/src/data.ts index 636d6321fa0bb0..4b12c57e2b7a02 100644 --- a/packages/service-worker/worker/src/data.ts +++ b/packages/service-worker/worker/src/data.ts @@ -284,7 +284,8 @@ export class DataGroup { } catch (err) { // Writing lru cache table failed. This could be a result of a full storage. // Continue serving clients as usual. - this.debugHandler.log(err, `DataGroup(${this.config.name}@${this.config.version}).syncLru()`); + this.debugHandler.log( + err as Error, `DataGroup(${this.config.name}@${this.config.version}).syncLru()`); // TODO: Better detect/handle full storage; e.g. using // [navigator.storage](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorStorage/storage). } @@ -457,7 +458,7 @@ export class DataGroup { // Saving the API response failed. This could be a result of a full storage. // Since this data is cached lazily and temporarily, continue serving clients as usual. this.debugHandler.log( - err, + err as Error, `DataGroup(${this.config.name}@${this.config.version}).safeCacheResponse(${ req.url}, status: ${res.status})`); diff --git a/packages/service-worker/worker/src/driver.ts b/packages/service-worker/worker/src/driver.ts index 43d4788f968276..37eab38774e681 100644 --- a/packages/service-worker/worker/src/driver.ts +++ b/packages/service-worker/worker/src/driver.ts @@ -31,10 +31,10 @@ const MAX_IDLE_DELAY = 30000; const SUPPORTED_CONFIG_VERSION = 1; -const NOTIFICATION_OPTION_NAMES: (keyof Notification)[] = [ +const NOTIFICATION_OPTION_NAMES = [ 'actions', 'badge', 'body', 'data', 'dir', 'icon', 'image', 'lang', 'renotify', 'requireInteraction', 'silent', 'tag', 'timestamp', 'title', 'vibrate' -]; +] as (keyof Notification)[]; interface LatestEntry { latest: string; @@ -142,7 +142,7 @@ export class Driver implements Debuggable, UpdateSource { await this.cleanupOldSwCaches(); } catch (err) { // Nothing to do - cleanup failed. Just log it. - this.debugger.log(err, 'cleanupOldSwCaches @ activate: cleanup-old-sw-caches'); + this.debugger.log(err as Error, 'cleanupOldSwCaches @ activate: cleanup-old-sw-caches'); } }); })()); @@ -407,7 +407,7 @@ export class Driver implements Debuggable, UpdateSource { client.postMessage({ ...response, status: false, - error: e.toString(), + error: (e as Error).toString(), }); } } @@ -476,7 +476,7 @@ export class Driver implements Debuggable, UpdateSource { // Handle the request. First try the AppVersion. If that doesn't work, fall back on the // network. res = await appVersion.handleFetch(event.request, event); - } catch (err) { + } catch (err: any) { if (err.isUnrecoverableState) { await this.notifyClientsAboutUnrecoverableState(appVersion, err.message); } @@ -628,7 +628,7 @@ export class Driver implements Debuggable, UpdateSource { // it fails, then full initialization was attempted and failed. await this.scheduleInitialization(this.versions.get(hash)!); } catch (err) { - this.debugger.log(err, `initialize: schedule init of ${hash}`); + this.debugger.log(err as Error, `initialize: schedule init of ${hash}`); return false; } })); @@ -778,8 +778,8 @@ export class Driver implements Debuggable, UpdateSource { try { await appVersion.initializeFully(); } catch (err) { - this.debugger.log(err, `initializeFully for ${appVersion.manifestHash}`); - await this.versionFailed(appVersion, err); + this.debugger.log(err as Error, `initializeFully for ${appVersion.manifestHash}`); + await this.versionFailed(appVersion, err as Error); } }; // TODO: better logic for detecting localhost. @@ -829,7 +829,7 @@ export class Driver implements Debuggable, UpdateSource { } catch (err2) { // We are already in a bad state. No need to make things worse. // Just log the error and move on. - this.debugger.log(err2, `Driver.versionFailed(${err.message || err})`); + this.debugger.log(err2 as Error, `Driver.versionFailed(${err.message || err})`); } } @@ -888,7 +888,7 @@ export class Driver implements Debuggable, UpdateSource { return true; } catch (err) { - this.debugger.log(err, `Error occurred while updating to manifest ${hash}`); + this.debugger.log(err as Error, `Error occurred while updating to manifest ${hash}`); this.state = DriverReadyState.EXISTING_CLIENTS_ONLY; this.stateMessage = `Degraded due to failed initialization: ${errorToString(err)}`; @@ -967,7 +967,7 @@ export class Driver implements Debuggable, UpdateSource { } catch (err) { // Oh well? Not much that can be done here. These caches will be removed on the next attempt // or when the SW revs its format version, which happens from time to time. - this.debugger.log(err, 'cleanupCaches'); + this.debugger.log(err as Error, 'cleanupCaches'); } } @@ -1133,7 +1133,7 @@ export class Driver implements Debuggable, UpdateSource { try { return await this.scope.fetch(req); } catch (err) { - this.debugger.log(err, `Driver.fetch(${req.url})`); + this.debugger.log(err as Error, `Driver.fetch(${req.url})`); return this.adapter.newResponse(null, { status: 504, statusText: 'Gateway Timeout', diff --git a/packages/service-worker/worker/src/idle.ts b/packages/service-worker/worker/src/idle.ts index 36bae8d1c06668..0ba38747de01d0 100644 --- a/packages/service-worker/worker/src/idle.ts +++ b/packages/service-worker/worker/src/idle.ts @@ -73,7 +73,7 @@ export class IdleScheduler { try { await task.run(); } catch (err) { - this.debug.log(err, `while running idle task ${task.desc}`); + this.debug.log(err as Error, `while running idle task ${task.desc}`); } }, Promise.resolve()); } diff --git a/packages/service-worker/worker/testing/events.ts b/packages/service-worker/worker/testing/events.ts index bedd3a7ce1787a..ed5f8232ddf852 100644 --- a/packages/service-worker/worker/testing/events.ts +++ b/packages/service-worker/worker/testing/events.ts @@ -72,6 +72,7 @@ export class MockActivateEvent extends MockExtendableEvent { export class MockFetchEvent extends MockExtendableEvent implements FetchEvent { readonly preloadResponse = Promise.resolve(); + handled = Promise.resolve(undefined); response: Promise = Promise.resolve(undefined); constructor( diff --git a/packages/upgrade/package.json b/packages/upgrade/package.json index 3e2c07c4fcb326..69fe4d75b9b7b7 100644 --- a/packages/upgrade/package.json +++ b/packages/upgrade/package.json @@ -8,7 +8,7 @@ "node": "^12.14.1 || >=14.0.0" }, "dependencies": { - "tslib": "^2.2.0" + "tslib": "^2.3.0" }, "peerDependencies": { "@angular/core": "0.0.0-PLACEHOLDER", diff --git a/packages/upgrade/src/common/src/downgrade_injectable.ts b/packages/upgrade/src/common/src/downgrade_injectable.ts index af2c7a20bd623e..cbb01d888a32a1 100644 --- a/packages/upgrade/src/common/src/downgrade_injectable.ts +++ b/packages/upgrade/src/common/src/downgrade_injectable.ts @@ -83,7 +83,7 @@ export function downgradeInjectable(token: any, downgradedModule: string = ''): const injector: Injector = $injector.get(injectorKey); return injector.get(token); } catch (err) { - throw new Error(`Error while ${attemptedAction}: ${err.message || err}`); + throw new Error(`Error while ${attemptedAction}: ${(err as Error).message || err}`); } }; (factory as any)['$inject'] = [$INJECTOR]; diff --git a/packages/zone.js/lib/common/events.ts b/packages/zone.js/lib/common/events.ts index 186773e39c4653..e325211f5d46cf 100644 --- a/packages/zone.js/lib/common/events.ts +++ b/packages/zone.js/lib/common/events.ts @@ -120,11 +120,11 @@ export function patchEventTarget( // need to try/catch error here, otherwise, the error in one event listener // will break the executions of the other event listeners. Also error will // not remove the event listener when `once` options is true. - let error; + let error: Error|undefined; try { task.invoke(task, target, [event]); } catch (err) { - error = err; + error = err as Error; } const options = task.options; if (options && typeof options === 'object' && options.once) { diff --git a/packages/zone.js/lib/extra/bluebird.ts b/packages/zone.js/lib/extra/bluebird.ts index e06b2ce0c6b790..2319223a551eaa 100644 --- a/packages/zone.js/lib/extra/bluebird.ts +++ b/packages/zone.js/lib/extra/bluebird.ts @@ -73,7 +73,7 @@ Zone.__load_patch('bluebird', (global: any, Zone: ZoneType, api: _ZonePrivate) = e.isHandledByZone = true; throw e; }); - } catch (err) { + } catch (err: any) { err.isHandledByZone = false; api.onUnhandledError(err); } diff --git a/packages/zone.js/lib/zone-spec/long-stack-trace.ts b/packages/zone.js/lib/zone-spec/long-stack-trace.ts index a4dc1683470b01..50ee9826faa6ac 100644 --- a/packages/zone.js/lib/zone-spec/long-stack-trace.ts +++ b/packages/zone.js/lib/zone-spec/long-stack-trace.ts @@ -30,7 +30,7 @@ function getStacktraceWithCaughtError(): Error { try { throw getStacktraceWithUncaughtError(); } catch (err) { - return err; + return err as Error; } } diff --git a/packages/zone.js/lib/zone.ts b/packages/zone.js/lib/zone.ts index 01e13c8dce790d..dc1f7b26c1e60c 100644 --- a/packages/zone.js/lib/zone.ts +++ b/packages/zone.js/lib/zone.ts @@ -1380,7 +1380,7 @@ const Zone: ZoneType = (function(global: any) { try { task.zone.runTask(task, null, null); } catch (error) { - _api.onUnhandledError(error); + _api.onUnhandledError(error as Error); } } } diff --git a/packages/zone.js/package.json b/packages/zone.js/package.json index 13edca69e3cf64..689119119cb9b4 100644 --- a/packages/zone.js/package.json +++ b/packages/zone.js/package.json @@ -8,7 +8,7 @@ "fesm2015": "./fesm2015/zone.js", "typings": "./zone.d.ts", "dependencies": { - "tslib": "^2.2.0" + "tslib": "^2.3.0" }, "devDependencies": { "@externs/nodejs": "^1.5.0", @@ -19,7 +19,7 @@ "mocha": "^9.0.0", "mock-require": "3.0.3", "promises-aplus-tests": "^2.1.2", - "typescript": "~4.3.4" + "typescript": "~4.4.2" }, "scripts": { "closuretest": "./scripts/closure/closure_compiler.sh", diff --git a/packages/zone.js/test/browser/XMLHttpRequest.spec.ts b/packages/zone.js/test/browser/XMLHttpRequest.spec.ts index 2c21c49f411d98..ee79d3f1f95c54 100644 --- a/packages/zone.js/test/browser/XMLHttpRequest.spec.ts +++ b/packages/zone.js/test/browser/XMLHttpRequest.spec.ts @@ -280,7 +280,7 @@ describe('XMLHttpRequest', function() { expect(req.responseType).toBe('document'); } catch (e) { // Android browser: using this setter throws, this should be preserved - expect(e.message).toBe('INVALID_STATE_ERR: DOM Exception 11'); + expect((e as Error).message).toBe('INVALID_STATE_ERR: DOM Exception 11'); } }); diff --git a/packages/zone.js/test/browser/browser.spec.ts b/packages/zone.js/test/browser/browser.spec.ts index 7c88afcb0e14b0..0a2055da8e1d81 100644 --- a/packages/zone.js/test/browser/browser.spec.ts +++ b/packages/zone.js/test/browser/browser.spec.ts @@ -2969,25 +2969,30 @@ describe('Zone', function() { }); })); + // Note: `navigator` is cast to `any` in this test, because the preferred way of accessing + // `getUserMedia` is through `navigator.mediaDevices`, however some older browsers still + // expose it directly on `navigator`. it('navigator.getUserMedia should in zone', ifEnvSupportsWithDone( () => { - return !isEdge() && navigator && typeof navigator.getUserMedia === 'function'; + return !isEdge() && navigator && + typeof (navigator as any).getUserMedia === 'function'; }, (done: Function) => { const zone = Zone.current.fork({name: 'media'}); zone.run(() => { const constraints = {audio: true, video: {width: 1280, height: 720}}; - navigator.getUserMedia( - constraints, - () => { - expect(Zone.current.name).toEqual(zone.name); - done(); - }, - () => { - expect(Zone.current.name).toEqual(zone.name); - done(); - }); + (navigator as any) + .getUserMedia( + constraints, + () => { + expect(Zone.current.name).toEqual(zone.name); + done(); + }, + () => { + expect(Zone.current.name).toEqual(zone.name); + done(); + }); }); })); }); diff --git a/packages/zone.js/test/common/zone.spec.ts b/packages/zone.js/test/common/zone.spec.ts index 7216ee371fde3a..4ce765e72676d7 100644 --- a/packages/zone.js/test/common/zone.spec.ts +++ b/packages/zone.js/test/common/zone.spec.ts @@ -185,8 +185,9 @@ describe('Zone', function() { try { zone.cancelTask(task); } catch (e) { - expect(e.message).toContain( - 'macroTask \'test\': can not transition to \'canceling\', expecting state \'scheduled\' or \'running\', was \'notScheduled\'.'); + expect((e as Error).message) + .toContain( + 'macroTask \'test\': can not transition to \'canceling\', expecting state \'scheduled\' or \'running\', was \'notScheduled\'.'); } }); diff --git a/packages/zone.js/test/test-util.ts b/packages/zone.js/test/test-util.ts index ace7c1432d10f5..92b6510c64e8cd 100644 --- a/packages/zone.js/test/test-util.ts +++ b/packages/zone.js/test/test-util.ts @@ -79,8 +79,8 @@ export function isSupportSetErrorStack() { throw new Error('test'); } catch (err) { try { - err.stack = 'new stack'; - supportSetErrorStack = err.stack === 'new stack'; + (err as Error).stack = 'new stack'; + supportSetErrorStack = (err as Error).stack === 'new stack'; } catch (error) { supportSetErrorStack = false; } diff --git a/packages/zone.js/test/typings/package.json b/packages/zone.js/test/typings/package.json index bdf3334b3fa5d7..d59ea5c84d9f35 100644 --- a/packages/zone.js/test/typings/package.json +++ b/packages/zone.js/test/typings/package.json @@ -14,6 +14,6 @@ "zone.js": "file:../../../../dist/bin/packages/zone.js/npm_package" }, "devDependencies": { - "typescript": "~4.3.4" + "typescript": "~4.4.2" } } diff --git a/packages/zone.js/yarn.lock b/packages/zone.js/yarn.lock index c10986e1f4ede6..eeeac33744a672 100644 --- a/packages/zone.js/yarn.lock +++ b/packages/zone.js/yarn.lock @@ -3931,7 +3931,7 @@ tr46@^2.1.0: dependencies: punycode "^2.1.1" -tslib@^2.2.0: +tslib@^2.3.0: version "2.3.1" resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01" integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw== @@ -3970,10 +3970,10 @@ typedarray-to-buffer@^3.1.5: dependencies: is-typedarray "^1.0.0" -typescript@~4.3.4: - version "4.3.5" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.3.5.tgz#4d1c37cc16e893973c45a06886b7113234f119f4" - integrity sha512-DqQgihaQ9cUrskJo9kIyW/+g0Vxsk8cDtZ52a3NGh0YNTfpUSArXSohyUGnvbPazEPLu398C0UxmKSOrPumUzA== +typescript@~4.4.2: + version "4.4.2" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.4.2.tgz#6d618640d430e3569a1dfb44f7d7e600ced3ee86" + integrity sha512-gzP+t5W4hdy4c+68bfcv0t400HVJMMd2+H9B7gae1nQlBzCqvrXX+6GL/b3GAgyTH966pzrZ70/fRjwAtZksSQ== unbox-primitive@^1.0.1: version "1.0.1" diff --git a/yarn.lock b/yarn.lock index 20dad4ded95863..af9c7b2f1dab1b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -13657,7 +13657,7 @@ typescript@4.2.4: resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.2.4.tgz#8610b59747de028fda898a8aef0e103f156d0961" integrity sha512-V+evlYHZnQkaz8TRBuxTA92yZBPotr5H+WhQ7bD3hZUndx5tGOa1fuCgeSjxAzM1RiN5IzvadIXTVefuuwZCRg== -typescript@4.3.5, typescript@~4.3.4, typescript@~4.3.5: +typescript@4.3.5, typescript@~4.3.5: version "4.3.5" resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.3.5.tgz#4d1c37cc16e893973c45a06886b7113234f119f4" integrity sha512-DqQgihaQ9cUrskJo9kIyW/+g0Vxsk8cDtZ52a3NGh0YNTfpUSArXSohyUGnvbPazEPLu398C0UxmKSOrPumUzA== @@ -13667,7 +13667,7 @@ typescript@^3.9.5, typescript@^3.9.7: resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.9.10.tgz#70f3910ac7a51ed6bef79da7800690b19bf778b8" integrity sha512-w6fIxVE/H1PkLKcCPsFqKE7Kv7QUwhU8qQY2MueZXWx5cPZdwFupLgKK3vntcK98BtNHZtAF4LA/yl2a7k8R6Q== -typescript@~4.4.0: +typescript@~4.4.0, typescript@~4.4.2: version "4.4.2" resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.4.2.tgz#6d618640d430e3569a1dfb44f7d7e600ced3ee86" integrity sha512-gzP+t5W4hdy4c+68bfcv0t400HVJMMd2+H9B7gae1nQlBzCqvrXX+6GL/b3GAgyTH966pzrZ70/fRjwAtZksSQ==