Adds support for TypeScript 4.7. Changes include:
* Bumping the TS version as well as some Bazel dependencies to include https://github.com/bazelbuild/rules_nodejs/pull/3420.
* Adding a backwards-compatibility layer for calls to `updateTypeParameterDeclaration`.
* Making `LView` generic in order to make it easier to type the context based on the usage. Currently the context can be 4 different types which coupled with stricter type checking would required a lot of extra casting all over `core`.
* Fixing a bunch of miscellaneous type errors.
* Removing assertions of `ReferenceEntry.isDefinition` in a few of the language service tests. The field isn't returned by TS anymore and we weren't using it for anything.
* Resolving in error in the language service that was caused by TS attempting to parse HTML files when we try to open them. Previous TS was silently setting them as `ScriptKind.Unknown` and ignoring the errors, but now it throws. I've worked around it by setting them as `ScriptKind.JSX`.
PR Close#45749
Before standalone, everything that could appear in an NgModule's `imports`
was relevant to DI, and needed to be emitted in the `imports` of the
generated `InjectorDef` definition. With the introduction of standalone
types, NgModule `imports` can now contain components, directives, and pipes
which are standalone. Only standalone components need to be included in
the `imports` of the generated injector definition - directives and pipes
have no effect on DI. Having them present doesn't cause any errors in the
runtime (they're filtered out by the injector itself) but it does prevent
tree-shaking.
With this commit, the generation of `InjectorDef` now filters the `imports`
to exclude directives and pipes as much as possible. It's not _always_
possible because an expression in `imports` may pull in both a directive and
a `ModuleWithProviders` reference, and we have no way of referencing just
the MWP part of that expression. Therefore this is an optimization, not a
rule of `InjectorDef` compilation.
PR Close#45701
Previously, the NgModule handler would resolve the `imports` field as one
unit, producing an array of `Reference`s. With this refactoring, if
`imports` is a literal array, each individual element will be resolved
independently. This will allow filtering in the future at the element level,
since there will be a separate `ts.Expression` for each individual element.
PR Close#45701
This commit updates the `ForeignFunctionResolver` used by the NgModule
handler to resolve `ModuleWithProvider` types. Previously, this resolver
returned the NgModule `Reference` directly, but there are two problems with
this:
* It's not completely accurate, as the expression returned by the MWP call
will not return the NgModule at runtime.
* We need the ability to distinguish the MWP call itself from an ordinary
NgModule reference in future optimizations.
PR Close#45701
This commit reworks the partial evaluation system's concept of a
ForeignFunctionResolver. Previously, resolvers were expected to return a
`ts.Expression` which the partial evaluator would continue evaluating,
eventually returning a value.
This works well for "transparent" foreign functions like `forwardRef`,
but for things like `ModuleWithProviders` it breaks down, because the
desired resolution value (the NgModule `Reference`) is _not_ the "correct"
evaluation of the function call.
To support better FFR implementations, this commit refactors the FFR system
so that resolvers operate on the `ts.CallExpression` instead, and are
given a callback to resolve further expressions if needed. If they cannot
resolve a given call expression, they have an `unresolvable` value that they
can return to indicate that.
PR Close#45701
This commit adds a type field to .d.ts metadata for directives, components,
and pipes which carries a boolean literal indicating whether the given type
is standalone or not. For backwards compatibility, this flag defaults to
`false`.
Tests are added to validate that standalone types coming from .d.ts files
can be correctly imported into new standalone components.
PR Close#45672
Standalone component scopes were first implemented in the
`ComponentDecoratorHandler` itself, due to an assumption that "standalone"
allowed for a localized analysis of the component's dependencies. However,
this is not strictly true. Other compiler machinery also needs to understand
component scopes, including standalone component scopes. A good example is
the template type-checking engine, which uses a `ComponentScopeReader` to
build full metadata objects (that is, metadata that considers the entire
inheritance chain) for type-checking purposes. Therefore, the
`ComponentScopeReader` should be able to give the scope for a standalone
component.
To achieve this, a new `StandaloneComponentScopeReader` is implemented, and
the return type of `ComponentScopeReader.getScopeForComponent` is expanded
to express standalone scopes. This cleanly integrates the "standalone"
concept into the existing machinery.
PR Close#45672
This commit expands on the unified dependency tracking in the previous
commit and adds tracking of NgModule dependencies. These are not used for
standard components, but are emitted for standalone components to allow the
runtime to roll up providers from those NgModules into standalone injectors.
PR Close#45672
Previously, the compiler tracked directives and pipes in template scopes
separately. This commit refactors the scope system to unify them into a
single data structure, disambiguated by a `kind` field.
PR Close#45672
Previously, the compiler would represent template dependencies of a
component in its component definition through separate fields (`directives`,
`pipes`).
This commit refactors the compiler/runtime interface to use a single field
(`dependencies`). The runtime component definition object still has separate
`directiveDefs` and `pipeDefs`, which are calculated from the `dependencies`
when the definition is evaluated.
This change is also reflected in partially compiled declarations. To ensure
compatibility with partially compiled code already on NPM, the linker
will still honor the old form of declaration (with separate fields).
PR Close#45672
`PipeSymbol` contains logic to detect changes in the public API surface of
pipes, which includes the pipe name. However, the pipe handler inadvertently
uses the pipe class name instead of the actual pipe name to initialize the
`PipeSymbol`, which breaks incremental compilation when pipe names change.
There is a test which attempts to verify that this logic is working, but the
test actually passes for a different reason. The test swaps the names of 2
pipes that are both used in a component, and asserts that the component is
re-emitted, theoretically because the public APIs of the pipes is changed.
However, the emit order of the references to the pipes depends on the order
in which they match in the template, which changes when the names are
swapped. This ordering dependency is picked up by the semantic dependency
tracking system, and is what actually causes the component to be re-emitted
and therefore the pipe test to pass in spite of the bug with name tracking.
This commit fixes the `PipeSymbol` initialization to use the correct pipe
name. The test is still flawed in that it's sensitive to the ordering of
pipe emits, but this ordering is due to change soon as a result of the
standalone components work, so this issue will be resolved in a future
commit.
PR Close#45672
This commit adds a new internal scope to `R3Injector` for
`EnvironmentInjector`s specifically. This will allow us to scope services to
the environment side of the injector hierarchy specifically, as opposed to
the `'any'` scope which also includes view-side injectors created via
`Injector.create`. For now, this functionality is not exposed publicly, but
is available to use within `@angular/core` only.
PR Close#45626
This commit fixes an inconsistency where a type check location for an inline
type check block would be interpreted to occur in a type-checking shim instead.
This resulted in a missing template mapping, causing a crash due to an unsafe
non-null assertion operator.
In the prior commit the `TcbLocation` has been extended with an `isShimFile`
field that is now being used to look for the template mapping in the correct
location. Additionally, the non-null assertion operator is refactored such
that a missing template mapping will now ignore the warning instead of crashing
the compiler.
Fixes#45413
PR Close#45454
Extends `TcbPosition` with a field that indicates whether the `tcbPath` is a
type-checking shim file, or an original source file with an inline type check
block.
This field is used in an upcoming commit that fixes an inconsistency with how
inline type check blocks are incorrectly interpreted as a type-checking shim
file instead.
PR Close#45454
Inline type check blocks (TCBs) are emitted into the original source file, but
node positions would still be represented as a `ShimLocation` with a `shimPath`
corresponding with the type-checking shim file. This results in inconsistencies,
as the `positionInShimFile` field of `ShimLocation` would not correspond with
the `shimPath` of that `ShimLocation`.
This commit is a precursor to letting `ShimLocation` also represent the correct
location for inline type check blocks, by renaming the interface to
`TcbLocation`. A followup commit addresses the actual inconsistency.
PR Close#45454
This commit implements the next step of Angular's "standalone" functionality,
by allowing directives/components/pipes declared as `standalone` to be imported
into NgModules. Errors are raised when such a type is not standalone but is
included in an NgModule's imports.
PR Close#44973
This commit moves the error for declaring a standalone directive/component/
pipe to the `LocalModuleScopeRegistry`. Previously the error was produced
by the `NgModuleHandler` directly.
Producing the error in the scope registry allows the scope to be marked as
poisoned when the error occurs, preventing spurious downstream errors from
surfacing.
PR Close#44973
This commit improves the error messages generated by the compiler when NgModule
scope analysis finds structural issues within a compilation. In particular,
errors are now shown on a node within the metadata of the NgModule which
produced the error, as opposed to the node of the erroneous declaration/import/
export. For example, if an NgModule declares `declarations: [FooCmp]` and
`FooCmp` is not annotated as a directive, component, or pipe, the error is now
shown on the reference to `FooCmp` in the `declarations` array expression.
Previously, the error would have been shown on `FooCmp` itself, with a mention
in the error text of the NgModule name.
Additional error context in some cases has been moved to related information
attached to the diagnostic, which further improves the legibility of such
errors. Error text has also been adjusted to be more succinct, since more info
about the error is now delivered through context.
PR Close#44973
Before the `SemanticSymbol` system which now powers incremental compilation,
the compiler previously needed to track which NgModules contributed to the
scope of a component in order to recompile correctly if something changed.
This commit removes that legacy field (which had no consumers) as well as the
logic to populate it.
PR Close#44973
As mentioned in previous commits (check them for more details), `@bazel/typescript`
no longer contains `ts_library`-specific code, so we no longer need that dependency.
PR Close#45431
.substr() is deprecated so we replace it with functions which work similarily but aren't deprecated
Signed-off-by: Tobias Speicher <rootcommander@gmail.com>
PR Close#45397
Drops support for TypeScript older than 4.6 and removes some workarounds in the compiler.
BREAKING CHANGE:
TypeScript versions older than 4.6 are no longer supported.
PR Close#45394
In early versions of Angular, it was sometimes necessary to provide a
`moduleId` to `@Component` metadata, and the common pattern for doing this
was to set `moduleId: module.id`. This relied on the bundler to fill in a
value for `module.id`.
However, due to the superficial similarity between `Component.moduleId` and
`NgModule.id`, many users ended up setting `id: module.id` in their
NgModules. This is an anti-pattern that has a few negative effects,
including preventing the NgModule from tree-shaking properly.
This commit changes the compiler to ignore `id: module.id` in NgModules, and
instead provide a warning which suggests removing the line entirely.
PR Close#45024
Previously, the `TraitCompiler` would naively consider a compilation as
failed if either analysis or resolution produced any diagnostics. This
commit adjusts the logic to only consider error diagnostics, which allows
warnings to be produced from `DecoratorHandler`s.
This is a precursor commit to introducing such a warning. As such, the
logic here will be tested in the next commit.
PR Close#45024
Angular contains an NgModule registry, which allows a user to declare
NgModules with string ids and retrieve them via those ids, using the
`getNgModuleById` API.
Previously, we attempted to structure this registration in a clever fashion
to allow for tree-shaking of registered NgModules (that is, those with ids).
This sort of worked due to the accidental alignment of behaviors from the
different tree-shakers involved. However, this trick relies on the
generation of `.ngfactory` files and how they're specifically processed in
various bundling scenarios. We intend to remove `.ngfactory` files, hence
we can no longer rely on them in this way.
The correct solution here is to recognize that `@NgModule({id})` is
inherently declaring a global side-effect, and such classes should not
really be eligible for tree-shaking in the first place. This commit removes
all the old registration machinery, and standardizes on generating a side-
effectful call to `registerNgModuleType` for NgModules that have ids.
There is some risk here that NgModules with unnecessary `id`s may not
tree-shake as a result of this change, whereas they would have in previous
circumstances. The fix here should be to remove the `id` if it's not needed.
Specifying an `id` is a request that the NgModule be retained regardless of
any other references, in case it is later looked up by string id.
PR Close#45024
The `compileNgModule` operation previously supported a flag `emitInline`,
which controlled whether template scoping information for the NgModule was
emitted directly into the compiled NgModule definition, or whether an
associated statement was generated which patched the information onto the
NgModule definition. Both options are useful in different contexts.
This commit changes this flag to an enum (and renames it), which allows for
a third option - do not emit any template scoping information. This option
is added to better represent the actual behavior of the Angular Linker,
which sometimes configures `compileNgModule` to use the side-effectful
statement generation but which does not actually emit such associated
statements. In other words, the linker effectively does not generate
scoping information for NgModules at all (in some configurations) and this
option more directly expresses that behavior.
This is a refactoring as no generated code is changed as a result of
introducing this flag, due to the linker's behavior of not emitting
associated statements.
PR Close#45024
When parsing interpolations, the input string is _decoded_ from what was
in the orginal template. This means that we cannot soley rely on the input
string to compute source spans because it does not necessarily reflect
the exact content of the original template. Specifically, when there is
an HTML entity (i.e. ` `), this will show up in its decoded form
when processing the interpolation (' '). We need to compute offsets
using the original _encoded_ string.
Note that this problem only surfaces in the splitting of interpolations.
The spans to this point have already been tracked accurately. For
example, given the template ` <div></div>`, the source span for the
`div` is already correctly determined to be 6. Only when we encounter
interpolations with many parts do we run into situations where we need
to compute new spans for the individual parts of the interpolation.
PR Close#44811
Proactively replaces our usages of the deprecated `ts.create*` methods in favor of using `ts.factory.create*` so that we're not surprised when the TS removes them in the future. Also accounts for some cases where the signature had changed.
PR Close#45134
Before this, the compiler resolves the value in the DTS as dynamic.
If the `trigger` is imported from `@angular/animations`, this PR will
use FFR to simulate the actual implementation in JS and extracts the
animation name.
PR Close#45107
This commit implements the first phase of standalone components in the Angular
compiler. This mainly includes the scoping rules for standalone components
(`@Component({imports})`).
Significant functionality from the design is _not_ implemented by this PR,
including:
* imports of standalone components into NgModules.
* the provider aspect of standalone components
Future commits will address these issues, as we proceed with the design of
this feature.
PR Close#44812
In preparation for standalone components, this commit moves the logic which
determines the potential set of components/directives/pipes in a template into
a separate function. This is a simple but crucial refactoring that breaks the
assumption that all template scopes come from NgModules.
PR Close#44812
Previously each `DecoratorHandler` in the compiler was stored in a single file
in the 'annotations' package. The `ComponentDecoratorHandler` in particular was
several thousand lines long.
Prior to implementing the new standalone functionality for components, this
commit refactors 'annotations' to split these large files into their own build
targets with multiple separate files. This should make the implementation of
standalone significantly cleaner.
PR Close#44812
The logical filesystem would store a cached result based on the canonical path,
where the cached value contains the physical path that was originally provided.
This meant that other physical paths with an identical canonical path would use
a cached result derived from another physical path.
This inconsistency is not known to result in actual issues but is primarily
being made as a performance improvement, as using the provided physical paths
as cache key avoids the need to canonicalize the path if its result is already
cached.
PR Close#44798
The generated imports should normally use module specifiers that are valid for
use in production code, where arbitrary relative imports into e.g. node_modules
are not allowed. For template type-checking code it is however acceptable to
use relative imports, as such files are never emitted to JS code. It is
desirable to allow a filesystem relative import as fallback if an import would
otherwise fail to be generated, as doing so allows fewer situations from
needing an inline type constructor.
PR Close#44798
This commit removes the leftover `Identifiers` class that was used in the
ViewEngine compiler. The remaining usages of the `inlineInterpolate` and
`interpolate` instructions were refactored to make use of an
`InterpolationExpression` output expression to capture the argument list of an
interpolation expression. An attempt was made to refactor this further by
converting to the desired interpolation instruction immediately, but some
downstream consumers are designed in a way where the argument list itself is
needed, e.g. as other arguments need to be prepended/appended.
PR Close#44676
So-called "Quote expressions" were added in b6ec2387b3
to support foreign syntax to be used in Angular templates, requiring a custom
template transform to convert them somehow during compilation. Support for template
transforms was originally implemented in a43ed79ee7 but
has since been dropped. Since the compiler is not public API the quote expressions
should not have any usages anymore. Removing support for them can improve error
reporting for expressions that contain a `:`, e.g. binding to a URL without quotes:
```html
<a [href]="http://google.com">Click me</a>
```
Here, `http` would be parsed as foreign "http" quote expression with `//google.com` as
value, later reporting the error "Quotes are not supported for evaluation!" because
there was no template transform to convert that code.
Closes#40398
PR Close#44915
TypeScript configures `strictNullChecks` to be disabled by default, so the nullish
coalescing check should follow the same default. The rule actively depends on
`strictNullChecks`, as TypeScript doesn't include `null`/`undefined` in its types
otherwise so the check wouldn't have a way to differentiate between them.
This commit also takes the `strict` flag into account when `strictNullChecks` itself
is not configured.
PR Close#44862
The initial commit e9124b42d5 stored the errors rather than
throwing but did not store them in a place that was accessible to consumers. Instead,
the errors should be added to the IndexedComponent so they can be surfaced where the
index results are consumed
PR Close#44884
When the indexer encounters a location where the source span doesn't
match up with the expected identifier, the current visitor code throws
an error. Instead, this change creates an error and moves on to the next
template item. This allows the indexer to continue analysis even when
there are errors in the source mapping. In addition, it still allows callers
to surface those errors in their own way while still providing as much indexed
information as possible about a node.
PR Close#44825
An `ng-template` with an inline template (i.e. has a structural
directive) would previously not get an `undefined` `tagName` because the
logic assumed the element would be `t.Element` or `t.Content` and read
the tag name from the `name` property. For a `t.Template`, this exists
instead on the `t.tagName`. The final result would be an `tagName` of `undefined`
for the parent `t.Template`, causing failures in the indexer downstream.
This `undefined` value is actually expected in the renderer code, even
though the type does not specify this possibility. This change updates
the type of `tagName` to be `string|null` and explicitly handles the
case where there is a structural directive on an `ng-template`. You can
see how the two are differentiated in the compliance code that was
modified in this commit.
PR Close#44788
The previous fix for correcting spans with comments in
59eef29a6c
had the unfortunate side effect of _breaking_ the spans with comments
when there was leading whitespace. This happened because the previous
fix was testing one without a comment, identifying that the offset shouldn't
have anything added to it, and then removing that offset adjustment
(`offsets[i] + (expressionText.length - sourceToLex.length)`).
Upon further investigation, this offset adjustment _was actually
necessary_ for when the input had comments, but this was only because
the `stripComments` function used `trim` to remove whitespace for these
cases. This is the real problem -- not only does it create a ton of confusion
but also it means that the behavior of the lexer and resulting spans is
different between inputs with comments and inputs without comments.
After reviewing how the `inputLength` of `_ParseAST` was used, it
appears that the correct behavior would be to _not_ trim the input. The
`inputLength` is used to advance the current index beyond points which
have been processed. This _should_ include any whitespace. Additionally,
`inputLength` doesn't appear to be needed at all. When there was no
comment in the input, it was always equal to the `input.length` anyways.
When there _is_ a comment, it should include that comment anyways to
advance the index beyond the comment.
PR Close#44785
The original fix for svg elements in
92b23f4851
did not account for svg elements when they also had a structural
directive on them, making the node a template. This resulted in the
logic added in fix above not being applied.
PR Close#44785
Previously, if a bad extended diagnostic category was given, it would fail with the expected error as well as an unexpected assertion error:
```
$ ng build -c development
✔ Browser application bundle generation complete.
./src/main.ts - Error: Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):
Error: Unexpected call to 'assertNever()' with value:
test
at /home/douglasparker/Source/ng-new/node_modules/@ngtools/webpack/src/ivy/loader.js:77:18
at processTicksAndRejections (internal/process/task_queues.js:95:5)
./src/polyfills.ts - Error: Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):
Error: Unexpected call to 'assertNever()' with value:
test
at /home/douglasparker/Source/ng-new/node_modules/@ngtools/webpack/src/ivy/loader.js:77:18
at processTicksAndRejections (internal/process/task_queues.js:95:5)
Error: error NG4004: Angular compiler option "extendedDiagnostics.checks['invalidBananaInBox']" has an unknown diagnostic category: "test".
Allowed diagnostic categories are:
warning
error
suppress
```
The assertion comes from `ExtendedTemplateCheckerImpl`, which expects a well-formed configuration, yet the compiler would construct it even when errors were found. This commit skips constructing and running extended diagnostics if the configuration had errors, which should avoid triggering these assertion errors.
I'm unfortunately not able to actually test this change. The test passes even before the fix because the `ngc` binary and end-to-end tests [don't request diagnostics unless the configuration is considered valid](ed21f5c753/packages/compiler-cli/src/perform_compile.ts (L292-L293)). See [Slack](https://angular-team.slack.com/archives/C4WHZQMRA/p1642641305003800) for more details.
PR Close#44778
Refs #42966.
There were two remaining places where `_extendedTemplateDiagnostics` needed to be set which should have been removed in #44712 but got missed. This updates them to only require `strictTemplates` and not `_extendedTemplateDiagnostics` so the feature is properly enabled in production.
PR Close#44777
Refs #42966.
Extended diagnostics provide additional analysis about Angular templates by emitting warnings for specific patterns known to be error prone or cause developer confusion. Currently, there are two such diagnostics which are enabled by default:
* `invalidBananaInBox` emits a warning if a user writes a two-way binding backwards like `([foo])="bar"`, when they actually wanted `[(foo)]="bar"`.
* `nullishCoalescingNotNullable` emits a warning if a binding attempts to perform nullish coalescing (`??`) on a type which does not include `null` or `undefined`, such as `{{ foo ?? 'bar' }}` where `foo` is defined as `string` instead of `string | null`.
These diagnostics are enabled as warnings by default, but this can be configured in the `tsconfig.json` like so:
```jsonc
{
"angularCompilerOptions": {
"extendedDiagnostics": {
// The categories to use for specific diagnostics.
"checks": {
// Maps check name to its category.
"invalidBananaInBox": "suppress"
},
// The category to use for any diagnostics not listed in `checks` above.
"defaultCategory": "error"
}
}
}
```
Allowed categories for a diagnostic are `warning` (default), `error`, or `suppress`. `warning` emits the diagnostic but allows the compilation to succeed, `error` *will* fail the compilation, while `suppress` will ignore the diagnostic altogether.
The initial release has two diagnostics, and we are hoping to expand this longer term to add more diagnostics and provide additional insight into Angular templates to detect and surface developer mistakes *before* hours of debugging are wasted.
PR Close#44712