Commit Graph

6790 Commits

Author SHA1 Message Date
Alan Agius 0929099e41 refactor(compiler-cli): remove TypeScript 3.9 workarounds (#39586)
With this change we remove code which was used to support both TypeScript 3.9 and TypeScript 4.0

This code is now no longer needed because G3 is on TypeScript 4.0

PR Close #39586
2020-11-06 15:26:51 -08:00
George Kalpakas bdce7698fc fix(elements): update the view of an `OnPush` component when inputs change (#39452)
As with regular Angular components, Angular elements are expected to
have their views update when inputs change.

Previously, Angular Elements views were not updated if the underlying
component used the `OnPush` change detection strategy.

This commit fixes this by calling `markForCheck()` on the component
view's `ChangeDetectorRef`.

NOTE:
This is similar to how `@angular/upgrade` does it:
3236ae0ee1/packages/upgrade/src/common/src/downgrade_component_adapter.ts (L146).

Fixes #38948

PR Close #39452
2020-11-06 09:31:46 -08:00
George Kalpakas 9cd2741d6c test(elements): fix `ComponentNgElementStrategy` test for components without `ngOnChanges` (#39452)
`ComponentNgElementStrategy` is supposed to call `ngOnChanges()` on the
underlying component instance if available, but not fail if the
component does not have an `ngOnChanges()` method. This works as
expected. However, the test used to verify that was invalid; i.e. the
test would pass even if `ComponentNgElementStrategy` would try to call
`ngOnChanges()` on a component without such a method.

This commit replaces the invalid test with a new one that correctly
verifies that `ComponentNgElementStrategy` does not try to call
`ngOnChanges()`.

PR Close #39452
2020-11-06 09:31:46 -08:00
George Kalpakas f60687220b test(elements): simplify creation of `FakeComponentFactory#componentRef` (#39452)
Previously, the `componentRef` property of `FakeComponentFactory` used
in `elements` tests was initialy set to a spy object with all mock
properties defined as spied methods. Later, the properties where
overwritten to the actual mock values.

This commit simplifies the creation of `componentRef` by correctly using
the arguments of [jasmine.createSpyObj()][1] to specify the desired
shape of the spy object (separating spied properties from methods and
directly providing the mock values).

[1]: https://jasmine.github.io/api/3.5/jasmine.html#.createSpyObj

PR Close #39452
2020-11-06 09:31:46 -08:00
George Kalpakas 5540fc718a test(elements): fix typo in test description (`even if when` --> `even if`) (#39452)
This commit fixes a typo in a test description.

PR Close #39452
2020-11-06 09:31:46 -08:00
Jessica Janiuk 290ea57a93 fix(core): Access injected parent values using SelfSkip (#39464)
In ViewEngine, SelfSkip would navigate up the tree to get tokens from
the parent node, skipping the child. This restores that functionality in
Ivy. In ViewEngine, if a special token (e.g. ElementRef) was not found
in the NodeInjector tree, the ModuleInjector was also used to lookup
that token. While special tokens like ElementRef make sense only in a
context of a NodeInjector, we preserved ViewEngine logic for now to
avoid breaking changes.

We identified 4 scenarios related to @SkipSelf and special tokens where
ViewEngine behavior was incorrect and is likely due to bugs. In Ivy this
is implemented to provide a more intuitive API. The list of scenarios
can be found below.

1. When Injector is used in combination with @Host and @SkipSelf on the
first Component within a module and the injector is defined in the
module, ViewEngine will get the injector from the module. In Ivy, it
does not do this and throws instead.

2. When retrieving a @ViewContainerRef while @SkipSelf and @Host are
present, in ViewEngine, it throws an exception. In Ivy it returns the
host ViewContainerRef.

3. When retrieving a @ViewContainerRef on an embedded view and @SkipSelf
is present, in ViewEngine, the ref is null. In Ivy it returns the parent
ViewContainerRef.

4. When utilizing viewProviders and providers, a child component that is
nested within a parent component that has @SkipSelf on a viewProvider
value, if that provider is provided by the parent component's
viewProviders and providers, ViewEngine will return that parent's
viewProviders value, which violates how viewProviders' visibility should
work. In Ivy, it retrieves the value from providers, as it should.

These discrepancies all behave as they should in Ivy and are likely bugs
in ViewEngine.

PR Close #39464
2020-11-06 09:23:45 -08:00
Pete Bacon Darwin b9b9178458 fix(compiler-cli): do not drop non-Angular decorators when downleveling (#39577)
There is a compiler transform that downlevels Angular class decorators
to static properties so that metadata is available for JIT compilation.
The transform was supposed to ignore non-Angular decorators but it was
actually completely dropping decorators that did not conform to a very
specific syntactic shape (i.e. the decorator was a simple identifier, or
a namespaced identifier).

This commit ensures that all non-Angular decorators are kepts as-is
even if they are built using a syntax that the Angular compiler does not
understand.

Fixes #39574

PR Close #39577
2020-11-06 09:21:51 -08:00
Andrew Scott 3a1d36cce3 refactor(language-service): Use compiler APIs in Ivy to get definitions for external resources (#39476)
Rather than re-reading component metadata that was already interpreted
by the Ivy compiler, the Language Service should instead use the
compiler APIs to get information it needs about the metadata.

PR Close #39476
2020-11-06 09:17:33 -08:00
Pete Bacon Darwin 1f956184c4 fix(compiler): skipping leading whitespace should not break placeholder source-spans (#39486)
Tokenized text node may have leading whitespace skipped from their
source-span. But the source-span is used to compute where there are
interpolated blocks, resulting in placeholder nodes whose source-spans
are offset by the amount of skipped characters.

This fix uses the `fullStart` location of text source-spans for computing
the source-span of placeholders, so that they are accurate.

Fixes #39195

PR Close #39486
2020-11-06 09:01:37 -08:00
Pete Bacon Darwin 43d8e9aad2 refactor(compiler): capture `fullStart` locations when tokenizing (#39486)
This commit ensures that when leading whitespace is skipped by
the tokenizer, the original start location (before skipping) is captured
in the `fullStart` property of the token's source-span.

PR Close #39486
2020-11-06 09:01:37 -08:00
Pete Bacon Darwin 8d90c1ad97 refactor(compiler): store the `fullStart` location on `ParseSourceSpan`s (#39486)
The lexer is able to skip leading trivia in the `start` location of tokens.
This makes the source-span more friendly since things like elements
appear to begin at the start of the opening tag, rather than at the
start of any leading whitespace, which could include newlines.

But some tooling requires the full source-span to be available, such
as when tokenizing a text span into an Angular expression.

This commit simply adds the `fullStart` location to the `ParseSourceSpan`
class, and ensures that places where such spans are cloned, this
property flows through too.

PR Close #39486
2020-11-06 09:01:37 -08:00
Pete Bacon Darwin 3f4fe45277 fix(compiler): ensure that i18n message-parts have the correct source-span (#39486)
In an i18n message, two placeholders next to each other must have
an "empty" message-part to separate them. Previously, the source-span
for this message-part was pointing to the wrong original location.
This caused problems in the generated source-maps and lead to extracted
i18n messages from being rendered incorrectly.

PR Close #39486
2020-11-06 09:01:37 -08:00
JiaLiPassion 27358eb60f feat(zone.js): monkey patches queueMicrotask() (#38904)
Close #38863

Monkey patches `queueMicrotask()` API, so the callback runs in the zone
when scheduled, and also the task is run as `microTask`.

```
Zone.current.fork({
  name: 'queueMicrotask',
  onScheduleTask: (delegate: ZoneDelegate, curr: Zone, target: Zone, task: Task) => {
    logs.push(task.type);
    logs.push(task.source);
    return delegate.scheduleTask(target, task);
  }
}).run(() => {
    queueMicrotask(() => {
      expect(logs).toEqual(['microTask', 'queueMicrotask']);
      expect(Zone.current.name).toEqual('queueMicrotask');
      done();
  });
});

```

PR Close #38904
2020-11-05 11:23:33 -08:00
Kristiyan Kostadinov 27ae0604c6 test(compiler-cli): resolve test failure (#39568)
Narrows down an assertion in one of our tests so it's less prone to failure due to
extra commas.

PR Close #39568
2020-11-04 12:02:09 -08:00
Andrew Kushnir e96b379385 fix(forms): remove validators while cleaning up a control (#39234)
Prior to this commit, the `cleanUpControl` function (responsible for cleaning up control instance)
was not taking validators into account. As a result, these validators remain registered on a detached
form control instance, thus causing memory leaks. This commit updates the `cleanUpControl` function
logic to also run validators cleanup.

As a part of this change, the logic to setup and cleanup validators was refactored and moved to
separate functions (with completely opposite behavior), so that they can be reused in the future.

This commit doesn't add the `cleanUpControl` calls to all possible places, it just fixes the cases
where this function is being called, but doesn't fully perform a cleanup. The `cleanUpControl`
function calls will be added to other parts of code (to avoid more memory leaks) in a followup PR.

PR Close #39234
2020-11-04 10:58:24 -08:00
JoostK 306a1307c7 refactor(compiler-cli): rename `$ngDeclareDirective`/`$ngDeclareComponent` to use `ɵɵ` prefix (#39518)
For consistency with other generated code, the partial declaration
functions are renamed to use the `ɵɵ` prefix which indicates that it is
generated API.

This commit also removes the declaration from the public API golden
file, as it's not yet considered stable at this point. Once the linker
is finalized will these declaration function be included into the golden
file.

PR Close #39518
2020-11-04 10:44:37 -08:00
JoostK 87e9cd643b feat(compiler-cli): implement partial directive declaration linking (#39518)
This commit implements the logic to compile a partial declaration of a
directive into its full AOT compilation output.

PR Close #39518
2020-11-04 10:44:37 -08:00
JoostK 8c0a92bb45 feat(compiler-cli): partial compilation of directives (#39518)
This commit implements partial code generation for directives, which
will be transformed by the linker plugin to fully AOT compiled code in
follow-up work.

PR Close #39518
2020-11-04 10:44:37 -08:00
JoostK ded7beed32 test(compiler-cli): run the linker transform in the compliance test's prelink target (#39518)
In PR #38938 an additional Bazel target was introduced for the compliance
tests, as preparation to run the compliance tests in partial compilation
mode and then apply the linker transform. The linker plugin itself was
not available at the time but has since been implemented, so this commit
updates the prelink target of the compliance tests to apply the linker
transform using the Babel plugin.

Actually emitting partial compilations to be transformed will be done in
follow-up work.

PR Close #39518
2020-11-04 10:44:37 -08:00
JoostK 4eda87c86c refactor(compiler-cli): extend AST object and value helpers (#39518)
This introduces `AstObject.toMap` as an alternative to `AstObject
.toLiteral`, and adds `AstValue.getSymbolName` to query the symbol name
of a value using the encapsulated AST host.

PR Close #39518
2020-11-04 10:44:37 -08:00
Kristiyan Kostadinov 7e33cb9626 fix(compiler-cli): generating invalid setClassMetadata call in ES5 for class with custom decorator (#39527)
When a class with a custom decorator is transpiled to ES5, it looks something like this:

```
var SomeClass = (function() {
  function SomeClass() {...};
  var SomeClass_1 = __decorate([Decorator()], SomeClass);
  SomeClass = SomeClass_1;
  return SomeClass;
})();
```

The problem is that if the class also has an Angular decorator that refers to the class itself
(e.g. `{provide: someToken, useClass: SomeClass}`), the generated `setClassMetadata` code will
be emitted after the IIFE, but will still refer to the intermediate `SomeClass_1` variable from
inside the IIFE. This happens, because we generate the `setClassMetadata` call directly from
the source AST which contains identifiers that TS will rename when it emits the ES5 code.

These changes resolve the issue by looking through the metadata AST and cloning any `Identifier`
that is referring to the class. Since TS doesn't have references to the clone, it won't rename
it when transpiling to ES5.

Fixes #39509.

PR Close #39527
2020-11-03 14:52:59 -08:00
Keen Yee Liau 3cab823222 docs(bazel): Mention Alex Eagle's article on migration doc (#39507)
Alex Eagle wrote an external article on our decision to move Bazel out of
Angular repo, and it's useful for users who want to know more about what's next.

PR Close #39507
2020-11-02 13:34:35 -08:00
Eduard Bondarenko ad62edac9c docs: update forwardRef example (#39519)
Replace the deprecated api ReflectiveInjector.resolveAndCreat with Injector.create

PR Close #39519
2020-11-02 11:40:17 -08:00
Alex Rickabaugh eaace44d57 refactor(language-service): refactor `HybridVisitor` and expand its capabilities (#39505)
This commit takes the `HybridVisitor` in the language service and gives it
the ability to return not just a node but the template context in which it
appears. In the future, more context regarding where a node appears in the
template might become necessary (ex: the microsyntax container for binding
nodes), and this refactoring enables that.

In the process, `HybridVisitor` is renamed and the concept of a
`TemplateTarget` interface is introduced to contain the results of this
operation.

PR Close #39505
2020-11-02 10:29:50 -08:00
Alex Rickabaugh 643c96184c refactor(language-service): introduce DisplayParts abstraction for Ivy (#39505)
This commit refactors the QuickInfo abstraction shared between the VE and
Ivy services and used to implement hover tooltips (quick info), which was
extracted from the VE code in commit faa81dc. The new DisplayParts
abstraction is more general and can be used to extract information needed by
various LS functions (e.g. autocompletion).

This commit effectively reverts faa81dc, returning the original code to the
VE implementation as the Ivy code is now diverged.

PR Close #39505
2020-11-02 10:29:50 -08:00
JoostK 8317042483 perf(core): do not recurse into modules that have already been registered (#39514)
When registering an NgModule based on its id, all transitively imported
NgModules are also registered. This commit introduces a visited set to
avoid traversing into NgModules that are reachable from multiple import
paths multiple times.

Fixes #39487

PR Close #39514
2020-11-02 07:51:18 -08:00
JoostK 40bf1e0475 test(compiler-cli): remove spurious `console.error` call from a test (#39321)
Reporting the source file text to the console was left as a debugging
artifact.

PR Close #39321
2020-11-02 07:50:41 -08:00
JoostK 5d731354d0 perf(compiler-cli): only generate template context declaration when used (#39321)
The variable declaration for a template context is only needed when it
is referenced from somewhere, so the TCB operation to generate the
declaration is marked as optional.

PR Close #39321
2020-11-02 07:50:41 -08:00
JoostK 3b0b7d2210 fix(compiler-cli): report missing pipes when `fullTemplateTypeCheck` is disabled (#39320)
Even if `fullTemplateTypeCheck` is disabled should missing pipes still
be reported, as was the case in View Engine.

Fixes #38195

PR Close #39320
2020-10-30 18:01:51 -07:00
Andrew Scott 3af585c004 fix(router): Ensure all outlets are used when commands have a prefix (#39456)
When there is a primary outlet present in the outlets map and the object is also prefixed
with some other commands, the current logic only uses the primary outlet and ignores
the others. This change ensures that all outlets are respected at the
segment level when prefixed with other commands.

PR Close #39456
2020-10-30 16:23:03 -07:00
Andrew Scott ff7a62ee21 refactor(router): Small refactor of createUrlTree and extra tests (#39456)
This commit has a small refactor of some methods in create_url_tree.ts
and adds some test cases, including two that will fail at the moment but
should pass. A follow-up commit will make use of the refactorings to fix
the test with minimal changes.

PR Close #39456
2020-10-30 16:23:03 -07:00
Kristiyan Kostadinov cbc0907bfd fix(compiler): preserve this.$event and this.$any accesses in expressions (#39323)
Currently expressions `$event.foo()` and `this.$event.foo()`, as well as `$any(foo)` and
`this.$any(foo)`, are treated as the same expression by the compiler, because `this` is considered
the same implicit receiver as when the receiver is omitted. This introduces the following issues:

1. Any time something called `$any` is used, it'll be stripped away, leaving only the first parameter.
2. If something called `$event` is used anywhere in a template, it'll be preserved as `$event`,
rather than being rewritten to `ctx.$event`, causing the value to undefined at runtime. This
applies to listener, property and text bindings.

These changes resolve the first issue and part of the second one by preserving anything that
is accessed through `this`, even if it's one of the "special" ones like `$any` or `$event`.
Furthermore, these changes only expose the `$event` global variable inside event listeners,
whereas previously it was available everywhere.

Fixes #30278.

PR Close #39323
2020-10-30 10:49:15 -07:00
Andrew Kushnir 4e68254514 fix(common): change the week-numbering year format from `r` -> `Y` (#39495)
This commit updates the week-numbering year format from `r` -> `Y` based on the description in
http://www.unicode.org/reports/tr35/tr35-dates.html#dfst-year.

Note: this is not a breaking change, since the week-numbering year format was introduced in
v11.0.0-next.3 (984ed39195)
and the major version that contains that change was not released yet.

PR Close #39495
2020-10-30 10:24:43 -07:00
Andrew Scott beb935613e refactor(compiler-cli): Store inline templates and styles in the resource registry (#39482)
The Language Service is not only interested in external resources, but
also inline styles and templates. By storing the expression of the
inline resources, we can more easily determine if a given position is
part of the inline template/style expression.

PR Close #39482
2020-10-30 09:58:21 -07:00
ayazhafiz 3241d922fc refactor(compiler): parse bindings "by hand" rather than via regex (#39375)
To support recovery of malformed binding property names like `([a)`,
`[a`, or `()`, the binding parser needs to be more permissive w.r.t. the
kinds of bindings it can detect. This is difficult to do maintainably
with a regex, but is trivial with a "hand-rolled" string parser. This
commit refactors render3's binding attribute parsing to use this method
for multi-delimited bindings (namely via the `()`, `[]`, and `[()]`)
syntax, making the way recovery of malformed bindings in a future patch.

Note that we can keep using a regex for prefix-only binding syntax
(e.g. `bind-`, `ref-`) because validation of the binding is complete
once we have matched the prefix, and the only thing left to do is check
that the binding identifier is non-empty, which is trivial.

Part of #38596

PR Close #39375
2020-10-30 09:40:56 -07:00
Andrew Kushnir c83b2ad87f docs: tView.preOrderHooks and tView.preOrderCheckHooks docs update (#39497)
This commit updates the docs for the `tView.preOrderHooks` and `tView.preOrderCheckHooks` TView
fields. Current docs are not up-to-date as it was pointed out in #39439.

Closes #39439.

PR Close #39497
2020-10-29 16:25:39 -07:00
Kristiyan Kostadinov fe343d8d96 refactor(compiler): clean up i18n attribute generation logic (#39498)
This is follow-up from [an earlier discussion](https://github.com/angular/angular/pull/39408#discussion_r511908358).
After some testing, it looks like the type of `Element.attributes` was correct in specifying that it
only has `TextAttribute` instances. This means that the extra checks that filter out `BoundAttribute`
instances from the array isn't necessary. There is another loop a bit further down that actually
extracts the bound i18n attributes.

PR Close #39498
2020-10-29 16:07:50 -07:00
JiaLiPassion 4a8d5ae970 fix(core): markDirty() should only mark flags when really scheduling tick. (#39316)
Close #39296

Fix an issue that `markDirty()` will not trigger change detection.

The case is for example we have the following component.

```
export class AppComponent implements OnInit {
  constructor(private router: Router) {}

  ngOnInit() {
    this.router.events
      .pipe(filter((e) => e instanceof NavigationEnd))
      .subscribe(() => ɵmarkDirty(this));
  }
}

export class CounterComponent implements OnInit, OnDestroy {
  ngOnInit() {
    this.countSubject.pipe(takeUntil(this.destroy)).subscribe((count) => {
      this.count = count;
      ɵmarkDirty(this);
    });
  }
```

Then the app navigate from `AppComponent` to `CounterComponent`,
so there are 2 `markDirty()` call at in a row.

The `1st` call is from `AppComponent` when router changed, the
`2nd` call is from `CounterComponent.ngOnInit()`.

And the `markDirty()->scheduleTick()` code look like this

```
function scheduleTick(rootContext, flags) {
    const nothingScheduled = rootContext.flags === 0 /* Empty */;
    rootContext.flags |= flags;
    if (nothingScheduled && rootContext.clean == _CLEAN_PROMISE) {
      rootContext.schedule(() => {
	...
        if (rootContext.flags & RootContextFlags.DetectChanges)
          rootContext.flags &= ~RootContextFlags.DetectChanges;
          tickContext();

        rootContext.clean = _CLEAN_PROMISE;
        ...
      });
```

So in this case, the `1st` markDirty() will
1. set rootContext.flags = 1
2. before `tickContext()`, reset rootContext.flags = 0
3. inside `tickContext()`, it will call `CounterComponent.ngOnint()`,
   so the `2nd` markDirty() is called.
4. and the `2nd` scheduleTick is called, `nothingScheduled` is true,
   but rootContext.clean is not `_CLEAN_PROMISE` yet, since the `1st` markDirty tick
   is still running.
5. So nowhere will reset the `rootContext.flags`.
6. then in the future, any other `markDirty()` call will not trigger the tick, since
   `nothingScheduled` is always false.

So `nothingScheduled` means no tick is scheduled, `rootContext.clean === _CLEAN_PROMISE`
means no tick is running.
So we should set the flags to `rootContext` only when `no tick is scheudled or running`.

PR Close #39316
2020-10-29 16:07:10 -07:00
JiaLiPassion 170af0740d release: cut the zone.js-0.11.3 release (#39440)
PR Close #39440
2020-10-29 15:40:29 -07:00
Igor Minar 904b213954 build: update to @angular/cli@11.0.0-rc.0 (#39432)
This updates just the cli packages, the material and cdk packages
will be updated separately.

PR Close #39432
2020-10-29 13:47:12 -07:00
ayazhafiz e3365724f2 feat(compiler): recover expression parsing in more malformed pipe cases (#39437)
This commit handles the following cases:
- incomplete pipes in a pipe chain
- incomplete arguments in a pipe chain
- incomplete arguments provided to a pipe
- nested pipes

The idea is to unconditionally recover on the presence of a pipe, which
should be okay because expression parsing can be independently between
pipes.

PR Close #39437
2020-10-29 12:38:40 -07:00
Bjarki f54662e931 fix(core): mark Trusted Types as declarations (#39471)
Angular-internal type definitions for Trusted Types were added in #39211.
When compiled using the Closure compiler with certain optimization
flags, identifiers from these type definitions (such as createPolicy)
are currently uglified and renamed to shorter strings. This causes
Angular applications compiled in this way to fail to create a Trusted
Types policy, and fall bock to using strings.

To fix this, mark the internal Trusted Types definitions as declarations
using the "declare" keyword. Also convert types to interfaces, for
the reasons explained in https://ncjamieson.com/prefer-interfaces/

PR Close #39471
2020-10-29 11:58:48 -07:00
Michael Ziluck 8af32fcb16 docs(forms): update ngModel documentation (#39481)
This commit improves the ngModel docs, specifically:
- clarifies purpose of the name attribute in ngModelOptions
- clarifies on the interaction with a parent form or lack thereof
- fix inconsistency with analogy for two-way binding
- cleans up some typos and extra wordiness
- clarifies language around common properties
- adds missing preposition to commit message format origins
PR Close #39481
2020-10-29 11:18:54 -07:00
Alan Agius dd0ba3f4ab docs: rename `ng xi18n` to `ng extract-i18n` (#39337)
In Angular CLI version 11, xi18n has been changed from `ng xi18n` to `ng extract-i18n`.

PR Close #39337
2020-10-28 14:42:27 -07:00
Thibaut ACKERMANN 62a58e23b6 docs(router): Fix ActivationEnd link (#39469)
ActivationEnd goes to ActivationEnd and not to ActivationStart section

PR Close #39469
2020-10-28 11:06:04 -07:00
JiaLiPassion 3e47b25d19 docs(zone.js): update release doc (#39442)
In the current release doc, we are using some shortcut of `git` command
such as `git ci` `git co`, so in this PR we are updating them
to the normal command, so these commands will work event without
these shortcuts.

PR Close #39442
2020-10-28 10:59:47 -07:00
Andrew Scott 371fb9a955 refactor(compiler-cli): Track external component resources in ResourceRegistry (#39373)
In addition to the template mapping that already existed, we want to also track the mapping for external
style files. We also store the `ts.Expression` in the registry so external tools can look up a resource
on a component by expression and avoid reading the value.

PR Close #39373
2020-10-28 10:57:14 -07:00
twerske e6ca3d3841 refactor(core): add top 10 runtime error codes (#39188)
adds RuntimeError and code enum to improve debugging experience
refactor ExpressionChangedAfterItHasBeenCheckedError to code NG0100
refactor CyclicDependency to code NG0200
refactor No Provider to code NG0201
refactor MultipleComponentsMatch to code NG0300
refactor ExportNotFound to code NG0301
refactor PipeNotFound to code NG0302
refactor BindingNotKnown to code NG0303
refactor NotKnownElement to code NG0304

PR Close #39188
2020-10-28 10:05:01 -07:00
Andrew Kushnir 0723331b2a refactor(forms): move common validators-related logic to the `AbstractControlDirective` class (#38280)
This commit refactors validators-related logic that is common across most of the directives.

A couple notes on this refactoring:
* common logic was moved to the `AbstractControlDirective` class (including `validator` and
`asyncValidator` getters)
* sync/async validators are now composed in `AbstractControlDirective` class eagerly when validators
are set with `_setValidators` and `_setAsyncValidators` calls and the result is stored in directive
instance (thus getters return cached versions of validator fn). This is needed to make sure composed
validator function remains the same (retains its identity) for a given directive instance, so that
this function can be added and later removed from an instance of an AbstractControl-based class
(like `FormControl`). Preserving validator function is required to perform proper cleanup (in followup
PRs) of the AbstractControl-based classes when a directive is destroyed.

PR Close #38280
2020-10-28 09:48:20 -07:00
JiaLiPassion e49a9b298c docs(core): update a typo in the comment of ngZoneEventCoalescing (#39423)
PR Close #39423
2020-10-27 14:27:15 -07:00
ayazhafiz 19b88cef71 fix(compiler): do not throw away render3 AST on errors (#39413)
Currently render3's `parseTemplate` throws away the parsed AST and
returns an empty list of HTML nodes if HTML->R3 translation failed. This
is not preferrable in some contexts like that of a language service,
where we would like a well-formed AST even if it is has errors.

PR Close #39413
2020-10-27 13:37:19 -07:00
Pete Bacon Darwin 0a63eeaff1 Revert "perf(ngcc): allow immediately reporting a stale lock file (#37250)" (#39435)
This reverts commit 561c0f81a0.

The original commit provided a quick escape from an already terminal
situation by killing the process if the PID in the lockfile was not
found in the list of processes running on the current machine.

But this broke use-cases where the node_modules was being shared between
multiple machines (or more commonly Docker containers on the same actual
machine).

Fixes #38875

PR Close #39435
2020-10-27 13:36:27 -07:00
Jack Reed 9891d67e31 docs(zone.js): Update docs property to disable IntersectionObserver (#39429)
Update the property in this documentation to reflect the correct syntax for disabling IntersectionObserver

PR Close #39429
2020-10-27 13:32:55 -07:00
Kristiyan Kostadinov 58408d6a60 fix(compiler): treat i18n attributes with no bindings as static attributes (#39408)
Currently `i18n` attributes are treated the same no matter if they have data bindings or not. This
both generates more code since they have to go through the `ɵɵi18nAttributes` instruction and
prevents the translated attributes from being injected using the `@Attribute` decorator.

These changes makes it so that static translated attributes are treated in the same way as regular
static attributes and all other `i18n` attributes go through the old code path.

Fixes #38231.

PR Close #39408
2020-10-27 13:31:29 -07:00
pmartijena 421efbf69b docs: fix grammatical errors and typos (#38868)
Fixed run on sentences, grammatical errors, and made "ivy" "Ivy" everywhere for consistency.
PR Close #38868
2020-10-27 13:18:01 -07:00
Alex Rickabaugh 0ecdef9cfa refactor(compiler-cli): API to get directives/pipes in scope (#39278)
This commit introduces two new methods to the TemplateTypeChecker, which
retrieve the directives and pipes that are "in scope" for a given component
template. The metadata returned by this API is minimal, but enough to power
autocompletion of selectors and attributes in templates.

PR Close #39278
2020-10-27 13:17:14 -07:00
Alex Rickabaugh 01cc949722 refactor(compiler-cli): cache Symbols in the TemplateTypeCheckerImpl (#39278)
This commit introduces caching of `Symbol`s produced by the template type-
checking infrastructure, in the same way that autocompletion results are
now cached.

PR Close #39278
2020-10-27 13:17:14 -07:00
Alex Rickabaugh c4f99b6e52 refactor(compiler-cli): move global completion into new CompletionEngine (#39278)
This commit refactors the previously introduced `getGlobalCompletions()` API
for the template type-checker in a couple ways:

 * The return type is adjusted to use a `Map` instead of an array, and
   separate out the component context completion position. This allows for a
   cleaner integration in the language service.
 * A new `CompletionEngine` class is introduced which powers autocompletion
   for a single component, and can cache completion results.
 * The `CompletionEngine` for each component is itself cached on the
   `TemplateTypeCheckerImpl` and is invalidated when the component template
   is overridden or reset.

This refactoring simplifies the `TemplateTypeCheckerImpl` class by
extracting the autocompletion logic, enables caching for better performance,
and prepares for the introduction of other autocompletion APIs.

PR Close #39278
2020-10-27 13:17:14 -07:00
AleksanderBodurri cc4e0c66f6 docs: fix typo in initializeInputAndOutputAliases docstring (#39438)
PR Close #39438
2020-10-27 10:46:37 -07:00
Andrew Kushnir b56cc4059f refactor(core): remove expandoStartIndex workaround (#39416)
This commit removes a workaround to calculate the `expandoStartIndex` value. That workaround was needed
because the `expandoStartIndex` was updated previously, so it pointed at the wrong location. The problem
was fixed in PR #39301 and the workaround is no longer needed.

PR Close #39416
2020-10-27 10:45:52 -07:00
JoostK 3c6edcdf93 fix(core): do not error when `ngDevMode` is undeclared (#39415)
In production mode, the `ngDevMode` global may not have been declared.
This is typically not a problem, as optimizers should have removed all
usages of the `ngDevMode` variables. This does however require the
bundler/optimizer to have been configured in a certain way, as to allow
for `ngDevMode` guarded code to be removed.

As an example, Terser can be configured to remove the `ngDevMode`
guarded code using the following configuration:

```js
const terserOptions = {
  // ...
  compress: {
    // ...
    global_defs: require('@angular/compiler-cli').GLOBAL_DEFS_FOR_TERSER,
  }
}
```

(Taken from https://github.com/angular/angular/issues/31595#issuecomment-519129090)

If this is not done, however, the bundle should still work (albeit with
larger code size due to missed tree-shaking opportunities). This commit
adds a check for whether `ngDevMode` has been declared, as it is a
top-level statement that executes before `ngDevMode` has been initialized.

Fixes #31595

PR Close #39415
2020-10-27 10:45:18 -07:00
Pete Bacon Darwin 0ed2c4fef9 fix(localize): render placeholder types in extracted XLIFF files (#39398)
The previous ViewEngine extraction tooling added `ctype` and `type`
attributes to XLIFF 1.2 and 2.0 translation files, respectively.

This commit adds this to the new $localize based extraction tooling.
Since the new extraction tooling works from the compiled output rather
than having direct access to the template content, the placeholder types
must be inferred from the name of the placeholder.  This is considered
reasonable, since it already does this to compute opening and closing
tag placeholders.

Fixes #38791

PR Close #39398
2020-10-27 10:42:15 -07:00
Andrew Kushnir 9186ad84ae refactor(core): remove unused i18n placeholder for projection (#39172)
Runtime i18n logic doesn't distinguish `<ng-content>` tag placeholders and regular element tag
placeholders in i18n messages, so there is no need to have a special marker for projection-based
placeholders and element markers can be used instead.

PR Close #39172
2020-10-27 10:39:37 -07:00
AleksanderBodurri f6dfd2ffed docs(forms): add section under Validators.pattern detailing use of global and sticky flags gotcha (#39055)
Due to how the global and sticky flag make RegExp objects stateful,
adds section detailing how it is not recommended
to use these flags for control validations.

PR Close #39055
2020-10-27 10:38:48 -07:00
Pete Bacon Darwin 57ead7aa53 fix(localize): serialize all the message locations to XLIFF (#39411)
Previously only the first message, for each id, was serialized
which meant that additional message location information
was lost.

Now all the message locations are included in the serialized
messages.

Fixes #39330

PR Close #39411
2020-10-26 10:52:29 -07:00
Andrew Kushnir 1db4f212e5 docs: improve DefaultValueAccessor directive docs (#39404)
This commit improves the DefaultValueAccessor directive docs by:
- adding the `ngDefaultControl` as a search keyword to the description
- adding an example of the `ngDefaultControl` usage

Closes #35375.

PR Close #39404
2020-10-26 10:50:41 -07:00
JiaLiPassion 90c0772743 fix(zone.js): remove global declaration (#37861)
Close #37531

Remove `global` declaration in `zone.ts` to avoid compile error when
upgrade to `@types/node` v12.12.68. Since the new type of global become
`NodeJS.global & typeof globalThis` and not compatible with `zone.ts` declaration.

PR Close #37861
2020-10-23 15:19:49 -07:00
Joey Perrott 67069ce42a fix(bazel): only providing stamping information if the --stamp flag is used (#39392)
Previously the volatile status file was always provided to the ng_rollup
action which prevented it from being cacheable remotely.  This change to
only provide this file as an input when the --stamp flag is used will allow
for the action to be remotely cached and prevent needing to run the action
on every CI run.

PR Close #39392
2020-10-23 15:18:14 -07:00
Pete Bacon Darwin 27a4adebcb refactor(compiler-cli): support namespaced references (#39346)
The compiler uses a `Reference` abstraction to refer to TS nodes
that it needs to refer to from other parts of the source. Such
references keep track of any identifiers that represent the referenced
node.

Prior to this commit, the compiler (and specifically `ReferenceEmitter`
classes) assumed that the reference identifiers are always free standing.
In other words a reference identifier would be an expression like
`FooDirective` in the expression `class FooDirective {}`.

But in UMD/CommonJS source, a reference can actually refer to an "exports"
declaration of the form `exports.FooDirective = ...`.
In such cases the `FooDirective` identifier is not free-standing
since it is part of a property access, so the `ReferenceEmitter`
should take this into account when emitting an expression that
refers to such a `Reference`.

This commit changes the `LocalIdentifierStrategy` reference emitter
so that if the `node` being referenced is not a declaration itself and
is in the current file, then it should be used directly, rather than
trying to use one of its identifiers.

PR Close #39346
2020-10-23 15:17:11 -07:00
Pete Bacon Darwin 413b55273b fix(ngcc): capture UMD/CommonJS inner class implementation node correctly (#39346)
Previously, UMD/CommonJS class inline declarations of the form:

```ts
exports.Foo = (function() { function Foo(); return Foo; })();
```

were capturing the whole IIFE as the implementation, rather than
the inner class (i.e. `function Foo() {}` in this case). This caused
the interpreter to break when it was trying to access such an export,
since it would try to evaluate the IIFE rather than treating it as a class
declaration.

PR Close #39346
2020-10-23 15:17:11 -07:00
twerske dcafac1b8f refactor(core): group provider and circular errors (#39251)
group together similar error messages as part of error code efforts
ProviderNotFound & NodeInjector grouped into throwProviderNotFoundError
Cyclic dependency errors grouped into throwCyclicDependencyError

PR Close #39251
2020-10-22 13:42:34 -07:00
ayazhafiz 3f00c6150b test(compiler): Demonstrate recoverable parsing of unterminated pipes (#39113)
There is no actionable change in this commit other than to pretty-print
EOF tokens. Actual parsing of unterminated pipes is already supported,
this just adds a test for it.

Part of #38596

PR Close #39113
2020-10-22 13:41:51 -07:00
JiaLiPassion 6085d2acc9 test(zone.js): add zone.js externs test (#39108)
Add back the zone.js externs file test for google closure compiler.
The test compiles a test program with and without `zone_externs`.

1. With `zone_externs`, the code should keep the APIs defined in the `zone_externs`.
2. Without `zone_externs`, the code will not keep these APIs.

PR Close #39108
2020-10-22 13:40:08 -07:00
ayazhafiz e44e10bb81 feat(compiler): support recovery of malformed property writes (#39103)
This feature is trivial to support since
89c5255b8c has landed.

PR Close #39103
2020-10-22 13:36:50 -07:00
Misko Hevery d939b5f598 refactor(core): Improve tree shakability of i18n code. (#39301)
`TNode.insertBeforeIndex` is only populated when i18n is present. This
change puts all code which reads `insertBeforeIndex` behind a
dynamically loaded functions which are set only when i18n code executes.

PR Close #39301
2020-10-22 09:35:49 -07:00
Misko Hevery 68d4de6770 refactor(core): Replace `ExpandoInstructions` with `HostBindingOpCodes` (#39301)
The `ExpandoInstructions` was unnecessarily convoluted way to solve the
problem of calling the `HostBindingFunction`s on components and
directives. The code was complicated and hard to fallow.

The replacement is a simplified way to achieve the same thing, which
is also more efficient in space and speed.

PR Close #39301
2020-10-22 09:35:48 -07:00
Misko Hevery 08f3d62391 refactor(core): clean up circular dependencies (#39233)
Moved code from `interfaces/i18n.ts` which was causing circular dependencies

PR Close #39233
2020-10-21 18:33:00 -07:00
Misko Hevery 2c31533f0a refactor(core): Use `~x` instead of `-x` which can result in `-0` (#39233)
`expandoInstructions` uses negative numbers by `-x`. This has lead to
issues in the paste as `-0` is processed as float rather than integer
leading to de-optimization.

PR Close #39233
2020-10-21 18:33:00 -07:00
Misko Hevery 54303688fa refactor(core): Consistent use of `HEADER_OFFSET` (in `ɵɵ*` instructions only) (#39233)
IMPORTANT: `HEADER_OFFSET` should only be refereed to the in the `ɵɵ*` instructions to translate
instruction index into `LView` index. All other indexes should be in the `LView` index space and
there should be no need to refer to `HEADER_OFFSET` anywhere else.

PR Close #39233
2020-10-21 18:33:00 -07:00
Misko Hevery bc5005e35b refactor(core): cleanup i18n/icu data structures (#39233)
- Made `*OpCodes` array branded for safer type checking.
- Simplify `I18NRemoveOpCodes` encoding.
- Broke out  `IcuCreateOpCodes` from `I18nMutableOpCodes`.

PR Close #39233
2020-10-21 18:33:00 -07:00
Misko Hevery e1f80d73a8 refactor(core): rename `COMMENT_MARKER` to `ICU_MARKER` (#39233)
`COMMENT_MARKER` is a generic name which does not make it obvious that
it is used for ICU use case. `ICU_MARKER` is more explicit as it is used
exclusively with ICUs.

PR Close #39233
2020-10-21 18:33:00 -07:00
Misko Hevery 1b9193b3fb refactor(core): Rename `debugMatch` to `matchDebug` for consistency (#39233)
Previous function name `debugMatch` was not consistent with other match
functions.

PR Close #39233
2020-10-21 18:33:00 -07:00
Misko Hevery 70f1e2e04a refactor(core): Create `TNodeType.Text` to display full template in `TView` debug (#39233)
When looking at `TView` debug template only Element nodes were displayed
as `TNode.Element` was used for both `RElement` and `RText`.
Additionally no text was stored in `TNode.value`. The result was that
the whole template could not be reconstructed. This refactoring creates
`TNodeType.Text` and store the text value in `TNode.value`.

The refactoring also changes `TNodeType` into flag-like structure make
it more efficient to check many different types at once.

PR Close #39233
2020-10-21 18:33:00 -07:00
Misko Hevery d50df92568 refactor(core): Remove hack where we `TIcu` was stored in `tagName` (#39233)
Remove casting where we stored `TIcu` in `TNode.tagName` which was of
type `string` rather than `TIcu'. (renamed to `TNode.value` in previous
commit.)

PR Close #39233
2020-10-21 18:33:00 -07:00
Misko Hevery 2e237abb09 refactor(core): Change `TName.tagName` to a more generic `value` name. (#39233)
This is a pre-requisite for making the `TNode.value` a generic storage
mechanism for attaching data to `TNode`.

PR Close #39233
2020-10-21 18:33:00 -07:00
Misko Hevery ca11ef2376 fix(core): Store ICU state in `LView` rather than in `TView` (#39233)
Before this refactoring/fix the ICU would store the current selected
index in `TView`. This is incorrect, since if ICU is in `ngFor` it will
cause issues in some circumstances. This refactoring properly moves the
state to `LView`.

closes #37021
closes #38144
closes #38073

PR Close #39233
2020-10-21 18:33:00 -07:00
Misko Hevery 6790848f68 refactor(core): move `i18n_spec.ts` into `i18n` subfolder (#39233)
`i18n_spec.ts` file was incorrectly in the `render3` folder rather than `render3/i18n`

PR Close #39233
2020-10-21 18:32:59 -07:00
Misko Hevery 61d56be83e refactor(core): Change `TemplateFixture` to named parameters (#39233)
`TemplateFixture` used to have positional parameters and many tests got
hard to read as number of parameters reach 10+ with many of them `null`.
This refactoring changes `TemplateFixture` to take named parameters
which improves usability and readability in tests.

PR Close #39233
2020-10-21 18:32:59 -07:00
Joey Perrott eb4c05d97a build: update bazelversion (#39351)
Updates to the latest version of bazel

PR Close #39351
2020-10-21 11:59:40 -07:00
Keen Yee Liau 7768aeb62f fix(platform-server): Resolve absolute URL from baseUrl (#39334)
This commit fixes a bug when `useAbsoluteUrl` is set to true and
`ServerPlatformLocation` infers the base url from the supplied
`url`. User should explicitly set the `baseUrl` when they turn on
`useAbsoluteUrl`.

Breaking change:
If you use `useAbsoluteUrl` to setup `platform-server`, you now need to
also specify `baseUrl`.
We are intentionally making this a breaking change in a minor release,
because if `useAbsoluteUrl` is set to `true` then the behavior of the
application could be unpredictable, resulting in issues that are hard to
discover but could be affecting production environments.

PR Close #39334
2020-10-21 09:41:58 -07:00
Kristiyan Kostadinov 9fb7bdea89 fix(router): incorrect signature for createUrlTree (#39347)
The type of the `navigationExtras` param was accidetally changed to the wrong symbol
in 783a5bd7bb.
These changes revert it to the correct one.

PR Close #39347
2020-10-20 13:36:12 -07:00
Joey Perrott a7964f4eca fix(common): update locales using new CLDR data (#39343)
Update the derived locales based on the new CLDR data.

PR Close #39343
2020-10-20 13:22:37 -07:00
Andrew Kushnir f5a3e44e9d refactor(compiler): remove support for TypeScript 3.9 (#39313)
This commit removes TypeScript 3.9 support.

BREAKING CHANGE:

TypeScript 3.9 is no longer supported, please upgrade to TypeScript 4.0.

PR Close #39313
2020-10-19 14:34:45 -07:00
Pete Bacon Darwin 7e742aea7c refactor(compiler-cli): linker - add Babel plugin, FileLinker and initial PartialLinkers (#39116)
This commit adds the basic building blocks for linking partial declarations.
In particular it provides a generic `FileLinker` class that delegates to
a set of (not yet implemented) `PartialLinker` classes.

The Babel plugin makes use of this `FileLinker` providing concrete classes
for `AstHost` and `AstFactory` that work with Babel AST. It can be created
with the following code:

```ts
const plugin = createEs2015LinkerPlugin({ /* options */ });
```

PR Close #39116
2020-10-19 11:23:45 -07:00
Keen Yee Liau 0268b72d2c Revert "test(language-service): Make project service a singleton (#39308)" (#39322)
This reverts commit 1b21350e17.

PR Close #39322
2020-10-19 09:25:19 -07:00
Keen Yee Liau 1b21350e17 test(language-service): Make project service a singleton (#39308)
Constructing a project service is expensive. Making it a singleton could
speed up tests considerably.

On my MacBook Pro, test execution went from 24.4s to 14.5s (~40% improvement).

PR Close #39308
2020-10-16 12:34:16 -07:00
Keen Yee Liau 0c01c4a898 test(language-service): wrap setup() in beforeAll to speed up fit() test (#39305)
Test harness `setup()` is expensive, in the order of ~2.5 seconds.

We could speed up `fit()` tests considerably if `setup()` is wrapped
in `beforeAll()` to avoid running it unnecessarily.

PR Close #39305
2020-10-16 12:33:36 -07:00
Andrew Scott 563fb6cdbe feat(language-service): Implement go to definition for style and template urls (#39202)
This commit enables the Ivy Language Service to 'go to definition' of a
templateUrl or styleUrl, which would jump to the template/style file
itself.

PR Close #39202
2020-10-16 12:31:54 -07:00
Andrew Scott 087596bbde refactor(language-service): Move some util functions to common (#39202)
These functions will be useful to the Ivy language service as well to
provide 'go to definition' functionality for template and style urls.

PR Close #39202
2020-10-16 12:31:54 -07:00
JiaLiPassion a38293d213 release: cut the zone.js-0.11.2 release to fix several new issues (#39298)
PR Close #39298
2020-10-16 10:18:55 -07:00
Bjarki 81aa119739 fix(core): convert legacy-sanitized values to Trusted Types (#39218)
Use the bypass-specific Trusted Types policy for automatically upgrade
any values from custom sanitizers or the bypassSecurityTrust functions
to a Trusted Type. Update tests to reflect the new behavior.

PR Close #39218
2020-10-16 08:13:52 -07:00
Bjarki 49197d12a0 feat(core): create a Trusted Types policy for bypass conversions (#39218)
When an application uses a custom sanitizer or one of the
bypassSecurityTrust functions, Angular has no way of knowing whether
they are implemented in a secure way. (It doesn't even know if they're
introduced by the application or by a shady third-party dependency.)
Thus using Angular's main Trusted Types policy to bless values coming
from these two sources would undermine the security that Trusted Types
brings.

Instead, introduce a Trusted Types policy called angular#unsafe-bypass
specifically for blessing values from these sources. This allows an
application to enforce Trusted Types even if their application uses a
custom sanitizer or the bypassSecurityTrust functions, knowing that
compromises to either of these two sources may lead to arbitrary script
execution. In the future Angular will provide a way to implement
custom sanitizers in a manner that makes better use of Trusted Types.

PR Close #39218
2020-10-16 08:13:52 -07:00
Bjarki 9ec2bad4dc refactor(core): make HTML sanitizer return TrustedHTML (#39218)
Make Angular's HTML sanitizer return a TrustedHTML, as its output is
trusted not to cause XSS vulnerabilities when used in a context where a
browser may parse and evaluate HTML. Also update tests to reflect the
new behaviour.

PR Close #39218
2020-10-16 08:13:52 -07:00
Bjarki e8d47c2d41 feat(core): allow returning Trusted Types from SanitizerFn (#39218)
Sanitizers in Angular currently return strings, which will then
eventually make their way down to the DOM, e.g. as the value of an
attribute or property. This may cause a Trusted Types violation. As a
step towards fixing that, make it possible to return Trusted Types from
the SanitizerFn interface, which represents the internal sanitization
pipeline. DOM renderer interfaces are also updated to reflect the fact
that setAttribute and setAttributeNS must be able to accept Trusted
Types.

PR Close #39218
2020-10-16 08:13:52 -07:00
Bjarki 765fa337e3 fix(compiler): use Trusted Types policy in JIT compiler (#39210)
The JIT compiler uses the Function constructor to compile arbitrary
strings into executable code at runtime, which causes Trusted Types
violations. To address this, JitEvaluator is instead made to use the
Trusted Types compatible Function constructor introduced by Angular's
Trusted Types policy for JIT.

PR Close #39210
2020-10-16 08:13:14 -07:00
Bjarki 6570292672 feat(core): create a Trusted Types policy for JIT compiler (#39210)
Introduce a Trusted Types policy for use by Angular's JIT compiler named
angular#unsafe-jit. As the compiler turns arbitrary untrusted strings
into executable code at runtime, using Angular's main Trusted Types
policy does not seem appropriate, unless it can be ensured that the
provided strings are indeed trusted. Until then, this JIT policy can be
allowed by applications that rely on the JIT compiler but want to
enforce Trusted Types, knowing that a compromise of the JIT compiler can
lead to arbitrary script execution. In particular, this is required for
enabling Trusted Types in Angular unit tests, since they make use of the
JIT compiler.

Also export the internal Trusted Types definitions from the core package
so that they can be used in the compiler package.

PR Close #39210
2020-10-16 08:13:14 -07:00
mcalmus 4610093c87 fix(core): guard reading of global `ngDevMode` for undefined. (#36055)
When reading globals such as `ngDevMode` the read should be guarded by `typeof ngDevMode` otherwise it will throw if not
defined in `"use strict"` mode.

PR Close #36055
2020-10-16 08:12:22 -07:00
Jessica Janiuk a3812c6cbd refactor(core): renames checkNoChangesMode to be clearer (#39277)
getCheckNoChangesMode was discovered to be unclear as to the purpose of
it. This refactor is a simple renaming to make it much clearer what that
method and property does.

PR Close #39277
2020-10-15 17:01:20 -07:00
Andrew Scott 5bda62c51d refactor(language-service): Return directive defs when input name is part of selector (#39243)
When an input name is part of the directive selector, it would be good to return the directive as well
when performing 'go to definition' or 'go to type definition'. As an example, this would allow
'go to type definition' for ngIf to take the user to the NgIf directive.
'Go to type definition' would otherwise return no results because the
input is a generic type. This would also be the case for all primitive
input types.

PR Close #39243
2020-10-15 14:17:24 -07:00
Bjarki 6e18d2dacc fix(compiler): promote constants in templates to Trusted Types (#39211)
Angular treats constant values of attributes and properties in templates
as secure. This means that these values are not sanitized, and are
instead passed directly to the corresponding setAttribute or setProperty
function. In cases where the given attribute or property is
security-sensitive, this causes a Trusted Types violation.

To address this, functions for promoting constant strings to each of the
three Trusted Types are introduced to Angular's private codegen API. The
compiler is updated to wrap constant strings with calls to these
functions as appropriate when constructing the `consts` array. This is
only done for security-sensitive attributes and properties, as
classified by Angular's dom_security_schema.

PR Close #39211
2020-10-15 09:08:01 -07:00
Bjarki 9bfb508b87 build: replace @types/trusted-types dep with minimal type defs (#39211)
The @types/trusted-types type definitions are currently imported in
types.d.ts, which causes them to eventually be imported in core.d.ts.
This forces anyone compiling against @angular/core to provide the
@types/trusted-types package in their compilation unit, which we don't
want.

To address this, get rid of the @types/trusted-types and instead import
a minimal version of the Trusted Types type definitions directly into
Angular's codebase.

Update the existing references to Trusted Types to point to the new
definitions.

PR Close #39211
2020-10-15 09:08:00 -07:00
JiaLiPassion 497af77d7a build(zone.js): zone.js should output esm format for fesm2015 bundles (#39203)
Zone.js support `Angular package format` since `0.11`, but the `fesm2015` bundles
are not `esm` format, it still use `umd` bundle which is not correct, in this PR,
a new `esm` bundle output is added in `rollup_bundle` rule under `tools`, so
zone.js can use the new rule to generate `esm` bundles.

PR Close #39203
2020-10-15 09:07:38 -07:00
Pete Bacon Darwin 822b838fbc fix(ngcc): ensure that "inline exports" can be interpreted correctly (#39267)
Previously, inline exports of the form `exports.foo = <implementation>;` were
being interpreted (by the ngtsc `PartialInterpeter`) as `Reference` objects.
This is not what is desired since it prevents the value of the export
from being unpacked, such as when analyzing `NgModule` declarations:

```
exports.directives = [Directive1, Directive2];

@NgImport({declarations: [exports.directives]})
class AppModule {}
```

In this example the interpreter would think that `exports.directives`
was a reference rather than an array that needs to be unpacked.

This bug was picked up by the ngcc-validation repository. See
https://github.com/angular/ngcc-validation/pull/1990 and
https://circleci.com/gh/angular/ngcc-validation/17130

PR Close #39267
2020-10-14 14:11:45 -07:00
Pete Bacon Darwin ac0016cd82 refactor(compiler-cli): visit inline declarations with implementations differently (#39267)
Some inline declarations are of the form:

```
exports.<name> = <implementation>;
```

In this case the declaration `node` is `exports.<name>`.
When interpreting such inline declarations we actually want
to visit the `implementation` expression rather than visiting
the declaration `node`.

This commit adds `implementation?: ts.Expression` to the
`InlineDeclaration` type and updates the interpreter to visit
these expressions as described above.

PR Close #39267
2020-10-14 14:11:45 -07:00
George Kalpakas eb9eebbb45 refactor(elements): simplify code after IE<11 support removal (#39265)
Support for IE<11 is being removed in v11. PR #39090 removed some code
that was no longer needed.

Now that there are no longer multiple code-paths (which was previously
needed for IE<11 support), this commit simplifies the code further (for
example, to avoid unnecessary functions calls and to avoid iterating
over a component's inputs multiple times).

PR Close #39265
2020-10-14 14:11:22 -07:00
Keen Yee Liau 8f1317f06f fix(language-service): [Ivy] create compiler only when program changes (#39231)
This commit fixes a bug in which a new Ivy Compiler is created every time
language service receives a new request. This is not needed if the
`ts.Program` has not changed.

A new class `CompilerFactory` is created to manage Compiler lifecycle and
keep track of template changes so that it knows when to override them.
With this change, we no longer need the method `getModifiedResourceFile()`
on the adapter. Instead, we call `overrideComponentTemplate` on the
template type checker.

This commit also changes the incremental build strategy from
`PatchedIncrementalBuildStrategy` to `TrackedIncrementalBuildStrategy`.

PR Close #39231
2020-10-14 14:10:37 -07:00
Andrew Kushnir a83693ddd9 refactor(core): use relative import paths in micro benchmarks (#39142)
This commit updates micro benchmarks to use relative path to Ivy runtime code. Keeping absolute
locations caused issues with build optimizer that retained certain symbols and they appeared in the
output twice.

PR Close #39142
2020-10-14 14:10:13 -07:00
Andrew Kushnir dd66aa290a test(core): add micro benchmarks for i18n scenarios (#39142)
This commit adds micro benchmarks to run micro benchmarks for i18n-related logic in the
following scenarios:

- i18n static attributes
- i18n attributes with interpolations
- i18n blocks of static text
- i18n blocks of text + interpolations
- simple ICUs
- nested ICUs

First 4 scenarios also have baseline scenarios (non-i18n) so that we can compare i18n perf with
non-i18n logic.

PR Close #39142
2020-10-14 14:10:13 -07:00
Adam Plumer 0ec7043490 feat(core): add initialNavigation schematic (#36926)
Add a schematic to update users to the new v11 `initialNavigation`
options for `RouterModule`. This replaces the deprecated/removed
`true`, `false`, `legacy_disabled`, and `legacy_enabled` options
with the newer `enabledBlocking` and `enabledNonBlocking` options.

PR Close #36926
2020-10-14 12:01:07 -07:00
Adam c4becca0e4 feat(router): add new initialNavigation options to replace legacy (#37480)
As of Angular v4, four of the options for
`ExtraOptions#initialNavigation` have been deprecated. We intend
to remove them in v11. The final state for these options is:
`enabledBlocking`, `enabledNonBlocking`, and `disabled`. We plan
to remove and deprecate the remaining option in the next two
major releases.

New options:
- `enabledNonBlocking`: same as legacy_enabled
- `enabledBlocking`: same as enabled

BREAKING CHANGE:

* The `initialNavigation` property for the options in
  `RouterModule.forRoot` no longer supports `legacy_disabled`,
  `legacy_enabled`, `true`, or `false` as valid values.
  `legacy_enabled` (the old default) is instead `enabledNonBlocking`
* `enabled` is deprecated as a valid value for the
  `RouterModule.forRoot` `initialNavigation` option. `enabledBlocking`
  has been introduced to replace it

PR Close #37480
2020-10-14 11:20:51 -07:00
Joey Perrott 93ee05d92a fix(router): create schematic for preserveQueryParams (#38762)
Create a schematic for migrating preserveQueryParams to use queryParamsHandler
instead.

PR Close #38762
2020-10-14 10:40:55 -07:00
Joey Perrott 783a5bd7bb fix(router): remove preserveQueryParams symbol (#38762)
Remove preserveQueryParams as it was deprecated for removal in v4, use
queryParamsHandling="preserve" instead.

BREAKING CHANGE: preserveQueryParams has been removed, use
queryParamsHandling="preserve" instead

PR Close #38762
2020-10-14 10:40:55 -07:00
JoostK 898be92f70 perf(ngcc): do not rescan program source files when referenced from multiple root files (#39254)
When ngcc is configured to run with the `--use-program-dependencies`
flag, as is the case in the CLI's asynchronous processing, it will scan
all source files in the program, starting from the program's root files
as configured in the tsconfig. Each individual root file could
potentially rescan files that had already been scanned for an earlier
root file, causing a severe performance penalty if the number of root
files is large. This would be the case if glob patterns are used in the
"include" specification of a tsconfig file.

This commit avoids the performance penalty by keeping track of the files
that have been scanned across all root files, such that no source file
is scanned multiple times.

Fixes #39240

PR Close #39254
2020-10-14 09:34:11 -07:00
Bjarki f6d5cdfbd7 fix(core): use Trusted Types policy in named_array_type (#39209)
Address a Trusted Types violation that occurs in createNamedArrayType
during development mode. Instead of passing strings directly to "new
Function", use the Trusted Types compatible function constructor exposed
by the Trusted Types policy.

PR Close #39209
2020-10-14 09:33:48 -07:00
Bjarki 5913e5c4e8 feat(core): add Trusted Types workaround for Function constructor (#39209)
Chrome currently does not support passing TrustedScript to the Function
constructor, and instead fails with a Trusted Types violation when
called. As the Function constructor is used in a handful of places
within Angular, such as in the JIT compiler and named_array_type, the
workaround proposed on the following page is implemented:
https://github.com/w3c/webappsec-trusted-types/wiki/Trusted-Types-for-function-constructor

To be precise, it constructs a string representing an anonymous function
in a way that is equivalent to what the Function constructor does,
promotes it to a TrustedScript and then calls eval.

To facilitate backwards compatibility, new Function is used directly in
environments that do not support Trusted Types.

PR Close #39209
2020-10-14 09:33:47 -07:00
JiaLiPassion c53f19ac47 refactor(zone.js): rename several internal apis in fake async zone spec (#39127)
In `FakeAsyncZoneSpec`, there are several variables and APIs to identify
different times, and the names are confusing, in this commit, they are
renamed for more clear understandings.

1. currentTickTime, the tick millis advanced.
2. getFakeBaseSystemTime(), return the fake base system time.
3. setFakeBaseSystemTime(), set the fake base system time.
4. getRealSystemTime(), get the underlying native system time.

PR Close #39127
2020-10-13 15:56:22 -07:00
JiaLiPassion ffc3332dcd fix(zone.js): jest getRealSystemTime should return native time (#39127)
`jest.getRealSystemTime()` should return native `Date.now()`, the
current implemenation return the wrong value which is the fixed
number.

PR Close #39127
2020-10-13 15:56:22 -07:00
Andrew Kushnir 8fd25d9614 docs: remove IE10 references from comments in the code (#39090)
PR Close #39090
2020-10-13 15:51:49 -07:00
Andrew Kushnir 0001dbdede refactor(core): remove IE-sepcific logic from setClassMetadata function (#39090)
This commit simplifies the logic in the `setClassMetadata` function to avoid the code needed to
support IE 9 and IE 10.

PR Close #39090
2020-10-13 15:51:49 -07:00
Andrew Kushnir cbef410e3f refactor(elements): remove code to support IE9/10 (#39090)
Since support for IE 9 and IE 10 browsers is removed in v11, the code that was added to support
these browsers is no longer needed.

PR Close #39090
2020-10-13 15:51:49 -07:00
Andrew Kushnir db37c17e02 refactor(core): remove NG_PROV_DEF_FALLBACK needed for IE10 only (#39090)
This commit removes a workaround previously used for IE 9 and 10 to identify whether InjectableDef
was defined on a given class instance. Since support for IE 9 and 10 is removed, this fallback is
no longer needed.

PR Close #39090
2020-10-13 15:51:48 -07:00
Andrew Kushnir 61e6ca9b1f test(platform-browser): remove IE9 and IE10 checks from tests (#39090)
This commit removes IE 9 and IE 10 checks from the browser detection spec.
Also unblocks tests that were previously disabled due to issues in IE10.

PR Close #39090
2020-10-13 15:51:48 -07:00
Andrew Kushnir 78a33eeef9 test(core): remove code specific to IE 9 and IE 10 (#39090)
This commit updates core tests and removes the code needed to support IE 9 and IE 10 only.
The code is no longer needed since IE 9 and IE 10 support is removed in v11.

PR Close #39090
2020-10-13 15:51:48 -07:00
Bjarki 7d4929918d fix(core): use Trusted Types policy in inert DOM builder (#39208)
When Angular is used in an environment that enforces Trusted Types, the
inert DOM builder raises a Trusted Types violation due to its use of
DOMParser and element.innerHTML with plain strings. Since it is only
used internally (in the HTML sanitizer and for i18n ICU parsing), we
update it to use Angular's Trusted Types policy to promote the provided
HTML to TrustedHTML.

PR Close #39208
2020-10-13 14:58:06 -07:00
JiaLiPassion b642f0bf45 docs(zone.js): update changelog to add jest useFakeTimers feature (#39126)
Since we are merged https://github.com/angular/angular/issues/38851 PR
about integration of jest.useFakeTimers with fakeAsync, so the
new release should also include this feature, this PR updated the zone.js
0.11.2 changelog.

PR Close #39126
2020-10-13 14:57:09 -07:00
Bjarki 0875fd2360 feat(core): create internal Trusted Types module (#39207)
Add a module that provides a Trusted Types policy for use internally by
Angular. The policy is created lazily and stored in a module-local
variable. For now the module does not allow configuring custom policies
or policy names, and instead creates its own policy with 'angular' as a
fixed policy name. This is to more easily support tree-shakability.

Helper functions for unsafely converting strings to each of the three
Trusted Types are also introduced, with documentation that make it clear
that their use requires a security review. When Trusted Types are not
available, these helper functions fall back to returning strings.

PR Close #39207
2020-10-13 11:23:36 -07:00
Bjarki c4266fb729 feat(core): depend on type definitions for Trusted Types (#39207)
To facilitate the upcoming Trusted Types support being added to Angular,
add the TypeScript type definitions for the Trusted Types browser API as
a dependency in the root package.json and types.d.ts since they're
needed for compiling the Angular packages.

PR Close #39207
2020-10-13 11:23:36 -07:00
Kristiyan Kostadinov 5ce71e0fbc feat(core): add automated migration to replace async with waitForAsync (#39212)
Adds a migration that finds all imports and calls to the deprecated `async` function from
`@angular/core/testing` and replaces them with `waitForAsync`.

These changes also move a bit of code out of the `Renderer2` migration so that it can be reused.

PR Close #39212
2020-10-13 09:55:34 -07:00
Andrew Scott 437e563507 refactor(language-service): Allow "go to definition" for directives in Ivy (#39228)
For directives/components, it would be generally more appropriate for
"go to type definition" to be the function which navigates to the class
definition. However, for a better user experience, we should do this
for "go to definition" as well.

PR Close #39228
2020-10-13 08:52:29 -07:00
Adrien Crivelli b0b4953fd6 fix(router): Allow undefined inputs on routerLink (#39151)
This make it coherent with typing of Router.createUrlTree to which
those inputs are directly forwarded to. And hence it allow to pass
`undefined`, `null` or a value to the routerLink directive.

BREAKING CHANGE: in most cases this should not break, but if you were
accessing the values of `queryParams`, `fragment` or `queryParamsHandling`
you might need to relax the typing to also accept `undefined` and `null`.

Signed-off-by: Adrien Crivelli <adrien.crivelli@gmail.com>

PR Close #39151
2020-10-12 12:52:37 -07:00
Taymon A. Beal 5471789664 refactor(animations): do not assign to innerHTML (#37397)
This should not change behavior, but it prevents false-positive warnings in various static analysis
tools, including tools used internally at Google.

PR Close #37397
2020-10-12 10:44:59 -07:00
Pete Bacon Darwin 952710b43b refactor(compiler-cli): ensure `isNamed....()` helpers check name is identity (#38959)
Previously the `node.name` property was only checked to ensure it was
defined. But that meant that it was a `ts.BindingName`, which also includes
`ts.BindingPattern`, which we do not support. But these helper methods were
forcefully casting the value to `ts.Identifier.

Now we also check that the `node.name` is actually an `ts.Identifier`.

PR Close #38959
2020-10-12 08:32:47 -07:00
Pete Bacon Darwin 2736a43ecb fix(compiler-cli): support namespaced query types in directives (#38959)
Previously directive "queries" that relied upon a namespaced type

```ts
queries: {
  'mcontent': new core.ContentChild('test2'),
}
```

caused an error to be thrown. This is now supported.

PR Close #38959
2020-10-12 08:32:47 -07:00
Pete Bacon Darwin f4fee86f77 fix(ngcc): support inline export declarations in UMD files (#38959)
Previously, any declarations that were defined "inline" were not
recognised by the `UmdReflectionHost`.

For example, the following syntax was completely unrecognized:

```ts
var Foo_1;
exports.Foo = Foo_1 = (function() {
  function Foo() {}
  return Foo;
})();
exports.Foo = Foo_1 = __decorate(SomeDecorator, Foo);
```

Such inline classes were ignored and not processed by ngcc.

This lack of processing led to failures in Ivy applications that relied
on UMD formats of libraries such as `syncfusion/ej2-angular-ui-components`.

Now all known inline UMD exports are recognized and processed accordingly.

Fixes #38947

PR Close #38959
2020-10-12 08:32:46 -07:00
Pete Bacon Darwin 47eab61cad test(ngcc): use `isNamedDeclaration()` helper to simplify tests (#38959)
Previously these tests were checking multiple specific expression
types. The new helper function is more general and will also support
`PropertyAccessExpression` nodes for `InlineDeclaration` types.

PR Close #38959
2020-10-12 08:32:46 -07:00
Pete Bacon Darwin 0accd1e68d refactor(compiler-cli): implement `DeclarationNode` node type (#38959)
Previously the `ConcreteDeclaration` and `InlineDeclaration` had
different properties for the underlying node type. And the `InlineDeclaration`
did not store a value that represented its declaration.

It turns out that a natural declaration node for an inline type is the
expression. For example in UMD/CommonJS this would be the `exports.<name>`
property access node.

So this expression is now used for the `node` of `InlineDeclaration` types
and the `expression` property is dropped.

To support this the codebase has been refactored to use a new `DeclarationNode`
type which is a union of `ts.Declaration|ts.Expression` instead of `ts.Declaration`
throughout.

PR Close #38959
2020-10-12 08:32:46 -07:00
Pete Bacon Darwin 2c0282f4c2 test(ngcc): use `isNamedFunctionDeclaration()` in UMD tests (#38959)
This makes these tests more resilient to changes in the test code
structure. For example switching from

```
var SomeClass = <implementation>;
exports.SomeClass = SomeClass;
```

to

```
exports.SomeClass = <implementation>;
```

PR Close #38959
2020-10-12 08:32:46 -07:00
Pete Bacon Darwin 6650d71fe2 test(compiler-cli): make the `getDeclaration()` utility more resilient to code format (#38959)
Previously `getDeclaration()` would only return the first node that matched
the name passed in and then assert the predicate on this single node.
It also only considered a subset of possible declaration types that we might
care about.

Now the function will parse the whole tree collecting an array of all the
nodes that match the name. It then filters this array based on the predicate
and only errors if the filtered array is empty.

This makes this function much more resilient to more esoteric code formats
such as UMD.

PR Close #38959
2020-10-12 08:32:46 -07:00
Pete Bacon Darwin 65997c0649 refactor(ngcc): simplify and break up ES2015 functions with helpers (#38959)
The protected helper functions can then be overridden by subclasses of the
Esm2015ReflectionHost.

PR Close #38959
2020-10-12 08:32:46 -07:00
Pete Bacon Darwin 1d6e67478e refactor(ngcc): simplify and rename `getClassDeclarationFromInnerDeclaration()` (#38959)
The new function does not try to restrict the kind of AST node that it
finds, leaving that to the caller. This will make it more resuable in the
UMD reflection host.

PR Close #38959
2020-10-12 08:32:46 -07:00