Commit graph

3165 commits

Author SHA1 Message Date
Dylan Hunn
3343ceb82d refactor(compiler): Update pipe test golden for alternative create order (#52289)
We roughly attempt to match TemplateDefinitionBuilder's pipe creation order, by placing pipe creation instructions after their target elements. However, we cannot fully emulate the "inside-out" ordering TemplateDefinitionBuilder uses when multiple pipes apply to one element, because TemplateDefinitionBuilder creates the pipes as expressions are visited, from the leaves up. Our order is perfectly adequate though.

We also add a non-compatibility-mode ordering, which just appends them to the end of the create block. This is better because it allows for more chaining opportunities.

PR Close #52289
2023-10-24 11:07:49 -07:00
Dylan Hunn
0491fba523 refactor(compiler): Fix a special case involving var counting for singleton propertyInterpolate (#52289)
Singleton property interpolation instructions consume only one variable, but are still emitted as an interpolation instruction (they cannot be collapsed because `propertyInterpolate` implicitly stringifies its argument.)

PR Close #52289
2023-10-24 11:07:49 -07:00
Dylan Hunn
f6cc09b0f4 refactor(compiler): The projection instruction takes an array literal (#52289)
We were incorrectly emiting a extracted constant pool index for the final argument of the projection instruction. It actually takes an array literal.

(N.B.: This means we re-create the array every time! We should probably modify the runtime to use a const index for this.)

Additionally, we alter the projection op to not extend the element op base type.

PR Close #52289
2023-10-24 11:07:49 -07:00
Dylan Hunn
9f839272bd refactor(compiler): Improve the ordering of update ops (#52289)
The correct order of attributes and properties is:

1. Interpolated properties
2. Interpolated attributes
3. Non-interpolated properties
4. Non-interpolated attributes

This includes an additional nuance: singleton attribute interpolations, such as `[attr.foo]="{{bar}}"`, will be "collaped" into a simple `attribute` instruction. However, this is *not* the case for singleton property interpolations! The ordering phase must take this nuance into account to match the TemplateDefinitionBuilder order.

After the project lands, it might be nice to also collapse singleton property interpolations.

PR Close #52289
2023-10-24 11:07:49 -07:00
Dylan Hunn
d55ff744e3 refactor(compiler): Order elements before other phases (#52289)
Previously, we ran the ordering phase near the end of the compilation. However, this meant that phases like slot assignment and variable offset assignment would happen first, and then the nice, monotonically-increasing orders would be scrambled by the reordering.

It's much more intelligible to order first, and then perform these assignments. However, to make this happen, some modifications to the ordering phase are required. In particular, we can no longer rely on `advance` instructions to break up orderable groups.

PR Close #52289
2023-10-24 11:07:49 -07:00
Dylan Hunn
b814b97d8e refactor(compiler): Imitate TemplateDefinitionBuilder's variable offset assignment order (#52289)
Many instructions consume variable slots, which are used to persist data between update runs. For top-level instructions, the offset into the variable data array is implicitly advanced, because those instructions always run.

However, instructions in non-top-level expressions cannot be assumed to run every time, because they might be conditionally executed. Therefore, they cannot implicitly advance the offset into the variable data, and must be given an explicitly assigned variable offset.

TemplateDefinitionBuilder assigned offsets top-to-bottom for all instructions *except* pure functions. Pure functions would be assigned offsets lazily, on a second pass.

Template Pipeline can now imitate this behavior, when in compatibility mode: pure functions are assigned offsets on a second pass.

This also makes the "variadic var offsets" phase unnecessary -- the new approach is more general and correct.

PR Close #52289
2023-10-24 11:07:49 -07:00
Dylan Hunn
044df0c1a8 refactor(compiler): Use already available context in closures, instead of saving it (#52289)
Previously, inside an event listener, template pipeline would always save the context from restoring a view, e.g.

```
const restored_ctx = r0.ɵɵrestoreView(s);
```

This is usually correct! However, consider the case of a listener in the template's root view. The appropriate context will already be available via closure capture, and we can just use it (as `ctx`).

Now, the context resolution phase understands that we don't need to use the restored view's saved context if we would have access to it by closure.

Note: we also create a new golden, because the const array is in a harmlessly different order.

PR Close #52289
2023-10-24 11:07:48 -07:00
Dylan Hunn
f5dffe1c5b refactor(compiler): Empty context variable reads are $implicit (#52289)
Previously, the template pipeline did not handle "empty" reads gracefully: it would emit syntactically invalid reads of empty properties. Now we read `$implicit`.

This allows us to enable a test that relies on `$implicit`. However, we also have to create another golden, because our variable inlining is more aggressive.

PR Close #52289
2023-10-24 11:07:48 -07:00
Dylan Hunn
5d527e8c6b refactor(compiler): Update golden for pipe binding collapsing (#52289)
We currently allow elements to be collapsed around pipe creation instructions. TemplateDefinitionBuilder disallows this, but only sometimes. Collapsing in this case is actually less generated code, and it's OK to allow it.

PR Close #52289
2023-10-24 11:07:48 -07:00
Dylan Hunn
efe170fb2a refactor(compiler): Enable already-passing tests (#52289)
Some tests are already passing, but were not enabled at the time they were previously fixed.

PR Close #52289
2023-10-24 11:07:48 -07:00
Kristiyan Kostadinov
b6b5adca38 fix(compiler): account for type-only imports in defer blocks (#52343)
Fixes that `@defer` blocks didn't account for type-only imports which could cause the import to be considered as not deferrable.

PR Close #52343
2023-10-24 09:20:49 -07:00
Dylan Hunn
30e81d4469 refactor(compiler): Support track functions and context variables in @for loops for template pipeline (#52001)
The template pipeline can now generate track functions, and extract them into the constant pool (or optimize them if needed). Additionally, context variables such as `$index` can be used inside track functions and for loop bodies.

PR Close #52001
2023-10-23 13:44:29 -07:00
Dylan Hunn
c8a5a4f852 refactor(compiler): Support @for blocks in template pipeline (#52001)
Add support for `repeaterCreate` and `repeater` instructions. Correctly count decls and vars, and support primary and empty blocks.

`track` functions are not yet extracted.

PR Close #52001
2023-10-23 13:44:29 -07:00
Kristiyan Kostadinov
dc3f7cb3bf fix(compiler): template type checking not reporting diagnostics for incompatible type comparisons (#52322)
In #52110 the compiler was changed to produce `if` statements when type checking `@switch` in order to avoid a bug in the TypeScript compiler. In order to avoid duplicate diagnostics, the main `@switch` expression was ignored in each of the `@case` comparisons. This appears to have caused a regression where comparing incompatible types wasn't being reported anymore.

These changes resolve the issue by wrapping the expression in parentheses which allows the compiler to report comparison diagnostics while ignoring diagnostics in the expression itself.

Fixes #52315.

PR Close #52322
2023-10-23 09:27:23 -07:00
Payam Valadkhan
ae3acca20d refactor(compiler-cli): remove unnecessary compilationMode args (#52215)
After previous commits, some `compilationMode` args in some helper functions became unused. In this change those args are cleaned up.

PR Close #52215
2023-10-19 09:38:30 -07:00
Payam Valadkhan
56a76d73e0 fix(compiler-cli): modify getConstructorDependencies helper to work with reflection host after the previous change (#52215)
Now the method `getConstructorDependencies` no longer needs to do any post analysis, and can rely on the reflection host's result to generate ctor params. This will automatically include invalid factories which fix the issue.

PR Close #52215
2023-10-19 09:38:30 -07:00
Payam Valadkhan
749d4c498e refactor(compiler-cli): add local compilation logic to reflection host getConstructorParameters method (#52215)
Currently the reflection host's `getConstructorParameters` method is not aware of the compilation mode, and it generates result mainly assuming the compilation mode is full and we have access to global type info. As a result, its result is not very suitable for local compilation usage, particularly for deciding if a symbol is imported as type or not. This change plumbs a flag `isLocalCompilation` into reflection host to make it aware of the compilation mode.

Also changes made to the logic in the method `getConstructorParameters` so that in local compilation mode:
 - returns NO_VALUE_DECLARATION type value ref only if the type is a type parameter
 - returns local type value ref for any imported symbol, unless the import is type only in which case returns TYPE_ONLY_IMPORT type value ref

PR Close #52215
2023-10-19 09:38:30 -07:00
Andrew Scott
459b275a3a docs: Update control flow diagnostic to direct devs to built-ins (#52268)
The commit adds messaging to the control flow template diagnostic to direct developers to the new
built-in control flow syntax in Angular.

PR Close #52268
2023-10-19 09:24:08 -07:00
Miles Malerba
1cb039fa53 refactor(compiler): Wrap bare ICUs in an i18n block (#52250)
ICUs can be used outside of an i18n block. In this case the ICU should
be automatically wrapped in a new i18n block. This commit adds a new
phase to handle wrapping these bare ICUs.

PR Close #52250
2023-10-18 14:00:04 +02:00
Miles Malerba
1cd51d6d68 refactor(compiler): Resolve ICU params during i18n post-processing (#52250)
ICU params in i18n messages are now resolved in the post-processing call
rather than in the initial message creation. This matches the output
generated by TemplateDefinitionBuilder.

PR Close #52250
2023-10-18 14:00:03 +02:00
Miles Malerba
8eed992052 refactor(compiler): Add support for ingesting ICUs (#52250)
ICUs are now ingested by adding ops to both the creation and update IR.
Both of these ops are ultimately removed before reification, but they
are needed to coordinate and link data between the creation and update
ops. This is done in a new ICU extraction phase that removes both ICU
ops and adds an i18nExpr op to the update IR.

PR Close #52250
2023-10-18 14:00:03 +02:00
Angular Robot
6fefbe8fca build: update babel dependencies to v7.23.2 (#52236)
See associated pull request for more information.

PR Close #52236
2023-10-17 18:11:09 +02:00
Jeremy Elbourn
634c529504 refactor(compiler): extract generic info for api reference (#52204)
This commit extracts the API reference info for generic parameters for
classes, methods, interfaces, and functions. It includes any constraints
and the default type if present.

PR Close #52204
2023-10-17 12:29:24 +02:00
Miles Malerba
9bc9464a54 test(compiler): Update golden partial file (#52202)
Updates the golden partial file to account for the newly added test

PR Close #52202
2023-10-17 10:13:23 +02:00
Miles Malerba
7929097820 refactor(compiler): Fix handling of structural directive on i18n element (#52202)
Placing a structural directive on an element with an `i18n` attribute
was generating too many i18n blocks. This was due to both the element
and the template generating their own i18n block. To fix the issue, we
no longer generate top-level i18n blocks for structural directive
templates.

PR Close #52202
2023-10-17 10:13:23 +02:00
Miles Malerba
197819ee5e refactor(compiler): Fix handling of sturctural directive on ng-template (#52202)
Structural directives on an ng-template (e.g. <ng-template *ngIf>) were
being assigned the wrong tag name ('ng-template' instead of null).

PR Close #52202
2023-10-17 10:13:23 +02:00
Miles Malerba
9f4927e778 refactor(compiler): Fix i18n placeholders for slef-closing elements (#52195)
Fixes handling of placeholders for self-closing tags. Self-closing tags
set a combined value for the start tag placeholder, rather than separate
values for the start and close placeholders.

This commit also enables a number of now passing tests. For some of
these tests I had create a separate golden file due to the different
ordering of the const array. In the template pipeline, i18n and
attribute const collection happen in different pahses and we therefore
get a different order than TemplateDefinitionBuilder, which collected
everything in one pass. The order should not affect the overall behavior.

PR Close #52195
2023-10-16 19:25:05 +02:00
Miles Malerba
3f2620c1f3 refactor(compiler): Fix propagation of child i18n params (#52195)
The way we were propagating params up to parent i18n ops didn't account
for the fact that a parent and child could both have a value for the
same placeholder. In order to properly merge the value for these cases,
we need to propagate the params up *before* serialization. Therefore I
removed the standalone param propagation phase and folded the logic into
the placeholder resolution phase.

PR Close #52195
2023-10-16 19:25:05 +02:00
Pawel Kozlowski
4da0dbedf5 Revert "refactor(compiler-cli): remove MethodIdentifier type (#49611)" (#52174)
This reverts commit c2b1a242e8.

PR Close #52174
2023-10-12 12:35:48 +02:00
Matthieu Riegler
c2b1a242e8 refactor(compiler-cli): remove MethodIdentifier type (#49611)
`MethodIdentifier` is unused as is `IdentifierKind.Method`. They both can be removed.

PR Close #49611
2023-10-11 12:34:49 -07:00
Kristiyan Kostadinov
9d19c8e317 fix(compiler): don't allocate variable to for loop expression (#52158)
Currently the compiler allocates a variable slot to the `@for` loop expression which ends up unused since we don't store the result on the `LView`.

PR Close #52158
2023-10-11 09:12:57 -07:00
Payam Valadkhan
1eefa0c9c4 refactor(compiler-cli): include forbidOrphanComponents option in component's debug info (#52061)
A new flag added to the component's debug info to determine whether to throw runtime error (in dev mode) if component is being rendered without its NgModule. This flag is only set for non-standalone components.

PR Close #52061
2023-10-10 15:30:26 -07:00
Payam Valadkhan
e8201a5962 refactor(compiler-cli): add a compiler option to enable checking for orphan component (#52061)
Orphan component is an anti-pattern in Angular where a component is rendered while the NgModule declaring it is not installed. It is not easy to capture this scenario, specially in compile time. But it is possible to capture a special case in runtime where the component is being rendered without its NgModule even loaded into the browser. This change adds a flag in cli compiler option to enable such checking, and throwing a runtime exception if it happens. Note that such check is only done in dev mode.

Currently the check requires some generated code that is behind ngJitMode flag (i.e., call to ɵɵsetNgModuleScope), and the new flag can be set only if JIT mode is enabled (i.e., supportJitMode=true) otherwise an error will be thrown.

The orphan component is a main blocker for rolling out local compilation in g3. This option is needed for identifying and isolating such cases.

PR Close #52061
2023-10-10 15:30:26 -07:00
Kristiyan Kostadinov
5a969e06b7 build: remove Windows CI check (#52140)
Based on recent discussions, these changes remove the Windows CI check because it has been too flaky for too long. Furthermore, we've concluded that the simulated file system in the compiler tests already catches the same set of bugs as running the tests on a real Windows system.

PR Close #52140
2023-10-10 14:07:03 -07:00
Jeremy Elbourn
1934524a0c feat(compiler): add docs extraction for type aliases (#52118)
This commit adds support for extracting type alises. It currently
extracts the raw written type from the source without performing any
resolution, such as for resolving `typeof` queries, as current Angular
public APIs do not rely on this.

PR Close #52118
2023-10-10 12:40:10 -07:00
Matthieu Riegler
8eef694def feat(core): Provide a diagnostic for missing Signal invocation in template interpolation. (#49660)
To improve DX for beginners, this commit adds an extended diagnostic for Signals in template interpolations.

PR Close #49660
2023-10-10 11:55:13 -07:00
Kristiyan Kostadinov
861ce3a7c5 fix(compiler): pipes using DI not working in blocks (#52112)
Fixes that the new block syntax was generating instructions in the wrong order which meant that pipes were being declared too early. This meant that if the block is first in the template, any pipes used in it won't be able to inject things like `ChangeDetectorRef`.

These changes update the compiler and add a bunch of tests to ensure that pipes work as expected.

Fixes #52102.

PR Close #52112
2023-10-10 09:48:37 -07:00
Kristiyan Kostadinov
ac0d5dcfd6 fix(compiler): narrow the type of expressions in event listeners inside switch blocks (#52069)
Since expressions in event listener are added inside of a callback, type narrowing won't apply to them anymore. These changes add the logic to create a guard expression that will re-narrow the expression in the callback.

Fixes #52052.

PR Close #52069
2023-10-10 09:47:47 -07:00
Kristiyan Kostadinov
16ff08ec70 fix(compiler): narrow the type of expressions in event listeners inside if blocks (#52069)
Since expressions in event listener are added inside of a callback, type narrowing won't apply to them anymore. These changes add the logic to create a guard expression that will re-narrow the expression in the callback.

Fixes #52052.

PR Close #52069
2023-10-10 09:47:47 -07:00
Kristiyan Kostadinov
503e67dca2 refactor(compiler): clean up compatibility code for old TS versions (#52099)
Cleans up some code that was left in place to support old versions of TypeScript.

PR Close #52099
2023-10-10 09:37:38 -07:00
Angular Robot
b9a4941a32 build: update babel dependencies (#51898)
See associated pull request for more information.

PR Close #51898
2023-10-09 17:01:20 -07:00
Andrew Kushnir
2eebd47733 refactor(core): make timer-related @defer logic tree-shakable (#52042)
This commit updates `@defer` logic related to handling `after` and `minimum` parameters tree-shakable.

If `after` or `minimum` was used on a `@loading` or `@placeholder` blocks, compiler generates an extra argument for the `ɵɵdefer` instruction. This extra argument is a reference to a function that brings timer-related code.

PR Close #52042
2023-10-09 15:57:59 -07:00
Payam Valadkhan
acd468f804 refactor(compiler-cli): add debug info to components (#51919)
A new statement will be generated for components which will attach some useful debug info to them to be used in runtime error handling. Currently this only happens in full and local compilation modes.

PR Close #51919
2023-10-09 15:57:03 -07:00
Payam Valadkhan
11bb19cafc fix(compiler-cli): handle nested qualified names in ctor injection in local compilation mode (#51947)
The current implementation assumes a qualified name consists of just two identifier, e.g., Foo.Bar. However it can be more nested, like Foo.Bar.Baz.XX.YY. While such nested patterns are quite uncommon and devs mostly just use two identifier here, the TS compiler seems to throw error if we make such assumption and it broke quite a lot of targets in g3 when compiled in local mode. So here we handle this nested property of qualified names.

PR Close #51947
2023-10-09 14:34:55 -07:00
Miles Malerba
371cd58eec refactor(compiler): Fix advance instructions for i18n expressions (#51988)
The custom logic in the generate advance phase for i18n expressions did
not work in all cases. Instead we add a new phase to update the
expression's target op, and then allow the standard advance generation
code to determine the number of advance instructions needed.

Co-authored-by: Dylan Hunn <dylhunn@users.noreply.github.com>

PR Close #51988
2023-10-09 12:35:15 -07:00
Miles Malerba
d8bc6aa129 refactor(compiler): Propagate i18n blocks through child templates (#51988)
Adds a phase to the template pipeline to recursively create child i18n
blocks for ng-template views existing inside an i18n block.

PR Close #51988
2023-10-09 12:35:15 -07:00
Jeremy Elbourn
7bfe20707f feat(compiler): extract api for fn overloads and abtract classes (#52040)
This commit adds support for extracting function overloads. Interestingly, this worked in an earlier version when the code was extracting all statements in every source file, but the existing compiler API for extracting all exported declarations from an entry-point only returns the first function declaration in cases when there are overloads.

This also marks abstract classes as abstract, required inputs as required, and filters out Angular-private APIs.

PR Close #52040
2023-10-09 12:03:20 -07:00
Kristiyan Kostadinov
386e1e9500 fix(compiler): work around TypeScript bug when narrowing switch statements (#52110)
We type check `@switch` blocks by generating identical TS `switch` statements in the TCB, however TS currently has a bug where parenthesized `switch` block expressions don't narrow their types. Since we use parenthesized expressions to wrap AST nodes for diagnostics, this will bug will affect all Angular-generated `switch` statements.

These changes work around the issue by generating `if`/`else if`/`else` statements that represent the `switch`.

Some alternatives that were considered:
1. Moving the `switch` expression to a constant - this is fairly simple to implement, but it won't fully resolve the narrowing issue since the same constant will have to be used in expressions inside the different cases.
2. Removing the outer-most parenthesis from the switch expression - this works and allows us to continue using switch statements, but because we use parenthesized expressions to map diagnostics to their template locations, I wasn't sure if it won't lead to worse template dignostics.

Fixes #52077.

PR Close #52110
2023-10-09 10:54:28 -07:00
Andrew Scott
023a181ba5 feat(language-service): Implement outlining spans for control flow blocks (#52062)
This commit implements the getOutlingSpans to retrieve Angular-specific
outlining spans. At the moment, these spans are limited to control-flow
blocks in templates.

This is required for folding ranges (https://github.com/angular/vscode-ng-language-service/issues/1930)

PR Close #52062
2023-10-09 10:20:26 -07:00
Kristiyan Kostadinov
17078a3fe1 fix(compiler): pipes used inside defer triggers not being picked up (#52071)
Fixes that the compiler wasn't picking up pipes used inside defer block triggers as dependencies. We had implemented the `visitDeferredTrigger` visitor method, but it wasn't being called, because we weren't going through the `visitAll` method of the deferred block. We don't use `visitAll`, because child nodes have to be processed differently than the connected blocks and triggers.

Fixes #52068.

PR Close #52071
2023-10-06 08:52:57 -07:00
Andrew Kushnir
317ed8e10e test(compiler-cli): drop unused config option from tests (#52066)
The `_enabledBlockTypes` config option was removed recently, since we've enabled @-syntax by default. This commit removes `_enabledBlockTypes` references from the `compiler-cli` test cases.

PR Close #52066
2023-10-06 08:41:53 -07:00
Kristiyan Kostadinov
40c53577b8 refactor(compiler): introduce unknown block node (#52047)
Adds an `UnknownBlock` node to the Ivy AST to represent blocks that haven't been recognized by the compiler. This will make it easier to integrate blocks into the language service.

PR Close #52047
2023-10-05 13:10:05 -07:00
Jeremy Elbourn
a7fa25306f feat(compiler): extract api docs for interfaces (#52006)
This adds API doc extraction for interfaces, largely using the same code paths for classes. The primary difference between classes and interfaces is that classes have member _declarations_ while interfaces have member _signatures_. This largely doesn't matter for the purposes of extraction, but the types are distinct with no common base types, so we have to do a fair amount of type unioning and aliasing.

PR Close #52006
2023-10-04 11:58:09 -07:00
Dylan Hunn
422a3db2a8 refactor(compiler): Enable passing and nearly-passing Template Pipeline tests (#51950)
A couple tests were already passing, and just needed to be enabled. This includes tests pertaining to:
* ng-template
* host binding styling slots
* and host animation bindings
* some literal tests (which were missing some $foo$ escaped names)

We add pipeline-specific versions of the following tests, and enable them:
* A local refs test. The consts for the element attributes and the consts for local reference are collected in the reverse order, but the emitted template is functionally the same.
* A safe accesstest. Consider the expression `$any(val)?.foo`. `TemplateDefinitionBuilder` extracts a temporary variable: `($tmp_0_0$ = $ctx$.val) == null ? null : $tmp_0_0$.foo`. It presumably does this because it considers the `$any(...)` to be a function call. However, this is not a real call, so Template Pipeline safely ignores it and declines to generate a temporary.
* Another local refs test. AttributeMarker.Template is emitted at the end of the const array (instead of the middle)

PR Close #51950
2023-10-04 09:00:54 -07:00
Dylan Hunn
4b4dd2bf3a refactor(compiler): Don't emit properties on structural ng-templates (#51950)
Consider an `ng-template` which is generated as a result of a structural directive:

```
<div *ngFor="let inner of items"
             (click)="onClick(inner)"
             [title]="getTitle()"
             >
```

This should logically expand into something like the following:

```
<ng-template [ngForOf]="..." >
        <div (click)="..." [title]="..."></div>
</ng-template>
```

Note that the `(click)` handler and the `[title]` property are only present on the inner div, *not* on the enclosing generated `ng-template`.

Previously, Template Pipeline would place these bindings on *both* the tempate and the inner element.

However, we can't just remove them completely, because these bindings should still be matchable on the generated `ng-template` (which is very surprising, but nonetheless true).

We resolve this issue with two improvements:
(1) The ingestion step is now much smarter about determining not only if a binding is on a template element, but whether it actually targets that template element.
(2) We use `ExtractedAttributeOp` directly, rather than going through `BindingOp`, to cause the `ng-template` to still receive these bindings in its `consts` array for matching purposes.

PR Close #51950
2023-10-04 09:00:54 -07:00
Dylan Hunn
04436cfd60 refactor(compiler): Drop !important when parsing host style/class bindings (#51950)
For components, the parser already extracts the `important` property (and it is later disregarded). However, because host bindings use a totally separate parsing code path, this was never happing for host bindings.

Here, we add some code to the host style parsing phase to drop the `!important` suffix.

We could solve this category of problems for good by parsing host bindings with the same code as template bindings.

PR Close #51950
2023-10-04 09:00:54 -07:00
Dylan Hunn
aa6bb8ee95 refactor(compiler): Fix a bug in which temporaries were being declared in the wrong places (#51950)
Previously, we always generated temporary variable declarations at the beginning of each view's update block. This is wrong, for two reasons:
1. Temporaries can be used in the create block
2. When listeners use temporaries, we should declare them inside the listener.

Now, we always place temporaries at the beginning of the enclosing OpList, and recursively try to generate them when we find a listener.

PR Close #51950
2023-10-04 09:00:54 -07:00
Kristiyan Kostadinov
1d871c03a5 fix(compiler): forward referenced dependencies not identified as deferrable (#52017)
Fixes that we weren't accounting for dependencies using `forwardRef` when determining if they can be lazy-loaded.

Fixes #52014.

PR Close #52017
2023-10-04 08:57:47 -07:00
Kristiyan Kostadinov
02edb43067 fix(compiler): narrow the type of the aliased if block expression (#51952)
Currently the TCB for aliased `if` blocks looks something like this:

```
// Markup: `@if (expr; as alias) { {{alias}} }

if (block.condition) {
  var alias = block.condition;
  "" + alias;
}
```

The problem with this approach is that the type of `alias` won't be narrowed. This is something that `NgIf` currently supports.

These changes resolve the issue by emitting the variable outside the `if` block and using the variable reference instead:

```
// Markup: `@if (expr; as alias) { {{alias}} }

var alias = block.condition;
if (alias) {
  "" + alias;
}
```

PR Close #51952
2023-10-04 08:49:59 -07:00
Kristiyan Kostadinov
e5bca43224 perf(compiler): further reduce bundle size using arrow functions (#52010)
Reworks a few more places to output arrow functions instead of function declarations in order to reduce the amount of code we generate. Some of these places include:
* Factories in injectable definitions.
* Forward references.
* `dependencies` function in the component definition.
* `consts` function in the component definition.

PR Close #52010
2023-10-04 07:25:54 -07:00
Kristiyan Kostadinov
0eae992c4e fix(compiler): allow nullable values in for loop block (#51997)
Updates the TCB for `@for` loop blocks to allow nullable values. The runtime already supports it and this makes it easier to switch from `NgFor`.

Fixes #51993.

PR Close #51997
2023-10-04 06:39:43 -07:00
Dylan Hunn
07602eb298 refactor(compiler): Implement basic support for defer in Template Pipeline (#51942)
The template pipeline now supports basic forms of `defer` blocks. This includes the `loading`, `placeholder`, and `error` blocks, as well as the loading and placeholder configuration options.

Lazy dependencies and prefetch are not yet implemented.

PR Close #51942
2023-10-03 19:40:04 -07:00
Kristiyan Kostadinov
43e6fb0606 feat(core): enable block syntax (#51994)
Enables the new `@` block syntax by default by removing the `enabledBlockTypes` flags. There are still some internal flags that allow special use cases to opt out of the block syntax, like during XML parsing and when compiling older libraries (see #51979).

PR Close #51994
2023-10-03 15:26:05 -07:00
Kristiyan Kostadinov
1beef49d80 fix(compiler): update the minVersion if component uses block syntax (#51979)
Increases the `minVersion` of component declarations that use bloks to v17 in order to indicate to users that they need to update if the library they're using is on the new syntax, while preserving backwards compatibility for libraries that do not use the syntax.

PR Close #51979
2023-10-03 11:48:13 -07:00
Kristiyan Kostadinov
9acd2ac98b fix(compiler): enable block syntax in the linker (#51979)
Adds some logic to enable parsing of block syntax in the linker. Note that the syntax is only enabled on code compiled with Angular v17 or later.

PR Close #51979
2023-10-03 11:48:13 -07:00
Dylan Hunn
32cfbb4306 refactor(compiler): Emit pure functions as arrow functions (#51961)
We were previously emitting pure functions as `function foo(args) {return bar;}`, but `TemplateDefinitionBuilder` uses arrow functions instead (`const foo = (args) => bar`). By matching this behavior, we can enable many additional tests.

PR Close #51961
2023-10-02 16:58:03 -07:00
Dylan Hunn
489ec15e1d refactor(compiler): Fix pipeBinding variable offsets in template pipeline (#51961)
This is a deceptively simple fix for a deep issue. Consider the following template:

```
<button [title]="myTitle" [id]="(auth().identity() | async)" [tabindex]="1">
```

`TemplateDefinitionBuilder` allocates the following variable (binding) slots:

v[0] = [title] binding
v[1] = [id] binding
v[2] = [tabindex] binding
v[3] = pipe binding
v[4] = pipe binding

As you can see, all three top-level property bindings were assigned variable indices. Then, variables for nested expressions were assigned.

Before this change, Template Pipeline would choose the following order:

v[0] = [title] binding
v[1] = [id] binding
v[2] = pipe binding
v[3] = pipe binding
v[4] = [tabindex] binding

With this order, nested expressions have their variables counted and assigned before subsequent top-level property bindings. This results in different variable indices for `pipeBinding` expressions that are not inside the final property binding.

However, this is not just different -- it's actually incorrect! Consider a case like the following:

```
<button [p1]="c ? (a | pipe) : 3" [p2]="b | pipe">
```

These pipe bindings are executed *conditionally*. This means that, because we don't count and assign all the "fixed" variable slots first, i.e. those belonging to the property bindings, their indices might end up incorrect, depending on whether or not a pipeBinding happened as part of the update block.

With this change, we count all variables on top-level ops first, and then descend into all expressions.

PR Close #51961
2023-10-02 16:58:03 -07:00
Dylan Hunn
408d3b44c7 refactor(compiler): Implement if aliases in template pipeline (#51931)
An `if` block can specify an alias for its main expression. We now support these in the template pipeline:
- We generate a temporary variable for the original expression
- We pass the temporary to the `conditional` instruction's context argument
- We provide the alias's name in the ambient context variables map

The context variables map now also accepts a name whose lookup value on the context object is empty. This will be interpreted as a read of the entire context object.

PR Close #51931
2023-09-29 14:05:30 -07:00
Dylan Hunn
56d25add17 refactor(compiler): Add support for basic if/else blocks. (#51931)
This entails adding a bit of extra logic to the existing conditional ingestion and corresponding phase, because `if` blocks lack a test expression.

Additionally, enable a couple more `switch` tests by resolving a curious issue --  we now consume a variable for conditionals.

PR Close #51931
2023-09-29 14:05:30 -07:00
Miles Malerba
8d09e9e013 test: Update golden partial file (#51876)
Updates the golden partial file to account for the newly added test

PR Close #51876
2023-09-29 10:54:01 -07:00
Miles Malerba
859b6c298f refactor(compiler): Additional fixes for pipes in i18n (#51876)
Adds a new test to verify pipe behavior in i18n blocks, and makes
serveral fixes to allow the test to pass.

PR Close #51876
2023-09-29 10:53:59 -07:00
Miles Malerba
705439aaad refactor(compiler): Enable some more passing i18n tests (#51876)
Enables a handful of additional i18n tests that pass with the changes
made so far.

PR Close #51876
2023-09-29 10:53:58 -07:00
Miles Malerba
5409b3f8d4 refactor(compiler): Fill in i18n expression placeholders (#51876)
Fills in the correct values for expression placeholders in the i18n
messages.

PR Close #51876
2023-09-29 10:53:51 -07:00
Miles Malerba
5ba9093c45 refactor(compiler): Add support for i18n expressions (#51876)
Adds support for i18n expressions in i18n messages, and allows i18n
messages on templates.

Co-authored-by: Alex Rickabaugh <alxhub@users.noreply.github.com>
Co-authored-by: Dylan Hunn <dylhunn@users.noreply.github.com>

PR Close #51876
2023-09-29 10:53:46 -07:00
Kristiyan Kostadinov
e2e3d69a27 feat(core): support deferred triggers with implicit triggers (#51922)
Adds support for defining `viewport`, `interaction` and `hover` triggers with no parameters. If the framework encounters such a case, it resolves the trigger to the root element of the `@placeholder` block. Triggers with no parameters have the following restrictions:
1. They have to be placed on an `@defer` block that has an `@placeholder`.
2. The `@placeholder` can only have one root node.
3. The root placeholder node has to be an element.

PR Close #51922
2023-09-27 12:59:34 -07:00
Kristiyan Kostadinov
23bfa10ac8 fix(compiler): add diagnostic for inaccessible deferred trigger (#51922)
If a trigger element can't be accessed from the defer block, we don't generate any instructions for it. These changes add a diagnostic that will surface the error to users.

PR Close #51922
2023-09-27 12:59:34 -07:00
Miles Malerba
c52995d9f1 refactor(compiler): Output i18n message parameter maps in sorted order (#51911)
Changes `TemplateDefinitionBuilder` to output i18n message parameters in
sorted order to make it easier for the template pipeline to generate
identical output. This does not result in any functional change, but
will make it much easier to shared output golden files with the template
pipeline.

PR Close #51911
2023-09-27 09:23:49 -07:00
Kristiyan Kostadinov
31295a3cf9 fix(compiler): allocating unnecessary slots in conditional instruction (#51913)
Fixes that we were allocating slots for the expressions of `if`, `else if`, `switch` and `case` blocks which we weren't using for anything.

PR Close #51913
2023-09-26 15:22:49 -07:00
Dylan Hunn
c3cb26527e refactor(compiler): Add source maps in template pipeline for expressions and additional ops (#51877)
Enable source maps in a variety of new cases, including most AST expressions, as well as several ops as didn't yet have them.

PR Close #51877
2023-09-26 10:58:09 -07:00
Payam Valadkhan
f91f222b55 fix(compiler-cli): resolve component encapsulation enum in local compilation mode (#51848)
Currently the field encapsulation undergoes some static analysis to check if it is `ViewEncapsulation` enum. Such static check fails in local compilation mode in g3 as the symbol cannot be resolved. On the other hand this field has to be resolved statically as its value determined the generated code. So in local compilation mode we add a lighter resolving logic which relies only on local information.

PR Close #51848
2023-09-26 09:11:15 -07:00
Payam Valadkhan
377a7abfda fix(compiler-cli): bypass static resolving of the component's changeDetection field in local compilation mode (#51848)
Currently the field changeDetection undergoes some static analysis to check if it is `ChangeDetectionStrategy` enum. Such static check fails in local compilation mode in g3 as the symbol cannot be resolved. So in local compilation mode we bypass such resolving and just write the expression as is into the component definition.

PR Close #51848
2023-09-26 09:11:15 -07:00
Kristiyan Kostadinov
8be2c48b7c feat(core): implement new block syntax (#51891)
Switches the syntax for blocks from `{#block}{/block}` to `@block {}` based on the feedback from the community.

Read more about the decision-making process in our blog: https://blog.angular.io/meet-angulars-new-control-flow-a02c6eee7843

The existing block types changed in the following ways:

**Conditional blocks:**
```html
<!-- Before -->
{#if cond}
  Main content
  {:else if otherCond}
    Else if content
  {:else}
    Else content
{/if}

<!-- After -->
@if (cond) {
  Main content
} @else if (otherCond) {
  Else if content
} @else {
  Else content
}
```

**Deferred blocks**
```html
<!-- Before -->
{#defer when isLoaded}
  Main content
  {:loading} Loading...
  {:placeholder} <icon>pending</icon>
  {:error} Failed to load
{/defer}

<!-- After -->
@defer (when isLoaded) {
  Main content
} @loading {
  Loading...
} @placeholder {
  <icon>pending</icon>
} @error {
  Failed to load
}
```

**Switch blocks:**
```html
<!-- Before -->
{#switch value}
  {:case 1}
    One
  {:case 2}
    Two
  {:default}
    Default
{/switch}

<!-- After -->
@switch (value) {
  @case (1) {
    One
  }

  @case (2) {
    Two
  }

  @default {
    Default
  }
}
```

**For loops**
```html
<!-- Before -->
{#for item of items; track item}
  {{item.name}}
  {:empty} No items
{/for}

<!-- After -->
@for (item of items; track item) {
  {{item.name}}
} @empty {
  No items
}
```

PR Close #51891
2023-09-26 09:10:04 -07:00
Kristiyan Kostadinov
d6bfebe2c8 refactor(compiler): generate arrow functions for setClassMetadata calls (#51637)
Reworks the `setClassMetadata` calls to generate arrow functions instead of full anonymous function declarations. While this won't have an effect on production bundle sizes, it's easier to read and it should lead to small parsing time gains in dev mode.

PR Close #51637
2023-09-25 09:27:26 -07:00
Kristiyan Kostadinov
16f5fc40a4 feat(core): support deferred viewport triggers (#51874)
Adds support for `on viewport` and `prefetch on viewport` triggers which will load the deferred content when the element comes into the view.

PR Close #51874
2023-09-25 09:17:03 -07:00
Kristiyan Kostadinov
687b96186c feat(core): support deferred hover triggers (#51874)
Adds support for `on hover` and `prefetch on hover` triggers. Some code had to be moved around so it could be reused from the `on interaction` triggers.

PR Close #51874
2023-09-25 09:17:03 -07:00
Kristiyan Kostadinov
00e6013661 refactor(compiler): implement final instruction generation for interaction triggers (#51830)
Updates the logic that generates the instructions for the `on interaction` and `prefetch on interaction` triggers to their final shape. Now the instructions take two arguments:
1. `triggerIndex` - index at which to find the trigger in the view where it will be rendered.
2. `walkUpTimes` - tells the runtime how many views up it needs to go to find the trigger element. If the argument is omitted, it means that the trigger is in the same view as the deferred block. A positive number means that the runtime needs to go up X amount of times to find the trigger. A negative number means that the trigger is inside the root view of the placeholder block. Negative numbers are capped at -1 since the placeholder is always in the same position at runtime.

PR Close #51830
2023-09-22 12:17:54 -07:00
Kristiyan Kostadinov
7cce28ae9c refactor(compiler): extract deferred block trigger information (#51830)
Reworks the compiler to use the API introduced in #51816 to match triggers to the element nodes they point to. This will be used to generate the new instructions for `on interaction` and `prefetch on interaction`.

PR Close #51830
2023-09-22 12:17:54 -07:00
Jeremy Elbourn
34495b3533 feat(compiler): extract docs via exports (#51828)
So far this docs extraction has pulls API info from all exported symbols in the program. This commit changes to extracting only symbols that are exported via a specified entry-point. This commit also exports the docs entities through the compiler-cli `index.ts`.

PR Close #51828
2023-09-20 18:34:55 +02:00
Payam Valadkhan
5b66330329 fix(compiler-cli): allow non-array imports for standalone component in local compilation mode (#51819)
Currently the compiler in local mode assumes that the standalone component imports are array expressions. This is not always true as they can be const variables as well. This change allow non-array expressions for standalone component imports field and passes that expression to the downstream tools such as deps tracker to compute the component's deps in runtime.

PR Close #51819
2023-09-20 12:24:54 +02:00
Payam Valadkhan
19c3dc18d3 fix(compiler-cli): fix NgModule injector def in local compilation mode when imports/exports are non-array expressions (#51819)
Current implementation assumes that NgModule imports/exports fields are always arrays and thus it concats them for the injector definition. But this is not always the case and imports/exports could be non-arrays such as const variable. Such pattern happens in g3 and so must be addressed.

PR Close #51819
2023-09-20 12:24:54 +02:00
Kristiyan Kostadinov
14d89d79ba refactor(compiler): implement template type checking for tracking expressions (#51690)
Adds support for template type checking of the `track` expression of a `for` loop block. Tracking expressions are treated as any other expression for type checking, however we have some special validation that doesn't allow them to access template variables and local references.

PR Close #51690
2023-09-20 11:26:05 +02:00
Kristiyan Kostadinov
aaa597393d refactor(compiler): implement template type checking for loop blocks (#51690)
Adds support for template type checking inside `for` blocks. It is implemented by generating a JS `for...of` statement inside the TCB. The various loop variables (e.g. `$index`) are implemented by declaring a local number variable.

PR Close #51690
2023-09-20 11:26:05 +02:00
Kristiyan Kostadinov
d42e02333a refactor(compiler): implement template type checking for if blocks (#51690)
Adds support for template type checking inside `if` blocks. It is implemented by generating a JS `if` statement inside the TCB which allows us to do type narrowing of the expression. The `as` parameter is implemented by declaring a variable inside the `if` statement.

PR Close #51690
2023-09-20 11:26:05 +02:00
Kristiyan Kostadinov
29ced9b066 refactor(compiler): implement template type checking for switch blocks (#51690)
Adds support for template type checking inside `switch` blocks. It is implemented by generating a JS `switch` statement inside the TCB which allows us to do type narrowing of the expression.

PR Close #51690
2023-09-20 11:26:05 +02:00
Kristiyan Kostadinov
8c10ba1a38 refactor(compiler): update binder to account for new semantics (#51816)
When the `TargetBinder` was written, the only embedded-view-based nodes were templates, but now we have `{#if}`, `{#switch}` and `{#defer}` which have similar semantics. These changes rework the binder to account for the new nodes.

PR Close #51816
2023-09-19 12:16:00 +02:00
Kristiyan Kostadinov
988e6c3fab refactor(compiler): require a reference in interaction and hover triggers (#51816)
Updates the parsing for `interaction` and `hover` triggers to require a reference to an element.

PR Close #51816
2023-09-19 12:16:00 +02:00
Dylan Hunn
8b0340626e refactor(compiler): Enable some additional passing tests for template pipeline (#51544)
A couple more tests pertaining to animations became passing at some point recently, as well as a few form other assorted areas.

PR Close #51544
2023-09-19 12:05:47 +02:00
Dylan Hunn
40f2b2690a refactor(compiler): Support ngProjectAs attributes (#51544)
Content project allows the content to specify its own selector for matching against content projection slots, using the `ngProjectAs` special attribute. We can now treat this attribue specially, and generate the appropriate flag in the consts array, followed by the parsed CSS selector.

PR Close #51544
2023-09-19 12:05:47 +02:00
Dylan Hunn
05393cb545 refactor(compiler): Support content projection in template pipeline (#51544)
Supporting content projection requires us to emit three new kinds of output:

1. An `ngContentSelectors` field on the component metadata, which points to an array in the constant pool with all of the `select` attributes from `<ng-content>` elements.
2. One `projectionDef` instruction at the beginning of each root view template function for a component. That `projectionDef` points to a constant pool expression, which contains *parsed* selectors for all `<ng-content>` elements in the root's entire view tree.
3. A `projection` instruction for each `<ng-content>` slot in the view tree. These each get a data slot, a monotonically increasing "content slot", and a pointer to the tag's attributes in the component const array.

We support the first two features entirely within a new compilation phase.

The third feature, collection of processed attributes, is a bit trickier. We now treat `<ng-content>` tags as element-like ops, and use the normal attribute ingestion pipeline to process any attributes, and assign the appropriate `ConstIndex`.

**Note**: We also split up a number of the tests into two expectations files, one for the view functions, and one for other const listerals from the constant pool. This is because `TemplateDefinitionBuilder` emits the literals in a quirky order (mixed in with the view functions) due to how it lazily generates view functions. Our eager ordering is totally different, but by splitting the expectations, we can still share the same tests with `TemplateDefinitionBuilder`.

PR Close #51544
2023-09-19 12:05:47 +02:00
Kristiyan Kostadinov
e23aaa7d75 feat(core): drop support for older TypeScript versions (#51792)
Drops support for versions of TypeScript older than 5.2

BREAKING CHANGE:
Versions of TypeScript older than 5.2 are no longer supported.

PR Close #51792
2023-09-19 12:04:09 +02:00
Payam Valadkhan
fbf3ac247b refactor(compiler-cli): move NgModule bootstrap definition to runtime in local compilation mode (#51767)
Today in local compilation mode the NgModule bootstrap definition is moved as it is into the runtime `ɵɵdefineNgModule`. This runtime was initially made for AoT full compilation mode and assumes that the bootstrap info is already flattened and resolved. This is not the case in local compilation where the bootstrap is the raw expression coming from the NgModule decorator and can be a nested array. To get around this problem we move the bootstrap along with other scope info (e.g., declarations, imports, exports) to the runtime`ɵɵsetNgModuleScope` to be further analyzed and flattened in runtime.

PR Close #51767
2023-09-18 16:59:55 +02:00
Jeremy Elbourn
2e41488296 feat(compiler): extract docs info for enums, pipes, and NgModules (#51733)
Based on top of #51717

This commit adds extraction for enums, pipes, and NgModules. It also adds a couple of tests for JsDoc extraction that weren't covered in the previous commit.

PR Close #51733
2023-09-18 12:29:30 +02:00
Jeremy Elbourn
e0b1bb33d7 feat(compiler): extract doc info for JsDoc (#51733)
Based on top of #51713

This commit adds docs extraction for information provided in JsDoc comments, including descriptions and Jsdoc tags.

PR Close #51733
2023-09-18 12:29:28 +02:00
Jeremy Elbourn
a24ae994a0 feat(compiler): extract docs for top level functions and consts (#51733)
Based on top of ##51700

Also updates extraction to ignore un-exported statements.

PR Close #51733
2023-09-18 12:29:26 +02:00
Jeremy Elbourn
b9c70158ab feat(compiler): extract docs for accessors, rest params, and types (#51733)
Based on top of #51697

Adds extraction for accessors (getters/setters), rest params, and resolved type info for everything so far. This also refactors function extraction into a new class and splits tests for common class info and directive info into separate files.

PR Close #51733
2023-09-18 12:29:24 +02:00
Jeremy Elbourn
c7daf7ea16 feat(compiler): extract directive docs info (#51733)
Based on top of #51685

This expands on the extraction with information for directives, including inputs and outputs. As part of this change, I've refactored the extraction code related to class and to directives into their own extractor classes to more cleanly separate extraction logic based on type of statement.

PR Close #51733
2023-09-18 12:29:22 +02:00
Jeremy Elbourn
7f6d9a73ab feat(compiler): expand class api doc extraction (#51733)
Based on top of #51682

This expands on the skeleton previously added to extract docs info for classes, including properties, methods, and method parameters. Type information and Angular-specific info (e.g. inputs) will come in future PRs.

PR Close #51733
2023-09-18 12:29:20 +02:00
Jeremy Elbourn
7e82df45c5 feat(compiler): initial skeleton for API doc extraction (#51733)
This commit adds a barebones skeleton for extracting information to be used for extracting info that can be used for API reference generation. Subsequent PRs will expand on this with increasingly real extraction. I started with @alxhub's #51615 and very slightly polished to get to this minimal commit.

PR Close #51733
2023-09-18 12:29:19 +02:00
Kristiyan Kostadinov
75380bf220 test(compiler): attempt to deflake windows tests (#51804)
Another try at deflaking the tests on Windows. I'm trying a couple of fixes here:
1. I noticed that it's usually the indexer tests that fail during flaky runs. These tests also happen to be the only ones that don't pass in the `files` argument of `NgtscTestEnvironment.setup`. When `files` isn't passed in, we don't hit the file path that sets up the `MockFileSystem`. With these changes I make it so that we always initialize the mock file system.
2. The missing file system error usually comes from the `absoluteFrom` call that initializes the optional `workingDir` argument. My theory is that because it's a default value for an argument, it gets called too early before everything is initialized. These changes move the `absoluteFrom` call further down until it's needed.

PR Close #51804
2023-09-18 10:46:37 +02:00
Angular Robot
25b9b86373 build: update babel dependencies (#50932)
See associated pull request for more information.

PR Close #50932
2023-09-15 09:03:24 +02:00
Alan Agius
59aa0634f4 build: remove support for Node.js v16 (#51755)
BREAKING CHANGE: Node.js v16 support has been removed and the minimum support version has been bumped to 18.13.0.

Node.js v16 is planned to be End-of-Life on 2023-09-11. Angular will stop supporting Node.js v16 in Angular v17. For Node.js release schedule details, please see: https://github.com/nodejs/release#release-schedule

PR Close #51755
2023-09-13 10:49:06 -07:00
Kristiyan Kostadinov
2a1723c945 test(compiler): fix broken integrity check (#51751)
The `verifyPlaceholdersIntegrity` check in the compliance tests was basically a noop, because it was returning false inside a `forEach` callback. Fixing it revealed that it had fallen out of date, because one of the regexes it uses was incorrect. The problem is that it assumed the placeholder keys would always be string literals, however it's possible that they're identifiers. These changes resolve the issue by not looking at the keys at all since we don't do anything with them.

PR Close #51751
2023-09-13 10:48:32 -07:00
Kristiyan Kostadinov
59387ee476 feat(core): support styles and styleUrl as strings (#51715)
Adds support for passing in `@Component.styles` as a string. Also introduces a new `styleUrl` property on `@Component` for providing a single stylesheet. This is more convenient for the most common case where a component only has one stylesheet associated with it.

PR Close #51715
2023-09-12 13:57:07 -07:00
Kristiyan Kostadinov
f9939757d3 build: skip simulated file system tests on Windows (#51738)
The code for detecting a Windows CI run from #51701 didn't work, because Bazel isolates the environment variables. These changes work around the issue by passing in a custom variable with the `--test_env` flag.

PR Close #51738
2023-09-12 12:56:27 -07:00
Kristiyan Kostadinov
52cc7f839b build: align with internal tsconfig options (#51728)
Currently internally Angular has some customized tsconfig files, because we don't align with the tsconfig of the rest of g3. These changes enable `noImplicitReturns` and `noPropertyAccessFromIndexSignature` to align better with the internal config.

PR Close #51728
2023-09-12 11:39:42 -07:00
Kristiyan Kostadinov
b3edcda9e6 build: attempt to deflake windows tests (#51701)
Adds some logic to try and deflake the tests on Windows.

PR Close #51701
2023-09-08 09:28:02 -07:00
Kristiyan Kostadinov
88a0af64fd perf(core): generate arrow functions for pure function calls (#51668)
Reworks the pure functions to use arrow functions with an implicit return instead of function expressions. This allows us to shave off some bytes for each pure function, because we can avoid some of the syntax.

PR Close #51668
2023-09-06 15:32:02 +00:00
Kristiyan Kostadinov
7c068861b7 refactor(compiler): output arrow functions for deferred dependencies functions (#51650)
Reworks the compiler to generate arrow functions for the deferred dependencies which reduces the number of bytes we generate.

PR Close #51650
2023-09-05 18:16:59 +00:00
Kristiyan Kostadinov
7fa17d00f6 test(compiler): fix failing tests (#51656)
Fixes some tests that started failing, because a couple of connected PRs landed at the same time.

PR Close #51656
2023-09-05 15:02:52 +00:00
Kristiyan Kostadinov
05a16b973d refactor(compiler): add support for advanced tracking expressions (#51618)
These changes build on top of #51514 to add support for advanced expressions inside the `track` parameter of `for` loop blocks. There are two different outputs that the compiler can generate:

1. If the tracking function only references the item or `$index`, the compiler generates a pure arrow function as a constant references in the `repeaterCreate` instruction.
2. If the tracking function has references to properties outside of the `for` loop block, the compiler will rewrite those references to go through `this` and generate a function declaration. The runtime will `bind` the declaration to the current component instance so that the rewritten `this` references are resolved correctly.

Advanced tracking expression come with the following limitations to ensure the best possible performance:
1. They can only reference the item, `$index` and properties directly on the component instance. This means that there'll be an error when accessing this like local template variables and references. While we could get this to work, we would have to traverse the context tree at runtime which will degrade the performance of the loop, because it's a linear time operation that is performed on each comparison. Furthermore, allowing local references would require us re-evaluate the list when any one of them has changed.
2. Pipes aren't allowed inside the tracking function.
3. Object literals and pipes used inside the tracking expression will be recreated on each invocation.

PR Close #51618
2023-09-05 14:19:18 +00:00
Kristiyan Kostadinov
6ecafa3305 refactor(compiler): computed for loop variables exposed on the wrong scope (#51618)
Fixes that the computed for loop variables (e.g. $first and $last) were exposed on the parent scope instead of the for loop scope.

PR Close #51618
2023-09-05 14:19:18 +00:00
Kristiyan Kostadinov
75ab0bdf45 refactor(compiler): type check deferred when and prefetch when triggers (#51570)
Adds type checking support to the deferred `when` and `prefetch when` triggers.

PR Close #51570
2023-09-05 14:18:44 +00:00
Kristiyan Kostadinov
0c8917b348 refactor(compiler): type check contents of control flow blocks (#51570)
Adds type checking for the contents of `if`, `switch` and `for` blocks.

**Note:** this is just an initial implementation to get some basic type checking working and to figure out the testing setup. We'll need special TCB structures for this syntax so that we can support type narrowing.

PR Close #51570
2023-09-05 14:18:44 +00:00
Kristiyan Kostadinov
1ce9f0aff3 refactor(compiler): type check the contents of defer blocks (#51570)
Fixes that the contents of `defer` blocks weren't being type checked.

PR Close #51570
2023-09-05 14:18:44 +00:00
Matthieu Riegler
525acbb165 docs: remove NG6999 error page. (#51588)
`NGMODULE_VE_DEPENDENCY_ON_IVY_LIB` was a ViewEngine related error. This commit removes the doc page but keeps a redirection for older versions still throwing this error.

PR Close #51588
2023-08-31 17:30:57 +00:00
Joey Perrott
3bca9db4a5 fix(compiler-cli): remove unnecessary escaping in regex expressions (#51554)
Correct various Useless regular-expression character escape issues.

PR Close #51554
2023-08-29 21:52:33 +00:00
Joey Perrott
de2550d988 fix(compiler-cli): correct incomplete escaping (#51557)
Correct incomplete escaping and replace all instances of `

PR Close #51557
2023-08-29 19:48:25 +00:00
Kristiyan Kostadinov
685d01e106 perf(core): chain template instructions (#51546)
With the new control flow and defer blocks it'll be common for several template instructions to be declare one after another. These changes add support for chaining to the `template` instruction which will allow us to save some bytes.

PR Close #51546
2023-08-29 16:38:52 +00:00
Kristiyan Kostadinov
d83dfaa8ea refactor(compiler): generate for loop block instructions (#51514)
Adds the initial implementation to generate the instructions for the `for` loop block.

**Note:** the expressions we support in the `track` paramateter are currently limited to tracking by identity or index, or a specific property of the item. Supporting more advanced expression will require additional work that I'll do in a follow-up PR.

PR Close #51514
2023-08-29 16:38:22 +00:00
Dylan Hunn
ab0f9eeba5 refactor(compiler): Implement switch blocks in template pipeline (#51518)
`switch` blocks are part of the new control flow syntax. This commit adds support for processing them, and emitting the appropriate templates and conditional instructions.

PR Close #51518
2023-08-29 00:16:00 +00:00
Dylan Hunn
c2d859241b refactor(compiler): Enable additional passing tests (#51498)
Some additional tests were already passing.

PR Close #51498
2023-08-28 21:51:04 +00:00
Dylan Hunn
c013bff48a refactor(compiler): Support $event in host bindings (#51498)
Run the existing phase that deals with `$event` during host binding compilation.

PR Close #51498
2023-08-28 21:51:04 +00:00
Dylan Hunn
bca26b88b1 refactor(compiler): Generalize the ordering phase to also order create mode (#51498)
`syntheticHostListener` and `listener` have ordering dependencies. We reuse the existing ordering phase, and generalize it to also order create mode instructions.

PR Close #51498
2023-08-28 21:51:04 +00:00
Dylan Hunn
f13223b140 refactor(compiler): Support host animation events. (#51498)
Animation listeners on host bindings result in a special `syntheticHostListener` instruction. We can now emit this instruction.

Additionally, the naming phase for events has been slightly refactored to smoothly incorporate whether the event is from a host listener, as well as whether it is an animation listener.

PR Close #51498
2023-08-28 21:51:04 +00:00
Dylan Hunn
1ea8617cd2 refactor(compiler): Support host binding listeners (#51498)
We can now ingest host bindings listeners into the template pipeline, and process them using the pre-existing phases.

PR Close #51498
2023-08-28 21:51:04 +00:00
Dylan Hunn
5546cb3197 refactor(compiler): More closely match TDB binding ordering (#51498)
For host bindings, `TemplateDefinitionBuilder` seems to use a different binding ordering, in which style bindings come after all the property bindings. We approximate that by treating `hostProperty` differently from `property` in the ordering phase.

PR Close #51498
2023-08-28 21:51:04 +00:00
Dylan Hunn
cae01dae1b refactor(compiler): Support class and style attrs in host bindings (#51498)
The template pipeline is already capable of parsing and processing class and style attributes on templates. We now extend that functionality to host bindings.

The parser, for some reason, splits out class and style attributes into a `specialAttributes` field. We merge them back into the main attributes map, and allow the template pipeline to process them normally.

PR Close #51498
2023-08-28 21:51:04 +00:00
Dylan Hunn
d0b83b14be refactor(compiler): Backwards compatibility with TDB for host attributes (#51498)
TemplateDefinitionBuilder only extracts host attributes if they are text attributes. For example, `[attr.foo]="'my-value'"` is not extracted despite being a string literal, because it is not a text attribute.

PR Close #51498
2023-08-28 21:51:04 +00:00
Dylan Hunn
8f90630dc8 refactor(compiler): Support synthetic host property bindings. (#51498)
Host property bindings can be animation bindings, and should be ingested and emitted as such, as well as being processed by the renaming phase.

PR Close #51498
2023-08-28 21:51:04 +00:00
Dylan Hunn
0df7828637 refactor(compiler): Extract host binding static attributes to hostAttrs (#51498)
Host bindings can apply static attributes. These will be extracted to a `hostAttrs` field on the host binding function's metadata.

In order to achieve this, we add an `attributes` field to the host binding job. Then, we peform attribute exraction on host bindings. We finally populate the `attributes` field directly, instead of relying on a `consts` array.

PR Close #51498
2023-08-28 21:51:04 +00:00
Alex Rickabaugh
575a5588f8 refactor(compiler): initial implementation of i18n blocks (#51353)
Adds i18n block start & end ops, as well as a new phase to construct the
i18n message variable to be added to the consts array.

Co-authored-by: Alex Rickabaugh <alx+alxhub@alxandria.net>
Co-authored-by: Dylan Hunn <dylhunn@gmail.com>

PR Close #51353
2023-08-28 18:57:08 +00:00
Andrew Kushnir
c4deaac5b0 refactor(core): initial implementation of {#defer} block runtime (#51347)
This commit adds an initial implementation of the `{#defer}` block runtime, which supports the `when` conditions. More conditions and basic prefetching support will be added in followup PRs.

PR Close #51347
2023-08-28 17:09:52 +00:00
Kristiyan Kostadinov
fa72384ec5 refactor(compiler): introduce AST for outputting arrow functions (#51436)
Extends the compiler to add support for generating arrow functions in the output AST. This will be required for the `for` control flow block and we can potentially leverage it in other places to reduces the amount of generated code.

PR Close #51436
2023-08-23 14:45:33 -07:00
Kristiyan Kostadinov
9cc0cbed0c refactor(compiler): generate if block instructions (#51380)
Adds the logic to generate the instructions for `if` blocks. There are two primary use cases we need to account for:

A conditional that doesn't use the `as` parameter of the `if` block. To support it we generate a nested ternary expression that evaluates to the index of the template whose condition is truthy. If the block doesn't have an `else` branch, we pass in a special `-1` value which means that no view will be rendered.

Example with an `else`:
```ts
// {#if expr}
//   ...
//   {:else if otherExpr} ...
//   {:else} ...
// {/if}

if (rf & 1) {
  ɵɵtemplate(0, App_Conditional_0_Template, 0, 0);
  ɵɵtemplate(1, App_Conditional_1_Template, 0, 0);
  ɵɵtemplate(2, App_Conditional_2_Template, 0, 0);
}
if (rf & 2) {
  ɵɵconditional(0, ctx.expr ? 0 : ctx.otherExpr ? 1 : 2);
}
```

Example without an `else`:
```ts
// {#if expr}
//   ...
//   {:else if otherExpr} ...
// {/if}

if (rf & 1) {
  ɵɵtemplate(0, App_Conditional_0_Template, 0, 0);
  ɵɵtemplate(1, App_Conditional_1_Template, 0, 0);
}
if (rf & 2) {
  ɵɵconditional(0, ctx.expr ? 0 : ctx.otherExpr ? 1 : -1);
}
```

If a conditional captures it's value in an alias (e.g. `{#if expr; as foo}`) we need to assign the value to a temporary variable before passing it along to `conditional`.

```ts
// {#if expr; as alias}...{/if}
if (rf & 1) {
  ɵɵtemplate(0, App_Conditional_0_Template, 1, 0);
}
if (rf & 2) {
  let App_contFlowTmp;
  ɵɵconditional(0, (App_contFlowTmp = ctx.expr) ? 0 : -1, App_contFlowTmp);
}
```

PR Close #51380
2023-08-18 10:01:02 -07:00
Kristiyan Kostadinov
0c4c773fca refactor(compiler): generate switch block instructions (#51380)
Adds the logic to generate the instructions for `switch` instructions. For the following block:

```html
{#switch value()}
  {:case 0} case 0
  {:case 1} case 1
  {:case 2} case 2
  {:default} default
{/switch}
```

The compiler will produce the following output:

```ts
function App_Template(rf, ctx) {
  if (rf & 1) {
    ɵɵtemplate(0, App_Case_0_Template, 1, 0);
    ɵɵtemplate(1, App_Case_1_Template, 1, 0);
    ɵɵtemplate(2, App_Case_2_Template, 1, 0);
    ɵɵtemplate(3, App_Case_3_Template, 1, 0);
  }
  if (rf & 2) {
    let App_contFlowTmp;
    ɵɵconditional(0, (App_contFlowTmp = ctx.value()) === 0 ? 0 : App_contFlowTmp === 1 ? 1 : App_contFlowTmp === 2 ? 2 : 3);
  }
}
```

PR Close #51380
2023-08-18 10:01:02 -07:00
JoostK
5bd9fbd2c3 fix(compiler-cli): enforce a minimum version to be used when a library uses input transform (#51413)
Angular 16.1 introduced the input transform feature, requiring the partial compilation output to be extended
with a reference to the input transform function. This has resulted in a subtle breaking change, where older
versions of the Angular linker can no longer consume libraries that have started to use this feature.

We do try to support using a 16.1 library from an Angular 16.0 application, but if a library actually
adopts a new feature then this is no longer possible. In such cases, it is desirable to report a message
telling the user that their version of the Angular compiler is too old, as determined by the `"minVersion"`
property that is present in each partial declaration. This version would still indicate that the declaration
required at least Angular 14.0 to be compiled, but this is not accurate once input transforms are being
used. Consequently, this error would not be reported, causing a less informative error once the input transform
was being observed.

Fixes #51411

PR Close #51413
2023-08-18 07:58:53 -07:00
Kristiyan Kostadinov
9cc52b9b85 feat(core): support TypeScript 5.2 (#51334)
Updates the project to support TypeScript 5.2.

PR Close #51334
2023-08-18 07:55:16 -07:00
Payam Valadkhan
0b901a814b refactor(compiler-cli): better error messages when external strings used for template and styles in local compilation mode (#51338)
In local compilation mode it is not possible to use an imported string for component's template or styles as it cannot be resolved statically in compile time. There are some such use cases in g3 and potentially devs might incorporate such pattern. At the moment such pattern will cause the local compilation fail with generic error messages (e.g., so and so at position 1 is not a reference, etc). This change makes specific error messages with helpful hints for such cases. These new error messages can help devs to quickly resolve the issue as well as make it possible to identify existing issues in g3.

PR Close #51338
2023-08-17 14:02:52 -07:00
Paul Gschwendtner
552ea77854 refactor(compiler-cli): drop tsickle code paths (#50602)
`tsickle` is not used in any code paths in 3P and we can remove
this complexity. The `tsickle` npm package has not been released
in a while and we are risking breakages with e.g. future TypeScript
versions.

Note that the `ng_module` rule was updated to not emit through
tsickle at all. The tsickle in 1P is done directly by `tsc_wrapped`
and our code path in `compiler-cli` is not needed at all.

PR Close #50602
2023-08-17 10:23:49 -07:00
Andrew Kushnir
bcc3c43fca refactor(core): update TestBed to handle async component metadata (#51182)
This commit updates TestBed to wait for async component metadata resolution before compiling components.
Async metadata is added by the compiler in case a component uses defer blocks, which contain deferrable
symbols.

PR Close #51182
2023-08-15 11:32:09 -07:00
Andrew Kushnir
c41a1950fd refactor(compiler): apply component metadata asynchronously when defer blocks are present (#51182)
This commit updates compiler logic to generate the `setClassMetadataAsync` calls for components that used defer blocks. The `setClassMetadataAsync` function loads deferrable dependencies and invokes the `setClassMetadata` synchronously once everything is loaded. This change is needed to avoid eager references to deferrable symbols in component metadata in generated code.

PR Close #51182
2023-08-15 11:32:09 -07:00
Kristiyan Kostadinov
422d0d5ca3 refactor(compiler): handle deferred when trigger with a pipe (#51368)
Fixes that we weren't processing `when` conditions correctly which led to a compilation error when a pipe is used inside the expression.

PR Close #51368
2023-08-15 10:03:59 -07:00
Kristiyan Kostadinov
5212b47bbf refactor(compiler): introduce defer trigger instructions (#51315)
Adds the logic for generating the instructions for the various deferred triggers.

PR Close #51315
2023-08-11 06:55:13 -07:00
Kristiyan Kostadinov
79f9d49fad refactor(compiler): introduce defer block instructions (#51315)
Adds the logic for generating `{#defer}`, `{:placeholder}`, `{:loading}` and `{:error}` block instructions in the compiler.

PR Close #51315
2023-08-11 06:55:13 -07:00
Kristiyan Kostadinov
36b180ade4 refactor(compiler): implement conditional block AST (#51299)
Adds the AST for `if`, `else if` and `else` blocks.

PR Close #51299
2023-08-10 13:48:55 -07:00
Kristiyan Kostadinov
4424920f0b refactor(compiler): implement for block AST (#51299)
Adds the AST for `for` and `empty` blocks.

PR Close #51299
2023-08-10 13:48:55 -07:00
Kristiyan Kostadinov
31c6c5e944 refactor(compiler): implement switch block AST (#51299)
Adds the AST for `switch`, `case` and `default` blocks.

PR Close #51299
2023-08-10 13:48:55 -07:00
Payam Valadkhan
1eda1bdfcc refactor(compiler-cli): ctor dependencies in local compilation mode (#51089)
Ctor deps are added to the fctory function for all the angular classes: NgModule, Component, Pipe, Directive and Injectable

PR Close #51089
2023-08-08 13:58:48 -07:00
Payam Valadkhan
827e10ae0e refactor(compiler): add a factory for component dependencies in local compilation mode (#51089)
A factory generator function called "i0.ɵɵgetComponentDepsFactory" is added to generate a factory function for component dependencies. This function will use the deps tracker to calculate the component's dependencies.

For standalone components the component imports (if exists) will be passed to this function. Alternatively this function can grab the imports directly from the decorate, but such extraaction needs some runtime logic which overlapps with what the trait compiler is doing. So better to pass the imports directly to this function at compile time.

PR Close #51089
2023-08-08 13:58:48 -07:00
Payam Valadkhan
e26080be0b refactor(compiler-cli): ng module injector compilation in local mode (#51089)
In local mode the compiler combines the raw imports and exports and pass them to the injector definition as the imports field. It is not possible to filter out ng modules at compile time though, and it will be done in runtime.

Unit tests also added, and since that was the first time adding tests for local compilation some tweaks had to be made in order to disable diagnostics in local compilation mode in order for tests to run (such situation is also the case in real compilation where we ignore all teh diagnostics basically)

PR Close #51089
2023-08-08 13:58:48 -07:00
Andrew Kushnir
6f506cdff0 refactor(compiler): drop regular imports when symbols can be defer-loaded (#51171)
This commit updates the logic to drop regular imports when all symbols that it brings can be defer-loaded.
The change ensures that there is no mix of regular and dynamic imports present in a source file.

PR Close #51171
2023-08-04 11:28:07 -04:00
Kristiyan Kostadinov
d11548f2ef refactor(compiler): store deferred triggers as a map (#51262)
Stores the `deferred` block triggers as a map instead of an array, because triggers can't be duplicated and because having to search through an array will be inconvenient later on.

I've also added a `DeferredBlock.visitAll` method to deduplicate the logic from the various visitor implementations.

PR Close #51262
2023-08-04 11:27:39 -04:00
Miles Malerba
74974f80e0 refactor(compiler): Parse extracted class attributes (#51258)
Adds logic to parse extracted class attributes into separate
ExtractedAttributeOps per class in the attribute.

PR Close #51258
2023-08-03 14:34:53 -04:00
Miles Malerba
2d52d5e62c refactor(compiler): support safe function calls (#51100)
Adds support for safe function calls in template pipeline compiler

PR Close #51100
2023-08-01 13:45:34 -07:00
Miles Malerba
42caeeef21 refactor(compiler): reuse temp vars when possible (#51100)
Updates the template pipeline's temporary variables phase to reuse
temporary variables within an expression. The algorithm implemented here
reuses variables more aggressively than TemplateDefinitionBuilder. This
change in behavior is acceptable, as it is unlikely to cause any
failures, and implementing the exact behavior observed in
TemplateDefinitionBuilder would be difficult.

PR Close #51100
2023-08-01 13:45:34 -07:00
Miles Malerba
b8ec182a2a test(compiler): allow alternate expected file for template pipeline (#51100)
In some cases it is not feasible to have the template pipeline produce
the exact same compiled output as the TemplateDefinitionBuilder. This
commit adds support to the testing infrastructure to have different
expected output files for each. This option should be used sparingly, as
we want the output to be as close as possible.

PR Close #51100
2023-08-01 13:45:34 -07:00
Andrew Kushnir
efb486e8bc refactor(compiler): handle defer blocks in TemplateDefinitionBuilder (#51162)
Updates the TemplateDefinitionBuilder class to generate the `defer` instruction for `{#defer}` blocks. Also generates dependency function that would be invoked at runtime (with dynamic imports inside).

PR Close #51162
2023-08-01 11:50:05 -07:00
Andrew Kushnir
08992a5f2f refactor(compiler): compute the list of dependencies for defer blocks (#51162)
This commit brings the logic to calculate teh set of dependencies for each defer block. For each dependency we also identify whether it can be defer-loaded or not.

PR Close #51162
2023-08-01 11:50:05 -07:00
Andrew Kushnir
f5116e739e refactor(compiler): extracting helper function and types to the top level (#51162)
This is a minor refactoring of the ComponentHandler class logic to extract helper function and types to the top level for simplicity and reuse across other functions of the class.

PR Close #51162
2023-08-01 11:50:05 -07:00
Andrew Kushnir
256e6826bc refactor(compiler): add DeferredSymbolTracker class to keep track of symbol usages (#51162)
This commit adds a new class called `DeferredSymbolTracker` to keep track of all usages of a particular symbol within a source file and allow to detect whether a symbol can be defer loaded (i.e. if there are any references to a symbol).

PR Close #51162
2023-08-01 11:50:04 -07:00
Miles Malerba
c1052cf7a7 refactor(compiler): add support for sanitizing properties and attributes (#51156)
Sets sanitizer functions when attempting to set sensitive properties and attributes

PR Close #51156
2023-07-28 15:11:51 -07:00
Miles Malerba
09bf32724f refactor(compiler): add support for animation listeners (#50975)
Adds support for binding animation listeners, e.g.

PR Close #50975
2023-07-28 14:40:13 -07:00
Miles Malerba
7dd99cd843 refactor(compiler): add support for animation properties (#50975)
Adds support for binding animation properties, e.g.

PR Close #50975
2023-07-28 14:40:13 -07:00
Dylan Hunn
50613117bd refactor(compiler): Ingest host attribute bindings in template pipeline (#51188)
Host property bindings beginning with `attr.` should have `Attribute` binding kind, and result in an `attribute` instruction.

This should really be handled in the parser in the future.

PR Close #51188
2023-07-28 11:47:57 -07:00
Dylan Hunn
a42c91e78b refactor(compiler): Generate temporaries in host bindings for template pipeline (#51188)
Add the ability to name and resolve generated temporary variables in host bindings, using the existing phase.

PR Close #51188
2023-07-28 11:47:57 -07:00
Dylan Hunn
72a59bdc4d refactor(compiler): Support svg and math namespace instructions in template pipeline (#51188)
Templates may contain special `svg` and `math` elements, as well as logical descendants of those elements (e.g. `svg` may contain `g`). These will be parsed with a special colon-prefixed *namespace identifier*, such as `:svg:svg`, or `:svg:g`, or `:math:infinity`.

The template pipeline now considers these namespace prefixes, and stores them specially on the Element and Template data structures, ultimately generating the appropriate runtime instructions to change namespaces when needed.

PR Close #51188
2023-07-28 11:47:57 -07:00
Dylan Hunn
c4b289ab8f refactor(compiler): Allow chaining of listeners in template pipeline (#51188)
Calls to the listener instruction can be chained.

PR Close #51188
2023-07-28 11:47:57 -07:00
Dylan Hunn
8f50385041 refactor(compiler): support ngNonBindable in the template pipeline (#51188)
When a container-like element has the `ngNonBindable` special attribute, bindings are disabled for it and its descendants. This requires emitting the `disableBindings` and `enableBindings` instructions when nested content exists.

PR Close #51188
2023-07-28 11:47:57 -07:00
Dylan Hunn
833cb8ef69 refactor(compiler): Enable additional tests for the template pipeline (#50899)
A number of tests were previously disabled, but are now passing with the latest changes.

PR Close #50899
2023-07-27 15:08:05 -07:00
Dylan Hunn
5a0ecdb58b refactor(compiler): Allow host binding functions to specialize bindings (#50899)
Interestingly, host bindings are parsed quite differently from template functions. For example, bindings such as `[style.foo]: 3px` would be parsed into a value, unit, and type when bound to a template, but will not be parsed as such when used in a host binding.

In this commit, we remedy this shortcoming by adding support for bindings in host binding functions to the template pipeline. In particular, we create a phase to process these bindings, and transform them into the correct output binding kind.

Additionally, we fix some other minor bugs and omissions.

Finally, we enable compilation of host bindings with the template pipeline, which requires us to turn off a number of failing tests.

PR Close #50899
2023-07-27 15:08:05 -07:00
Dylan Hunn
31ff476060 refactor(compiler): Introduce source maps in the template pipeline. (#50899)
Begin producing source maps for the template pipeline, for a couple fundamental kinds of instructions, including elements, templates, properties, text, and interpolations.

PR Close #50899
2023-07-27 15:08:04 -07:00
Dylan Hunn
8a6a72e7cb refactor(compiler): Fix $event in listeners for template pipeline (#50899)
Previously, `$event` was interpreted as a lexical read on the enclosing context. Now, a new pass converts such reads into simple output AST reads of `$event`, so they are not processed by the context resolution or naming phases. Additionally, the same pass sets a field on the enclosing listener op, so that the reify phase does not have to search for reads of `$event`.

PR Close #50899
2023-07-27 15:08:04 -07:00
Dylan Hunn
c6010f0610 refactor(compiler): Support $any in template pipeline (#50899)
`$any(...)` casts should be dropped, except when they are an explicit call on `this.$any(...)`. Fix a bug in which we were transforming `ThisReceiver` into an implicit receiver.

PR Close #50899
2023-07-27 15:08:04 -07:00
Jessica Janiuk
386cb2f18b Revert "docs: added the alt attribute in the img tag (#51102)" (#51107)
This reverts commit 3b248c59c6.

PR Close #51107
2023-07-19 18:48:59 +00:00
alkavats1
3b248c59c6 docs: added the alt attribute in the img tag (#51102)
PR Close #51102
2023-07-19 17:39:44 +00:00
Andrew Kushnir
24bf133eb6 refactor(compiler): add support for dynamic imports in the output AST (#51087)
This commit updates the output AST (and related visitors) to support dynamic imports. This functionality will be used later to generate the output for defer blocks.

PR Close #51087
2023-07-19 16:54:42 +00:00
Kristiyan Kostadinov
7410d6847b refactor(compiler): add compiler flag to enable deferred blocks for testing (#51079)
Adds a new compiler option that will allow `defer` (and other) blocks to be enabled when writing unit tests.

PR Close #51079
2023-07-18 17:05:29 +00:00
Kristiyan Kostadinov
9e61616ffe refactor(compiler): introduce deferred block AST (#51050)
Adds the logic to create `defer`-specific AST nodes from the generic HTML `BlockGroup` and `Block`. The logic for parsing the triggers will be in the next commit.

PR Close #51050
2023-07-17 21:05:47 +00:00
Miles Malerba
afd2fd8681 refactor(compiler): ensure correct ordering of properties and attributes (#50805)
Ensures that all property and attribute ops are ordered consistently
regardless of the order they appear in the template. This ensures
correct precedence (e.g. `[style.color]="'#000'"` awlays wins out over
`[style]="{color: '#fff'}"`)

PR Close #50805
2023-07-17 17:03:57 +00:00
Miles Malerba
03e6dc3f28 refactor(compiler): normalize style prop binding names (#50805)
Normalizes style property names in bindings by converting them to
kebab-case and stripping off `!important`

PR Close #50805
2023-07-17 17:03:57 +00:00
Miles Malerba
c27d6b6b37 build: enable newly passing style tests for the template compiler (#50805)
Enables style tests that are now passing in the template compiler thanks
to recent fixes

PR Close #50805
2023-07-17 17:03:57 +00:00
Miles Malerba
2f7072dc3f refactor(compiler): add support for class property bindings (#50805)
Adds support for bindings of the form `[class.some-class]="isActive"`

PR Close #50805
2023-07-17 17:03:57 +00:00
Miles Malerba
021025964a refactor(compiler): add support for class map interpolation bindings (#50805)
Adds support for bindings of the form `class="static {{dynamic}}"`

PR Close #50805
2023-07-17 17:03:57 +00:00
Miles Malerba
7e5e37af36 refactor(compiler): add support for class map bindings (#50805)
Adds support for bindings of the form `[class]="classActiveMap"`

PR Close #50805
2023-07-17 17:03:57 +00:00
Joey Perrott
743be79749 ci: migrate windows job to GHA (#51010)
Migrate windows job to use Github Actions

PR Close #51010
2023-07-17 14:51:36 +00:00
Payam Valadkhan
3b78d068ea refactor(compiler-cli): basic local compilation for components (#50545)
A minimal change to full compilation mode to work in local mode. Now compiler can compile components without ctor injections, though the compiled code missing the following items which will be added in subsequent commits:
* it does not produce `dependencies` for component definition.
* it fails if component has ctor injection

PR Close #50545
2023-07-13 09:34:53 -07:00
Payam Valadkhan
68fd99fad3 refactor(compiler-cli): Trait compiler workflow for local compilation mode (#50545)
The compiler will only include analysis and compile phases in local mode. Also a new `compileLocal` method is added to the annotation handler for local compilation.

This commit makes no change to the full/partial compilation code paths.

PR Close #50545
2023-07-13 09:34:53 -07:00
Charles Lyding
5bd530ab32 refactor(compiler-cli): add internal compiler option to control NgModule selector scope emit (#51007)
An internal compiler option named `supportJitMode` is now available for use by the Angular CLI.
This option currently controls the emit of NgModule selector scope information. This emitted
information is only needed in AOT mode when an application also uses JIT. However, AOT mode
combined with JIT mode is not currently supported nor will work in the Angular CLI. With
the Angular CLI, JIT mode is only supported if the entire application is built in JIT mode.
Without this option, the CLI needs to manually perform a code transform to remove the information
and also replicate TypeScript's import eliding. This is can be a complicated operation and must
be continually kept up to date with any changes to both the Angular compiler and TypeScript.
The introduction of this new option alleviates these concerns while also removing several build
time actions that would otherwise need to be performed on every application build.

PR Close #51007
2023-07-13 09:32:11 -07:00
Dylan Hunn
875851776c refactor(compiler): Generate attribute and attributeInterpolate instructions in template pipeline (#50818)
This commit adds the ability to generate attribute instructions as a result of property bindings such as `[attr.foo]='bar'` or `attr.foo='{{bar}}'`. "Singleton" interpolations, such as the previous example, will also be transformed into a simple `attribute` instruction.

PR Close #50818
2023-07-10 07:17:18 -07:00
Paul Gschwendtner
8a0c5c710a refactor: improve type safety of interpolation AST (#50903)
Instead of using `any`, we should use the actual types that
are available from the parser.

PR Close #50903
2023-07-10 07:08:28 -07:00
Payam Valadkhan
5724dbc82d test(compiler-cli): add compliance tests for NgModule only scenarios in local mode (#50577)
Reused the existing compliance tests for full compilation.

PR Close #50577
2023-06-30 11:38:36 -07:00
Payam Valadkhan
c1d46b8c08 refactor(compiler-cli): add local option to compliance test infra (#50577)
The option 'local compile' is added for the test cases, and the locally compiled file for an input `abc.ts` is compared by default with the file `abc.local.js`. This allows to use the same input `abc.ts` for both full compilation (compared with `abc.js`) and local compilation (compared with `abc.local.js`). An example is provided in the next commit when compliance tests are added for the NgModule local compilation.

PR Close #50577
2023-06-30 11:38:35 -07:00
Payam Valadkhan
a15a56cb5d refactor(compiler): add a new interface for NgModule metadata to t rebase be used in local compilation mode (#50577)
The new interface is discrete-unioned with the existing interface to cover the cases for local and global (i.e., full and partial) compilation modes.

This change of interface required some adjustmeents cross repo which explains the changes made to other files.

PR Close #50577
2023-06-30 11:38:35 -07:00
Payam Valadkhan
2034d8db27 refactor(compiler-cli): circuit out reference resolving in NgModule annotation handler in local compilation mode (#50577)
All attempts related to obtaining R3Reference for bootstrap, imports, exports and declarations are cut in local compilation mode.

This will allow the analysis to pass without any error diagnostics, but the result is a quite empty meta info. Next commits will add data to the meta so that the NgModule can be compiled more accurately.

PR Close #50577
2023-06-30 11:38:35 -07:00
Dylan Hunn
29bf476bfe refactor(compiler): Generate temporary variable assignments when function calls appear in a safe-access expression. (#50688)
The expression `a()?.b` should expand into `(tmp = a()) === null ? null : tmp.b`, in order to avoid calling the function `a()` twice.

This commit modifies the null-safe-expansion algorithm to emit temporary assignments, and provides the reification code to actually generate the declarations, assignments, and reads.

Note also that, with our bottom-up algorithm, there are some tricky cases when a function call exists inside an indexed access, such as `f1()?.[f2()?.a]?.b`. We add some special logic to avoid generating a double-assignment to the temporary storing the result of `f2()`.

Finally, there are opportunities to reuse the same temporary in expressions like `a?.[f()]?.[f()]`. We save this for the next commit.

PR Close #50688
2023-06-29 12:54:23 -07:00
Paul Gschwendtner
e699f1a75d build: allow for compliance specs only using template pipeline (#50835)
When writing signal compliance tests, we need to limit these to only the
template pipeline.

PR Close #50835
2023-06-26 13:36:06 -07:00
Miles Malerba
060830e936 refactor(compiler): add support for interpolation in style mappings (#50489)
Add support for interpolation in style map bindings in the template
pipeline

PR Close #50489
2023-06-26 13:09:25 -07:00
Miles Malerba
3c1feedff8 refactor(compiler): add support for interpolation in style properties (#50489)
Add support for interpolation in style property bindings in the template
pipeline

PR Close #50489
2023-06-26 13:09:24 -07:00
Miles Malerba
3627e4c4e7 refactor(compiler): add support for empty bindings (#50489)
Add support for empty bindings in the template pipeline

PR Close #50489
2023-06-26 13:09:24 -07:00
Miles Malerba
ebe10dd68f refactor(compiler): add support style property units (#50489)
Add support for specifying units in style property bindings in the
template pipeline

PR Close #50489
2023-06-26 13:09:24 -07:00
Miles Malerba
b289332f2c refactor(compiler): add support for style map bindings (#50489)
Add support for style map bindings in the template pipeline

PR Close #50489
2023-06-26 13:09:24 -07:00
Miles Malerba
1b038945ee refactor(compiler): add support for style property bindings (#50489)
Add support for style property bindings in the template pipeline

PR Close #50489
2023-06-26 13:09:24 -07:00
Angular Robot
bb617f580c build: update babel dependencies (#50509)
See associated pull request for more information.

PR Close #50509
2023-06-21 11:44:59 -07:00
Charles Lyding
64745a89b2 refactor(compiler-cli): remove unused HandlerFlags enum (#50604)
The `HandlerFlags` enum is a leftover remnant of ngcc and is no longer used.

PR Close #50604
2023-06-20 13:01:48 -07:00
Charles Lyding
47cc56858f refactor(compiler-cli): add internal compiler option to control class metadata emit (#50604)
An internal compiler option named `supportTestBed` is now available for use by the
Angular CLI. This option currently controls the extraction and emit of Angular class
metadata. This emitted information is only needed in AOT mode when using certain
TestBed APIs. However, AOT mode is currently not available for unit testing within
the Angular CLI. As a result, the metadata is not used within CLI generation applications
and in particular production applications. Without this option, the CLI needs to
manually perform a code transform to remove the metadata and also replicate TypeScript's
import eliding. This is can be a complicated operation and must be continually kept
up to date with any changes to both the Angular compiler and TypeScript. The introduction
of this new option alleviates these concerns.

PR Close #50604
2023-06-20 13:01:48 -07:00
Paul Gschwendtner
cec5cd6eb5 test: mark ngtsc test target as flaky (#50718)
A larger investigation on why this is flaky is needed. Currently the
test is flaky with around 77% sucess rate and negatively impacts team
productivity. Subjectively, as reported by team members this it's much
more flaky than a success rate of 77%.

PR Close #50718
2023-06-15 15:34:43 +02:00
Paul Gschwendtner
12bad6576d fix(compiler-cli): libraries compiled with v16.1+ breaking with Angular framework v16.0.x (#50714)
If a library is compiling with Angular v16.1.0, the library will break
for users that are still on Angular v16.0.x. This happens because the
`DirectiveDeclaration` or `ComponentDeclaration` types are not expecting
an extra field for `signals` metadata. This field was only added to the
generic types in `16.1.0`- so compilations fail with errors like this:

```
Error: node_modules/@angular/material/icon/index.d.ts:204:18 -
  error TS2707: Generic type 'ɵɵComponentDeclaration' requires between 7 and 9 type arguments.
```

To fix this, we quickly roll back the code for inserting this metadata
field. That way, libraries remain compatible with all v16.x framework
versions.

We continue to include the `signals` metadata if `signals: true` is set.
This is not public API anyway right now- so cannot happen- but imagine
we expose some signal APIs in e.g. 16.2.x, then we'd need this metadata
and can reasonably expect signal-component library users to use a more
recent framework core version.

PR Close #50714
2023-06-14 16:27:59 +02:00
Matthieu Riegler
8468df19c9 fix(migrations): Prevent a component from importing itself. (#50554)
This commit fixes the migrations for recursive components.

fixes #50525

PR Close #50554
2023-06-14 15:44:35 +02:00
Paul Gschwendtner
82adc86353 refactor(compiler-cli): fix incremental compilation breaking when running compiler through closure (#50673)
If the compiler CLI is running through closure compiler, the trait
decorator handlers are converted from classes to functions as ES5
is picked as default output target for the bundled version.

The problem is that currently all trait handlers end up having the
same `name`. i.e. an empty string, and therefore adopting previous
traits from a previous build iteration result in the incorrect handler
being used for e.g. registrering, compiling etc- causing
ambiguous/confusing errors down the line in other parts.

We can look into changing the output target in the future, but even
then we are safer using an actual literal due to property renaming.

```$$closure$$NgModuleDecoratorHandler = function() {}`.

It is is questionable if we should just simply NOT run the compiler
through JSCompiler.

PR Close #50673
2023-06-14 15:26:00 +02:00
Matthieu Riegler
595d8b54c0 refactor(compiler-cli): deprecate allowEmptyCodegenFiles (#50379)
The `allowEmptyCodegenFiles` is not used anymore.

PR Close #50379
2023-06-14 11:19:46 +02:00
Dylan Hunn
88962b72a9 refactor(compiler): Support safe property reads and keyed reads. (#50594)
Angular's null-safe access operators differ from Javascript's built-in semantics, in that they short-circuit to `null` instead of `undefined`. This necessitates providing a custom transformation, instead of relying on Typescript or Javascript itseld.

The old TemplateDefinitionBuilder uses a top-down approach based on the Visitor pattern, in which it recursively extracts the left-most safe access, and hoists it to a null check at the top. See `expression_converter.ts` for details.

In this commit, we replace that approach with a new bottom-up algorithm, as part of the template pipeline. This requires an intermediate expression type to represent the not-yet-expanded ternary operators, and is split into its own pass.

Null-safe function calls are not yet implemented, since they will rely on a future temporary variable allocation pass.

Co-authored-by: Alex Rickabaugh <alxhub@users.noreply.github.com>

PR Close #50594
2023-06-13 18:59:43 +02:00
Miles Malerba
15ab146e6c refactor(compiler): improve handling of bindings and attributes (#50664)
Refactor attribute and property binding ingestion and add an attribute extraction phase

Co-authored-by: Alex Rickabaugh <alxhub@users.noreply.github.com>
Co-authored-by: Dylan Hunn <dylhunn@users.noreply.github.com>

Only add the value to the ElementAttributes map for style and attribute kinds

Other kinds should not have their value represented in the consts array

Add missing attribute ingesiton for templates

Unify how template and element bindings are ingested

This resolves the issue of missing listener attributes on templates. In
order to avoid emitting extraneous instructions, listener ops on
templates are stripped in the attribute extraction phase instead.

Handle different binding types separately in ingest

Cleanup code and comments

Disable test that fails on new explicit error.

Previously the test was passing because ingestPropertyBinding treated
attribute bindings as normal bindings which happened to be ok for the
particular test. Now there's an explicit error that attrbiute bindings
aren't yet handled which causes the test to fail

Address feeback

PR Close #50664
2023-06-13 18:34:58 +02:00
Miles Malerba
9429f96f62 test(compiler): Prevent back-sliding on already passing template pipeline tests (#50582)
Add a flag to disable specific tests when testing the template pipeline

Mark the currently failing tests

Add the template pipeline tests to CI

Update package.json

Co-authored-by: Paul Gschwendtner <paulgschwendtner@gmail.com>

PR Close #50582
2023-06-12 18:25:41 +02:00
aanchal
24c8e4e753 docs: removed duplicated words (#50648)
PR Close #50648
2023-06-12 11:43:42 +02:00
Payam Valadkhan
9648fc49dd refactor(compiler-cli): Remove .d.ts files transformer in local compilation mode. (#50486)
In local mode we don't make use of .d.ts files for Angular compilation, so their transformation can be ditched.

PR Close #50486
2023-06-07 12:50:54 -07:00
Kristiyan Kostadinov
cf15c290f0 build: update to TypeScript 5.1 final (#50548)
Bumps us up to the final version of TypeScript 5.1 which dropped overnight.

PR Close #50548
2023-06-02 14:06:46 -07:00
Kristiyan Kostadinov
68017d4e75 feat(core): add ability to transform input values (#50420)
According to the HTML specification most attributes are defined as strings, however some can be interpreted as different types like booleans or numbers. [In the HTML standard](https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#boolean-attributes), boolean attributes are considered `true` if they are present on a DOM node and `false` if they are omitted. Common examples of boolean attributes are `disabled` on interactive elements like `<button>` or `checked` on `<input type="checkbox">`. Another example of an attribute that is defined as a string, but interpreted as a different type is the `value` attribute of `<input type="number">` which logs a warning and ignores the value if it can't be parsed as a number.

Historically, authoring Angular inputs that match the native behavior in a type-safe way has been difficult for developers, because Angular interprets all static attributes as strings. While some recent TypeScript versions made this easier by allowing setters and getters to have different types, supporting this pattern still requires a lot of boilerplate and additional properties to be declared. For example, currently developers have to write something like this to have a `disabled` input that behaves like the native one:

```typescript
import {Directive, Input} from '@angular/core';

@Directive({selector: 'mat-checkbox'})
export class MatCheckbox {
  @Input()
  get disabled() {
    return this._disabled;
  }
  set disabled(value: any) {
    this._disabled = typeof value === 'boolean' ? value : (value != null && value !== 'false');
  }
  private _disabled = false;
}
```

This feature aims to address the issue by introducing a `transform` property on inputs. If an input has a `transform` function, any values set through the template will be passed through the function before being assigned to the directive instance. The example from above can be rewritten to the following:

```typescript
import {Directive, Input, booleanAttribute} from '@angular/core';

@Directive({selector: 'mat-checkbox'})
export class MatCheckbox {
  @Input({transform: booleanAttribute}) disabled: boolean = false;
}
```

These changes also add the `booleanAttribute` and `numberAttribute` utilities to `@angular/core` since they're common enough to be useful for most projects.

Fixes #8968.
Fixes #14761.

PR Close #50420
2023-05-30 13:01:13 -07:00
Kristiyan Kostadinov
721bc72649 fix(compiler): resolve deprecation warning with TypeScript 5.1 (#50460)
We have a code path that accesses the `originalKeywordKind` property which logs a deprecation warning in version 5.1, but isn't available in some of the earlier versions that we support. These changes add a compatibility layer that goes through the non-deprecated function, if it exists.

PR Close #50460
2023-05-25 14:39:27 +00:00
BrianDGLS
2d411430e3 refactor(router): run spell check on router package (#50445)
Fix typos in router package.

PR Close #50445
2023-05-24 13:56:56 +00:00
Jan Kuehle
8933ca3275 refactor(compiler): remove convertIndexImportShorthand (#50343)
Remove convertIndexImportShorthand tsickle option. It's going to be
removed from tsickle in https://github.com/angular/tsickle/pull/1442.
`false` is the default value, so setting it here has no effect
currently.

PR Close #50343
2023-05-23 14:09:59 +00:00
Kristiyan Kostadinov
f6da091228 refactor(compiler): introduce compiler infrastructure for input transforms (#50225)
Adds the necessary compiler changes to support input transform functions. The compiler output has changed in the following ways:

### Directive handler
The directive handler now extracts a reference to the input transform function and it resolves the type of its first parameter. It also asserts that the type can be referenced in the compiled output and that it doesn't clash with any pre-existing `ngAcceptInputType_` members.

### .d.ts
In the generated declaration files the compiler now inserts an `ngAcceptInputType_` member for each input with a `transform` function. The member's type corresponds to the type of the first parameter of the function, e.g.

```typescript
// foo.directive.ts
@Directive()
export class Foo {
  @Input({transform: (incomingValue: string) => parseInt(incomingValue)}) value: number;
}

// foo.directive.d.ts
export class Foo {
  value: number;
  static ngAcceptInputType_value: string;
}
```

### Type check block
If an input has `transform` function, the TCB will use the type of its first parameter for the setter type. This uses the same infrastructure as the `ngAcceptInputType_` members.

### Directive declaration
The generated runtime directive declaration call now includes the `transform` function in the `inputs` map, if the input is being transformed. The function will be picked up by the runtime in the next commit to do the actual transformation.

```typescript
// foo.directive.ts
@Directive()
export class Foo {
  @Input({transform: (incomingValue: string) => parseInt(incomingValue)}) value: number;
}

// foo.directive.js
export class Foo {
  ɵdir = ɵɵdefineDirective({
    inputs: {
      value: ['value', 'value', incomingValue => parseInt(incomingValue)]
    }
  });
}
```

PR Close #50225
2023-05-22 14:48:02 +00:00
gdarnell
d0a5530f77 refactor: remove unnecessary array copying (#50370)
Removes `Array.from` and spread operators that have no functional effect.

PR Close #50370
2023-05-22 14:47:29 +00:00
Kristiyan Kostadinov
8b44ba3170 fix(core): host directives incorrectly validating aliased bindings (#50364)
Fixes that the host directives feature was incorrectly throwing the conflicting alias error when an aliased binding was being exposed under the same alias.

Fixes #48951.

PR Close #50364
2023-05-19 15:09:48 +00:00
Angular Robot
3239160ec9 build: update babel dependencies (#48273)
See associated pull request for more information.

PR Close #48273
2023-05-19 14:19:19 +00:00
Kristiyan Kostadinov
69dadd2502 feat(core): support TypeScript 5.1 (#50156)
Updates the project to support building with TypeScript 5.1.

PR Close #50156
2023-05-09 14:44:30 -07:00
Kristiyan Kostadinov
0f40756a8a refactor(compiler): introduce internal transplanted type (#50104)
Adds a new AST for a `TransplantedType` in the compiler which will be used for some upcoming work. A transplanted type is a type node that is defined in one place in the app, but needs to be copied to a different one (e.g. the generated .d.ts). These changes also include updates to the type translator that will rewrite any type references within the type to point to the new context file.

PR Close #50104
2023-05-09 14:41:14 -07:00
Angular Robot
84a2e7db55 build: lock file maintenance (#49914)
See associated pull request for more information.

PR Close #49914
2023-05-09 14:38:45 -07:00
Kristiyan Kostadinov
cb8cdadd3b refactor(compiler): reflect arrow function definition (#50084)
Adds some logic to reflect an arrow function to `ReflectionHost.getDefinitionOfFunction`. This will be useful for some upcoming work.

PR Close #50084
2023-05-04 08:56:24 +02:00
Leosvel Pérez Espinosa
cfab3ad706 refactor(compiler-cli): add back ngcc as a no-op with a warning (#50045)
This commit adds back `ngcc` as a no-op operation. When invoked it will warn providing details about removing `ngcc`.

In Angular 17, this will be removed.

PR Close #50045
2023-04-28 18:18:40 +02:00
Andrew Scott
ce00738f98 fix(compiler-cli): catch fatal diagnostic when getting diagnostics for components (#50046)
This commit adds similar handling to what was done in ed817e32fe.
The language service calls the `getDiagnosticsForComponent` function
when the file is not a typescript file.

fixes https://github.com/angular/vscode-ng-language-service/issues/1881

PR Close #50046
2023-04-28 15:18:03 +02:00
Andrew Scott
5214df4958 refactor(compiler-cli): Add signals to internal directive metadata (#49981)
This commit adds the `signals: boolean` property to the internal
directive/component metadata. This does not add it to the public API
yet, as the feature has no internal support other than compiler
detection.

PR Close #49981
2023-04-25 15:39:18 -07:00
Matthieu Riegler
b9c53658a4 refactor(compiler-cli): remove unecessary type assertion (#49971)
microsoft/TypeScript#43966 was fixed in 4.3.1

PR Close #49971
2023-04-24 11:51:18 -07:00
Payam Valadkhan
345dd6d81a refactor(compiler-cli): Add experimental local compilation mode. (#49846)
In this mode the compiler generates code based on each individual source file without using its dependencies. This mode is suitable only for fast edit/refresh during development.

PR Close #49846
2023-04-23 18:19:35 -07:00
Matthieu Riegler
2aa6d6d616 refactor(compiler-cli): cleanup inferences (#49863)
With the ts compiler updates these inferences have been fixed.

PR Close #49863
2023-04-17 17:23:29 +00:00
Matthieu Riegler
3ba5dcc150 refactor(compiler-cli): remove unused integration tests. (#49862)
Theses tests have been disabled when the ViewEngine code has been remove in v13.1

PR Close #49862
2023-04-17 14:57:02 +00:00
Matthieu Riegler
a7dbb23bc8 refactor(compiler-cli): remove incrementalDriver on the compiler (#49869)
The CLI now only uses the `incrementalDriver` property.

PR Close #49869
2023-04-17 14:54:53 +00:00
Alex Rickabaugh
78c76cecf9 perf(compiler-cli): optimize NgModule emit for standalone components (#49837)
NgModules which import standalone components currently list those components
in their injector definitions, because we assume that any standalone
component may export providers from its own imports.

This commit adds an optimization for that emit, which attempts to statically
analyze the NgModule imports and determine which standalone components, if
any are present, do not export providers and thus can be omitted.

This analysis is imperfect, because some imported components may be declared
outside of the current compilation, or transitively import types which are
declared outside the compilation. These types are therefore _assumed_ to
carry providers and so the optimization isn't applied to them.

PR Close #49837
2023-04-17 14:51:58 +00:00
Andrew Scott
e949548561 fix(compiler): Produce diagnositc if directive used in host binding is not exported (#49527)
The compiler currently does not check to make sure that directives in
the host bindings are exported. These directives are part of the public
API of the component so they do have to be.

PR Close #49527
2023-04-11 14:02:51 -07:00
Andrew Scott
8a75a8ad26 fix(compiler-cli): Catch FatalDiagnosticError during template type checking (#49527)
This commit updates the type checking operation to catch
`FatalDiagnosticError` and surface them as diagnostics rather than
crashing.

Fixes https://github.com/angular/vscode-ng-language-service/issues/1881

PR Close #49527
2023-04-11 14:02:51 -07:00
Kristiyan Kostadinov
8020347f26 fix(compiler): incorrectly matching directives on attribute bindings (#49713)
Fixes that the compiler was matching directives based on `attr` bindings which doesn't correspond to the runtime behavior. This wasn't a problem until now because the matched directives would basically be a noop, but they can cause issues with required inputs.

PR Close #49713
2023-04-11 12:40:57 -07:00
Andrew Kushnir
b98ecbc0ce build: update minimum supported Node version from 16.13.0 -> 16.14.0 (#49771)
This commit updates the minimum supported Node version across packages from 16.13.0 -> 16.14.0 to ensure compatibility with dependencies.

PR Close #49771
2023-04-11 07:56:31 -07:00
JoostK
6ca1a53a19 refactor(compiler-cli): workaround for CI failure in Windows (#49136)
It seems that changes in prior commits led to a new error in the Windows CI job,
likely due to its sandboxing setup in Bazel. This commit adds an explicit type
annotation that should avoid the error.

PR Close #49136
2023-04-03 19:20:01 -07:00
JoostK
ff6608c5fe refactor(compiler-cli): remove a flag that is always true in ngtsc (#49136)
This flag was set to `true` by ngcc, but now that ngcc is gone this flag can be removed.

PR Close #49136
2023-04-03 19:20:01 -07:00
JoostK
2d6e6a1510 refactor(compiler-cli): update comments to account for ngcc removal (#49136)
This commit updates comments to account for the removal of ngcc.

PR Close #49136
2023-04-03 19:20:01 -07:00
JoostK
e5a30d92d2 refactor(compiler-cli): update compilation error message to not mention ngcc (#49136)
No longer refer to an ngcc incompatibility now that ngcc has been removed.

PR Close #49136
2023-04-03 19:20:00 -07:00
JoostK
3f47535fbf refactor(compiler-cli): update TraitCompiler to account for ngcc deletion (#49136)
There used to be a subclass of `TraitCompiler` in ngcc, but now that ngcc has been removed
we can update `TraitCompiler` to no longer expose certain fields and methods.

PR Close #49136
2023-04-03 19:20:00 -07:00
JoostK
cfa9f31fff refactor(compiler-cli): avoid clang-format inconsistency (#49136)
There's an issue where formatting with `clang-format` doesn't agree with itself on how
the docblock for a field named `import` should be indented; if it is indented then it
removes the indentation, but then linting the source file reports an error where it
wants to revert the indentation change. By using computed property syntax this bug
is avoided.

PR Close #49136
2023-04-03 19:20:00 -07:00
JoostK
c20deb7e8d refactor(compiler-cli): only use a single type expression (#49136)
The concept of "internal" and "adjacent" type expression used to be necessary to support
ngcc, as it had to process downleveled class declarations using an IIFE, where the class
name within the IIFE could be different from the outer class name. With the removal of
ngcc we no longer need to make this distinction, so this commit removes these concepts
entirely.

PR Close #49136
2023-04-03 19:20:00 -07:00
JoostK
9540f6d118 refactor(compiler-cli): remove unused dts declaration logic (#49136)
This logic used to be in place to support ngcc, but with the removal of ngcc
this is no longer relevant.

PR Close #49136
2023-04-03 19:20:00 -07:00
JoostK
d9060d9cfb refactor(compiler-cli): remove ngcc-only builtin functions (#49136)
ngcc's reflection host would recognize tslib helpers and some JS builtin methods to allow
the static interpreter to evaluate compiled and downleveled JS code, but now that ngcc
has been removed this functionality is no longer being used.

PR Close #49136
2023-04-03 19:20:00 -07:00
JoostK
bbe4590b9d refactor(compiler-cli): remove support for ngcc-only declaration formats (#49136)
This commit simplifies various parts of ngtsc to no longer support synthetic decorators,
downleveled enum members and inline declarations. These concepts were present to support
ngcc, but can be dropped now that ngcc has been removed.

PR Close #49136
2023-04-03 19:20:00 -07:00
Matthieu Riegler
03d1d00ad9 feat(compiler-cli): Add an extended diagnostic for nSkipHydration (#49512)
This diagnostic ensures that the special attribute `ngSkipHydration` is not a binding and has no other value than `"true"` or an empty value.

Fixes #49501

PR Close #49512
2023-03-23 13:54:03 -07:00
tomalaforge
d47fef72cb fix(common): strict type checking for ngtemplateoutlet (#48374)
When we create a context to inject inside our ngTemplateOutlet, the context was declare as Object, therefore, there are no compilation error.

Now if we add a context, we get error at compile type.

BREAKING CHANGE:  If the 'ngTemplateOutletContext' is different from the context, it will result in a compile-time error.

Before the change, the following template was compiling:

```typescript
interface MyContext {
  $implicit: string;
}

@Component({
  standalone: true,
  imports: [NgTemplateOutlet],
  selector: 'person',
  template: `
    <ng-container
      *ngTemplateOutlet="
        myTemplateRef;
        context: { $implicit: 'test', xxx: 'xxx' }
      "></ng-container>
  `,
})
export class PersonComponent {
  myTemplateRef!: TemplateRef<MyContext>;
}
```
However, it does not compile now because the 'xxx' property does not exist in 'MyContext', resulting in the error: 'Type '{ $implicit: string; xxx: string; }' is not assignable to type 'MyContext'.'

The solution is either:
- add the 'xxx' property to 'MyContext' with the correct type or
- add '$any(...)' inside the template to make the error disappear. However, adding '$any(...)' does not correct the error but only preserves the previous behavior of the code.

fix #43510

PR Close #48374
2023-03-23 11:35:07 -07:00
Kristiyan Kostadinov
585e34bf6c feat(core): remove entryComponents (#49484)
`entryComponents` have been deprecated since version 9, because with Ivy they weren't necessary. These changes remove any remaining references.

BREAKING CHANGE:
* `entryComponents` has been deleted from the `@NgModule` and `@Component` public APIs. Any usages can be removed since they weren't doing anyting.
* `ANALYZE_FOR_ENTRY_COMPONENTS` injection token has been deleted. Any references can be removed.

PR Close #49484
2023-03-23 10:38:03 -07:00
Alan Agius
0f2937ef83 refactor: update code to be ES2022 compliant (#49559)
This commit updates parts of the FW to be ES2022 complaint.

These changes are needed to fix the following problems problems with using properties before they are initialized.

Example
```ts
class Foo {
   bar = this.buz;
   constructor(private buz: unknown){}
}
```

PR Close #49559
2023-03-23 08:18:45 -07:00
Andrew Scott
4d455e06c7 Revert "refactor: update code to be ES2022 compliant (#49332)" (#49554)
This reverts commit 349ff01c4b.

PR Close #49554
2023-03-22 14:34:25 -07:00
Alan Agius
349ff01c4b refactor: update code to be ES2022 compliant (#49332)
This commit updates parts of the FW to be ES2022 complaint.

These changes are needed to fix the following problems problems with using properties before they are initialized.

Example
```ts
class Foo {
   bar = this.buz;
   constructor(private buz: unknown){}
}
```

PR Close #49332
2023-03-22 14:00:19 -07:00
Kristiyan Kostadinov
8f539c11f4 feat(compiler): add support for compile-time required inputs (#49468)
Adds support for marking a directive input as required. During template type checking, the compiler will verify that all required inputs have been specified and will raise a diagnostic if one or more are missing. Some specifics:
* Inputs are marked as required by passing an object literal with a `required: true` property to the `Input` decorator or into the `inputs` array.
* Required inputs imply that the directive can't work without them. This is why there's a new check that enforces that all required inputs of a host directive are exposed on the host.
* Required input diagnostics are reported through the `OutOfBandDiagnosticRecorder`, rather than generating a new structure in the TCB, because it allows us to provide a better error message.
* Currently required inputs are only supported during AOT compilation, because knowing which bindings are present during JIT can be tricky and may lead to increased bundle sizes.

Fixes #37706.

PR Close #49468
2023-03-20 13:10:30 +01:00
Andrew Scott
8d99ad0a39 Revert "feat(compiler): add support for compile-time required inputs (#49453)" (#49467)
This reverts commit 13dd614cd1.

This breaks a g3 Typescript compilation tests where diagnostics are
expected for a missing input in the component.

PR Close #49467
2023-03-17 18:29:14 +01:00
Kristiyan Kostadinov
13dd614cd1 feat(compiler): add support for compile-time required inputs (#49453)
Adds support for marking a directive input as required. During template type checking, the compiler will verify that all required inputs have been specified and will raise a diagnostic if one or more are missing. Some specifics:
* Inputs are marked as required by passing an object literal with a `required: true` property to the `Input` decorator or into the `inputs` array.
* Required inputs imply that the directive can't work without them. This is why there's a new check that enforces that all required inputs of a host directive are exposed on the host.
* Required input diagnostics are reported through the `OutOfBandDiagnosticRecorder`, rather than generating a new structure in the TCB, because it allows us to provide a better error message.
* Currently required inputs are only supported during AOT compilation, because knowing which bindings are present during JIT can be tricky and may lead to increased bundle sizes.

Fixes #37706.

PR Close #49453
2023-03-17 11:49:17 +01:00
Alex Rickabaugh
560b226a43 Revert "feat(compiler): add support for compile-time required inputs (#49304)" (#49449)
This reverts commit 1a6ca68154.

This breaks tests in google3 which might be depending on private APIs. We
need to update these tests before we can land this PR.

PR Close #49449
2023-03-16 10:38:04 -07:00
Alan Agius
cf98777153 test: update tests to remove deprecated withServerTransition (#49422)
This commit removes the usages of `withServerTransition` form tests.

PR Close #49422
2023-03-15 17:08:18 -07:00
Kristiyan Kostadinov
1a6ca68154 feat(compiler): add support for compile-time required inputs (#49304)
Adds support for marking a directive input as required. During template type checking, the compiler will verify that all required inputs have been specified and will raise a diagnostic if one or more are missing. Some specifics:
* Inputs are marked as required by passing an object literal with a `required: true` property to the `Input` decorator or into the `inputs` array.
* Required inputs imply that the directive can't work without them. This is why there's a new check that enforces that all required inputs of a host directive are exposed on the host.
* Required input diagnostics are reported through the `OutOfBandDiagnosticRecorder`, rather than generating a new structure in the TCB, because it allows us to provide a better error message.
* Currently required inputs are only supported during AOT compilation, because knowing which bindings are present during JIT can be tricky and may lead to increased bundle sizes.

Fixes #37706.

PR Close #49304
2023-03-15 16:59:24 -07:00
Kristiyan Kostadinov
be97c87023 refactor(compiler): required inputs prerequisite refactors (#49333)
Based on the discussion in https://github.com/angular/angular/pull/49304#discussion_r1124732608. Reworks the compiler internals to allow for additional information about inputs to be stored. This is a prerequisite for required inputs.

PR Close #49333
2023-03-14 09:27:49 -07:00
Paul Gschwendtner
c241f63e8d refactor(compiler-cli): remove unused class decorator downlevel code (#49351)
The decorator downlevel transform is never used for actual class
decorators because Angular class decorators rely on immediate execution
for JIT. Initially we also supported downleveling of class decorators
for View Engine library output, but libraries are shipped using partial
compilation output and are not using this transform anymore.

The transform is exclusively used for JIT processing, commonly for
test files to help ease temporal dead-zone/forward-ref issues. We can
remove the class decorator downlevel logic to remove technical debt.

PR Close #49351
2023-03-08 17:59:12 +00:00
Alan Agius
1418d1937f test(compiler): add test case for merging objects in tsconfig (#49125)
This commit adds a test case for validate that we do not deep merge objects like like 'paths' and `extendedDiagnostics`.

PR Close #49125
2023-03-06 16:57:28 +00:00
Alan Agius
1407a9aeaf feat(compiler): support multiple configuration files in extends (#49125)
TypeScript 5 support `extends` to be an array, this commit adds support to allow extending `angularCompilerOptions` from multiple config files.

See: https://devblogs.microsoft.com/typescript/announcing-typescript-5-0-beta/#supporting-multiple-configuration-files-in-extends

PR Close #49125
2023-03-06 16:57:28 +00:00
Alan Agius
f594725951 refactor(core): remove Node.js v14 support (#49255)
BREAKING CHANGE: Node.js v14 support has been removed

Node.js v14 is planned to be End-of-Life on 2023-04-30. Angular will stop supporting Node.js v14 in Angular v16. Angular v16 will continue to officially support Node.js versions v16 and v18.

PR Close #49255
2023-02-28 11:00:25 -08:00
Kristiyan Kostadinov
99d874fe3b feat(core): add support for TypeScript 5.0 (#49126)
Updates the project to support TypeScript 5.0 and to resolve any errors that came up as a result of the update.

PR Close #49126
2023-02-28 08:24:47 -08:00
Paul Gschwendtner
b6c6dfd278 fix(compiler-cli): do not persist component analysis if template/styles are missing (#49184)
Consider the following scenario:

1. A TS file with a component and templateUrl exists
2. The template file does not exist.
3. First build: ngtsc will properly report the error, via a FatalDiagnosticError
4. The template file is now created
5. Second build: ngtsc still reports the same errror.

ngtsc persists the analysis data of the component and never invalidates
it when the template/style file becomes available later.

This breaks incremental builds and potentially common workflows
where resource files are added later after the TS file is created. This
did surface as an issue in the Angular CLI yet because Webpack requires
users to re-start the process when a new file is added. With ESBuild
this will change and this also breaks incremental builds with
Bazel/Blaze workers.

To fix this, we have a few options:

* Invalidate the analysis when e.g. the template file is missing. Never
  caching it means that it will be re-analyzed on every build iteration.
* Add the resource dependency to ngtsc's incremental file graph. ngtsc
  will then know via `host.getModifiedResources` when the file becomes
  available- and fresh analysis of component would occur.

The first approach is straightforward to implement and was chosen here.
The second approach would allow ngtsc to re-use more of the analysis
when we know that e.g. the template file still not there, but it
increases complexity unnecessarily because there is no **single**
obvious resource path for e.g. a `templateUrl`. The URL is attempted
to be resolved using multiple strategies, such as TS program root dirs,
or there is support for a custom resolution through
`host.resourceNameToFileName`.

It would be possible to determine some candidate paths and add them to
the dependency tracker, but it seems incomplete given possible external
resolvers like `resourceNameToFileName` and also would likely not have
a sufficient-enough impact given that a broken component decorator is
not expected to remain for too long between N incremental build
iterations.

PR Close #49184
2023-02-24 08:24:07 -08:00
Kristiyan Kostadinov
79cdfeb392 feat(compiler): drop support for TypeScript 4.8 (#49155)
Drops support for TypeScript 4.8 from the compiler and removes all of the compatibility code we had for it.

BREAKING CHANGE:
* TypeScript 4.8 is no longer supported.

PR Close #49155
2023-02-23 10:39:43 -08:00
Andrew Kushnir
83a6e203e3 refactor(compiler): drop obsolete NgFactory and NgSummary config options (#48268)
The options to generate NgFactory and NgSummary files were added to Ivy for backwards compatibility with ViewEngine. Since ViewEngine was deprecated and removed, the NgFactory and NgSummary files are no longer used as well.

This commit drops obsolete options to generate NgFactory and NgSummary files. Also, the logic that generates those files is also removed.

PR Close #48268
2023-02-21 13:03:59 -08:00
Alan Agius
48aa96ea13 refactor: remove Angular Compatibility Compiler (ngcc) (#49101)
This commit removes the NGCC code and all the related infra setup required to support it.

BREAKING CHANGE: Angular Compatibility Compiler (ngcc) has been removed and as a result Angular View Engine libraries will no longer work

PR Close #49101
2023-02-16 16:01:17 -08:00
Kristiyan Kostadinov
f3f139942c refactor(compiler): remove remaining usage of getMutableClone (#49070)
Uses an alternate approach of preserving default imports that doesn't involve the `getMutableClone` function that is being removed in TypeScript 5.0.

The alternate approach was already used in the downlevel transform and it works by patching the EmitResolver of the current transformation context to tell TypeScript to preserve the import.

PR Close #49070
2023-02-16 15:30:52 -08:00
Kristiyan Kostadinov
0cf11167f1 fix(compiler-cli): incorrectly detecting forward refs when symbol already exists in file (#48988)
In #48898 the `isForwardRef` flag was added to indicate whether a reference should be wrapped in a `forwardRef`. This logic assumed that the node can't be referring to another node within the same file, however from testing it looks like that's not actually the case, because we hit the same code path when an external import to the same symbol exists already.

PR Close #48988
2023-02-07 09:00:46 -08:00
Kristiyan Kostadinov
d0145033bd fix(language-service): generate forwardRef for same file imports (#48898)
Adds some logic that will generate a `forwardRef` if necessary when automatically fixing an import.

PR Close #48898
2023-02-02 13:40:17 -08:00
Kristiyan Kostadinov
59c0106654 refactor(compiler): indicate whether potential import is forward reference (#48898)
In the `PotentialImport` we indicate if it's in the same file by not setting a `moduleSpecifier`, but if that's the case, the imported symbol might need to be wrapped in a `forwardRef` to avoid generating an error. These changes expose this information so the various tools can take advantage of it.

PR Close #48898
2023-02-02 13:40:17 -08:00
Payam Valadkhan
9250afbffd refactor(compiler-cli): Export the interface PluginCompilerHost for 1p use. (#48874)
Some 1p module which uses the method TscPlugin.wrapHost requires to import this type to make its internal class definitions compatible with this type.

PR Close #48874
2023-02-02 09:44:18 -08:00
Kristiyan Kostadinov
06e161f2dd fix(compiler): incorrect code when non-null assertion is used after a safe access (#48801)
Fixes that the expression converter was producing code that throws a runtime error if a non-null assertion is used as a part of a safe read, write or call.

Fixes #48742.

PR Close #48801
2023-01-25 18:31:37 +00:00
JoostK
4da1f2948c fix(compiler-cli): resolve deprecation warning (#48812)
This commit updates one usage of the `ts.factory.createMethodDeclaration` API
to avoid a deprecated function signature, which avoids logging a warning.

PR Close #48812
2023-01-24 16:45:12 +00:00
Kristiyan Kostadinov
6beff5e8d7 refactor(compiler): rework and expose APIs to be used in schematics (#48730)
Reworks some of the existing compiler APIs to make them easier to use in a schematic and exposes a few new ones to surface information we already had. High-level list of changes:
* `getPotentialImportsFor` now requires a class reference, instead of a `PotentialDirective | PotentialPipe`.
* New `getNgModuleMetadata` method has been added to the type checker.
* New `getPipeMetadata` method has been added to the type checker.
* New `getUsedDirectives` method has been added to the type checker.
* New `getUsedPipes` method has been added to the type checker.
* The `decorator` property was exposed on the `TypeCheckableDirectiveMeta`. The property was already present at runtime, but it wasn't specified on the interface.

PR Close #48730
2023-01-13 12:24:32 -08:00
Dylan Hunn
141333411e feat(language-service): Introduce a new NgModuleIndex, and use it to suggest re-exports. (#48354)
NgModules can re-export other NgModules, which transitively includes all traits exported by the re-exported NgModule. We want to be able to suggest *all* re-exports of a component when trying to auto-import it.

Previously, we used an approximation when importing from NgModules: we looked at a Component's metadata, and just imported the declaring NgModule. However, this is not technically correct -- the declaring NgModule it is not necessarily the same one that exports it for the current scope. (Indeed, there could be multiple re-exports!) As a replacement, I have implemented a more general solution.

This PR introduces a new class on the template type checker, called `NgModuleIndex`. When queried, it conducts a depth-first-search over the NgModule import/export graph, in order to find all NgModules anywhere in the current dependency graph, as well as all exports of those NgModules. This allows the language service to suggest all of the re-exports, in addition to the original export.

PR Close #48354
2023-01-12 13:46:46 -08:00
Dylan Hunn
ea8b33934b refactor(compiler-cli): Make getKnown return an array of nodes. (#48354)
`MetadataReaderWithIndex.getKnown` currently returns an iterator. It will be easier to work with for upcoming usages if it returns an array instead.

PR Close #48354
2023-01-12 13:46:46 -08:00
Kristiyan Kostadinov
7243ae64a6 fix(compiler): resolve deprecation warning (#48652)
Fixes a deprecation warning that was being logged by compiler when generating aliases, because we weren't going through `ts.factory` to create an AST node.

PR Close #48652
2023-01-10 08:13:25 -08:00
Matthieu Riegler
123c95209f docs(compiler-cli): fix commands to run compliance unit test (#48559)
PR Close #48559
2023-01-10 07:59:52 -08:00
Kristiyan Kostadinov
33f35b04ef fix(compiler): type-only symbols incorrectly retained when downlevelling custom decorators (#48638)
In #47167 an `updateClassDeclaration` call was swapped out with a `createClassDeclaration` which caused a regression where interface references were being retained when using a custom decorator in a project that has `emitDecoratorMetadata` enabled.

These changes switch back to use `updateClassDeclaration`.

Fixes #48448.

PR Close #48638
2023-01-04 12:29:16 -08:00
Kristiyan Kostadinov
a532d71975 feat(compiler): allow self-closing tags on custom elements (#48535)
Allows for self-closing tags to be used for non-native tag names, e.g. `<foo [input]="bar"></foo>` can now be written as `<foo [input]="bar"/>`. Native tag names still have to have closing tags.

Fixes #39525.

PR Close #48535
2023-01-04 12:07:37 -08:00
Paul Gschwendtner
caedef0f5b fix(compiler-cli): update @babel/core dependency and lock version (#48634)
Similar to how the `@babel/core` dependency is managed for the localize
NPM package, the version should be locked. Also the version should
correspond to the version we install for building & testing.

Currently the Babel version allowed by the compiler-cli may not
work given the ESM -> CJS interop. causing errors like:

```
import { types as t } from "@babel/core";
         ^^^^^
SyntaxError: Named export 'types' not found. The requested module '@babel/core' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from '@babel/core';
const { types: t } = pkg;
```

We can only be confident about the interop if we know the version
installed- is the one we test.

PR Close #48634
2023-01-03 16:36:50 +00:00
Kristiyan Kostadinov
50f95f831e refactor(compiler): remove TypeScript 4.7 compatibility code (#48470)
We dropped support for TypeScript 4.7 in version 15, but we had to keep around the runtime code, because of g3. Now that g3 is on 4.8, we can remove the additional code.

PR Close #48470
2023-01-02 13:47:22 +00:00
Paul Gschwendtner
90c2088679 build: make devmode a noop and ensure it never runs (#48521)
This is basically a pre-step for combining devmode and prodmode into a
single compilation. We are already achieving this now, and can claim
with confidence that we reduced possible actions by half. This is
especially important now that prodmode is used more often, but rules
potentially still using the devmode ESM sources. We can avoid double
compilations (which existed before the whole ESM migration too!).

We will measure this more when we have more concrete documentation
of the changes & a better planning document.

Changes:

  * ts_library will no longer generate devmode `d.ts`. Definitions are
    generated as part of prodmode. That way only prodmode can be exposed
    via providers.
  * applied the same to `ng_module`.
  * updates migrations to bundle because *everything* using `ts_library`
    is now ESM. This is actually also useful in the future if
    schematics rely on e.g. the compiler.
  * updates schematics for localize to also bundle. similar reason as
    above.

PR Close #48521
2022-12-19 19:50:45 +00:00
Paul Gschwendtner
13d3039c7d refactor: convert AIO tooling scripts used in Bazel to ESM (#48521)
Since the Bazel setup in this repo will now always use ESM,
the tooling scripts/binaries in AIO need to be switched to ESM
too. Most of the scripts are already ESM, but a few had to be converted.

Note that the Dgeni generation does not use ESM because it's unaffected
and the Dgeni CLI is used. In the future we could also update the Dgeni
setup to ESM but there is no need currently.

PR Close #48521
2022-12-19 19:50:44 +00:00
Paul Gschwendtner
decae5b8e9 refactor: update compiler-cli to work with ESM (#48521)
Updates compiler-cli & tests to be full ESM compatible. Tests
no longer with CommonJS.

PR Close #48521
2022-12-19 19:50:43 +00:00
Paul Gschwendtner
619f0900a2 refactor: change ngcc to only rely on ESM features (#48521)
Refactors ngcc to only rely on ESM features because CJS
is no longer needed & tested.

PR Close #48521
2022-12-19 19:50:43 +00:00
Paul Gschwendtner
661134fd21 refactor: update compiler-cli babel linker to be ESM only (#48521)
Since the linker is no longer being tested with CommonJS, we can remove
most of the CJS/ESM interop trickery.

PR Close #48521
2022-12-19 19:50:43 +00:00
Paul Gschwendtner
c9415e4d75 build: ensure bootstrap transitive runfiles are made available (#48521)
Since we generate a `.mjs` file as entry-point for jasmine tests,
a couple of issues prevented the transitive dependencies from
bootstrap targets to be brought in (causing resolution errors):

1. The `_files` (previously `_esm2015`) targets are no longer needed,
   and they also miss all the information on runfiles.
2. The aspect for computing linker mappings does not respect the
   `bootstrap` attribute from the `spec_entrypoint` so we manually
   add the extract ESM output targets (this rule works with the aspect
   and forwards linker mappings).

PR Close #48521
2022-12-19 19:50:41 +00:00
Paul Gschwendtner
20551503fa build: replace _es2015 shorthand with more flexible _files suffix (#48521)
For every `ts_library` target we expose a shorthand that grants
access to the JS files because `DefaultInfo` of a ts library
only exposes the `.d.ts` files.

We rename this away from `es2015` since in practice it's a much
higher target these days. Additionally we no longer use the devmode
output but rather use the prodmode output which has the explicit
`.mjs` output- compatible with ESM.

PR Close #48521
2022-12-19 19:50:41 +00:00
Paul Gschwendtner
5c51c48f98 refactor: remove __ESM_IMPORT_META_URL__ workaround now that we can use ESM (#48521)
The `__ESM_IMPORT_META_URL__` trick was used because we used both ESM
and CommonJS in this repo. It was an interop needed because
`import.meta.url` syntax couldn't be used as it woud have caused syntax
errors.

We still need to keep the CommonJS/ESM interop in the compiler-cli
because g3 relies on the compiler and uses CommonJS. This affects very
few places, just in the compiler- so this is acceptable.

PR Close #48521
2022-12-19 19:50:41 +00:00
Paul Gschwendtner
9e91bbd329 build: refactor ngc-wrapped to support ESM (#48521)
Since this repo will now be strict ESM, and Angular Compiler packages
on NPM are also ESM-only, we can rework `ngc-wrapped` to remove
the CJS/ESM interop and we make it strict ESM too.

PR Close #48521
2022-12-19 19:50:40 +00:00
JoostK
a6849f27af fix(compiler-cli): evaluate const tuple types statically (#48091)
For standalone components it may be beneficial to group multiple declarations
into a single array, that can then be imported all at once in `Component.imports`.
If this array is declared within a library, however, would the AOT compiler
need to extract the contents of the array from the declaration file. This
requires that the array is constructed using an `as const` cast, which results
in a readonly tuple declaration in the generated .d.ts file of the library:

```ts
export declare const DECLARATIONS: readonly [typeof StandaloneDir];
```

The partial evaluator logic did not support this syntax, so this pattern was
not functional when a library is involved. This commit adds the necessary
logic in the static interpreter to evaluate this type at compile time.

Closes #48089

PR Close #48091
2022-12-07 14:10:26 -08:00
Alan Agius
ee78e73e8c refactor(compiler): replace deprecated sourcemap-codec (#48387)
`sourcemap-codec` as been deprecated in favor of `@jridgewell/sourcemap-codec`.

See: https://www.npmjs.com/package/sourcemap-codec?activeTab=versions

PR Close #48387
2022-12-07 14:09:17 -08:00
Angular Robot
126573d76b build: update all non-major dependencies (#48372)
See associated pull request for more information.

PR Close #48372
2022-12-06 11:06:39 -08:00
Kristiyan Kostadinov
dd42974b07 feat(core): support TypeScript 4.9 (#48005)
Updates to TypeScript 4.9 and resolves some of the errors and deprecation warnings that showed up as a result.

PR Close #48005
2022-12-06 10:45:33 -08:00
Andrew Scott
27eaded62d fix(compiler-cli): Produce diagnostic rather than crash when using invalid hostDirective (#48314)
Because the language service uses the compiler, we try to produce as
much useful information as possible rather than throwing hard errors.
Hard errors cause the compiler to crash. While this can be acceptable
when compiling a program as part of a regular build, this is undesirable
for the language service.

PR Close #48314
2022-12-01 13:43:30 -08:00
JoostK
7d88700933 fix(compiler-cli): accept inheriting the constructor from a class in a library (#48156)
The stricter checks under `strictInjectionParameters` in Angular 15 now enforce that
an inherited constructor must be compatible with DI, based on whether all parameters
are valid injection tokens. There is an issue when the constructor is inherited from
a class in a declaration file though, as information on the usage of `@Inject()` is
not present within a declaration file. This means that this stricter check cannot be
accurately performed, resulting in false positives.

This commit disables the stricter check to behave the same as it did prior to
Angular 15, therefore avoiding the false positive.

Fixes #48152

PR Close #48156
2022-11-23 12:10:37 -08:00
Kristiyan Kostadinov
0138d75335 refactor(language-service): make selector nullable (#48193)
This is a follow-up from https://github.com/angular/angular/pull/48147. Changes the `DirectiveSymbol.selector` to be nullable since it's possible to have directives without a selector.

PR Close #48193
2022-11-23 09:27:03 -08:00
Derek Cormier
f37dd0fc96 build(bazel): create AIO example playgrounds for manual testing
After the bazel migration, AIO examples are no longer fully formed in
the source tree.
2022-11-22 13:51:16 -07:00
Derek Cormier
bc1e93d639 build(bazel): refactor aio example e2es to fix windows performance
Use the same config flag to enable local vs npm deps as aio.
2022-11-22 13:51:16 -07:00
Derek Cormier
22a317de3d build(bazel): stamp targets to build, test, and serve aio against
first party deps

Architect is not compatible with disabling the rules_nodejs linker so
these targets must use npm_link to link first party deps
2022-11-22 13:51:16 -07:00
Derek Cormier
7a134cf41a build(bazel): incrementally run aio example e2e tests
Replaces the workflow where all example e2es are run at once
2022-11-22 13:51:16 -07:00
Kristiyan Kostadinov
fd2eea5961 fix(language-service): correctly handle host directive inputs/outputs (#48147)
Adds some logic to correctly handle hidden or aliased inputs/outputs in the language service.

Fixes #48102.

PR Close #48147
2022-11-22 09:47:49 -08:00
Dylan Hunn
ef6dbc8850 refactor(compiler): Add getPotentialPipes API method. (#48090)
`getPotentialPipes` returns possible pipes which can be used in the provided context, whether already in scope or requiring an import.

This is necessary to implement auto-import support for pipes in the language service.

PR Close #48090
2022-11-17 11:00:50 -08:00
Andrew Kushnir
2d8d562604 fix(core): hardening attribute and property binding rules for <iframe> elements (#47964)
This commit updates the logic related to the attribute and property binding rules for <iframe> elements. There is a set of <iframe> attributes that may affect the behavior of an iframe and this change enforces that these attributes are only applied as static attributes, making sure that they are taken into account while creating an <iframe>.

If Angular detects that some of the security-sensitive attributes are applied as an attribute or property binding, it throws an error message, which contains the name of an attribute that is causing the problem and the name of a Component where an iframe is located.

BREAKING CHANGE:

Existing iframe usages may have security-sensitive attributes applied as an attribute or property binding in a template or via host bindings in a directive. Such usages would require an update to ensure compliance with the new stricter rules around iframe bindings.

PR Close #47964
2022-11-09 00:47:56 -08:00
Dylan Hunn
ce8160ecb2 fix(language-service): Prevent crashes on unemitable references (#47938)
Currently, when generating an import of a selector, the language service might crash if the compiler cannot emit a reference to the new symbol's file from the target component's file. (This might happen because the two are the same file.) We should handle that case by reusing the existing import if possible, or otherwise failing gracefully.

PR Close #47938
2022-11-03 17:49:11 -07:00
Andrew Kushnir
13b863a1bf Revert "fix(core): hardening rules related to the attribute order on iframe elements (#47935)" (#47959)
This reverts commit 2d08965b1a.

The reason for revert is that we've identified some issues with implementation. The issues will get addressed soon and the fix would be re-submitted.

PR Close #47959
2022-11-03 11:20:32 -07:00
Andrew Kushnir
2d08965b1a fix(core): hardening rules related to the attribute order on iframe elements (#47935)
This commit updates the logic related to the attribute order on iframes and makes the rules more strict. There is a set of iframe attributes that may affect the behavior of an iframe, this change enforces that these attributes are applied before an `src` or `srcdoc` attributes are applied to an iframe, so that they are taken into account.

If Angular detects that some of the attributes are set after the `src` or `srcdoc`, it throws an error message, which contains the name of ann attribute that is causing the problem and the name of a Component where an iframe is located. In most cases, it should be enough to change the order of attributes in a template to move the `src` or `srcdoc` ones to the very end.

BREAKING CHANGE:

Existing iframe usages may have `src` or `srcdoc` preceding other attributes. Such usages may need to be updated to ensure compliance with the new stricter rules around iframe bindings.

PR Close #47935
2022-11-02 09:07:31 -07:00
Paul Gschwendtner
39b898d0cd refactor(compiler-cli): update emit signature to support for strongly typed emitCallback (#47893)
Currently `ngc-wrapped` mostly relies on any casts/or disabled
strictness checks to be able to use `tsickle`'s emit callback and
emit result merging for ngtsc. We should change this so that supertypes
of `ts.EmitResult` can be used in these optional callbacks- allowing us
to enable strictness checks in `packages/bazel/...` too.

PR Close #47893
2022-11-01 04:44:28 -07:00
Angular Robot
f02eae61fe build: update babel dependencies (#47765)
See associated pull request for more information.

PR Close #47765
2022-10-25 21:57:13 +02:00
Kristiyan Kostadinov
f97bebf17a fix(compiler-cli): implement more host directive validations as diagnostics (#47768)
Implements more of the runtime validations for host directives as compiler diagnostics so that they can be caught earlier. Also does some minor cleanup.

PR Close #47768
2022-10-17 12:12:22 +02:00
Charles Lyding
d684148f93 refactor(compiler-cli): use mkdirSync recursive option instead of custom implementation (#47678)
The supported Node.js versions for the `@angular/compiler-cli` package (^14.15.0 || >=16.10.0)
allow for the use of the `recursive` option of `mkdirSync`.  Using the `recursive` option
removes the need to manually create each subdirectory in a given path.

PR Close #47678
2022-10-13 13:51:03 -07:00
Alan Agius
38078e7adb fix(compiler-cli): add missing period to error message (#47744)
With this change we add a missing period to the error message.

PR Close #47744
2022-10-12 15:57:25 +00:00
Alan Agius
1b9fd46d14 feat(core): add support for Node.js version 18 (#47730)
This change aligns with the supported Node.js versions of the Angular CLI.
See: https://github.com/angular/angular-cli/pull/24026

BREAKING CHANGE: Angular no longer supports Node.js versions `14.[15-19].x` and `16.[10-12].x`. Current supported versions of Node.js are `14.20.x`, `16.13.x` and `18.10.x`.

PR Close #47730
2022-10-11 17:21:19 +00:00
JoostK
bc54687c7b fix(compiler-cli): exclude abstract classes from strictInjectionParameters requirement (#44615)
In AOT compilations, the `strictInjectionParameters` compiler option can
be enabled to report errors when an `@Injectable` annotated class has a
constructor with parameters that do not provide an injection token, e.g.
only a primitive type or interface.

Since Ivy it's become required that any class with Angular behavior
(e.g. the `ngOnDestroy` lifecycle hook) is decorated using an Angular
decorator, which meant that `@Injectable()` may need to have been added
to abstract base classes. Doing so would then report an error if
`strictInjectionParameters` is enabled, if the abstract class has an
incompatible constructor for DI purposes. This may be fine though, as
a subclass may call the constructor explicitly without relying on
Angular's DI mechanism.

Therefore, this commit excludes abstract classes from the
`strictInjectionParameters` check. This avoids an error from being
reported at compile time. If the constructor ends up being used by
Angular's DI system at runtime, then the factory function of the
abstract class will throw an error by means of the `ɵɵinvalidFactory`
instruction.

In addition to the runtime error, this commit also analyzes the inheritance
chain of an injectable without a constructor to verify that their inherited
constructor is valid.

BREAKING CHANGE: Invalid constructors for DI may now report compilation errors

When a class inherits its constructor from a base class, the compiler may now
report an error when that constructor cannot be used for DI purposes. This may
either be because the base class is missing an Angular decorator such as
`@Injectable()` or `@Directive()`, or because the constructor contains parameters
which do not have an associated token (such as primitive types like `string`).
These situations used to behave unexpectedly at runtime, where the class may be
constructed without any of its constructor parameters, so this is now reported
as an error during compilation.

Any new errors that may be reported because of this change can be resolved either
by decorating the base class from which the constructor is inherited, or by adding
an explicit constructor to the class for which the error is reported.

Closes #37914

PR Close #44615
2022-10-10 21:46:25 +00:00
Kristiyan Kostadinov
ed11a13c3c feat(core): drop support for TypeScript 4.6 and 4.7 (#47690)
Updates the version range in the compiler to require at least TypeScript 4.8. Note that I'm keeping the backwards-compatibility layer for 4.7 around for now until internal projects have been migrated to 4.8.

BREAKING CHANGE:
TypeScript versions older than 4.8 are no longer supported.

PR Close #47690
2022-10-10 16:18:56 +00:00
Charles Lyding
a792bf1703 perf(compiler-cli): minimize filesystem calls when generating shims (#47682)
Previously when a file was being analyzed to determine if a shim should
be generated, up to two calls to the host `fileExists` function per file
per generator were made. In the default host, each `fileExists` call made
two underlying file system calls. Following these calls, the file was then
read via `getSourceFile`. However, `getSourceFile` will return `undefined`
if the requested file does not exist. As a result, `getSourceFile` can be
used directly to request both potential file names and leverage the return
value to determine if the file does not exist. This avoids the need to call
`fileExists` at all.

PR Close #47682
2022-10-07 09:10:34 -07:00
Dylan Hunn
8df8c77915 refactor(compiler): Add getPotentialImportsFor method on template type checker (#47631)
`getPotentialImportsFor` returns an array of possible imports, including TypeScript module specifier and identifier name, for a requested trait in the context of a given component.

PR Close #47631
2022-10-05 13:44:05 -07:00
Martin Probst
19ad4987f9 fix(compiler-cli): use @ts-ignore. (#47636)
The previous commit 2e1dddec45 used `@ts-expect-error` to suppress the
current error, with the intent of being informed once that's no longer
an error, ie. when we updated to an upstream TS version that includes
this change.

However this unfortunately means the change is incompatible with the
fixed version, which prevents it from working with an updated TS version
in google3.

This change reverts back to the original `@ts-ignore` which is forwards
and backwards compatible, avoiding that problem (but unfortunately
losing the benefit of being notified once fixed).

PR Close #47636
2022-10-05 13:37:11 -07:00
Dylan Hunn
29194638c1 refactor(compiler): Rename PipeInScope -> PotentialPipe (#47561)
Now that `getPotentialTemplateDirectives` uses `PotentialDirective`, we should rename `PipeInScope` to match.

PR Close #47561
2022-10-04 14:40:04 -07:00
Dylan Hunn
79c016d433 refactor(compiler): Add getPotentialTemplateDirectives API method. (#47561)
`getPotentialTemplateDirectives` returns possible directives which can be used in the provided context, whether already in scope or requiring an import.

This is necessary to implement auto-import support for standalone components in the language service.

PR Close #47561
2022-10-04 14:40:04 -07:00
Dylan Hunn
3783ee01ac refactor(compiler): Rename DirectiveInScope -> PotentialDirective (#47561)
After implementing `getPotentialTemplateDirectives`, we will use this data struture to represent both in-scope and out-of-scope directives. So this rename is an advance cleanup.

PR Close #47561
2022-10-04 14:40:04 -07:00
Martin Probst
2e1dddec45 fix(compiler-cli): support hasInvalidatedResolutions. (#47585)
The latest TypeScript compiler exposes the previously private field
`hasInvalidatedResolutions`. That breaks Angular in the newer TS,
because the new field would be required on DelegatingCompilerHost.
However we cannot just add the field here, because it's not present in
the older compiler.

This change adds the field for delegation, which works at runtime
because the field is present. It suppresses the compiler error using a
`// @ts-expect-error`, which should be removed once Angular moves to a
TSC version that includes this change.

PR Close #47585
2022-10-04 11:50:47 -07:00
JoostK
8fcadaad48 perf(compiler-cli): cache source file for reporting type-checking diagnostics (#47471)
When reporting type-checking diagnostics in external templates we create a
`ts.SourceFile` of the template text, as this is needed to report Angular
template diagnostics using TypeScript's diagnostics infrastructure. Each
reported diagnostic would create its own `ts.SourceFile`, resulting in
repeatedly parsing of the template text and potentially high memory usage
if the template is large and there are many diagnostics reported. This commit
caches the parsed template in the template mapping, such that all reported
diagnostics get to reuse the same `ts.SourceFile`.

Closes #47470

PR Close #47471
2022-09-21 18:22:23 +02:00
Andrew Kushnir
710d1da4ed refactor(common): create an NgFor alias for NgForOf directive (#47309)
This commit adds a re-export of the `NgForOf` class as `NgFor` to improve the DX for cases when the directive is used as standalone. Developers can import `NgFor` class, which better matches the `ngFor` attribute used in a template.

PR Close #47309
2022-09-09 14:04:54 -07:00
JoostK
cf0c53aa1c fix(compiler): avoid errors for inputs with Object-builtin names (#47220)
Using raw objects as a lookup structure will inadvertently find methods defined on
`Object`, where strings are expected. This causes errors downstream when string
operations are applied on functions.

This commit switches over to use `Map`s in the DOM element schema registry to fix
this category of issues.

Fixes #46936

PR Close #47220
2022-09-06 11:55:13 -07:00
JoostK
4a53b7f36b refactor(compiler): show meaningful diagnostic when reporting a template error fails (#44001)
When the Angular compiler emits a diagnostic in a template file, it
forces TypeScript to parse that template. Templates are not TypeScript,
so this parse finds a bunch of parsing errors, which Angular then
ignores and we show the diagnostic anyways because we have more context.
This can lead to strange behavior in TypeScript because templates are so
weird that it can break the parser and crash the whole compiler.

For example, certain Angular templates can encounter failures fixed by
microsoft/TypeScript#45987, which are not easily debuggable and require
a TS upgrade to fix.

This commit introduces logic to handle the error gracefully, by falling
back to report the template error on the component class itself. The
diagnostic is extended to still reference the template location and
includes the failure's stack trace, to allow the parsing failure to be
reported to TypeScript (as parsing should in theory not cause a crash).

Closes #43970

PR Close #44001
2022-09-06 11:52:35 -07:00
Alan Agius
16f96eeabf refactor(compiler-cli): remove enableIvy options (#47346)
This option has no longer any effect as Ivy is the only rendering engine.

BREAKING CHANGE: Angular compiler option `enableIvy` has been removed as Ivy is the only rendering engine.

PR Close #47346
2022-09-06 11:33:48 -07:00
Kristiyan Kostadinov
54ceed53e2 refactor(compiler): add support for host directives (#46868)
This is the compile-time implementation of the `hostDirectives` feature plus a little bit of runtime code to illustrate how the newly-generated code will plug into the runtime. It works by creating a call to the new `ɵɵHostDirectivesFeature` feature whenever a directive has a `hostDirectives` field. Afterwards `ɵɵHostDirectivesFeature` will patch a new function onto the directive definition that will be invoked during directive matching.

For example, if we take the following definition:

```ts
@Directive({
  hostDirectives: [HostA, {directive: HostB, inputs: ['input: alias']}]
})
class MyDir {}
```

Will compile to:

```js
MyDir.ɵdir = ɵɵdefineComponent({
  features: [ɵɵHostDirectivesFeature([HostA, {
    directive: HostB,
    inputs: {
      input: "alias"
    }
  }])]
});
```

The template type checking is implemented during directive matching by adding the host directives applied on the host to the array of matched directives whenever the host is matched in a template.

Relates to #8785.

PR Close #46868
2022-08-22 16:00:35 -07:00
Dylan Hunn
edf7f670f0 refactor(compiler): Add a new helper method getOwningNgModule. (#47166)
This helper accepts a class for an Angular trait, and returns the NgModule which owns that trait. This will be useful for the language service import project, which needs to edit import arrays on the module.

PR Close #47166
2022-08-22 10:57:48 -07:00
Kristiyan Kostadinov
ddb95c5184 refactor(compiler): replace most usages of getMutableClone (#47167)
Replaces (almost) all of the usages of the deprecated `getMutableClone` function from TypeScript which has started to log deprecation warnings in version 4.8 and will likely be removed in version 5.0. The one place we have left is in the default import handling of ngtsc which will be more difficult to remove.

PR Close #47167
2022-08-22 10:40:50 -07:00
Dylan Hunn
fc97a41f07 refactor(compiler): Add a new helper method getPrimaryAngularDecorator. (#47180)
This helper accepts a class, and returns the primary Angular Decorator associated with that trait (e.g. the Component, Pipe, Directive, or NgModule decorator). This will be useful for the language service import project, which needs to edit import arrays inside the decorator.

PR Close #47180
2022-08-22 10:39:42 -07:00
Kristiyan Kostadinov
31429eaccc feat(core): support TypeScript 4.8 (#47038)
Adds support for TypeScript 4.8 and resolves some issues that came up as a result of the update.

Most of the issues came from some changes in TypeScript where the `decorators` and `modifiers` properties were removed from most node types, and were combined into a single `modifiers` array. Since we need to continue supporting TS 4.6 and 4.7 until v15, I ended up creating a new `ngtsc/ts_compatibility` directory to make it easier to reuse the new backwards-compatible code.

PR Close #47038
2022-08-16 16:02:47 +00:00