Commit Graph

7148 Commits

Author SHA1 Message Date
Pete Bacon Darwin 0fd06e5ab8 test(compiler-cli): add external template source-map tests (#40237)
This commit migrates, and supplements, compliance tests that
check the source-mapping of external templates.

PR Close #40237
2021-01-07 13:12:53 -08:00
Pete Bacon Darwin dfe64a0060 test(compiler-cli): improve source mapping compliance test failure messages (#40237)
Now, if a source-mapping compliance test fails, the message displays both
the path to the generated file, and more helpfully the path to the expected
file.

PR Close #40237
2021-01-07 13:12:53 -08:00
Pete Bacon Darwin 9f662e1313 test(compiler-cli): tidy up the line-ending compliance test TEST_CASES (#40237)
Previously the names of the source and expectation files were often reused,
which caused potential confusion.

There is now a single source file for
each test-case, which is important when they are being compiled with different
compiler options, since the GOLDEN_PARTIAL file will only contain one copy
per file name.

The names of the expectation files have now been changed so that is clearer
which test-case they are related to.

PR Close #40237
2021-01-07 13:12:53 -08:00
Pete Bacon Darwin 2224ab712d test(compiler-cli): fix up import paths in test code (#40237)
These imports were unnecessrily deep, since the files are actually in the
same directory.

PR Close #40237
2021-01-07 13:12:53 -08:00
Pete Bacon Darwin 8ebf538c04 refactor(compiler-cli): add file to Babel locations (#40237)
The filename of the source-span is now added to the Babel location
when setting the source-map range in the `BabelAstHost`.

Note that the filename is only added if it is different to the main file
being processed. Otherwise Babel will generate two entries in its
generated source-map.

PR Close #40237
2021-01-07 13:12:53 -08:00
Pete Bacon Darwin 3158858059 fix(compiler-cli): do not duplicate repeated source-files in rendered source-maps (#40237)
When a source-map/source-file tree has nodes that refer to the same file, the
flattened source-map rendering was those files multiple times, rather than
consolidating them into a single source-map source.

PR Close #40237
2021-01-07 13:12:53 -08:00
Pete Bacon Darwin e7c3687936 refactor(compiler): synthesize external template node for partial compilation (#40237)
When partially compiling a component with an external template, we must
synthesize a new AST node for the string literal that holds the contents of
the external template, since we want to source-map this expression directly
back to the original external template file.

PR Close #40237
2021-01-07 13:12:53 -08:00
Andrew Scott 2028a43580 fix(router): Remove usage of `Object.entries` to avoid the need for a polyfill (#40340)
`Object.entries` is not supported in IE11 without a polyfill. The quickest,
most straightfoward fix for this is to simply use `Object.keys` instead.
We may want to consider including the polyfill in the CLI in the future
or just wait until IE11 support is dropped before using
`Object.entries`.

PR Close #40340
2021-01-07 11:45:58 -08:00
Andrew Scott 989b4a94d4 refactor(compiler-cli): Return symbols for all matching outputs (#40144)
This commit ensures that the template type checker returns symbols for
all outputs if a template output listener binds to more than one.

PR Close #40144
2021-01-06 13:53:46 -08:00
Andrew Scott da2be4b710 refactor(compiler-cli): Return symbols for all matching inputs (#40144)
This commit ensures that the template type checker returns symbols for
all inputs if an attribute binds to more than one.

PR Close #40144
2021-01-06 13:53:46 -08:00
Andrew Scott 13020f904f fix(router): correctly deactivate children with componentless parent (#40196)
During route activation, a componentless route will not have a context created
for it, but the logic continues to recurse so that children are still
activated. This can be seen here:
362f45c4bf/packages/router/src/operators/activate_routes.ts (L151-L158)

The current deactivation logic does not currently account for componentless routes.

This commit adjusts the deactivation logic so that if a context cannot
be retrieved for a given route (because it is componentless), we
continue to recurse and deactivate the children using the same
`parentContexts` in the same way that activation does.

Fixes #20694

PR Close #40196
2021-01-06 13:49:30 -08:00
Keen Yee Liau 183fb7e7b9 fix(language-service): return all typecheck files via getExternalFiles (#40162)
We need a means to preserve typecheck files when a project is reloaded,
otherwise the Ivy compiler will throw an error when it's unable to find
them. This commit implements `getExternalFiles()` called by the langauge
server to achieve this goal.

For more info see https://github.com/angular/vscode-ng-language-service/issues/1030

PR Close #40162
2021-01-06 11:34:15 -08:00
Keen Yee Liau 0264f76e94 fix(language-service): LSParseConfigHost.resolve should not concat abs paths (#40242)
`ts.server.ServerHost.resolvePath()` is different from Angular's
`FileSystem.resolve()` because the signature of the former is

```ts
resolvePath(path: string): string;	// ts.server.ServerHost
```

whereas the signature of the latter is
```ts
resolve(...paths: string[]): AbsoluteFsPath; // FileSystem on compiler-cli
```

The current implementation calls `path.join()` to concatenate all the input
paths and pass the result to `ts.server.ServerHost.resolvePath()`, but doing
so results in filenames like
```
/foo/bar/baz/foo/bar/baz/tsconfig.json
```
if both input paths are absolute.

`ts.server.ServerHost` should not be used to implement the
`resolve()` method expected by Angular's `FileSystem`.
We should use Node's `path.resolve()` instead, which will correctly collapse
the absolute paths.

Fix https://github.com/angular/vscode-ng-language-service/issues/1035

PR Close #40242
2021-01-06 10:54:40 -08:00
Keen Yee Liau a62416c6e4 fix(language-service): include compilerOptions.rootDir in rootDirs (#40243)
When resolving references, the Ivy compiler has a few strategies it could use.

For relative path, one of strategies is [`RelativePathStrategy`](
https://github.com/angular/angular/blob/master/packages/compiler-cli/src/
ngtsc/imports/README.md#relativepathstrategy). This strategy
relies on `compilerOptions.rootDir` and `compilerOptions.rootDirs` to perform
the resolution, but language service only passes `rootDirs` to the compiler,
and not `rootDir`.

In reality, `rootDir` is very different from `rootDirs` even though they
sound the same.
According to the official [TS documentation][1],
> `rootDir` specifies the root directory of input files. Only use to control
> the output directory structure with --outDir.

> `rootDirs` is a list of root folders whose combined content represent the
> structure of the project at runtime. See [Module Resolution documentation](
> https://www.typescriptlang.org/docs/handbook/
> module-resolution.html#virtual-directories-with-rootdirs)
> for more details.

For now, we keep the behavior between compiler and language service consistent,
but we will revisit the notion of `rootDir` and how it is used later.

Fix angular/vscode-ng-language-service#1039

[1]: https://www.typescriptlang.org/docs/handbook/compiler-options.html

PR Close #40243
2021-01-06 10:54:11 -08:00
Kristiyan Kostadinov 335d6c8c00 fix(compiler): incorrectly encapsulating selectors with escape sequences (#40264)
CSS supports escaping in selectors, e.g. writing `.foo:bar` will match an element with the
`foo` class and `bar` pseudo-class, but `.foo\:bar` will match the `foo:bar` class. Our
shimmed shadow DOM encapsulation always assumes that `:` means a pseudo selector
which breaks a selector like `.foo\:bar`.

These changes add some extra logic so that escaped characters in selectors are preserved.

Fixes #31844.

PR Close #40264
2021-01-06 10:33:49 -08:00
Pete Bacon Darwin 8ebac24b48 fix(core): ensure sanitizer works if DOMParser return null body (#40107)
In some browsers, notably a mobile version of webkit on iPad, the
result of calling `DOMParser.parseFromString()` returns a document
whose `body` property is null until the next tick of the browser.
Since this is of no use to us for sanitization, we now fall back to the
"inert document" strategy for this case.

Fixes #39834

PR Close #40107
2021-01-06 10:32:24 -08:00
SylvainJanet fdec650ef2 docs(forms): typo word "property" was missing (#40323)
Word "property" was missing in @returns description of minLength
PR Close #40323
2021-01-06 08:44:03 -08:00
JoostK d4327d51d1 feat(compiler-cli): JIT compilation of component declarations (#40127)
The `ɵɵngDeclareComponent` calls are designed to be translated to fully
AOT compiled code during a build transform, but in cases this is not
done it is still possible to compile the declaration object in the
browser using the JIT compiler. This commit adds a runtime
implementation of `ɵɵngDeclareComponent` which invokes the JIT compiler
using the declaration object, such that a compiled component definition
is made available to the Ivy runtime.

PR Close #40127
2021-01-06 08:28:03 -08:00
JoostK 826b77b632 test(core): tag `render3` test targets as ivy-only (#40127)
The `render3` test targets are currently also executed for ViewEngine
builds, even though the `render3` infrastructure only concerns Ivy
infrastructure. This commit tags the test targets as ivy-only to disable
those tests for View Engine.

PR Close #40127
2021-01-06 08:28:03 -08:00
Pete Bacon Darwin 7c167629b8 fix(compiler-cli): ngcc - remove outdated link (#40285)
The link to the "speeding-up-ngcc-compilation" URL does not exist,
it was removed shortly after it was added, but the link in the ngcc
error message was not updated.

Fixes #39837

PR Close #40285
2021-01-06 07:10:39 -08:00
Kristiyan Kostadinov 6abc13330b fix(compiler): don't report parse error for interpolation inside string in property binding (#40267)
Currently we check whether a property binding contains an interpolation using a regex so
that we can throw an error. The problem is that the regex doesn't account for quotes
which means that something like `[prop]="'{{ foo }}'"` will be considered an error, even
though it's not actually an interpolation.

These changes build on top of the logic from #39826 to account for interpolation
characters inside quotes.

Fixes #39601.

PR Close #40267
2021-01-05 13:57:23 -08:00
Bjarki 6a9d7e5969 refactor(core): express trusted constants with tagged template literals (#40082)
The trustConstantHtml and trustConstantResourceUrl functions are only
meant to be passed constant strings extracted from Angular application
templates, as passing other strings or variables could introduce XSS
vulnerabilities.

To better protect these APIs, turn them into template tags. This makes
it possible to assert that the associated template literals do not
contain any interpolation, and thus must be constant.

Also add tests for the change to prevent regression.

PR Close #40082
2021-01-05 13:56:57 -08:00
Loic Yondjeu c1d7805acc docs(core): Fix spelling (#40296)
PR Close #40296
2021-01-05 13:55:14 -08:00
Andrew Scott 605775398f docs(router): Clarify 'parent' for params inheritance (#40304)
When talking about parameter inheritance, one might think that matrix
parameters can be inherited from the "parent" segment, or the segment
which appears immediately to the left. In reality, when we talk about
a "parent" in the `Router`, we mean the parent `Route` config. This
config may contain more than one segment and matrix parameters must
appear at the end or they do not "belong" to any config.

PR Close #40304
2021-01-05 13:54:41 -08:00
Andrew Scott e43f7e26fe fix(router): apply redirects should match named outlets with empty path parents (#40029)
There are two parts to this commit:
1. Revert the changes from #38379. This change had an incomplete view of
how things worked and also diverged the implementations of
`applyRedirects` and `recognize` even more.
2. Apply the fixes from the `recognize` algorithm to ensure that named
outlets with empty path parents can be matched. This change also passes
all the tests that were added in #38379 with the added benefit of being
a more complete fix that stays in-line with the `recognize` algorithm.
This was made possible by using the same approach for `split` by
always creating segments for empty path matches (previously, this was
only done in `applyRedirects` if there was a `redirectTo` value). At the
end of the expansions, we need to squash all empty segments so that
serializing the final `UrlTree` returns the same result as before.

Fixes #39952
Fixes #10726
Closes #30410

PR Close #40029
2021-01-05 12:43:47 -08:00
Andrew Scott 5842467134 refactor(router): Extract common functions for config matching (#40029)
The `applyRedirects` and `recognize` algorithms have the same overall goal:
match a `UrlTree` with the application's `Routes` config. There are a
few key functions in these algorithms which can be shared rather than
duplicated between the two. This also makes it easier to see how the two
are similar and where they diverge.

PR Close #40029
2021-01-05 12:43:47 -08:00
Andrew Scott 3966bcc5d9 fix(router): Ensure named outlets with empty path parents are recognized (#40029)
This commit updates the `recognize` algorithm to work with named outlets
which have empty path parents. For example, given the following config

```
  const routes = [
    {
      path: '',
      children: [
        {path: 'a', outlet: 'aux', component: AuxComponent}
    ]}
  ];
```

The url `/(aux:a)` should match this config. In order to do so, we need
to allow the children of `UrlSegmentGroup`s to match a `Route` config
for a different outlet (in this example, the `primary`) when it's an
empty path. This should also *only* happen if we were unable to find a
match for the outlet in the level above. That is, the matching strategy
is to find the first `Route` in the list which _matches the given
outlet_. If we are unable to do that, then we allow empty paths from
other outlets to match and try to find some child there whose outlet
matches our segment.

PR Close #40029
2021-01-05 12:43:47 -08:00
Andrew Scott a9f8deb173 refactor(router): make `recognize` synchronous (#40029)
To make the tests suite easier to follow, `Recognize#apply` can be made
into a synchronous function rather than one that return an `Observable`.

Also, as a chore, remove as many `any` types as possible.

PR Close #40029
2021-01-05 12:43:47 -08:00
Andrew Scott 6f1609e092 refactor(router): Update `recognize` to return `null` when there is no match (#40029)
This commit updates the `recognize` algorithm to return `null` when a
segment does not match a given config rather than throwing an error.
This makes the code much easier to follow because the "no match" result
has to be explicitly handled rather than catching the error in very
specific places.

PR Close #40029
2021-01-05 12:43:47 -08:00
Andrew Scott 77f47da016 refactor(router): Use for...of rather than `mapChildrenIntoArray` helper (#40029)
When stepping through the `recognize` algorithm, it is much easier to
follow when using a simple `for...of` rather than the helper
`mapChildrenIntoArray` with the passed closure. The only special thing that
`mapChildrenIntoArray` does is ensure the primary route appears first.
This change will have no affect on the result because `processChildren` later calls
`sortActivatedRouteSnapshots`, which does the same thing.

PR Close #40029
2021-01-05 12:43:47 -08:00
Andrew Kushnir a3849611b7 fix(forms): clean up connection between FormControl/FormGroup and corresponding directive instances (#39235)
Prior to this commit, removing `FormControlDirective` and `FormGroupName` directive instances didn't clear
the callbacks previously registered on FromControl/FormGroup class instances. As a result, these callbacks
were executed even after `FormControlDirective` and `FormGroupName` directive instances were destroyed. That was
also causing memory leaks since these callbacks also retained references to DOM elements.

This commit updates the cleanup logic to take care of properly detaching FormControl/FormGroup/FormArray instances
from the view by removing view-specific callback at destroy time.

Closes #20007, #37431, #39590.

PR Close #39235
2021-01-05 11:15:08 -08:00
Andrew Kushnir 3735633bb0 fix(core): take @Host into account while processing `useFactory` arguments (#40122)
DI providers can be defined via `useFactory` function, which may have arguments configured via `deps` array.
The `deps` array may contain DI flags represented by DI decorators (such as `@Self`, `@SkipSelf`, etc). Prior to this
commit, having the `@Host` decorator in `deps` array resulted in runtime error in Ivy. The problem was that the `@Host`
decorator was not taken into account while `useFactory` argument list was constructed, the `@Host` decorator was
treated as a token that should be looked up.

This commit updates the logic which prepares `useFactory` arguments to recognize the `@Host` decorator.

PR Close #40122
2021-01-05 10:14:25 -08:00
Pete Bacon Darwin 212245f197 fix(localize): ensure extracted messages are serialized in a consistent order (#40192)
The CLI integration can provide code files in a non-deterministic
order, which led to the extracted translation files having
messages in a non-consistent order between extractions.

This commit fixes this by ensuring that serialized messages
are ordered by their location.

Fixes #39262

PR Close #40192
2021-01-05 10:10:43 -08:00
Andrew Scott 805b4f936b feat(core): Add schematic to fix invalid `Route` configs (#40067)
`Route` configs with `redirectTo` as well as `canActivate` are not valid
because the `canActivate` guards will never execute. Redirects are
applied before activation. There is no error currently for these
configs, but another commit will change this so that an error does
appear in dev mode. This migration fixes the configs by removing the
`canActivate` property.

PR Close #40067
2021-01-05 10:09:28 -08:00
Andrew Scott df85f3727f refactor(router): Produce error message when canActivate is used with redirectTo (#40067)
Redirects in the router are processed before activations. This means that a canActivate will
never execute if a route has a redirect. Rather than silently ignoring
the invalid config, developers should be notified so they know why it
doesn't work.

Closes #18605
The feature request for a function/class redirect is covered in #13373.

PR Close #40067
2021-01-05 10:09:27 -08:00
Andrew Scott d466db8285 fix(language-service): Do not include $event parameter in reference results (#40158)
Given the template
`<div (click)="doSomething($event)"></div>`

If you request references for the `$event`, the results include both `$event` and `(click)="doSomething($event)"`.

This happens because in the TCB, `$event` is passed to the `subscribe`/`addEventListener`
function as an argument. So when we ask typescript to give us the references, we
get the result from the usage in the subscribe body as well as the one passed in as an argument.

This commit adds an identifier to the `$event` parameter in the TCB so
that the result returned from `getReferencesAtPosition` can be
identified and filtered out.

fixes #40157

PR Close #40158
2021-01-05 10:07:20 -08:00
Andrew Scott 4eac7e6436 fix(router): Router should focus element after scrolling (#40241)
According to the [spec](https://html.spec.whatwg.org/#scroll-to-fragid),
we should attempt to set the browser focus after scrolling to a
fragment. Note that this change does not exactly follow the robust steps
outlined in the spec by finding a fallback target if the original is not
focusable. Instead, we simply attempt to focus the element by calling
`focus` on it, which will do nothing if the element is not focusable.

fixes #30067

PR Close #40241
2021-01-05 09:48:48 -08:00
Andrew Scott 112dff81b0 test(router): update scroller tests to use real objects (#40241)
The current tests in the router scroller are
[change-detector tests](https://testing.googleblog.com/2015/01/testing-on-toilet-change-detector-tests.html)
and do not ensure the correct behavior of the scroller.
This commit updates the tests to assert actual scrolling behavior of the
browser.

PR Close #40241
2021-01-05 09:48:48 -08:00
Andrew Scott a55f581add refactor(router): Remove unused property in `BrowserViewportScroller` (#40241)
The `BrowserViewportScroller` injects but does not use the `ErrorHandler`.
This commit removes the `ErrorHandler` from the constructor.

PR Close #40241
2021-01-05 09:48:47 -08:00
Howard Jing c22d00547a docs(router): fix typo (#40244)
Replace the word Angualr with Angular.

PR Close #40244
2020-12-23 10:05:31 -08:00
JoostK 9186f1feea feat(compiler-cli): JIT compilation of directive declarations (#40101)
The `ɵɵngDeclareDirective` calls are designed to be translated to fully
AOT compiled code during a build transform, but in cases this is not
done it is still possible to compile the declaration object in the
browser using the JIT compiler. This commit adds a runtime
implementation of `ɵɵngDeclareDirective` which invokes the JIT compiler
using the declaration object, such that a compiled directive definition
is made available to the Ivy runtime.

PR Close #40101
2020-12-23 09:52:19 -08:00
JoostK 7dcf2864a3 feat(compiler-cli): expose function to allow short-circuiting of linking (#40137)
The linker is implemented using a Babel transform such that Babel needs
to parse and walk a source file to find the declarations that need to be
compiled. If it can be determined that a source file is known not to
contain any declarations the parsing and walking can be skipped as a
performance improvement. This commit adds an exposed function for tools
that integrate the linker to use to allow short-circuiting of the linker
transform.

PR Close #40137
2020-12-22 14:53:02 -08:00
Kristiyan Kostadinov e4fbab9ec8 fix(core): error if detectChanges is called at the wrong time under specific circumstances (#40206)
Internally we store lifecycle hooks in the format `[index, hook, index, hook]` and when
iterating over them, we check one place ahead to figure out whether we've hit found
a hook or an index. The problem is that the loop is set up to iterate up to `hooks.length`
which means that we may go out of bounds on the last iteration, depending on where
we started. This appears to happen under a specific set of circumstances where a
directive calls `detectChanges` from an input setter while it has `ngOnChanges` and
`ngAfterViewInit` hooks.

These changes resolve the issue by only iterating up to `length - 1` which guarantees that
we can always look one place ahead.

This appears to have regressed some time in version 10.

Fixes #38611.

PR Close #40206
2020-12-22 14:52:12 -08:00
Pete Bacon Darwin 34f083c8ed fix(compiler-cli): handle `\r\n` line-endings correctly in source-mapping (#40187)
Previously `\r\n` was being treated as a single character in source-map
line start positions, which caused segment positions to become offset.

Now the `\r` is ignored when splitting, leaving it at the end of the
previous line, which solves the offsetting problem, and does not affect
source-mappings.

Fixes #40169
Fixes #39654

PR Close #40187
2020-12-22 14:50:57 -08:00
Andrew Scott 12cb39c1a4 fix(language-service): shorthand syntax with variables (#40239)
This commit fixes an issue in the ivy native language service
that caused the logic that finds a target node given a template
position to throw away the results. This happened because the
source span of a variable node in the shorthand structural
directive syntax (i.e. `*ngIf=`) included the entire binding.

The result was that we would add the variable node to the path and then
later detect that the cursor was outside the key and value spans and
throw away the whole result. In general, we do this because we do not
want to show information when the cursor is between a key/value
(`inputA=¦"123"`). However, when using the shorthand syntax, we run into
the situation where we can match an `AttributeBinding` as well as the
vaariable in `*ngIf="som¦eValue as myLocalVar"`. This commit updates the
visitor to retain enough information in the visit path to throw away
invalid targets but keep valid ones if there were multiple results on a
`t.Element` or `t.Template`.

PR Close #40239
2020-12-22 14:50:22 -08:00
JoostK 382f906948 refactor(compiler-cli): include linker entry-points in NPM package (#40180)
The linker entry-points were not previously exposed in the NPM Bazel
target so they were omitted from the bundle. This commit adds the
necessary entry-points to the compiler-cli's npm_package target.

PR Close #40180
2020-12-22 11:48:11 -08:00
JoostK e23fd1f382 refactor(compiler-cli): emit `forwardRef` invocation for forward type references (#40117)
The types of directives and pipes that are used in a component's
template may be emitted into the partial declaration wrapped inside a
closure, which is needed when the type is declared later in the module.
This poses a problem for JIT compilation of partial declarations, as
this closure is indistinguishable from a class reference itself. To mark
the forward reference function as such, this commit changes the partial
declaration codegen to emit a `forwardRef` invocation wrapped around
the closure, which ensures that the closure is properly tagged as a
forward reference. This allows the forward reference to be treated as
such during JIT compilation.

PR Close #40117
2020-12-22 08:39:58 -08:00
Misko Hevery fc1cd07eb0 fix(core): Call `onDestroy` in production mode as well (#40120)
PR #39876 introduced an error where the `onDestroy` of `ComponentRef`
would only get called if `ngDevMode` was set to true. This was because
in dev mode we would freeze `TCleanup` to verify that no more
static cleanup would get added to `TCleanup` array. This ensured
that `TCleanup` was always present in dev mode. In production the
`TCleanup` would get created only when needed. The resulting cleanup
code was incorrectly indented and would only run if `TCleanup` was
present causing this issue.

Fix #40105

PR Close #40120
2020-12-22 08:02:27 -08:00
Alan Agius 475468cc8f refactor(core): remove custom globalThis (#40123)
This is provided by TypeScript since version 3.4

PR Close #40123
2020-12-17 11:43:28 -08:00
Alan Agius 70b4816cd5 fix(core): set `ngDevMode` to `false` when calling `enableProdMode()` (#40124)
The `ngDevMode` description also mentions that calling `enableProdMode` will set this the value to `false`.
4610093c87/packages/core/src/util/ng_dev_mode.ts (L22) which is currently not the case.

PR Close #40124
2020-12-16 13:20:58 -08:00
Misko Hevery 47d9b6d72d fix(core): fix possible XSS attack in development through SSR. (#40136)
Escape the content of the strings so that it can be safely inserted into a comment node.
The issue is that HTML does not specify any way to escape comment end text inside the comment.
`<!-- The way you close a comment is with "-->". -->`. Above the `"-->"` is meant to be text
not an end to the comment. This can be created programmatically through DOM APIs.

```
div.innerHTML = div.innerHTML
```
One would expect that the above code would be safe to do, but it turns out that because comment
text is not escaped, the comment may contain text which will prematurely close the comment
opening up the application for XSS attack. (In SSR we programmatically create comment nodes which
may contain such text and expect them to be safe.)
This function escapes the comment text by looking for the closing char sequence `-->` and replace
it with `-_-_>` where the `_` is a zero width space `\u200B`. The result is that if a comment
contains `-->` text it will render normally but it will not cause the HTML parser to close the
comment.

PR Close #40136
2020-12-16 09:38:08 -08:00
Andrew Kushnir caa4666335 fix(compiler): avoid duplicate i18n blocks for i18n attrs on elements with structural directives (#40077)
Currently when `ɵɵtemplate` and `ɵɵelement` instructions are generated by compiler, all static attributes are
duplicated for both instructions. As a part of this duplication, i18n translation blocks for static i18n attributes
are generated twice as well, causing duplicate entries in extracted translation files (when Ivy extraction mechanisms
are used). This commit fixes this issue by introducing a cache for i18n translation blocks (for static attributes
only).

Also this commit further aligns `ɵɵtemplate` and `ɵɵelement` instruction attributes, which should help implement
more effective attributes deduplication logic.

Closes #39942.

PR Close #40077
2020-12-15 13:40:09 -08:00
Zach Arend db97453ca0 refactor(compiler-cli): move template parse errors to TemplateData (#40026)
Durring analysis we find template parse errors. This commit changes
where the type checking context stores the parse errors. Previously, we
stored them on the AnalysisOutput this commit changes the errors to be
stored on the TemplateData (which is a property on the shim). That way,
the template parse errors can be grouped by template.

Previously, if a template had a parse error, we poisoned the module and
would not procede to find typecheck errors. This change does not poison
modules whose template have typecheck errors, so that ngtsc can emit
typecheck errors for templates with parse errors.

Additionally, all template diagnostics are produced in the same place.
This allows requesting just the template template diagnostics or just
other types of errors.

PR Close #40026
2020-12-15 13:30:52 -08:00
Zach Arend 9dedb62494 test(compiler-cli): fix i18n error tests (#40026)
Refactors the i18n error tests to be unit tests in ngtsc_spec.ts. There
is two reasons for doing this.

First is that the tests in compliace_old expected an expection to be be
thrown but did not fail the test if no exception was thrown. That means
that this test could miss catching a bug. It is also a big hacky to call
compile directly and expect an exception to be thrown for diagnostics.

Also, this can easily be unit tested and an end-to-end test is not
necessary since we are not making use of the goldfiles for these tests.

It is easier to maintain and less hacky to validate that we get helpful
error messages when nesting i18n sections by calling getDiagnostics
directly.

PR Close #40026
2020-12-15 13:30:52 -08:00
Alex Rickabaugh 973bb403a5 fix(compiler-cli): remove classes in .d.ts files from provider checks (#40118)
This commit temporarily excludes classes declared in .d.ts files from checks
regarding whether providers are actually injectable.

Such classes used to be ignored (on accident) because the
`TypeScriptReflectionHost.getConstructorParameters()` method did not return
constructor parameters from d.ts files, mostly as an oversight. This was
recently fixed, but caused more providers to be exposed to this check, which
created a breakage in g3.

This commit temporarily fixes the breakage by continuing to exclude such
providers from the check, until g3 can be patched.

PR Close #40118
2020-12-14 16:14:25 -08:00
Alex Rickabaugh 2a7443117b feat(language-service): completions for structural directives (#40032)
This comit adds support for autocompletion of attributes that create
structural directives. Such completions differ from those of normal
attributes, as the structural directive syntax creates a synthetic
<ng-template> node which has different attributes from the main element.

PR Close #40032
2020-12-14 12:08:41 -08:00
Alex Rickabaugh c55bf4a4a3 refactor(compiler-cli): identify structural directives (#40032)
This commit introduces an `isStructural` flag on directive metadata, which
is `true` if the directive injects `TemplateRef` (and thus is at least
theoretically usable as a structural directive). The flag is not used for
anything currently, but will be utilized by the Language Service to offer
better autocompletion results for structural directives.

PR Close #40032
2020-12-14 12:08:41 -08:00
Alex Rickabaugh cbb6eae4a9 feat(language-service): autocomplete pipe binding expressions (#40032)
This commit adds autocompletion for pipe expressions, built on existing APIs
for checking which pipes are in scope.

PR Close #40032
2020-12-14 12:08:41 -08:00
Alex Rickabaugh 66378ed0ef feat(language-service): complete attributes on elements (#40032)
This commit adds attribute completion to the Language Service. It completes
from 3 sources:

1. inputs/outputs of directives currently present on the element
2. inputs/outputs/attributes of directives in scope for the element, that
   would become present if the input/output/attribute was added
3. DOM properties and attributes

We distinguish between completion of a property binding (`[foo|]`) and a
completion in an attribute context (`foo|`). For the latter, bindings to
the attribute are offered, as well as a property binding which adds the
square bracket notation.

To determine hypothetical matches (directives which would become present if
a binding is added), directives in scope are scanned and matched against a
hypothetical version of the element which has the attribute.

PR Close #40032
2020-12-14 12:08:41 -08:00
Alex Rickabaugh c0ab43f3c8 refactor(compiler-cli): introduce APIs to support directive autocompletion (#40032)
This commit adds two new APIs to the `TemplateTypeChecker`:
`getPotentialDomBindings` and `getDirectiveMetadata`. Together, these will
support the Language Service in performing autocompletion of directive
inputs/outputs.

PR Close #40032
2020-12-14 12:08:41 -08:00
Alex Rickabaugh a543e69497 refactor(compiler-cli): make `TypeCheckingScopeRegistry` a general utility (#40032)
The `annotations` package in the compiler previously contained a registry
which tracks NgModule scopes for template type-checking, including unifying
all type-checking metadata across class inheritance lines.

This commit generalizes this utility and prepares it for use in the
`TemplateTypeChecker` as well, to back APIs used by the language service.

PR Close #40032
2020-12-14 12:08:41 -08:00
Alex Rickabaugh e42250f139 feat(language-service): autocompletion of element tags (#40032)
This commit expands the autocompletion capabilities of the language service
to include element tag names. It presents both DOM elements from the Angular
DOM schema as well as any components (or directives with element selectors)
that are in scope within the template as options for completion.

PR Close #40032
2020-12-14 12:08:40 -08:00
Alex Rickabaugh ccaf48de8f refactor(language-service): add context to template target system (#40032)
This commit extends the template targeting system, which determines the node
being referenced given a template position, to return additional context if
needed about the particular aspect of the node to which the position refers.
For example, a position pointing to an element node may be pointing either
to its tag name or to somewhere in the node body. This is the difference
between `<div|>` and `<div foo | bar>`.

PR Close #40032
2020-12-14 12:08:40 -08:00
Zach Arend 19d43af627 fix(dev-infra): add vim .swp files to gitignore (#40094)
The vim editor produces temporarily files that can end in both .swo and
.swp. This commits add .swp to the .gitignore so we don't accidentaly
commit temporary files.

PR Close #40094
2020-12-14 11:39:41 -08:00
Andrew Kushnir c977e1b629 test(compiler): use `yarn bazel` instead of `bazel` in error message (#40078)
This commit replaces `bazel` with `yarn bazel` in the error message (that instructs to regenerate golden file)
thrown while executing compliance tests. We use `yarn bazel` in other places (so we use the local version of bazel,
not the global one).

PR Close #40078
2020-12-14 11:34:41 -08:00
JiaLiPassion 35a1975697 build: update to use npm_package.pack rule (#39636)
Remove the work around solution for the `npm pack`, we can now
use `npm_package.pack` rule of bazel, since the windows os issue
has been fixed here https://github.com/bazelbuild/rules_nodejs/commit/bc36519

PR Close #39636
2020-12-14 11:29:33 -08:00
Alex Rickabaugh 028e4f7f6d fix(language-service): force compileNonExportedClasses: false in LS (#40092)
Projects opened in the LS are often larger in scope than the compilation
units seen by the compiler when actually building. For example, in the LS
it's not uncommon for the project to include both application as well as
test files. This can create issues when the combination of files results
in errors that are not otherwise present - for example, if test files
have inline NgModules that re-declare components (a common Angular pattern).
Such code is valid when compiling the app only (test files are excluded, so
only one declaration is seen by the compiler) or when compiling tests only
(since tests run in JIT mode and are not seen by the AOT compiler), but when
both sets of files are mixed into a single compilation unit, the compiler
sees the double declaration as an error.

This commit attempts to mitigate the problem by forcing the compiler flag
`compileNonExportedClasses` to `false` in a LS context. When tests contain
duplicate declarations, often such declarations are inline in specs and not
exported from the top level, so this flag can be used to greatly improve the
IDE experience.

PR Close #40092
2020-12-14 10:09:21 -08:00
Andrew Scott 2b74a05a65 refactor(compiler-cli): Enable pipe information when checkTypeOfPipes=false (#39555)
When `checkTypeOfPipes` is set to `false`, the configuration is meant to
ignore the signature of the pipe's `transform` method for diagnostics.
However, we still should produce some information about the pipe for the
`TemplateTypeChecker`. This change refactors the returned symbol for
pipes so that it also includes information about the pipe's class
instance as it appears in the TCB.

PR Close #39555
2020-12-11 16:19:15 -08:00
Andrew Scott 6e4e68cb30 refactor(compiler-cli): Add flag to TCB for non-diagnostic requests (#40071)
The TCB utility functions used to find nodes in the TCB are currently
configured to ignore results when an ignore marker is found. However,
these ignore markers are only meant to affect diagnostics requests. The
Language Service may have a need to find nodes with diagnostic ignore
markers. The most common example of this would be finding references for
generic directives. The reference appears to the generic directive's
class appears on the type ctor in the TCB, which is ignored for
diagnostic purposes.
These functions should only skip results when the request is in the
context of a larger request for _diagnostics_. In all other cases, we
should get matches, even if a diagnostic ignore marker is encountered.

PR Close #40071
2020-12-11 13:56:35 -08:00
Andrew Scott 81718769c4 refactor(compiler-cli): rename ignore marker and helpers to be more clear (#40071)
The ignore marker is only used to ignore certain nodes in the TCB for
the purposes of diagnostics. The marker itself has been renamed as well
as the helper function to see if the marker is present. Both now
indicate that the marker is specifically for diagnostics.

PR Close #40071
2020-12-11 13:56:35 -08:00
Miloš Lapiš 19b9ec8e4b docs(router): Correct equivalent for 'enabled' initial navigation (#40061)
With regard to the code in `router_module.ts`, the correct equivalent for `enabled`
should be` enabledBlocking` and not `enabledNonBlocking`.

PR Close #40061
2020-12-10 14:07:42 -08:00
Keen Yee Liau 2a386415ce build(language-service): install @angular/language-service in root node_modules (#40058)
https://github.com/angular/vscode-ng-language-service/pull/994 changed the
structure of the vscode-ng-language-service repository to be a monorepo,
so @angular/language-service should be installed in root node_modules.

PR Close #40058
2020-12-10 13:48:04 -08:00
Andrew Scott 973f797ad5 feat(language-service): enable get references for directive and component from template (#40054)
This commit adds the ability to find references for a directive or component
from within a component template. That is, you can find component references
from the element tag `<my-c|omp></my-comp>` (where `|` is the cursor position)
as well as find references for directives that match a given attribute
`<div d|ir></div>`.

PR Close #40054
2020-12-10 13:45:40 -08:00
Andrew Scott 1bf1b685d6 fix(language-service): Prevent matching nodes after finding a keySpan (#40047)
If we've already identified that we are within a `keySpan` of a node, we
exit the visitor logic early. It can be the case that we have two nodes
which technically match a given location when the end span of one node
touches the start of the keySpan for the candidate node. Because
our `isWithin` logic is inclusive on both ends, we can match both nodes.
This change exits the visitor logic once we've identified a node where
the position is within its `keySpan`.

PR Close #40047
2020-12-10 13:44:18 -08:00
Andrew Scott 371a2c82ea refactor(language-service): adjust hybrid visitor to not throw away valid results (#40047)
The visitor has a check in it with the goal of preventing the structural directive
parent elements from matching when we have already found the candidate we want.
However, this code did not check to ensure that it was looking at the correct
type of node for this case and was evaluating this logic in places it shouldn't.
This special check can be more easily done by simply not traversing the
template children if we've already found a candidate on the template
node itself.

PR Close #40047
2020-12-10 13:44:18 -08:00
George Kalpakas b4b21bdff4 fix(upgrade): fix HMR for hybrid applications (#40045)
Previously, trying to apply a change via Hot Module Replacement (HMR) in
a hybrid app would result in an error. This was caused by not having the
AngularJS app destroyed and thus trying to bootstrap an AngularJS app on
the same element twice.

This commit fixes HMR for hybrid apps by ensuring the AngularJS app is
destroyed when the Angular `PlatformRef` is [destroyed][1] in the
[`module.hot.dispose()` callback][2].

NOTE:
For "ngUpgradeLite" apps (i.e. those using `downgradeModule()`), HMR
will only work if the downgraded module has been bootstrapped and there
is at least one Angular component present on the page. The is due to a
combination of two facts:
- The logic for setting up the listener that destroys the AngularJS app
  depends on the downgraded module's `NgModuleRef`, which is only
  available after the module has been bootstrapped.
- The [HMR dispose logic][3] depends on having an Angular element
  (identified by the auto-geenrated `ng-version` attribute) present in
  the DOM in order to retrieve the Angular `PlatformRef`.

[1]:
https://github.com/angular/angular-cli/blob/205ea2b638f154291993bfd9e065cd66ff20503/packages/angular_devkit/build_angular/src/webpack/plugins/hmr/hmr-accept.ts#L75
[2]:
205ea2b638/packages/angular_devkit/build_angular/src/webpack/plugins/hmr/hmr-accept.ts (L31)
[3]:
205ea2b638/packages/angular_devkit/build_angular/src/webpack/plugins/hmr/hmr-accept.ts (L116)

Fixes #39935

PR Close #40045
2020-12-10 13:40:53 -08:00
George Kalpakas d08222157c refactor(upgrade): create a helper for cleaning jqLite/jQuery data (#40045)
This commit moves the code for cleaning jqLite/jQuery data on an element
to a re-usable helper function. This way it is easier to keep the code
consistent across all places where we need to clean data (now and in the
future).

PR Close #40045
2020-12-10 13:40:53 -08:00
George Kalpakas 61376d5a6e refactor(upgrade): remove unused variables (#40045)
This commit removes a couple of unused variables.

PR Close #40045
2020-12-10 13:40:53 -08:00
JoostK 1f73af77a7 refactor(compiler-cli): use `ngDevMode` guard for `setClassMetadata` call (#39987)
Prior to this change, the `setClassMetadata` call would be invoked
inside of an IIFE that was marked as pure. This allows the call to be
tree-shaken away in production builds, as the `setClassMetadata` call
is only present to make the original class metadata available to the
testing infrastructure. The pure marker is problematic, though, as the
`setClassMetadata` call does in fact have the side-effect of assigning
the metadata into class properties. This has worked under the assumption
that only build optimization tools perform tree-shaking, however modern
bundlers are also able to elide calls that have been marked pure so this
assumption does no longer hold. Instead, an `ngDevMode` guard is used
which still allows the call to be elided but only by tooling that is
configured to consider `ngDevMode` as constant `false` value.

PR Close #39987
2020-12-10 13:23:13 -08:00
Andrew Scott 112324a614 feat(router): add `relativeTo` as an input to `routerLink` (#39720)
Allow configuration of `relativeTo` in the `routerLink` directive. This
is related to the clearing of auxiliary routes, where you need to use
`relativeTo: route.parent` in order to clear it from the activated
auxiliary component itself. This is because `relativeTo: route` will
consume the segment that we're trying to clear, so there is really no
way to do this with routerLink at the moment.

Related issue: #13523
Related (internal link): https://yaqs.corp.google.com/eng/q/5999443644645376

PR Close #39720
2020-12-10 11:21:00 -08:00
Kristiyan Kostadinov dc6d40e5bc fix(compiler): handle strings inside bindings that contain binding characters (#39826)
Currently the compiler treats something like `{{  '{{a}}' }}` as a nested
binding and throws an error, because it doesn't account for quotes
when it looks for binding characters. These changes add a bit of
logic to skip over text inside quotes when parsing.

Fixes #39601.

PR Close #39826
2020-12-10 11:11:21 -08:00
Alex Rickabaugh 93a83266f9 feat(language-service): autocompletion within expression contexts (#39727)
This commit adds support to the Language Service for autocompletion within
expression contexts. Specifically, this is auto completion of property reads
and method calls, both in normal and safe-navigational forms.

PR Close #39727
2020-12-10 11:09:53 -08:00
Andrew Scott 269a775287 refactor(compiler-cli): produce binding access when checkTypeOfOutputEvents is false (#39515)
When `checkTypeOfOutputEvents` is `false`, we still need to produce the access
to the `EventEmitter` so the Language Service can still get the
type information about the field. That is, in a template `<div
(output)="handle($event)"`, we still want to be able to grab information
when the cursor is inside the "output" parens. The flag is intended only
to affect whether the compiler produces diagnostics for the inferred
type of the `$event`.

PR Close #39515
2020-12-10 11:04:46 -08:00
Andrew Scott 702d6bfe8f refactor(compiler-cli): use keySpan for output event lookup (#39515)
PR #39665 added the `keySpan` to the output field access so we no longer
need to get there from the call expression and can instead just find the
node we want directly.

PR Close #39515
2020-12-10 11:04:46 -08:00
Pete Bacon Darwin 85760cb170 test(compiler-cli): fix and re-enable compliance source-map tests (#40040)
These tests started failing because they had type-check
errors in their templates, and a recent commit turned on
full template type-checking by default.\

This commit fixes those templates and updates the expected
files as necessary.

PR Close #40040
2020-12-09 09:21:32 -08:00
Julien 42d478b16a docs(common): use table layout for Pre-defined format options (#40036)
easier to read
PR Close #40036
2020-12-09 09:11:03 -08:00
Andrew Scott cfb094dbaf test(compiler-cli): temporary disable source mapping tests which have errors (#40033)
These tests do not pass the typecheck phase of the compiler and fail.
The option to disable typechecking was removed recently so these tests
need to be fixed to be valid applications.

PR Close #40033
2020-12-08 19:17:22 -08:00
Benjamin Kindle ca08625227 fix(animations): implement getPosition in browser animation builder (#39983)
Forward `getPosition` to `animation_group_player`.

PR Close #39983
2020-12-08 16:24:41 -08:00
Andrew Scott 6cc9ab120b refactor(compiler-cli): remove internal only flag to disable type checking (#40013)
A couple reasons to justify removing the flag:

* It adds code to the compiler that is only meant to support test cases
and not any production. We should avoid code in that's only
meant to support tests.
* The flag enables writing tests that do not mimic real-world behavior
because they allow invalid applications

PR Close #40013
2020-12-08 16:19:07 -08:00
Andrew Scott 2f8a42036a refactor(compiler-cli): Return addEventListener symbol for native output bindings (#39312)
Rather than returning `null`, we can provide some useful information to the Language Service
by returning a symbol for the `addEventListener` function call when the consumer
of a binding as an element.

PR Close #39312
2020-12-08 16:18:24 -08:00
Christoph Guttandin 74e42cf7d5 fix(service-worker): handle error with ErrorHandler (#39990)
Errors thrown by calling serviceWorker.register() are now passed to the global ErrorHandler.

Fixes #39913

PR Close #39990
2020-12-08 12:03:27 -08:00
George Kalpakas 6dc43a475b fix(upgrade): avoid memory leak when removing downgraded components (#39965)
Previously, due to the way the AngularJS and Angular clean-up processes
interfere with each other when removing an AngularJS element that
contains a downgraded Angular component, the data associated with the
host element of the downgraded component was not removed. This data was
kept in an internal AngularJS cache, which prevented the element and
component instance from being garbage-collected, leading to memory
leaks.

This commit fixes this by ensuring the element data is explicitly
removed when cleaning up a downgraded component.

NOTE:
This is essentially the equivalent of #26209 but for downgraded (instead
of upgraded) components.

Fixes #39911
Closes #39921

PR Close #39965
2020-12-08 12:02:48 -08:00
George Kalpakas 988b1e3506 refactor(upgrade): remove unused parameters/properties/variables (#39965)
This commit removes some unused parameters, properties and variables in
various `@angular/upgrade` functions.

PR Close #39965
2020-12-08 12:02:46 -08:00
JoostK e69288418c refactor(compiler-cli): reformat directive/pipe metadata extraction (#39961)
The prior usage of a ternary expression caused the code to be formatted
in a weird way, so this commit replaces the ternary with an `if` statement.

PR Close #39961
2020-12-08 12:02:00 -08:00
JoostK dd8a31838c refactor(compiler-cli): extract parsing of interpolation config (#39961)
Prior to this change the interpolation config value was cast to
`[string, string]` without checking whether there really were two
string values available. This commit extracts the logic of parsing the
interpolation config into a separate function and adds a check that
the array contains exactly two strings.

PR Close #39961
2020-12-08 12:01:59 -08:00
JoostK c0bccc39db refactor(compiler-cli): carry type information into AST value types (#39961)
This change allows the `AstObject` and `AstValue` types to provide
their represented type as a generic type argument, which is helpful
for documentation and discoverability purposes.

PR Close #39961
2020-12-08 12:01:57 -08:00
JoostK 5fa026fd81 refactor(compiler): add type information to `DefinitionMap` (#39961)
This allows the code generation to correspond with a type, which is
helpful for documentation and discoverability purposes. This does not
offer any type-safety with respect to the actually generated code.

PR Close #39961
2020-12-08 12:01:56 -08:00
Daniel Eisterhold 5848439a48 docs(platform-browser): fix spelling of deserialized (#36102)
PR Close #36102
2020-12-08 12:01:04 -08:00
Kalle Järvenpää 5a2a907adf docs(animations): a small typo (#37164)
Removed two extra closing parentheses in docs.
PR Close #37164
2020-12-08 09:22:22 -08:00
Andrew Scott a694838c41 refactor(compiler-cli): TemplateTypeChecker with checkTypeOfAttributes=false should still work (#39537)
When the compiler option `checkTypeOfAttributes` is `false`, we should
still be able to produce type information from the
`TemplateTypeChecker`. The current behavior ignores all attributes that
map to directive inputs. This commit includes those attribute bindings
in the TCB but adds the "ignore for diagnostics" marker so they do not
produce errors. This way, consumers of the TTC (the Language Service)
can still get valid information about these attributes even when the
user has configured the compiler to not produce diagnostics/errors for them.

PR Close #39537
2020-12-08 09:14:27 -08:00
JoostK 3ec2807e38 refactor(compiler-cli): add script to update all golden partial files (#39989)
The golden files for the partial compliance tests need to be updated
with individual Bazel run invocations, which is not very ergonomic when
a large number of golden files need to updated. This commit adds a
script to query the Bazel targets that update the goldens and then runs
those targets sequentially.

PR Close #39989
2020-12-07 16:21:42 -08:00
Pete Bacon Darwin b8714c384f test(compiler-cli): add source-map compliance tests for inline-templates (#39939)
This test migrates source-mapping tests to the new compliance test framework.
The original tests are found in the file at:
`packages/compiler-cli/test/ngtsc/template_mapping_spec.ts`.

These new tests also check the mappings resulting from partial compilation
followed by linking, after flattening the pair of source-maps that each
process generates.

Note that there are some differences between the mappings for full compile
and linked compile modes, due to how TypeScript and Babel use source-span
information on AST nodes.  To accommodate this, there are two expectation
files for most of these source files.

PR Close #39939
2020-12-07 16:21:07 -08:00
Pete Bacon Darwin 9066ca9e92 test(compiler-cli): add support for source-map checks in compliance tests (#39939)
This commit allows compliance test-cases to be written that specify
source-map mappings between the source and generated code.

To check a mapping, add a `// SOURCE:` comment to the end of a line:

```
<generated code> // SOURCE: "<source-url>" <source code>
```

The generated code will still be checked, stripped of the `// SOURCE` comment,
as normal by the `expectEmit()` helper.

In addition, the source-map segments are checked to ensure that there is a
mapping from `<generated code>` to `<source code>` found in the file at
`<source-url>`.

Note:

* The source-url should be absolute, with the directory containing the
  TEST_CASES.json file assumed to be `/`.
* Whitespace is important and will be included when comparing the segments.
* There is a single space character between each part of the line.
* Newlines within a mapping must be escaped since the mapping and comment
  must all appear on a single line of this file.

PR Close #39939
2020-12-07 16:21:05 -08:00
Pete Bacon Darwin 09ba30ef29 test(compiler-cli): improve compliance test compile mode filtering (#39939)
Previously one could set a flag in a `TEST_CASES.json` file to exclude
the test-cases from being run if the input files were being compiled
partially and then linked.

There are also scenarios where one might want to exclude test-cases
from "full compile" mode test runs.

This commit changes the compliance test tooling to support a new
property `compilationModeFilter`, which is an array containing one or
more of `"full compile"` and `"linked compile"`. Only the tests
whose `compilationModeFilter` array contains the current compilation
mode will be run.

PR Close #39939
2020-12-07 16:21:04 -08:00
Pete Bacon Darwin c5ea3d5b0e test(compiler-cli): ensure that golden partial files are parsed accurately (#39939)
Previously files were serialized with an extra newline seperator that
was not removed when parsing. This caused the parsed file to start with
an extra newline that invalidated its source-map.

Also, the splitting was producing an empty entry at the start of the extracted
golden files which is now ignored.

PR Close #39939
2020-12-07 16:21:02 -08:00
Pete Bacon Darwin 2afa3801bc test(compiler-cli): fix TEST_CASES.json schema (#39939)
The schema accidentally included the `expectedErrors` and `extraCheck`
properties below the `files` property instead of below the `expectations`
property.

PR Close #39939
2020-12-07 16:21:01 -08:00
Bjarki ef892743ec feat(compiler): support tagged template literals in code generator (#39122)
Add a TaggedTemplateExpr to represent tagged template literals in
Angular's syntax tree (more specifically Expression in output_ast.ts).
Also update classes that implement ExpressionVisitor to add support for
tagged template literals in different contexts, such as JIT compilation
and conversion to JS.

Partial support for tagged template literals had already been
implemented to support the $localize tag used by Angular's i18n
framework. Where applicable, this code was refactored to support
arbitrary tags, although completely replacing the i18n-specific support
for the $localize tag with the new generic support for tagged template
literals may not be completely trivial, and is left as future work.

PR Close #39122
2020-12-07 16:20:04 -08:00
Andrew Scott e92d8a8e8f test(compiler-cli): Add test for checkTypeOfDomReferences = false (#39539)
Add test for when `checkTypeOfDomReferences = false` to ensure that we
do not regress in behavior at any point. The desired behavior for this
case is that the `TemplateTypeChecker` will honor the user's
configuration and not produce symbols for the dom reference.

PR Close #39539
2020-12-07 13:22:29 -08:00
Misko Hevery 5fc45082ca fix(core): Support extending differs from root `NgModule` (#39981)
Differs tries to inject parent differ in order to support extending.
This does not work in the 'root' injector as the provider overrides the
default injector. The fix is to just assume standard set of providers
and extend those instead.

PR close #25015
Issue close #11309 `Can't extend IterableDiffers`
Issue close #18554 `IterableDiffers.extend is not AOT compatible`
  (This is fixed because we no longer have an arrow function in the
  factory but a proper function which can be imported.)

PR Close #39981
2020-12-07 09:51:27 -08:00
George Kalpakas a8aeb74714 test(upgrade): run tests against AngularJS v1.8.x as well (#39972)
We intend to run the `@angular/upgrade` tests against all supported
versions of AngularJS (v1.5+). Previously, we only ran them against
v1.5, v1.6 and v1.7.

Since AngularJS v1.8 was released recently, this commit adds it to the
list of AngularJS versions we test against.

PR Close #39972
2020-12-07 09:40:49 -08:00
arturovt 7954c8dfa3 perf(forms): use `ngDevMode` to tree-shake `_ngModelWarning` (#39964)
This commit adds `ngDevMode` guard to call `_ngModelWarning` only
in dev mode (similar to how things work in other parts of Ivy runtime code).
The `ngDevMode` flag helps to tree-shake this function from production builds
(since it will act as no-op, in dev mode everything will work as it works right now)
to decrease production bundle size.

PR Close #39964
2020-12-04 16:08:02 -08:00
arturovt 9ebe42370a perf(animations): use `ngDevMode` to tree-shake warning (#39964)
This commit adds ngDevMode guard to show warning only
in dev mode (similar to how things work in other parts of Ivy runtime code).
The ngDevMode flag helps to tree-shake this warning from production builds
(in dev mode everything will work as it works right now) to decrease production bundle size.

PR Close #39964
2020-12-04 16:08:01 -08:00
arturovt f022efa06f perf(common): use `ngDevMode` to tree-shake warnings (#39964)
This commit adds ngDevMode guard to show warnings only
in dev mode (similar to how things work in other parts of Ivy runtime code).
The ngDevMode flag helps to tree-shake these warnings from production builds
(in dev mode everything will work as it works right now) to decrease production bundle size.

PR Close #39964
2020-12-04 16:08:00 -08:00
arturovt e1fe9ecffe perf(core): use `ngDevMode` to tree-shake `checkNoChanges` (#39964)
This commit adds `ngDevMode` guard to run `checkNoChanges` only
in dev mode (similar to how things work in other parts of Ivy runtime code).
The `ngDevMode` flag helps to tree-shake this code from production builds
(in dev mode everything will work as it works right now) to decrease production bundle size.

PR Close #39964
2020-12-04 16:07:59 -08:00
Pete Bacon Darwin d2042a0da2 refactor(compiler-cli): use semver range checking for partial versions (#39847)
The partial compiler will add a version number to the objects that are
generated so that the linker can select the appropriate partial linker
class to process the metadata.

Previously this version matching was a simple number check. Now
the partial compilation writes the current Angular compiler version
into the generated metadata, and semantic version ranges are used
to select the appropriate partial linker.

PR Close #39847
2020-12-04 10:26:17 -08:00
arturovt 8b0cccca45 perf(core): use `ngDevMode` to tree-shake warnings (#39959)
This commit adds `ngDevMode` guard to show sanitization warnings only
in dev mode (similar to how things work in other parts of Ivy runtime code).
The `ngDevMode` flag helps to tree-shake these warnings from production builds
(in dev mode everything will work as it works right now) to decrease production bundle size.

PR Close #39959
2020-12-04 10:21:36 -08:00
Alex Rickabaugh 28a0bcb424 feat(language-service): implement autocompletion for global properties (Ivy) (#39250)
This commit adds support in the Ivy Language Service for autocompletion in a
global context - e.g. a {{foo|}} completion.

Support is added both for the primary function `getCompletionsAtPosition` as
well as the detail functions `getCompletionEntryDetails` and
`getCompletionEntrySymbol`. These latter operations are not used yet as an
upstream change to the extension is required to advertise and support this
capability.

PR Close #39250
2020-12-04 10:19:45 -08:00
cexbrayat 67c5fe06e6 docs: improve FormBuilder.group deprecation message (#39946)
This expands the deprecation message that started to pop up in v11.0.3
after the landing of commit e148382bd0,
that deprecated the `{[key: string]: any}` type for the options property of the `FormBuilder.group` method.

It turns out that having a custom validator declared as
`{ validators: (group: FormGroup) => ValidationErrors|null }` works in practice,
but is now inferred by TS as the deprecated version of `group`
(because `FormGroup` is a subclass of `AbstractControl` that `ValidatorFn` expects).
We considered the possibility of tweaking the forms API to accept such validators,
but it turns out to generate too many changes in the framework or possible breaking changes for Angular users.

We settled for a more explicit deprecation message, elaborated with the help of @petebacondarwin.
This will hopefully help developers to understand why the deprecation warning is showing up
when they think they are already using the non-deprecated overload.

PR Close #39946
2020-12-04 10:18:48 -08:00
JoostK a7e4db3344 test(compiler-cli): improve compliance test performance (#39956)
The newly built compliance test runner was not using the shared source
file cache that was added in b627f7f02e,
which offers a significant performance boost to the compliance test
targets.

PR Close #39956
2020-12-04 10:17:21 -08:00
Zach Arend de8f0fe5ee test(language-service): convert ivy diagnostics tests from legacy (#39957)
This commit updates the tests for the diagnostics in the ivy language
service to use the new in-memory test environment.

PR Close #39957
2020-12-04 10:16:43 -08:00
ayazhafiz 3b700985f0 fix(language-service): do not treat file URIs as general URLs (#39917)
In the past, the legacy (VE-based) language service would use a
`UrlResolver` instance to resolve file paths, primarily for compiler
resources like external templates. The problem with this is that the
UrlResolver is designed to resolve URLs in general, and so for a path
like `/a/b/#c`, `#c` is treated as hash/fragment rather than as part
of the path, which can lead to unexpected path resolution (f.x.,
`resolve('a/b/#c/d.ts', './d.html')` would produce `'a/b/d.html'` rather
than the expected `'a/b/#c/d.html'`).

This commit resolves the issue by using Node's `path` module to resolve
file paths directly, which aligns more with how resources are resolved
in the Ivy compiler.

The testing story here is not great, and the API for validating a file
path could be a little bit prettier/robust. However, since the VE-based
language service is going into more of a "maintenance mode" now that
there is a clear path for the Ivy-based LS moving forward, I think it is
okay not to spend too much time here.

Closes https://github.com/angular/vscode-ng-language-service/issues/892
Closes https://github.com/angular/vscode-ng-language-service/issues/1001

PR Close #39917
2020-12-03 13:45:30 -08:00
Andrew Scott dd18cfd983 refactor(language-service): create findRenameLocations stubs (#39919)
Create stubs for `findRenameLocations` for both VE and Ivy Language Service
implementations. This will prevent failed requests when it is implemented on the vscode plugin side.

PR Close #39919
2020-12-03 13:44:49 -08:00
arturovt 5a3a154cd8 fix(core): unsubscribe from the `onError` when the root view is removed (#39940)
At the moment, when creating a root module, a subscription to the
`onError` subject is also created. It captures the scope where `NgModuleRef`
is created and prevents it from being garbage collected. Also note that this
`NgModuleRef` has a reference to the root module instance (e.g. `AppModule`),
which also prevents it from being GC'd.

PR Close #39940
2020-12-03 13:44:17 -08:00
Alex Rickabaugh c7c5b2fc1e fix(compiler-cli): correct incremental behavior even with broken imports (#39923)
When the compiler is invoked via ngc or the Angular CLI, its APIs are used
under the assumption that Angular analysis/diagnostics are only requested if
the program has no TypeScript-level errors. A result of this assumption is
that the incremental engine has not needed to resolve changes via its
dependency graph when the program contained broken imports, since broken
imports are a TypeScript error.

The Angular Language Service for Ivy is using the compiler as a backend, and
exercising its incremental compilation APIs without enforcing this
assumption. As a result, the Language Service has run into issues where
broken imports cause incremental compilation to fail and produce incorrect
results.

This commit introduces a mechanism within the compiler to keep track of
files for which dependency analysis has failed, and to always treat such
files as potentially affected by future incremental steps. This is tested
via the Language Service infrastructure to ensure that the compiler is doing
the right thing in the case of invalid imports.

PR Close #39923
2020-12-03 13:42:13 -08:00
Alex Rickabaugh a6c8cc3215 test(compiler-cli): validate broken external template incrementality (#39923)
Previously, if a component had an external template with a hard error, the
compiler would "forget" the link between that component and its NgModule.
Additionally, the NgModule would be marked as being in error, because the
template issue would prevent the compiler from registering the component
class as a component, so from the NgModule it would look like a declaration
of a non-directive/pipe class. As a combined result, the next incremental
step could fix the template error, but would not refresh diagnostics for the
NgModule, leading to an incrementality issue.

The various facets of this problem were fixed in prior commits. This commit
adds a test verifying the above case works now as expected.

PR Close #39923
2020-12-03 13:42:13 -08:00
Alex Rickabaugh 0823622202 fix(compiler-cli): track poisoned scopes with a flag (#39923)
To avoid overwhelming a user with secondary diagnostics that derive from a
"root cause" error, the compiler has the notion of a "poisoned" NgModule.
An NgModule becomes poisoned when its declaration contains semantic errors:
declarations which are not components or pipes, imports which are not other
NgModules, etc. An NgModule also becomes poisoned if it imports or exports
another poisoned NgModule.

Previously, the compiler tracked this poisoned status as an alternate state
for each scope. Either a correct scope could be produced, or the entire
scope would be set to a sentinel error value. This meant that the compiler
would not track any information about a scope that was determined to be in
error.

This method presents several issues:

1. The compiler is unable to support the language service and return results
when a component or its module scope is poisoned.

This is fine for compilation, since diagnostics will be produced showing the
error(s), but the language service needs to still work for incorrect code.

2. `getComponentScopes()` does not return components with a poisoned scope,
which interferes with resource tracking of incremental builds.

If the component isn't included in that list, then the NgModule for it will
not have its dependencies properly tracked, and this can cause future
incremental build steps to produce incorrect results.

This commit changes the tracking of poisoned module scopes to use a flag on
the scope itself, rather than a sentinel value that replaces the scope. This
means that the scope itself will still be tracked, even if it contains
semantic errors. A test is added to the language service which verifies that
poisoned scopes can still be used in template type-checking.

PR Close #39923
2020-12-03 13:42:13 -08:00
Alex Rickabaugh 6d42954327 fix(compiler-cli): remove the concept of an errored trait (#39923)
Previously, if a trait's analysis step resulted in diagnostics, the trait
would be considered "errored" and no further operations, including register,
would be performed. Effectively, this meant that the compiler would pretend
the class in question was actually undecorated.

However, this behavior is problematic for several reasons:

1. It leads to inaccurate diagnostics being reported downstream.

For example, if a component is put into the error state, for example due to
a template error, the NgModule which declares the component would produce a
diagnostic claiming that the declaration is neither a directive nor a pipe.
This happened because the compiler wouldn't register() the component trait,
so the component would not be recorded as actually being a directive.

2. It can cause incorrect behavior on incremental builds.

This bug is more complex, but the general issue is that if the compiler
fails to associate a component and its module, then incremental builds will
not correctly re-analyze the module when the component's template changes.
Failing to register the component as such is one link in the larger chain of
issues that result in these kinds of issues.

3. It lumps together diagnostics produced during analysis and resolve steps.

This is not causing issues currently as the dependency graph ensures the
right classes are re-analyzed when needed, instead of showing stale
diagnostics. However, the dependency graph was not intended to serve this
role, and could potentially be optimized in ways that would break this
functionality.

This commit removes the concept of an "errored" trait entirely from the
trait system. Instead, analyzed and resolved traits have corresponding (and
separate) diagnostics, in addition to potentially `null` analysis results.
Analysis (but not resolution) diagnostics are carried forward during
incremental build operations. Compilation (emit) is only performed when
a trait reaches the resolved state with no diagnostics.

This change is functionally different than before as the `register` step is
now performed even in the presence of analysis errors, as long as analysis
results are also produced. This fixes problem 1 above, and is part of the
larger solution to problem 2.

PR Close #39923
2020-12-03 13:42:13 -08:00
JoostK 76ae87406f test(compiler-cli): convert components & directives compliance tests (#39920)
This commit converts the components & directives compliance tests taken
from `r3_compiler_compliance_spec.ts` to the new test runner.

PR Close #39920
2020-12-03 13:41:20 -08:00
Keen Yee Liau 2b84882ab0 fix(language-service): do not return external template that does not exist (#39898)
There is a bug in tsserver that causes it to crash when it tries to create
script info for an external template that does not exist.

I've submitted an upstream PR
https://github.com/microsoft/TypeScript/pull/41737 to fix this, but before
the commit lands in the stable release, we'll have to workaround the issue
in language service.

Close https://github.com/angular/vscode-ng-language-service/issues/1001

PR Close #39898
2020-12-03 07:15:17 -08:00
Trotyl 8d613c1d42 feat(compiler): allow trailing comma in array literal (#22277)
Allows `[1, 2, ]` syntax in angular expressions.

closes #20773

PR Close #22277
2020-12-02 14:57:05 -08:00
JoostK efd0d33391 test(compiler-cli): convert bindings compliance tests (#39862)
This commit converts the binding compliance tests taken from
`r3_view_compiler_binding_spec.ts` to the new test runner.

PR Close #39862
2020-12-02 14:56:38 -08:00
JoostK eeab91af4e test(compiler-cli): log unexpected compilation errors in compliance test runner (#39862)
If the testcase has not specified that errors were expected, then any
errors that have occurred should be reported. These errors may have
prevented an output file from being generated, which resulted in hard
to debug test failures due to missing files.

PR Close #39862
2020-12-02 14:56:38 -08:00
Kristiyan Kostadinov 744f46c37d refactor(compiler-cli): migrate view compiler directive tests (#39929)
Migrates the compliance tests under `r3_view_compiler_directives` to the new format.

PR Close #39929
2020-12-02 14:55:58 -08:00
Andrew Kushnir a55e01b89c test(core): verify `onDestroy` callbacks are invoked when ComponentRef is destroyed (#39876)
This commit adds a few tests to verify that the `onDestroy` callbacks are invoked when `ComponentRef` instance
is destroyed and the logic is consistent between ViewEngine and Ivy.

PR Close #39876
2020-12-02 12:56:05 -08:00
arturovt df27027ecb fix(core): remove application from the testability registry when the root view is removed (#39876)
In the new behavior Angular removes applications from the testability registry when the
root view gets destroyed. This eliminates a memory leak, because before that the
TestabilityRegistry holds references to HTML elements, thus they cannot be GCed.

PR Close #22106

PR Close #39876
2020-12-02 12:56:04 -08:00
Andrew Scott 75fc89384d refactor(compiler-cli): expose TTC method to determine if file is tracked shim (#39768)
The Language Service "find references" currently uses the
`ngtypecheck.ts` suffix to determine if a file is a shim file. Instead,
a better API would be to expose a method in the template type checker
that does this verification so that the LS does not have to "know" about
the typecheck suffix. This also fixes an issue (albeit unlikely) whereby a file
in the user's program that _actually_ is named with the `ngtypecheck.ts`
suffix would have been interpreted as a shim file.

PR Close #39768
2020-12-02 12:54:22 -08:00
Andrew Scott 06a782a2e3 feat(language-service): Add "find references" capability to Ivy integrated LS (#39768)
This commit adds "find references" functionality to the Ivy integrated
language service. The basic approach is as follows:

1. Generate shims for all files to ensure we find references in shims
throughout the entire program
2. Determine if the position for the reference request is within a
template.
  * Yes, it is in a template: Find which node in the template AST the
  position refers to. Then find the position in the shim file for that
  template node. Pass the shim file and position in the shim file along
  to step 3.
  * No, the request for references was made outside a template: Forward
  the file and position to step 3.
3. (`getReferencesAtTypescriptPosition`): Call the native TypeScript LS
`getReferencesAtPosition`. For each reference that is in a shim file, map those
back to a template location, otherwise return it as-is.

PR Close #39768
2020-12-02 12:54:21 -08:00
Andrew Scott c69e67c9cb refactor(compiler-cli): Always wrap RHS of TCB writes in parens (#39768)
There were two issues with the current TCB:

1. The logic for only wrapping the right hand side of the property write
if it was not already a parenthesized expression was incorrect. A
parenthesized expression could still have a trailing comment, and if
that were the case, that span comment would still be ambiguous, as explained
by the comment in the code before `wrapForTypeChecker`.
2. The right hand side of keyed writes was not wrapped in parens at all

PR Close #39768
2020-12-02 12:54:20 -08:00
Andrew Scott 786295dfbd refactor(compiler-cli): Add nameSpan to SafePropertyRead TCB (#39768)
In order to map the a safe property read's method access in the type check block
directly back to the property in the template source, we need to
include the `SafePropertyRead`'s `nameSpan` with the `ts.propertyAccess` for
the pipe's transform method.

Note that this is specifically relevant to the Language Service's "find
references" feature. As an example, with something like `{{a?.value}}`,
when calling "find references" on the 'value' we want the text
span of the reference to just be `value` rather than the entire source
`a?.value`.

PR Close #39768
2020-12-02 12:54:19 -08:00
Andrew Scott 1a5e5f86a3 refactor(compiler-cli): Include pipe `nameSpan` in TCB (#39768)
In order to map the pipe's `transform` method in the type check block
directly back to the pipe name in the template source, we need to
include the `BindingPipe`'s `nameSpan` with the `ts.methodAccess` for
the pipe's transform method.

Note that this is specifically relevant to the Language Service's "find
references" feature. As an example, with something like `-2.5 | number:'1.0-0'`,,
when calling "find references" on the 'number' pipe we want the text
span of the reference to just be `number` rather than the entire binding
pipe's source `-2.5 | number:'1.0-0'`.

PR Close #39768
2020-12-02 12:54:18 -08:00
Eduardo Speroni 82e3f546db fix(zone.js): patch child method that overrides an already patched method (#39850)
Fix a case where, if the parent class had already been patched, it would
not patch the child class. In addition to checking if the method is
defined in the prototype, and not inherited, it also does the same for
the unpatched method.

PR Close #39850
2020-12-02 12:52:27 -08:00
Nicholas Papadopoulos 7851a254d8 docs(common): fix typo in HttpClient docs (#39904)
PR Close #39904
2020-12-02 11:16:43 -08:00
Иванов Дмитрий 215e9069e3 docs(forms): fix example 'Reset the form group values and disabled status' (#33137)
PR Close #33137
2020-12-02 11:14:25 -08:00
Kristiyan Kostadinov eac85b4e23 test(compiler-cli): migrate view compliance tests (#39914)
Migrates the `r3_view_compiler` tests to the new format.

PR Close #39914
2020-12-01 15:12:40 -08:00
Kristiyan Kostadinov 50962c1b0b test(compiler-cli): migrate template compliance tests (#39871)
Migrates the `r3_view_compiler_template` tests to the new format.
Also introduces a new matcher for unique function names.

PR Close #39871
2020-12-01 14:58:11 -08:00
Kristiyan Kostadinov 40b127c7a3 test(compiler-cli): migrate listener compliance tests (#39867)
Migrates the `r3_view_compiler_listener` compliance tests to the new format.

PR Close #39867
2020-12-01 14:56:59 -08:00
Kristiyan Kostadinov 97ea2c7bfd test(compiler-cli): migrate input/output compliance tests (#39867)
Migrates the `r3_view_compiler_input_outputs` compliance tests to the new format.

PR Close #39867
2020-12-01 14:56:59 -08:00
Fabian Wiles 7a5bc95614 refactor(http): inline HttpObserve (#18417)
Inline `HttpObserve` for better type safety.

Fix #18146

PR Close #18417
2020-12-01 12:13:04 -08:00
Kristiyan Kostadinov 11cd37fae3 fix(core): not invoking object's toString when rendering to the DOM (#39843)
Currently we convert objects to strings using `'' + value` which is quickest,
but it stringifies the value using its `valueOf`, rather than `toString`. These
changes switch to using `String(value)` which has identical performance
and calls the `toString` method as expected. Note that another option
was calling `toString` directly, but benchmarking showed it to be slower.

I've included the benchmark I used to verify the performance so we have it
for future reference and we can reuse it when making changes to `renderStringify`
in the future.

Also for reference, here are the results of the benchmark:

```
Benchmark: renderStringify
 concat: 2.006 ns(0%)
 concat with toString: 2.201 ns(-10%)
 toString: 237.494 ns(-11741%)
 toString with toString: 121.072 ns(-5937%)
 constructor: 2.201 ns(-10%)
 constructor with toString: 2.201 ns(-10%)
 toString mono: 14.536 ns(-625%)
 toString with toString mono: 9.757 ns(-386%)
```

Fixes #38839.

PR Close #39843
2020-11-30 15:49:57 -08:00
Kristiyan Kostadinov 71a5314335 test(compiler-cli): migrate providers compliance tests (#39878)
Migrates the `r3_view_compiler_providers` compliance tests to the new format.

PR Close #39878
2020-11-30 12:07:02 -08:00
Tzimpoulas Nikos 1539c64fb0 docs(common): change HTTPResponse to HttpResponse (#39860)
PR Close #39860
2020-11-30 12:04:34 -08:00
JoostK c5619ca56e test(compiler-cli): convert styling compliance tests (#39881)
This commit converts the DI compliance tests taken from
`r3_view_compiler_styling_spec.ts` to the new test runner.

PR Close #39881
2020-11-30 11:23:30 -08:00
JoostK c622b17b0d test(compiler-cli): convert di compliance tests (#39863)
This commit converts the DI compliance tests taken from
`r3_view_compiler_di_spec.ts` to the new test runner.

PR Close #39863
2020-11-30 11:21:23 -08:00
JoostK 157d690704 test(compiler-cli): expand logging when extra compliance check fails (#39863)
Previously this would have just printed that `false` was not equal to
`true`, which, although true, is not very helpful. This commit adds
details about which special check failed together with the generated
code, for easier debugging.

PR Close #39863
2020-11-30 11:21:23 -08:00
Andrew Scott 68d4a74411 fix(core): Ensure OnPush ancestors are marked dirty when events occur (#39833)
We currently only wrap the event listener in the function which ensures
ancestors are marked for check when the listener is placed on an element
that has a native method for listening to an event. We actually need to do
this wrapping in all cases so that events that are attached to non-rendered
template items (`ng-template` and `ng-container`) also mark ancestors for check
when they receive the event.

fixes #39832

PR Close #39833
2020-11-25 14:39:19 -08:00
Ryan Russell e148382bd0 docs(forms): Deprecate legacy options for FormBuilder.group (#39769)
DEPRECATION:

Mark the {[key: string]: any} type for the options property of the FormBuilder.group method as deprecated.
Using AbstractControlOptions gives the same functionality and is type-safe.

PR Close #39769
2020-11-25 14:28:11 -08:00
JiaLiPassion c43267b912 build: update peerDependencies of zone.js to 0.10~0.11 (#39809)
`@angular/core` support zone.js `^0.10.2 and ^0.11.3`, so this PR updates the
peerDependencies to `^0.10.2 || ^ 0.11.3`, so the app will not show warning about
peer denepdency not consistent when using zone.js 0.10.x version.

PR Close #39809
2020-11-25 14:25:48 -08:00
Charles Lyding 318255a5f8 build: support building with TypeScript 4.1 (#39571)
TypeScript 4.1 is now used to build and test within the repository.

PR Close #39571
2020-11-25 11:10:01 -08:00
Charles Lyding a7e7c211b5 feat(compiler-cli): add support for using TypeScript 4.1 (#39571)
This change enables projects to be built with TypeScript 4.1.  Support for TypeScript 4.0 is also retained.

PR Close #39571
2020-11-25 11:10:00 -08:00
Pete Bacon Darwin 2786292780 test(compiler-cli): migrate i18n compliance tests (#39661)
This commit provides the machinery for the new file-based compliance test
approach for i18n tests, and migrates the i18n tests to this new format.

PR Close #39661
2020-11-25 11:08:39 -08:00
Pete Bacon Darwin 63dcfb2913 test(compiler-cli): update new compliance test partial rules (#39661)
There is now a dedicated rule for debugging generation of partial
golden files. The README has been updated accordingly.

PR Close #39661
2020-11-25 11:08:39 -08:00
Basheer Ahmed bfa197f564 fix(animations): replace copy of query selector node-list from "spread" to "for" (#39646)
For element queries that return sufficiently large NodeList
objects, using spread syntax to populate the results array
causes a RangeError due to the call stack limit being reached.
This commit updates the code to use regular "for" loop instead.

Fixes #38551.

PR Close #39646
2020-11-25 11:01:58 -08:00
Pete Bacon Darwin 5684ac5e34 feat(localize): support Application Resource Bundle (ARB) translation file format (#36795)
The ARB format is a JSON file containing an object where the keys are the
message ids and the values are the translations.

It is extensible because it can also contain metadata about each message.

For example:

```
{
  "@@locale": "...",
  "message-id": "Translated message string",
  "@message-id": {
    "type": "text",
    "description": "Some description text",
    "x-locations": [{ "start": {"line": 23, "column": 145}, "file": "some/file.ts" }]
  },
}
```

For more information, see:
https://github.com/google/app-resource-bundle/wiki/ApplicationResourceBundleSpecification

PR Close #36795
2020-11-25 10:55:40 -08:00
Krzysztof Grzybek 94e790d4ee fix(compiler): report better error on interpolation in an expression (#30300)
Compiler results in weird error message when encounters interpolation inside
existing expression context, e.g. *ngIf="name {{ name }}"

PR Close #30300
2020-11-25 10:53:19 -08:00
Andrew Scott 8758006acc refactor(language-service): create getReferencesAtPosition stubs (#39829)
Create stubs for getTypeDefinitionAtPosition for both VE and Ivy Language Service
implementations. This will prevent failed requests when it is implemented on the vscode plugin side.

PR Close #39829
2020-11-24 14:19:48 -08:00
JoostK e75244ec00 feat(compiler-cli): support for partial compilation of components (#39707)
This commit implements partial compilation of components, together with
linking the partial declaration into its full AOT output.

This commit does not yet enable accurate source maps into external
templates. This requires additional work to account for escape sequences
which is non-trivial. Inline templates that were represented using a
string or template literal are transplated into the partial declaration
output, so their source maps should be accurate. Note, however, that
the accuracy of source maps is not currently verified in tests; this is
also left as future work.

The golden files of partial compilation output have been updated to
reflect the generated code for components. Please note that the current
output should not yet be considered stable.

PR Close #39707
2020-11-24 13:05:49 -08:00
JoostK f6be161a3c test(compiler-cli): default `enableI18nLegacyMessageIdFormat` to false in compliance tests (#39707)
In production mode this flag defaults to `true`, but the compliance
tests override this to `false` unless it is provided. As such, the
linker should also adhere to this default as otherwise the compilation
output would not align with the output of the full tests.

There are still tests that exercise the value of this flag, together
with it being `undefined` to verify the behavior of the actual default
value.

PR Close #39707
2020-11-24 13:05:47 -08:00
JoostK f4690cb527 test(compiler-cli): skip compliance tests that target ES5 for partial compilation tests (#39707)
The linker does not currently support outputting ES5 syntax, so any
compliance tests that request ES5 output cannot be run in partial
compilation mode. This commit marks these tests as pending.

PR Close #39707
2020-11-24 13:05:46 -08:00
JoostK 2484ba4f05 refactor(compiler-cli): prepare linker options for compilation of components (#39707)
This commit adds the `i18nUseExternalIds` option to the linker options,
as the compliance tests exercise compilation results with and without
this flag enabled. We therefore need to configure the linker to take
this option into account, as otherwise the compliance test output would
not be identical.

Additionally, this commit switches away from spread syntax to set
the default options. This introduced a problem when the user-provided
options object did specify the keys, but with an undefined value. This
would have prevented the default options from being applied.

PR Close #39707
2020-11-24 13:05:44 -08:00
JoostK 6c7eb351d4 refactor(compiler-cli): extract compilation utilities for partial compilation of components (#39707)
This commit is a precursor to supporting the partial compilation of
components, which leverages some of the compilation infrastructure that
is in place for directives.

PR Close #39707
2020-11-24 13:05:43 -08:00
JoostK 935b2ff99f refactor(compiler-cli): allow query metadata to be omitted (#39707)
The metadata specification of queries allows for the boolean properties
`first`, `descendants` and `static` to be missing, but the linker did
not account for their omission.

This fix is tested in subsequent commits that implement compilation of
components, at which point this will be covered by the compliance tests.

PR Close #39707
2020-11-24 13:05:41 -08:00
JoostK e79ce386fc refactor(compiler-cli): allow visiting call expressions without an active linker (#39707)
The compilation result of components may have inserted template
functions into the constant pool, which would be inserted into the Babel
AST upon program exit. Babel will then proceed with visiting this newly
inserted subtree, but we have already cleaned up the linker instance
when exiting the program. Any call expressions within the template
functions would then fail to be processed, as a file linker would no
longer be available.

Since the inserted AST subtree is known not to contain yet more partial
declarations, it is safe to skip visiting call expressions when no
file linker is available.

PR Close #39707
2020-11-24 13:05:40 -08:00
JoostK 8348556b77 test(compiler-cli): workaround for performance cliff in TypeScript (#39707)
The type checker had to do extensive work in resolving the
`NodePath.get` method call for the `NodePath` that had an intersection
type of `ts.VariableDeclarator&{init:t.Expression}`. The `NodePath.get`
method is typed using a conditional type which became expensive to
compute with this intersection type. As a workaround, the original
`init` property is explicitly omitted which avoids the performance
cliff. This brings down the compile time by 15s.

PR Close #39707
2020-11-24 13:05:38 -08:00
JoostK bfa20e11a6 test(compiler-cli): fix documentation and JSON schema references in compliance tests (#39707)
The JSON schema reference was off-by-one, preventing IDEs from finding
the file and offering suggestions and documentation. Additionally the
name of the golden file was slightly off.

PR Close #39707
2020-11-24 13:05:37 -08:00
Mitchell Wills a1b6ad07a8 fix(core): Allow passing AbstractType to the inject function (#37958)
This is a type only change that replaces `Type<T>|InjectionToken<T>` with
`Type<T>|AbstractType<T>|InjectionToken<T>` in the injector.

PR Close #37958
2020-11-24 10:42:21 -08:00
JoostK 453b32f4b9 fix(compiler-cli): report error when a reference target is missing instead of crashing (#39805)
If a template declares a reference to a missing target then referring to
that reference from elsewhere in the template would crash the template
type checker, due to a regression introduced in #38618. This commit
fixes the crash by ensuring that the invalid reference will resolve to
a variable of type any.

Fixes #39744

PR Close #39805
2020-11-24 08:46:37 -08:00
INFRAGISTICS\tiliev b5c0f9d7d1 feat(platform-browser): add doubletap HammerJS support (#26362)
Enables `doubletap` support in HammerJS.

PR Close  #23954

PR Close #26362
2020-11-24 08:45:49 -08:00
mchl18 0050b550e4 docs(core): fix typo (#39825)
PR Close #39825
2020-11-24 08:42:17 -08:00
Kapunahele Wong 2c275f6d7a docs: archive template expression operators doc, move pipes precedence section (#39170)
Archives most of the content in the template expression operators doc.
The pipes precedence section that was originally in
template expression operators moves into the pipes doc
with some editing and an addition of a ternary example.

PR Close #39170
2020-11-24 08:41:18 -08:00
zuckjet e7b67b9d67 docs(core): fix typo for getting component definition function (#39823)
PR Close #39823
2020-11-24 08:39:05 -08:00
George Kalpakas 6046419f6c fix(service-worker): correctly handle failed cache-busted request (#39786)
Since 5be4edfa17, a failing cache-busted
network request (such as requests for fetching uncached assets) will
cause the ServiceWorker to incorrectly enter a degraded
`EXISTING_CLIENTS_ONLY` mode. A failing network request could be caused
by many reasons, including the client or server being offline, and does
not necessarily signify a broken ServiceWorker state.

This commit fixes the logic in `cacheBustedFetchFromNetwork()` to
correctly handle errors in network requests.
For more details on the problem and the implemented fix see #39775.

Fixes #39775

PR Close #39786
2020-11-23 14:59:55 -08:00
Gautier Pelloux-Prayer 938abc03bc docs(http): Add mention to default value 'OK' for statusText. #23334 (#23494)
PR Close #23494
2020-11-23 08:31:24 -08:00
Bjarki 2ae3fa009e refactor(compiler): remove unnecessary trustConstantScript function (#39554)
Script tags, inline event handlers and other script contexts are
forbidden or stripped from Angular templates by the compiler. In the
context of Trusted Types, this leaves no sinks that require use of a
TrustedScript. This means that trustConstantScript is never used, and
can be removed.

PR Close #39554
2020-11-23 08:29:09 -08:00
Bjarki 4916870dff fix(compiler): only promote Trusted Types to constants when necessary (#39554)
Previously all constant values of security-sensitive attributes and
properties were promoted to Trusted Types. While this is not inherently
bad, it is also not optimal.

Use the newly added Trusted Types schema to restrict promotion to
constants that are in a Trusted Types-relevant context.

PR Close #39554
2020-11-23 08:29:08 -08:00
Bjarki c8a99ef458 fix(compiler): disallow i18n of security-sensitive attributes (#39554)
To minimize security risk (XSS in particular) in the i18n pipeline,
disallow i18n translation of attributes that are Trusted Types sinks.
Add integration tests to ensure that such sinks cannot be translated.

PR Close #39554
2020-11-23 08:29:06 -08:00
Bjarki bb70a9bda4 feat(compiler): support error reporting in I18nMetaVisitor (#39554)
Make it possible to report errors from the I18nMetaVisitor parser.

PR Close #39554
2020-11-23 08:29:05 -08:00
Bjarki 358c50e226 feat(compiler): add schema for Trusted Types sinks (#39554)
Create a schema with an associated function to classify Trusted Types
sinks.

Piggyback a typo fix.

PR Close #39554
2020-11-23 08:29:04 -08:00
David-Emmanuel DIVERNOIS c7f4abf18a feat(common): allow any Subscribable in async pipe (#39627)
As only methods from the Subscribable interface are currently used in the
implementation of the async pipe, it makes sense to make it explicit so
that it works successfully with any other implementation instead of
only Observable.

PR Close #39627
2020-11-23 08:28:11 -08:00
Krivokhizhin Anton b668768c0a test(forms): verify that an object is not a boxed value if only `disabled` field is present (#39801)
The value of a `FormControl` is treated in a special way (called boxed values) when it's an object with exactly
2 fields: `value` and `disabled`. This commit adds a test which verifies that an object is not treated as a boxed
value when `disabled` field is present, but `value` is missing.

PR Close #39801
2020-11-23 08:25:08 -08:00
Marcono1234 3e1e5a15ba docs: update links to use HTTPS as protocol (#39718)
PR Close #39718
2020-11-20 12:52:16 -08:00
Kristiyan Kostadinov 1a26f6da6e fix(core): migration error if program contains files outside of the project (#39790)
Currently all of our migrations are set up to find the tsconfig paths within a project,
create a `Program` out of each and migrate the files inside of the `Program`. The
problem is that the `Program` can include files outside of the project and the CLI
APIs that we use to interact with the file system assume that all files are within
the project.

These changes consolidate the logic, that determines whether a file can be migrated,
in a single place and add an extra check to exclude files outside of the root.

Fixes #39778.

PR Close #39790
2020-11-20 12:51:19 -08:00
Kara Erickson ff0a90e4a8 fix(core): meta addTag() adds incorrect attribute for httpEquiv (#32531)
Meta::addTag() adds a meta tag with httpEquiv attribute instead of http-equiv when
MetaDefinition contains httpEquiv property.

PR Close #32531
2020-11-20 09:26:08 -08:00
Keen Yee Liau 9aaa86967d build(language-service): include sources for Ivy LS (#39748)
We need to expose the declaration files for Ivy sources so that they can
be consumed by the Angular language server (`@angular/language-server`).

PR Close #39748
2020-11-20 09:23:45 -08:00
Andrew Scott c33a8235d9 fix(router): correctly handle string command in outlets (#39728)
There are many places where examples use just a string for the command
in outlets. When using nested outlets, we do not correctly handle
this case, as the types and algorithm always expect an array.
This PR updates the `createUrlTree` algorithm to account for the
possibility of a string literal as the command for an outlet.

Fixes #18928

PR Close #39728
2020-11-20 08:38:31 -08:00
Pete Bacon Darwin 969ad329de refactor(compiler): tidy up interpolation splitting (#39717)
When parsing for i18n messages, interpolated strings are
split into `Text` and `Placeholder` pieces.  The method that
does this `_visitTextWithInterpolation()` was becoming too
complex. This commit refactors that method along with some
associated functions that it uses.

PR Close #39717
2020-11-20 08:35:56 -08:00
Pete Bacon Darwin 0462a616c3 fix(compiler): ensure that placeholders have the correct sourceSpan (#39717)
When the `preserveWhitespaces` is not true, the template parser will
process the parsed AST nodes to remove excess whitespace. Since the
generated `goog.getMsg()` statements rely upon the AST nodes after
this whitespace is removed, the i18n extraction must make a second pass.

Previously this resulted in innacurrate source-spans for the i18n text and
placeholder nodes that were extracted in the second pass.

This commit fixes this by reusing the source-spans from the first pass
when extracting the nodes in the second pass.

Fixes #39671

PR Close #39717
2020-11-20 08:35:55 -08:00
Pete Bacon Darwin 6b38c44a22 test(compiler-cli): add source-mapping test helper (#39717)
This helper improves the message given when an expectation
fails in a source-mapping test.

PR Close #39717
2020-11-20 08:35:54 -08:00
JiaLiPassion 1cba56e11f refactor(core): remove unused fakeAsyncFallback and asyncFallback (#37879)
`zone.js` 0.8.25 introduces `zone-testing` bundle and move all `fakeAsync/async` logic
from `@angular/core/testing` to `zone.js` package. But in case some user still using the old
version of `zone.js`, an old version of `fakeAsync/async` logic were still kept inside `@angular/core/testing`
package as `fallback` logic. Since now `Angular8+` already use `zone.js 0.9+`, so
those fallback logic is removed.

PR Close #37879
2020-11-20 08:34:59 -08:00
Serginho 66d863febe fix(animations): getAnimationStyle causes exceptions in older browsers (#29709)
PR #29709 getAnimationStyle causes exceptions in older browsers

PR Close #29709
2020-11-20 08:33:19 -08:00
cexbrayat 5fa767363d fix(router): remove duplicated getOutlet function (#39764)
The codebase currently contains two `getOutlet` functions,
and they can end up in the bundle of an application.
A recent commit 6fbe21941d tipped us off
as it introduced several `noop` occurrences in the golden symbol files.
After investigating with @petebacondarwin,
we decided to remove the duplicated functions.

This probably shaves only a few bytes,
but this commit removes the duplicated functions,
by always using the one in `router/src/utils/config`.

PR Close #39764
2020-11-20 08:31:14 -08:00
WilliamKoza b1d300dc26 fix(common): Prefer to use pageXOffset / pageYOffset instance of scrollX / scrollY (#28262)
This fix ensures a better cross-browser compatibility.
This fix has been used for angular.io.

PR Close #28262
2020-11-19 12:22:03 -08:00
Sonu Kapoor be998e830b refactor(core): move `injectAttributeImpl` to avoid cycles (#37085)
This commit moves the `injectAttributeImpl` and other dependent code
to avoid circular dependencies.

PR Close #37085
2020-11-19 12:19:42 -08:00
Sonu Kapoor f5cbf0bb54 fix(core): support `Attribute` DI decorator in `deps` section of a token (#37085)
This commit fixes a bug when `Attribute` DI decorator is used in the
`deps` section of a token that uses a factory function. The problem
appeared because the `Attribute` DI decorator was not handled correctly
while injecting factory function attributes.

Closes #36479

PR Close #37085
2020-11-19 12:19:41 -08:00
Issei Horie a965589eb8 feat(core): adds get method to QueryList (#36907)
This commit adds get method to QueryList.
The method returns an item of the internal results by index number.

PR Close #29467

PR Close #36907
2020-11-19 12:18:30 -08:00
Andrew Scott 1eb4066c2e refactor(compiler-cli): Expose API for mappping from TCB to template location (#39715)
Consumers of the `TemplateTypeChecker` API could be interested in
mapping from a shim location back to the original source location in the
template. One concrete example of this use-case is for the "find
references" action in the Language Service. This will return locations
in the TypeScript shim file, and we will then need to be able to map the
result back to the template.

PR Close #39715
2020-11-19 12:15:22 -08:00
Andrew Scott fae2769f44 refactor(compiler-cli): Add additional shim locations to reference and variable symbols (#39715)
Both `ReferenceSymbol` and `VariableSymbol` have two locations of
interest to an external consumer.
1. The location for the initializers of the local TCB variables allow consumers
to query the TypeScript Language Service for information about the initialized type of the variable.
2. The location of the local variable itself (i.e. `_t1`) allows
consumers to query the TypeScript LS for references to that variable
from within the template.

PR Close #39715
2020-11-19 12:15:21 -08:00
cexbrayat 066126ae2f fix(core): remove duplicated noop function (#39761)
The codebase currently contains several `noop` functions,
and they can end up in the bundle of an application.
A recent commit 6fbe21941d tipped us off
as it introduced several `noop` occurrences in the golden symbol files.
After investigating with @petebacondarwin,
we decided to remove the duplicated functions.

This probably shaves only a few bytes,
but this commit removes the duplicated functions,
by always using the one in `core/src/utils/noop`.

PR Close #39761
2020-11-19 12:14:12 -08:00
Kristiyan Kostadinov 81d72a1e37 fix(router): migration incorrectly replacing deprecated key (#39763)
In #38762 we added a migration to replace the deprecated `preserveQueryParams`
option with `queryParamsHandling`, however due to a typo, we ended up replacing it
with `queryParamsHandler` which is invalid.

Fixes #39755.

PR Close #39763
2020-11-19 09:08:10 -08:00
JiaLiPassion 1951342124 docs(zone.js): update zone.js readme for the bundle format (#39508)
There is a typo in zone.js bundle format breaking change part,
the correct version should be `0.11.1` not `0.11.11`, and add
more clear text to explain the new bundle format directory structure.

PR Close #39508
2020-11-18 16:25:12 -08:00
Pete Bacon Darwin 5b45fab19d build: update to latest "yargs" package (#39749)
The 15.x versions of `yargs` relied upon a version of `y18n` that
has a SNYK vulnerability.
This commit updates the overall project, and therefore also the
`localize` and `compiler-cli` packages to use the latest version
of `yargs` that does not depend upon the vulnerable `y18n`
version.
The AIO project was already on the latest `yargs` version and so
does not need upgrading.

Fixes #39743

PR Close #39749
2020-11-18 16:09:39 -08:00
ayazhafiz 3a344d4e0e test(language-service): add renamed, deleted test file (#39742)
language_service_adapter_spec was renamed to adapters_spec as part of
d39c4bbe37, but I failed to check in
adapters_spec, thereby just deleting the spec. This reintroduces it.

PR Close #39742
2020-11-18 11:11:14 -08:00
Misko Hevery 3b2e5be6cb refactor(core): clean up circular dependencies (#39722)
Clean up circular dependencies in core by pulling symbols out to their
respective files.

PR Close #39722
2020-11-18 09:15:29 -08:00
Egor 6fbe21941d refactor(core): Replace non-null assertion operator with property initialization (#39730)
Reuse the `noop` function from the common utilities

PR Close #39730
2020-11-18 09:14:41 -08:00
ngdevelop-tech 7d68f92315 docs(core): fix directive.ts preserving whitespace example comment (#37377)
In directive.ts file - component preserving whitespace example's compiled output comment is wrongly written

PR Close #37377
2020-11-18 09:12:52 -08:00
Ray Logel b33b89d441 fix(common): add `HttpParamsOptions` to the public api (#35829)
The `HttpParamsOptions` was not documented or included in the public API even
though it is a constructor argument of `HttpParams` which is a part of the
public API. This commit adds the `HttpParamsOptions` into the exports, thus
making it a part of the public API.

Resolves #20276

PR Close #35829
2020-11-18 09:11:56 -08:00
ayazhafiz d39c4bbe37 refactor(language-service): language_service_adapter -> adapters (#39619)
This rename is done because we know have a file system adapter over a
project as well as the compiler adapter.

PR Close #39619
2020-11-17 14:45:09 -08:00
ayazhafiz 64c3135be7 refactor(compiler-cli): provide a host to readConfiguration (#39619)
Currently `readConfiguration` relies on the file system to perform disk
utilities needed to read determine a project configuration file and read
it. This poses a challenge for the language service, which would like to
use `readConfiguration` to watch and read configurations dependent on
extended tsconfigs (#39134). Challenges are at least twofold:

1. To test this, the langauge service would need to provide to the
   compiler a mock file system.
2. The language service uses file system utilities primarily through
   TypeScript's `Project` abstraction. In general this should correspond
   to the underlying file system, but it may differ and it is better to
   go through one channel when possible.

This patch alleviates the concern by directly providing to the compiler
a "ParseConfigurationHost" with read-only "file system"-like utilties.
For the language service, this host is derived from the project owned by
the language service.

For more discussion see
https://docs.google.com/document/d/1TrbT-m7bqyYZICmZYHjnJ7NG9Vzt5Rd967h43Qx8jw0/edit?usp=sharing

PR Close #39619
2020-11-17 14:45:09 -08:00
Sebastian Häni 39266654e6 fix(http): queue jsonp <script> tag onLoad event handler in microtask (#39512)
Before this change, when trying to load a JSONP script that calls the JSONP callback inside a
microtask, it will fail in Internet Explorer 11 and EdgeHTML. This commit changes the onLoad cleanup
to be queued after the loaded endpoint executed any potential microtask itself. This ensures that
the aforementioned browsers will first evaluate the loaded script calling the JSONP callback and
only then run the cleanup inside onLoad.

Fixes #39496

PR Close #39512
2020-11-17 13:09:08 -08:00
Alex Rickabaugh b6893d23c5 test(language-service): introduce new virtual testing environment (#39594)
This commit adds new language service testing infrastructure which allows
for in-memory testing. It solves a number of issues with the previous
testing infrastructure that relied on a single integration project across
all of the tests, and also provides for much faster builds by using
the compiler-cli's mock versions of @angular/core and @angular/common.

A new `LanguageServiceTestEnvironment` class (conceptually mirroring the
compiler-cli `NgtscTestEnvironment`) controls setup and execution of tests.
The `FileSystem` abstraction is used to drive a `ts.server.ServerHost`,
which backs the language service infrastructure.

Since many language service tests revolve around the template, the API is
currently optimized to spin up a "skeleton" project and then override its
template for each test.

The existing Quick Info tests (quick_info_spec.ts) were ported to the new
infrastructure for validation. The tests were cleaned up a bit to remove
unnecessary initializations as well as correct legitimate template errors
which did not affect the test outcome, but caused additional validation of
test correctness to fail. They still utilize a shared project with all
fields required for each individual unit test, which is an anti-pattern, but
new tests can now easily be written independently without relying on the
shared project, which was extremely difficult previously. Future cleanup
work might refactor these tests to be more independent.

PR Close #39594
2020-11-17 11:59:56 -08:00
Alex Rickabaugh a7155bc2fa test(language-service): move existing tests to legacy directory (#39594)
In preparation for in-memory testing infrastructure, the existing Ivy
language service tests are moved to a `legacy` directory. These existing
tests rely on a single integration project in `test/project/app`, which
presents a number of challenges:

 * adding extra fields/properties to the integration project for one test
   can cause others to fail/flake.
 * it's especially difficult to test any cases that require introducing
   intentional errors, as those tend to break other tests.
 * tests load files from disk, which is slower.
 * tests rely on the real built versions of @angular/core and
   @angular/common, which makes them both slow to build and require rebuilds
   on every compiler change.
 * tests share a single tsconfig.json, making it extremely difficult to test
   how the language service handles different configuration scenarios (e.g.
   different type-checking flags).

PR Close #39594
2020-11-17 11:59:56 -08:00
Alex Rickabaugh c243ff3b6b test(compiler-cli): add a `fake_common` package alongside `fake_core` (#39594)
ngtsc's testing infrastructure uses a mock version of @angular/core, which
allows tests to run without requiring the real version of core to be built.

This commit adds a mock version of @angular/common as well, as the language
service tests are written to test against common.

Only a handful of directives/pipes from common are currently supported.

PR Close #39594
2020-11-17 11:59:56 -08:00
Alex Rickabaugh 3613e7c4e5 test(compiler-cli): move testing utils to separate package (#39594)
ngtsc has a robust suite of testing utilities, designed for in-memory
testing of a TypeScript compiler. Previously these utilities lived in the
`test` directory for the compiler-cli package.

This commit moves those utilities to an `ngtsc/testing` package, enabling
them to be depended on separately and opening the door for using them from
the upcoming language server testing infrastructure.

As part of this refactoring, the `fake_core` package (a lightweight API
replacement for @angular/core) is expanded to include functionality needed
for Language Service test use cases.

PR Close #39594
2020-11-17 11:59:56 -08:00
JoostK d281ea820b perf(compiler): use raw bytes to represent utf-8 encoded strings (#39694)
The result of utf-8 encoding a string was represented in a string, where
each individual character represented a single byte according to its
character code. All usages of this data were interested in the byte
itself, so this required conversion from a character back to its code.
This commit simply stores the individual bytes in array to avoid the
conversion. This yields a ~10% performance improvement for i18n message
ID computation.

PR Close #39694
2020-11-17 10:09:28 -08:00
JoostK 604b4e46c8 perf(compiler): optimize computation of i18n message ids (#39694)
Message ID computation makes extensive use of big integer
multiplications in order to translate the message's fingerprint into
a numerical representation. In large compilations with heavy use of i18n
this was showing up high in profiler sessions.

There are two factors contributing to the bottleneck:

1. a suboptimal big integer representation using strings, which requires
repeated allocation and conversion from a character to numeric digits
and back.
2. repeated computation of the necessary base-256 exponents and their
multiplication factors.

The first bottleneck is addressed using a representation that uses an
array of individual digits. This avoids repeated conversion and
allocation overhead is also greatly reduced, as adding two big integers
can now be done in-place with virtually no memory allocations.

The second point is addressed by a memoized exponentiation pool to
optimize the multiplication of a base-256 exponent.

As an additional optimization are the two 32-bit words now converted to
decimal per word, instead of going through an intermediate byte buffer
and doing the decimal conversion per byte.

The results of these optimizations depend a lot on the number of i18n
messages for which a message should be computed. Benchmarks have shown
that computing message IDs is now ~6x faster for 1,000 messages, ~14x
faster for 10,000 messages, and ~24x faster for 100,000 messages.

PR Close #39694
2020-11-17 10:09:28 -08:00
Kristiyan Kostadinov a61fe96b70 fix(compiler-cli): incorrectly type checking calls to implicit template variables (#39686)
Currently when we encounter an implicit method call (e.g. `{{ foo(1) }}`) and we manage to resolve
its receiver to something within the template, we assume that the method is on the receiver itself
so we generate a type checking code to reflect it. This assumption is true in most cases, but it
breaks down if the call is on an implicit receiver and the receiver itself is being invoked. E.g.

```
<div *ngFor="let fn of functions">{{ fn(1) }}</div>
```

These changes resolve the issue by generating a regular function call if the method call's receiver
is pointing to `$implicit`.

Fixes #39634.

PR Close #39686
2020-11-16 09:36:10 -08:00
Andrew Scott 7e724add7e refactor(compiler-cli): Add additional key/value spans to TCB (#39665)
In order to more accurately map from a node in the TCB to a template position,
we need to provide more span information in the TCB. These changes are necessary
for the Language Service to map from a TCB node back to a specific
locations in the template for actions like "find references" and
"refactor/rename". After the TS "find references" returns results,
including those in the TCB, we need to map specifically to the matching
key/value spans in the template rather than the entire source span.

This also has the benefit of producing diagnostics which align more
closely with what TypeScript produces.
The following example shows TS code and the diagnostic produced by an invalid assignment to a property:

```
let a: {age: number} = {} as any;
a.age = 'laksjdf';
^^^^^ <-- Type 'string' is not assignable to type 'number'.
```
A corollary to this in a template file would be [age]="'someString'". The diagnostic we currently produce for this is:

```
Type 'number' is not assignable to type 'string'.

1 <app-hello [greeting]="1"></app-hello>
             ~~~~~~~~~~~~~~
```
Notice that the underlined text includes the entire span.
If we included the keySpan for the assignment to the property,
this diagnostic underline would be more similar to the one produced by TypeScript;
that is, it would only underline “greeting”.

[design/discussion doc]
(https://docs.google.com/document/d/1FtaHdVL805wKe4E6FxVTnVHl38lICoHIjS2nThtRJ6I/edit?usp=sharing)

PR Close #39665
2020-11-16 09:33:11 -08:00
Pete Bacon Darwin 7bcfc0db09 refactor(core): remove isObservable TODO (#39669)
This commit removes the TODO comment that proposed
that we use the built-in RxJS `isObservable()` function.

This is not a viable approach since the built-in function
requires that the `obj` contains additional methods that
our "observable" types (such as `EventEmitter`) do not
necessarily have.

See #39643 for more information.

PR Close #39669
2020-11-16 09:28:12 -08:00
Misko Hevery c461acd12e refactor(core): Remove circular dependency on `ApplicationRef` (#39621)
`ViewRef` and `ApplicationRef` had a circular reference. This change
introduces `ViewRefTracker` which is a subset of `ApplicationRef` for
this purpose.

PR Close #39621
2020-11-16 09:12:46 -08:00
Misko Hevery 1ac68e3f2b refactor(core): Remove circular dependency on `render3` JIT and ViewEngine (#39621)
JIT needs to identify which type is `ChangeDetectorRef`. It was doing so
by importing `ChangeDetectorRef` and than comparing the types. This creates
circular dependency as well as prevents tree shaking. The new solution is
to brand the class with `__ChangeDetectorRef__` so that it can be identified
without creating circular dependency.

PR Close #39621
2020-11-16 09:12:46 -08:00
Misko Hevery 6d1d3c6a98 refactor(core): Remove circular dependency on `render3` and `ng_module` (#39621)
Extracted `NgModeDef` into a separate file to break the circular dependency.

PR Close #39621
2020-11-16 09:12:46 -08:00
Misko Hevery e6ae0c5349 refactor(core): Remove circular dependency between `LContainer` and `ViewRef`. (#39621)
`LContainer` stores `ViewRef`s this is not quite right as it creates
circular dependency between the two types. Also `LContainer` should not
be aware of `ViewRef` which iv ViewEngine specific construct.

PR Close #39621
2020-11-16 09:12:46 -08:00
Misko Hevery 621c34ddec refactor(core): extract `DoBootstrap` to separate file. (#39621)
Extract `DoBootstrap` interface to a separate file to break circular dependency.

PR Close #39621
2020-11-16 09:12:46 -08:00
Misko Hevery 8574c3000e refactor(core): Cleanup non-standard `Injector` handling. (#39621)
Due to historical reasons `Injector.__NG_ELEMENT_ID__` was set to `-1`.
This changes it to be consistent with other `*Ref.__NG_ELEMENT_ID__`
constructs.

PR Close #39621
2020-11-16 09:12:46 -08:00
Misko Hevery 585875c3f4 refactor(core): Cleanup circular dependency between ViewEngine and Ivy `Renderer2`. (#39621)
`Renderer2` is declared in ViewEngine but it sub-classed in Ivy. This creates a circular
dependency between ViewEngine `Renderer2` which needs to declare `__NG_ELEMENT_ID__` and
ivy factory which needs to create it. The workaround used to be to pass the `Renderer2`
through stack but that created a very convoluted code. This refactoring simply bundles the
two files together and removes the stack workaround making the code simpler to follow.

PR Close #39621
2020-11-16 09:12:46 -08:00
Misko Hevery 24b57d8b41 refactor(core): Cleanup circular dependency between ViewEngine and Ivy `ChangeDetectorRef`. (#39621)
`ChangeDetectorRef` is declared in ViewEngine but it sub-classed in Ivy. This creates a circular
dependency between ViewEngine `ChangeDetectorRef` which needs to declare `__NG_ELEMENT_ID__` and
ivy factory which needs to create it. The workaround used to be to pass the `ChangeDetectorRef`
through stack but that created a very convoluted code. This refactoring simply bundles the
two files together and removes the stack workaround making the code simpler to follow.

PR Close #39621
2020-11-16 09:12:46 -08:00
Misko Hevery 739d745eb5 refactor(core): Cleanup circular dependency between ViewEngine and Ivy `ViewContainerRef`. (#39621)
`ViewContainerRef` is declared in ViewEngine but it sub-classed in Ivy. This creates a circular
dependency between ViewEngine `ViewContainerRef` which needs to declare `__NG_ELEMENT_ID__` and
ivy factory which needs to create it. The workaround used to be to pass the `ViewContainerRef`
through stack but that created a very convoluted code. This refactoring simply bundles the
two files together and removes the stack workaround making the code simpler to follow.

PR Close #39621
2020-11-16 09:12:46 -08:00
Misko Hevery 453f196c4d refactor(core): Cleanup circular dependency between ViewEngine and Ivy `TemplateRef`. (#39621)
`TemplateRef` is declared in ViewEngine but it sub-classed in Ivy. This creates a circular
dependency between ViewEngine `TemplateRef` which needs to declare `__NG_ELEMENT_ID__` and
ivy factory which needs to create it. The workaround used to be to pass the `TemplateRef`
through stack but that created a very convoluted code. This refactoring simply bundles the
two files together and removes the stack workaround making the code simpler to follow.

PR Close #39621
2020-11-16 09:12:45 -08:00
Misko Hevery aa4924513b refactor(core): Cleanup circular dependency between ViewEngine and Ivy `ElementRef`. (#39621)
`ElementRef` is declared in ViewEngine but it sub-classed in Ivy. This creates a circular
dependency between ViewEngine `ElementRef` which needs to declare `__NG_ELEMENT_ID__` and
ivy factory which needs to create it. The workaround used to be to pass the `ElementRef`
through stack but that created a very convoluted code. This refactoring simply bundles the
two files together and removes the stack workaround making the code simpler to follow.

PR Close #39621
2020-11-16 09:12:45 -08:00
JiaLiPassion 5e92d649f2 feat(core): add shouldCoalesceRunChangeDetection option to coalesce change detections in the same event loop. (#39422)
Close #39348

Now `NgZone` has an option `shouldCoalesceEventChangeDetection` to coalesce
multiple event handler's change detections to one async change detection.

And there are some cases other than `event handler` have the same issues.
In #39348, the case like this.

```
// This code results in one change detection occurring per
// ngZone.run() call. This is entirely feasible, and can be a serious
// performance issue.
for (let i = 0; i < 100; i++) {
  this.ngZone.run(() => {
    // do something
  });
}
```

So such kind of case will trigger multiple change detections.
And now with Ivy, we have a new `markDirty()` API will schedule
a requestAnimationFrame to trigger change detection and also coalesce
the change detections in the same event loop, `markDirty()` API doesn't
only take care `event handler` but also all other cases `sync/macroTask/..`

So this PR add a new option to coalesce change detections for all cases.

test(core): add test case for shouldCoalesceEventChangeDetection option

Add new test cases for current `shouldCoalesceEventChangeDetection` in `ng_zone.spec`, since
currently we only have integration test for this one.

PR Close #39422
2020-11-16 08:58:50 -08:00
Alex Rickabaugh 24e13e0ed6 refactor(core): document setComponentScope to provide context (#39662)
`setComponentScope` was previously undocumented. This commit adds a short
explanation of what the function does, and adds a link to a doc which
explains issues with cycles in more detail.

PR Close #39662
2020-11-13 11:57:20 -08:00
Alex Rickabaugh c59f401f9a fix(compiler-cli): setComponentScope should only list used components/pipes (#39662)
ngtsc will avoid emitting generated imports that would create an import
cycle in the user's program. The main way such imports can arise is when
a component would ordinarily reference its dependencies in its component
definition `directiveDefs` and `pipeDefs`. This requires adding imports,
which run the risk of creating a cycle.

When ngtsc detects that adding such an import would cause this to occur, it
instead falls back on a strategy called "remote scoping", where a side-
effectful call to `setComponentScope` in the component's NgModule file is
used to patch `directiveDefs` and `pipeDefs` onto the component. Since the
NgModule file already imports all of the component's dependencies (to
declare them in the NgModule), this approach does not risk adding a cycle.
It has several large downsides, however:

1. it breaks under `sideEffects: false` logic in bundlers including the CLI
2. it breaks tree-shaking for the given component and its dependencies

See this doc for further details: https://hackmd.io/Odw80D0pR6yfsOjg_7XCJg?view

In particular, the impact on tree-shaking was exacerbated by the naive logic
ngtsc used to employ here. When this feature was implemented, at the time of
generating the side-effectful `setComponentScope` call, the compiler did not
know which of the component's declared dependencies were actually used in
its template. This meant that unlike the generation of `directiveDefs` in
the component definition itself, `setComponentScope` calls had to list the
_entire_ compilation scope of the component's NgModule, including directives
and pipes which were not actually used in the template. This made the tree-
shaking impact much worse, since if the component's NgModule made use of any
shared NgModules (e.g. `CommonModule`), every declaration therein would
become un-treeshakable.

Today, ngtsc does have the information on which directives/pipes are
actually used in the template, but this was not being used during the remote
scoping operation. This commit modifies remote scoping to take advantage of
the extra context and only list used dependencies in `setComponentScope`
calls, which should ameliorate the tree-shaking impact somewhat.

PR Close #39662
2020-11-13 11:57:20 -08:00
Pete Bacon Darwin eea5d6b38f test(compiler-cli): convert element related compliance tests (#39617)
This commit converts a set of compliance tests in the `r3_compiler_compliance_spec.ts`
file to the new testing approach.

PR Close #39617
2020-11-13 11:25:57 -08:00
Pete Bacon Darwin e719419d3f test(compiler-cli): create initial "linked compile" compliance tests (#39617)
This commit adds bazel rules to test whether linking the golden partial
files for test cases produces the same output as a full compile of the
test case would.

PR Close #39617
2020-11-13 11:25:57 -08:00
Pete Bacon Darwin 10525af67b test(compiler-cli): generate golden files for partial compilation (#39617)
This commit adds a JS script that can generate a partial golden file
for test cases in the compiler compliance tests.

PR Close #39617
2020-11-13 11:25:56 -08:00
Pete Bacon Darwin 793d66afa5 test(compiler-cli): create "full compile" compliance test rules (#39617)
This commit contains the basic runner logic and a couple of sample test cases
for the "full compile" compliance tests, where source files are compiled
to full definitions and checked against expectations.

PR Close #39617
2020-11-13 11:25:56 -08:00
Pete Bacon Darwin 8d445e0dff refactor(compiler-cli): move legacy compliance tests to new folder (#39617)
This commit renames the original `compliance` test directory to `compliance_old`.
Eventually this directory will be deleted once all the tests have been
migrated to the new test case based compliance tests.

PR Close #39617
2020-11-13 11:25:56 -08:00
Pete Bacon Darwin 7b6ea973f6 refactor(compiler-cli): return the `FileSystem` from `initMockFileSystem()` (#39617)
It is common to want to use the file system once it is initialized,
so it makes sense for this function to return it.

PR Close #39617
2020-11-13 11:25:56 -08:00
Andrew Scott 8a1c98c5e8 refactor(compiler-cli): add keySpan to reference nodes (#39616)
Similar to #39613, #39609, and #38898, we should store the `keySpan` for
Reference nodes so that we can accurately map from a template node to a
span in the original file. This is most notably an issue at the moment
for directive references `#ref="exportAs"`. The current behavior for the
language service when requesting information for the reference
is that it will return a text span that results in
highlighting the entire source when it should only highlight "ref" (test
added for this case as well).

PR Close #39616
2020-11-12 15:12:53 -08:00
Andrew Scott c33326c538 refactor(compiler-cli): add keySpan to parsed events (#39609)
Though we currently have the knowledge of where the `key` for an
event binding appears during parsing, we do not propagate this
information to the output AST. This means that once we produce the
template AST, we have no way of mapping a template position to the key
span alone. The best we can currently do is map back to the
`sourceSpan`. This presents problems downstream, specifically for the
language service, where we cannot provide correct information about a
position in a template because the AST is not granular enough.

This is essentially identical to the change from #38898, but for event
bindings rather than input bindings.

PR Close #39609
2020-11-12 15:09:17 -08:00
Andrew Scott 21651d362d refactor(compiler-cli): add keySpan to text attributes (#39613)
Similar to #39609 and #38898, though we currently have the knowledge of where the key for an
attribute appears during parsing, we do not propagate this
information to the output AST. This means that once we produce the
template AST, we have no way of mapping a template position to the key
span alone. The best we can currently do is map back to the
sourceSpan. This presents problems downstream, specifically for the
language service, where we cannot provide correct information about a
position in a template because the AST is not granular enough.

PR Close #39613
2020-11-12 14:19:00 -08:00