To make our test output i.e. devmode output more aligned
with what we produce in the NPM packages, or to be more
aligned with what Angular applications will usually consume,
the devmode output is switched from ES5 to ES2015.
Additionally various tsconfigs (outside of Bazel) have been
updated to match with the other parts of the build. The rules
are:
ES2015 for test configurations, ES2020 for actual code that will
end up being shipped (this includes the IDE-only tsconfigs).
PR Close#44505
This commit finishes the removal of View Engine from the codebase, deleting
those pieces of @angular/compiler which were only used for VE.
Co-Authored-By: JoostK <joost.koehoorn@gmail.com>
PR Close#44368
This commit does a first-pass removal of the View Engine infrastructure
in compiler-cli. A more in-depth cleanup is necessary and large parts
of the View Engine compiler infrastructure remain within
`@angular/compiler`, this is just a first cleanup step.
PR Close#44269
As a preparation for the removal of the ViewEngine parts in
`compiler-cli`, this commit moves the version number helper functions
up one level such that the whole `diagnostics` subfolder can be removed.
PR Close#44269
Adds support for TypeScript 4.5. Includes the following changes:
* Bumping the package versions.
* Fixing a few calls to `createExportSpecifier` and `createImportSpecifier` that require an extra parameter.
* Adding some missing methods to the TS compiler hosts.
* Fixing an issue in the TS mocks for the ngcc tests where a regex was too agressive and was trying to match a path like `/node_modules/@typescript/lib-es5`.
* Accounting for type-only import specifiers when reporting DI errors (see #43620).
Fixes#43620.
PR Close#44164
The downlevel decorator transform (commonly used in the CLI and other
tooling of the ecosystem for enabling JIT ES2015+), is currently
incorrectly dealing with nested classes.
The transform will accidentally visit nested classes (in a constructor)
multiple times and generate duplicated instances of the `ctorParameters`
fields. This does not sound like an issue at first, but the duplicated
`ctorParameters` fields will miss significant type information that has
been elided by the first visit, resulting in generated code like the
following:
```js
let MyClass = /* @__PURE__ */ __name(class MyClass extends UpgradeNg1ComponentAdapter {
constructor(scope, injector3, elementRef) {
}
}, "MyClass");
MyClass.ctorParameters = () => [
{ type: void 0, decorators: [{ type: Inject, args: [$SCOPE] }] },
{ type: Injector },
{ type: ElementRef }
];
MyClass.ctorParameters = () => [
{ type: void 0 }, // <---- NOTE!
{ type: Injector },
{ type: ElementRef }
];
```
PR Close#44281
Now that the core package has been cleaned up to no longer contain Ivy
switch code, the transform to switch the `PRE_R3` markers to become
`POST_R3` is deleted as well.
PR Close#43891
This commit removes most tests that were designated as only covering View
Engine code. It also removes tag filters from CI and local commands to run
tests.
In a few cases (such as with the packages/compiler tests), this tag was
improperly applied, and certain test cases have been added back running in
Ivy mode.
This commit also empties `@angular/compiler/testing` as it is no longer
necessary (this is safe since compiler packages are not public API). It can
be deleted in the future.
PR Close#43884
When a partially compiled component or directive is "linked" in JIT mode, the body
of its declaration is evaluated by the JavaScript runtime. If a class is referenced
in a query (e.g. `ViewQuery` or `ContentQuery`) but its definition is later in the
file, then the reference must be wrapped in a `forwardRef()` call.
Previously, query predicates were not wrapped correctly in partial declarations
causing the code to crash at runtime. In AOT mode, this code is never evaluated
but instead transformed as part of the build, so this bug did not become apparent
until Angular Material started running JIT mode tests on its distributable output.
This change fixes this problem by noting when queries are wrapped in `forwardRef()`
calls and ensuring that this gets passed through to partial compilation declarations
and then suitably stripped during linking.
See https://github.com/angular/components/pull/23882 and https://github.com/angular/components/issues/23907
PR Close#44113
Currently the TS version checking function interprets a version like `1.2.3-rc.5` as `1.2.NaN` which would allow it to bypass the version checking altogether.
These changes add a little bit more logic to ensure that such versions are handled correctly. There's also an error if we don't manage to parse the version string.
Also it seemed like we never actually ran the version check unit tests, because they didn't have a test target.
PR Close#44109
When a safe method call such as `person?.getName()` is used, the
compiler would generate invalid code if the argument list also contained
a safe method call. For example, the following code:
```
person?.getName(config?.get('title').enabled)
```
would generate
```
let tmp;
ctx.person == null ? null : ctx.person.getName((tmp = tmp) == null ?
null : tmp.enabled)
```
Notice how the call to `config.get('title')` has completely disappeared,
with `(tmp = tmp)` having taken its place.
The issue occurred due to how the argument list would be converted
from expression AST to output AST twice. First, the outer safe method
call would first convert its arguments list. This resulted in a
temporary being allocated for `config.get('title')`, which was stored in
the internal `_resultMap`. Only after the argument list has been
converted would the outer safe method call realize that it should be
guarded by a safe access of `person`, entering the `convertSafeAccess`
procedure to convert itself. This would convert the argument list once
again, but this time the `_resultMap` would already contain the
temporary `tmp` for `config?.get('title')`. Consequently, the safe
method in the argument list would be emitted as `tmp`.
This commit fixes the issue by ensuring that nodes are only converted
once.
Closes#44069
PR Close#44088
This commit re-enables the `perform_watch` test target and updates the
test to run with the Ivy compiler.
Additionally, this target was switched over to use Angular v12 packages
as input to the test, to allow the ViewEngine tests to continue working
with v13 packages which are Ivy-only. This commit reverts those changes
now that View Engine tests are disabled, as it's desirable to test
against local artifacts that are build within the monorepo instead of
depending on NPM packages.
PR Close#43893
Using the tag "view-engine-only" better describes the expected usage of bazel targets with the test. They can
only be run with view engine.
PR Close#43862
Since building with ViewEngine is not longer desired on CI, removing the ivy vs non-ivy testing yarn scripts
is done, informing developers to instead use `yarn test` as all tests should be run using the Ivy complier.
PR Close#43862
This reverts commit bba0a87055.
The reason for rollback: this change is breaking some targets in Google's codebase when there is no attribute value is displayed (attr.aria-label) when translated.
PR Close#43882
While fully dynamic bound properties (and attributes) cannot be marked for localization, properties that only contain interpolation can.
This commit ensure that attribute bindings that only contain interpolation can also be marked for localization.
Closes#43260
PR Close#43815
When extracting i18n messages from templates, ICU messages are split out from the
message that contains them. This can make it difficult in the translation files to match up
the two messages, especially if the ICU is reused in multiple placeholders.
This commit builds on top of the previous one to expose the message ID of ICU messages
from the ICU placeholders as additional metadata in the `$localize` tagged strings.
Now the metablock following any placeholder can also contain the associated ID
delimited from the placeholder name by `@@`.
Fixes#17506
PR Close#43534
Refs #42966.
Previously, a build when emitted one warning and no errors would fail with a non-zero exit code. This is not what users would expect, but had not been an issue before since the compiler did not actually emit any warnings. With upcoming extended template diagnostics and other warnings, this is now a case that needs to be supported. Warnings are printed to `stderr` as before, but `ngc` now exits with code `0` and the build is considered successful.
Implemented this by adding a new `expectedExitCode` parameter to `driveDiagnostics()` which asserts against the real exit code. Most importantly, it does not **require** the the build to pass since any exit code can be given, so it is up to the test to assert this as well as many messages printed to make sure they are acceptable. This is useful for testing warnings and ensuring the build still passes.
PR Close#43673
Similar to the other private entry-points we have added for localize,
bazel or the migrations, we should expose the tooling code through
a dedicated private export. This will make the compiler-cli exports
more consistent and it will become easier for the CLI to export
necessary code.
PR Close#43431
Removes the remaining usages of dynamic require statements in the
package output. Since we declare all shipped packages as strict ESM,
we cannot use dynamic require statements anymore. This commit switches
these usages to actual `import` statements.
Note: Tsickle continues to remain an optional dependency since bundling
does not work with its UMD package output. Also tsickle is rarely used by
consumers, if at all, so bundling does not really provide any significant
value. To continue keeping tsickle optional (since it's still needed by the
`annotateForClosureCompiler` option which is also respected in ngtsc), we
pass-through a tsickle instance as a parameter to `main`. This allows us to
keep the compile functions synchronous without having to refactor the majority
of the watch compilation code, and majority of tests for ngc, ngtsc.
Consumers (like the `ngc` bin entry-point) can then load tsickle based on their
module format. e.g. tsickle can be imported through `require` to keep everything
sync, but in ESM, the dynamic import can be used beforehand to pass `tsickle` to
the `main` function. We can revisit this in the future but for now this does the
trick without exceeding the scope of this commit..
PR Close#43431
As outlined in the previous commit which enabled the `esModuleInterop`
TypeScript compiler option, we need to update all namespace imports
for `typescript` to default imports. This is needed to allow for
TypeScript to be imported at runtime from an ES module.
Similar changes are needed for modules like `semver` where the types incorrectly
suggest named exports that will not exist at runtime when imported from ESM.
This commit refactors all imports to match with the lint rule we have
configured in the previous commit. See the previous commit for more
details on why certain imports have been changed.
A special case are the imports to `@babel/core` and `@babel/types`. For
these a special interop is needed as both default imports, or named
imports break the other module format. e.g default imports would work
well for ESM, but it breaks for CJS. For CJS, the named imports would
only work, but in ESM, only the default export exist. We work around
this for now until the devmode is using ESM as well (which would be
consistent with prodmode and gives us more valuable test results). More
details on the interop can be found in the `babel_core.ts` files (two
interops are needed for both localize/or the compiler-cli).
PR Close#43431
The view engine language-service tests currently rely on the `npm_package` output
that is built locally. They rely on the package output mostly for
compiling test scenarios (with dependencies on e.g. forms), and for
the testing the metadata extraction (testing proper suggestions for VE).
The reliance on these packages becomes problematic with the new Angular
Package Format v13 where no metadata files are shipped. To continue
being able to test View Engine language-service compatibility, we will
use the v12.x framework packages for some of the test scenarios.
PR Close#43431
The View Engine ngc tests currently rely on the `npm_package` output
that is built locally. This becomes problematic with the new Angular
Package Format v13 where no metadata files are shipped. To continue
being able to test View Engine compilation, we will use the v12.x
framework packages for running the View Engine test.
Note: This means that we no longer test metadata extraction directly
for our framework packages, but given that any change to View Engine
will still land in patch, where the VE packaging still occurs, we should
be covered here.
PR Close#43431
Now that `Route.loadChildren` no longer accepts a string, there is no
need for tooling to find all string-based `loadChildren` to setup lazy
imports for them. As a result, the `listLazyRoutes` operation that
enumerates all string-based `loadChildren` occurrences is no longer
needed and is therefore removed from the compiler.
The `listLazyRoutes` API remains on the `Program` interface to avoid
breaking external tools that may be using this method, but those tools
should ultimately move away from using this API.
PR Close#43591
This commit removes the ability to configure lazy routes using a string
for `loadChildren`, together with the supporting classes to load an
`NgModuleFactory` at runtime.
BREAKING CHANGE:
It is no longer possible to use `Route.loadChildren` using a string
value. The following supporting classes were removed from
`@angular/core`:
- `NgModuleFactoryLoader`
- `SystemJsNgModuleFactoryLoader`
The `@angular/router` package no longer exports these symbols:
- `SpyNgModuleFactoryLoader`
- `DeprecatedLoadChildren`
The signature of the `setupTestingRouter` function from
`@angular/core/testing` has been changed to drop its `NgModuleFactoryLoader`
parameter, as an argument for that parameter can no longer be created.
PR Close#43591
When specifying the `deps` array in the `@Injectable` decorator to
inject dependencies into the injectable's factory function, it should
be possible to use an array literal to configure how the dependency
should be resolved by the DI system.
For example, the following example is allowed:
```ts
@Injectable({
providedIn: 'root',
useFactory: a => new AppService(a),
deps: [[new Optional(), 'a']],
})
export class AppService {
constructor(a) {}
}
```
Here, the `'a'` string token should be injected as optional. However,
the AOT compiler incorrectly used the array literal itself as injection
token, resulting in a failure at runtime. Only if the token were to be
provided using `[new Optional(), new Inject('a')]` would it work
correctly.
This commit fixes the issue by using the last non-decorator in the
array literal as the token value, instead of the array literal itself.
Note that this is a loose interpretation of array literals: if a token
is omitted from the array literal then the array literal itself is used
as token, but any decorator such as `new Optional()` would still have
been applied. When there's multiple tokens in the list then only the
last one will be used as actual token, any prior tokens are silently
ignored. This behavior mirrors the JIT interpretation so is kept as is
for now, but may benefit from some stricter checking and better error
reporting in the future.
Fixes#42987
PR Close#43226
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 `useUnknownInCatchVariables` compiler option has been disabled so that we don't have to cast error objects explicitly everywhere.
* 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.
PR Close#43281
Currently the compiler has three different classes to represent a "call to something":
1. `MethodCall` - `foo.bar()`
2. `SafeMethodCall` - `foo?.bar()`.
3. `FunctionCall` - Any calls that don't fit into the first two classes. E.g. `foo.bar()()`.
There are a few problems with this approach:
1. It is inconistent with the TypeScript AST which only has one node: `CallExpression`.
2. It means that we have to maintain more code, because the various parts of the compiler need to know about three node types.
3. It doesn't allow us to easily implement some new JS features like safe calls (e.g. `foo.bar?.())`).
These changes rework the compiler so that it produces only one node: `Call`. The new node behaves similarly to the TypeScript `CallExpression` whose `receiver` can be any expression.
There was a similar situation in the output AST where we had an `InvokeMethodExpression` and `InvokeFunctionExpression`. I've combined both of them into `InvokeFunctionExpression`.
PR Close#42882
Previously, the way templates were tokenized meant that we lost information
about the location of interpolations if the template contained encoded HTML
entities. This meant that the mapping back to the source interpolated strings
could be offset incorrectly.
Also, the source-span assigned to an i18n message did not include leading
whitespace. This confused the output source-mappings so that the first text
nodes of the message stopped at the first non-whitespace character.
This commit makes use of the previous refactorings, where more fine grain
information was provided in text tokens, to enable the parser to identify
the location of the interpolations in the original source more accurately.
Fixes#41034
PR Close#43132
The lexer now splits encoded entity tokens out from text and attribute value tokens.
Previously encoded entities would be decoded and the decoded value would be
included as part of the text token of the surrounding text. Now the entities
have their own tokens. There are two scenarios: text and attribute values.
Previously the contents of `<div>Hello & goodbye</div>` would be a single
TEXT token. Now it will be three tokens:
```
TEXT: "Hello "
ENCODED_ENTITY: "&", "&"
TEXT: " goodbye"
```
Previously the attribute value in `<div title="Hello & goodbye">` would be
a single text token. Now it will be three tokens:
```
ATTR_VALUE_TEXT: "Hello "
ENCODED_ENTITY: "&", "&"
ATTR_VALUE_TEXT: " goodbye"
```
- ENCODED_ENTITY tokens have two parts: "decoded" and "encoded".
- ENCODED_ENTITY tokens are always preceded and followed by either TEXT tokens
or ATTR_VALUE_TEXT tokens, depending upon the context, even if they represent
an empty string.
The HTML parser has been modified to recombine these tokens to allow this
refactoring to have limited effect in this commit. Further refactorings
to use these new tokens will follow in subsequent commits.
PR Close#43132
Previously, the decorator transformer was annotating the synthesized properties with TS type annotations. However, because it ran after the JSDoc transformer, the TS types were just dropped from the emitted JS. Attempting to move the decorator transformer before the JSDoc transformer causes tsickle crashes because synthetic AST fragments are not attached to a SourceFile node.
PR Close#43021
Return `TemplateDiagnostic` instead of `ts.Diagnostic` when getting the
extended template diagnostics. This makes the integration with the
language service easier. This also fixes the error code and now uses the
`ngErrorCode` for extended template diagnostics.
Refs #42966
PR Close#43134
This commit adds extended template diagnostics end-to-end tests, to make
sure the diagnostics are generated correctly. Template checks are
already tested with unit tests.
Refs #42966
PR Close#43107
Previously with View Engine output, the `enableResourceInlining` option
could be set to inline external templates and styles (also for the
resulting `.metadata.json` files). We want to do the same for the Ivy
compilation pipeline (regardless of the compilation mode). The full
compilation definitions, and partial declarations currently already
inline resources in a way that no external requests need to be made.
Although there is one exception currently. These are the calls for
setting class metadata (for testbed overrides). This commit updates
the set class metadata calls (for both partial and full compilation)
to always inline resources. This means that libraries do not need
to start shipping external styles/templates just for the
`setClassMetadata` calls.
Note: Only doing this for partial compilation has been considered, but
it seems like it would be simpler implementation-wise to do this for
full compilation as well. Given the external resources are already
inlined (through their `ecmp` definitions), it seems acceptable (or
even more aligned) to do the same for the set class metadata calls.
PR Close#43178
The compliance tests can check source-map segments against expectations
encoded into the expectation files. Previously, the encoding of the expected
segment was only delimited by whitespace, but this made it difficult to identify
segments that started or ended with whitespace.
Now these segment expectations are wrapped in double-quotes which makes
it easier to read and understand the expectation files.
PR Close#43129
Export `getSourceCodeForDiagnostic` from `ngtsc/testing` to make it
available for other packages. This will help confirm that the source
code is correct in other tests.
Refs #42966
PR Close#42984
Previously, the way templates were tokenized meant that we lost information
about the location of interpolations if the template contained encoded HTML
entities. This meant that the mapping back to the source interpolated strings
could be offset incorrectly.
Also, the source-span assigned to an i18n message did not include leading
whitespace. This confused the output source-mappings so that the first text
nodes of the message stopped at the first non-whitespace character.
This commit makes use of the previous refactorings, where more fine grain
information was provided in text tokens, to enable the parser to identify
the location of the interpolations in the original source more accurately.
Fixes#41034
PR Close#42062
The compliance tests can check source-map segments against expectations
encoded into the expectation files. Previously, the encoding of the expected
segment was only delimited by whitespace, but this made it difficult to identify
segments that started or ended with whitespace.
Now these segment expectations are wrapped in double-quotes which makes
it easier to read and understand the expectation files.
PR Close#42062
The static interpreter assumed that a foreign function expression would
have to be imported from the absolute module specifier that was used for
the foreign function itself. This assumption does not hold for the
`forwardRef` foreign function resolver, as that extracts the resolved
expression from the function's argument, which is not behind the
absolute module import of the `forwardRef` function.
The prior behavior has worked for the typical usage of `forwardRef`,
when it is contained within the same source file as where the static
evaluation started. In that case, the resulting reference would
incorrectly have an absolute module guess of `@angular/core`, but the
local identifier emit strategy was capable of emitting the reference
without generating an import using the absolute module guess.
In the scenario where the static interpreter would first have to follow
a reference to a different source that contained the `forwardRef` would
the compilation fail. In that case, there is no local identifier
available such that the absolute module emitter would try to locate the
imported symbol from `@angular/core`. which fails as the symbol is not
exported from there.
This commit fixes the issue by checking whether a foreign expression
occurs in the same source file as the call expression. If it does, then
the absolute module specifier that was used to resolve the call
expression is ignored.
Fixes#42865
PR Close#42887
In #41995 the type of `TrackByFunction` was changed such that the
declaration of a `trackBy` function did not cause the item type to be
widened to the `trackBy`'s item type, which may be a supertype of the
iterated type. This has introduced situations where the template type
checker is now reporting errors for cases where a `trackBy` function is
no longer assignable to `TrackByFunction`.
This commit fixes the error by also including the item type `T` in
addition to the constrained type parameter `U`, allowing TypeScript to
infer an appropriate `T`.
Fixes#42609
PR Close#42692